π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π style(task): collapse an over-long task instruction, expand to edit (#17886)
Arvin Xuad8ded155561
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex c5466e49e73..b251bd2ea34 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -879,6 +879,34 @@ checkout and appears right after a rebase that bumps the root range. Do not repoas a defect of the branch or of the base ref; note it as an environment finding andmove on. Back up the lockfile before `dedupe` anyway β it is the only copy.+### A fresh worktree installed with `--ignore-scripts` returns 500 on every `/trpc/lambda/*`++**Situation:** bootstrapping a new git worktree for a run β `pnpm install` at the root,+then `init-dev-env.sh dev`.++**Doesn't work:** `pnpm install --ignore-scripts`. The server starts and serves the SPA+normally, but Turbopack cannot instantiate `@icons-pack/react-simple-icons` (reached+through `packages/const/src/composio.ts` β `packages/database/src/schemas/*`), so every+`/trpc/lambda/*` route returns **500** while the page itself looks healthy. The CLI+surfaces this only as `Unable to transform response from server`, which reads as an auth+or API-key problem and sends you to `setup-auth.sh` instead of to the install. The Next+log holds the real cause (`module factory is not available`), and its own suggested fix+β clear the browser cache / service worker β is misleading here.++**Works:** install without `--ignore-scripts`, and clear the stale Turbopack cache+because the broken module graph is persisted:++```bash+.agents/acceptance/scripts/init-dev-env.sh stop-dev+rm -rf .next && pnpm install # no --ignore-scripts+.agents/acceptance/scripts/init-dev-env.sh dev+```++Gate on a real authenticated TRPC call rather than on the page rendering: a 200 from+`$SERVER_URL/` proves nothing about the lambda routes. Remember `apps/cli` and+`apps/desktop` are standalone installs (PROJECT.md Β§1), so each also needs its own+`pnpm install` in a fresh worktree.+## Detailed references- [Probe field notes](./references/probe-field-notes.md) β all historicaldiff --git a/src/components/CollapsibleContent/index.tsx b/src/components/CollapsibleContent/index.tsxindex 33a5c8c0a67..e87e89f8047 100644--- a/src/components/CollapsibleContent/index.tsx+++ b/src/components/CollapsibleContent/index.tsx@@ -2,18 +2,17 @@import { createStaticStyles } from 'antd-style';import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';-import type { CSSProperties, MouseEvent, ReactNode } from 'react';-import { memo, useCallback, useEffect, useRef, useState } from 'react';+import type { CSSProperties, ReactNode } from 'react';+import { memo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { useNaturalHeight } from './useNaturalHeight';+import { useCollapsible } from './useCollapsible';const DEFAULT_MAX_HEIGHT = 280;const DEFAULT_FADE_HEIGHT = 48;// The fade must stay under one line-height, or the last visible line is a ghost// and a short preview has nothing legible left in it.const FADE_RATIO = 0.2;-const VIEWPORT_RATIO = 0.35;// Only collapse when the overflow is meaningful; avoids hiding a button for a// handful of extra pixels.const OVERFLOW_THRESHOLD = 32;@@ -66,15 +65,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,}));-const computeThreshold = (limit: number) => {- if (typeof window === 'undefined') return limit;- return Math.min(limit, Math.round(window.innerHeight * VIEWPORT_RATIO));-};-interface CollapsibleContentProps {children: ReactNode;+ /** Controlled collapsed state. Omit to let the component own it. Pass it when something outside the toggle expands the content β an editor gaining focus, for instance. */+ collapsed?: boolean;/** Upper bound for the collapsed height; the effective clamp also honours the viewport. */maxHeight?: number;+ /** Fires on toggle with the next collapsed state. Required for the controlled mode; also useful as a plain notification in the uncontrolled one. */+ onCollapsedChange?: (collapsed: boolean) => void;+ /** Fires when the content crosses the overflow threshold, so the host can drop affordances that only make sense once nothing is hidden. */+ onOverflowChange?: (overflowing: boolean) => void;/** How far content must overflow before collapsing is worth a toggle. Lower it for short previews, where a couple of hidden lines already matter. */overflowThreshold?: number;}@@ -88,40 +88,37 @@ interface CollapsibleContentProps {** The clamp is capped by the viewport, not just `maxHeight`: on a short window a* 280px preview is most of the screen.+ *+ * Collapsing is self-managed by default. Pass `collapsed` + `onCollapsedChange`+ * to drive it from outside β the task instruction expands on editor focus, so+ * one click both opens the preview and puts the caret where it was aimed.*/const CollapsibleContent = memo<CollapsibleContentProps>(({children,+ collapsed: collapsedProp,maxHeight: maxHeightLimit = DEFAULT_MAX_HEIGHT,+ onCollapsedChange,+ onOverflowChange,overflowThreshold = OVERFLOW_THRESHOLD,}) => {const { t } = useTranslation('chat');const contentRef = useRef<HTMLDivElement | null>(null);- const [maxHeight, setMaxHeight] = useState(() => computeThreshold(maxHeightLimit));- const [collapsed, setCollapsed] = useState(true);-- const naturalHeight = useNaturalHeight(contentRef);-- useEffect(() => {- if (typeof window === 'undefined') return;-- const handleResize = () => setMaxHeight(computeThreshold(maxHeightLimit));- handleResize();-- window.addEventListener('resize', handleResize);- return () => window.removeEventListener('resize', handleResize);- }, [maxHeightLimit]);-- const shouldCollapse = naturalHeight > maxHeight + overflowThreshold;- const isCollapsed = shouldCollapse && collapsed;-- // Previews live inside clickable cards (a task run opens its drawer) β the- // toggle must not also trigger the card.- const handleToggle = useCallback((e: MouseEvent) => {- e.stopPropagation();- setCollapsed((prev) => !prev);- }, []);+ const {+ isCollapsed,+ maxHeight,+ shouldCollapse,+ showAsCollapsed: collapsed,+ toggle,+ } = useCollapsible({+ collapsed: collapsedProp,+ contentRef,+ maxHeightLimit,+ onCollapsedChange,+ onOverflowChange,+ overflowThreshold,+ });return (<div className={styles.container}>@@ -145,7 +142,7 @@ const CollapsibleContent = memo<CollapsibleContentProps>(aria-expanded={!collapsed}className={styles.toggleButton}type="button"- onClick={handleToggle}+ onClick={toggle}>{collapsed ? <ChevronDownIcon size={14} /> : <ChevronUpIcon size={14} />}{collapsed ? t('messageLongCollapse.expand') : t('messageLongCollapse.collapse')}diff --git a/src/components/CollapsibleContent/useCollapsible.test.ts b/src/components/CollapsibleContent/useCollapsible.test.tsnew file mode 100644index 00000000000..917f3ed5650--- /dev/null+++ b/src/components/CollapsibleContent/useCollapsible.test.ts@@ -0,0 +1,114 @@+import { act, renderHook } from '@testing-library/react';+import { type RefObject } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useCollapsible } from './useCollapsible';++const originalResizeObserver = globalThis.ResizeObserver;++// jsdom lays nothing out, so drive the measurement directly: `useNaturalHeight`+// reads `scrollHeight` on mount, which is all these cases need.+const contentRef = (scrollHeight: number) =>+ ({ current: { scrollHeight } as unknown as HTMLElement }) as RefObject<HTMLElement | null>;++// jsdom is 768px tall, so the 35% viewport cap clamps a 280px limit to 269px:+// 900 overflows past the 32px threshold, 100 comfortably fits.+const OVERFLOWING = 900;+const FITS = 100;+const MAX_HEIGHT_LIMIT = 280;+const CLAMPED = 269;++const options = (extra: Partial<Parameters<typeof useCollapsible>[0]> = {}) => ({+ contentRef: contentRef(OVERFLOWING),+ maxHeightLimit: MAX_HEIGHT_LIMIT,+ overflowThreshold: 32,+ ...extra,+});++const click = { stopPropagation: () => {} } as Parameters<+ ReturnType<typeof useCollapsible>['toggle']+>[0];++beforeEach(() => {+ globalThis.ResizeObserver = class {+ disconnect() {}+ observe() {}+ unobserve() {}+ } as unknown as typeof ResizeObserver;+});++afterEach(() => {+ globalThis.ResizeObserver = originalResizeObserver;+});++describe('useCollapsible', () => {+ it('caps the clamp at the viewport, not just the caller limit', () => {+ const { result } = renderHook(() => useCollapsible(options()));++ expect(result.current.maxHeight).toBe(CLAMPED);+ });++ it('leaves short content alone β nothing to collapse', () => {+ const onOverflowChange = vi.fn();++ const { result } = renderHook(() =>+ useCollapsible(options({ contentRef: contentRef(FITS), onOverflowChange })),+ );++ expect(result.current.shouldCollapse).toBe(false);+ expect(result.current.isCollapsed).toBe(false);+ expect(onOverflowChange).toHaveBeenCalledWith(false);+ });++ it('collapses long content by default and reports the overflow', () => {+ const onOverflowChange = vi.fn();++ const { result } = renderHook(() => useCollapsible(options({ onOverflowChange })));++ expect(result.current.shouldCollapse).toBe(true);+ expect(result.current.isCollapsed).toBe(true);+ expect(onOverflowChange).toHaveBeenCalledWith(true);+ });++ it('toggles itself when uncontrolled', () => {+ const onCollapsedChange = vi.fn();+ const { result } = renderHook(() => useCollapsible(options({ onCollapsedChange })));++ act(() => result.current.toggle(click));++ expect(result.current.isCollapsed).toBe(false);+ expect(result.current.showAsCollapsed).toBe(false);+ expect(onCollapsedChange).toHaveBeenCalledWith(false);+ });++ it('defers to the host when controlled', () => {+ const onCollapsedChange = vi.fn();+ const { rerender, result } = renderHook(+ ({ collapsed }) => useCollapsible(options({ collapsed, onCollapsedChange })),+ { initialProps: { collapsed: true } },+ );++ act(() => result.current.toggle(click));++ // The host owns the state: the toggle only reports the intent.+ expect(onCollapsedChange).toHaveBeenCalledWith(false);+ expect(result.current.isCollapsed).toBe(true);++ rerender({ collapsed: false });++ expect(result.current.isCollapsed).toBe(false);+ });++ it('reports the overflow once β not per render, and never before measuring', () => {+ const onOverflowChange = vi.fn();+ const { rerender } = renderHook(() =>+ // Fresh inline callback identity on every render, as a JSX host would pass.+ useCollapsible(options({ onOverflowChange: (v) => onOverflowChange(v) })),+ );++ rerender();+ rerender();++ expect(onOverflowChange).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/components/CollapsibleContent/useCollapsible.ts b/src/components/CollapsibleContent/useCollapsible.tsnew file mode 100644index 00000000000..fc9cef8ced5--- /dev/null+++ b/src/components/CollapsibleContent/useCollapsible.ts@@ -0,0 +1,90 @@+import { type MouseEvent, type RefObject, useCallback, useEffect, useRef, useState } from 'react';++import { useNaturalHeight } from './useNaturalHeight';++const VIEWPORT_RATIO = 0.35;++interface UseCollapsibleOptions {+ /** Controlled collapsed state. Omit to let the hook own it. */+ collapsed?: boolean;+ contentRef: RefObject<HTMLElement | null>;+ maxHeightLimit: number;+ onCollapsedChange?: (collapsed: boolean) => void;+ onOverflowChange?: (overflowing: boolean) => void;+ overflowThreshold: number;+}++/**+ * The clamp is capped by the viewport, not just the caller's limit: on a short+ * window a 280px preview is most of the screen.+ */+export const computeThreshold = (limit: number) => {+ if (typeof window === 'undefined') return limit;+ return Math.min(limit, Math.round(window.innerHeight * VIEWPORT_RATIO));+};++/**+ * Collapse state machine behind `CollapsibleContent`: resolves the effective+ * clamp, decides whether the overflow is even worth a toggle, and supports both+ * the self-managed and the controlled mode.+ */+export const useCollapsible = ({+ collapsed: collapsedProp,+ contentRef,+ maxHeightLimit,+ onCollapsedChange,+ onOverflowChange,+ overflowThreshold,+}: UseCollapsibleOptions) => {+ const [maxHeight, setMaxHeight] = useState(() => computeThreshold(maxHeightLimit));+ const [uncontrolledCollapsed, setUncontrolledCollapsed] = useState(true);+ const collapsed = collapsedProp ?? uncontrolledCollapsed;++ const naturalHeight = useNaturalHeight(contentRef);++ useEffect(() => {+ if (typeof window === 'undefined') return;++ const handleResize = () => setMaxHeight(computeThreshold(maxHeightLimit));+ handleResize();++ window.addEventListener('resize', handleResize);+ return () => window.removeEventListener('resize', handleResize);+ }, [maxHeightLimit]);++ const shouldCollapse = naturalHeight > maxHeight + overflowThreshold;++ // Held in a ref so an inline host callback doesn't re-fire the notification on+ // every render β only an actual overflow flip should reach the host. The+ // pre-measurement render reads as "fits", so hold the first report until the+ // element has a height, or every mount announces a false negative.+ const measured = naturalHeight > 0;+ const onOverflowChangeRef = useRef(onOverflowChange);+ onOverflowChangeRef.current = onOverflowChange;+ useEffect(() => {+ if (!measured) return;+ onOverflowChangeRef.current?.(shouldCollapse);+ }, [measured, shouldCollapse]);++ // Previews live inside clickable cards (a task run opens its drawer) β the+ // toggle must not also trigger the card.+ const toggle = useCallback(+ (e: MouseEvent) => {+ e.stopPropagation();+ const next = !collapsed;+ if (collapsedProp === undefined) setUncontrolledCollapsed(next);+ onCollapsedChange?.(next);+ },+ [collapsed, collapsedProp, onCollapsedChange],+ );++ return {+ /** Whether the clamp and fade mask are actually applied right now. */+ isCollapsed: shouldCollapse && collapsed,+ maxHeight,+ /** Whether the content overflows enough to deserve a toggle at all. */+ shouldCollapse,+ showAsCollapsed: collapsed,+ toggle,+ };+};diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsxindex bdd862d0bbf..05fea52aaca 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskInstruction.tsx@@ -4,6 +4,7 @@ import { Paperclip } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import CollapsibleContent from '@/components/CollapsibleContent';import { EditingIndicator, type EditLockClient, useEditLock } from '@/features/EditLock';import { EditorCanvas } from '@/features/EditorCanvas';import { seedAttachments } from '@/features/EditorCanvas/attachmentRegistry';@@ -24,6 +25,10 @@ const taskLockClient: EditLockClient = {},};+// Roomier than the chat-bubble default: the instruction is the primary content+// of the page, so the preview should carry a paragraph or two before it clamps.+const INSTRUCTION_MAX_HEIGHT = 320;+const TaskInstruction = memo(() => {const { t } = useTranslation('chat');const { allowed: canEditTask } = usePermission('create_content');@@ -39,10 +44,16 @@ const TaskInstruction = memo(() => {// Collaborative edit lock for workspace tasks (same model as pages): read-only// when another member is editing; acquired implicitly on the first edit.const [edited, setEdited] = useState(false);+ // A long instruction opens clamped so the properties, subtasks and activity+ // below it stay reachable; a short one never collapses and stays directly+ // editable. Both reset per task β the next task gets its own first read.+ const [expanded, setExpanded] = useState(false);+ const [overflowing, setOverflowing] = useState(false);const taskIdRef = useRef(taskId);if (taskIdRef.current !== taskId) {taskIdRef.current = taskId;setEdited(false);+ setExpanded(false);}const lock = useEditLock({client: taskLockClient,@@ -84,6 +95,25 @@ const TaskInstruction = memo(() => {pickAndInsertAttachments(editor);}, [editor]);+ // Clicking into the clamped text focuses the editor, so expanding on focus+ // makes one click both open the instruction and land the caret where it was+ // aimed β no "expand, then click again to type".+ const handleFocus = useCallback(() => setExpanded(true), []);++ const handleCollapsedChange = useCallback(+ (collapsed: boolean) => {+ // Collapsing while the editor still holds the caret would let Lexical+ // restore focus and immediately re-expand.+ if (collapsed) editor?.blur();+ setExpanded(!collapsed);+ },+ [editor],+ );++ // Attaching a file only makes sense once the whole instruction is in view;+ // while clamped, the collapse toggle is the single affordance below the text.+ const showAttach = !overflowing || expanded;+return (<Flexbox gap={4}><EditingIndicator@@ -92,23 +122,35 @@ const TaskInstruction = memo(() => {/>{/* editTask can update this mounted editor. The store revision changes only for externalsnapshots, so local autosave echoes and unchanged polling snapshots do not reload live- input. */}- <EditorCanvas- contentRevision={instructionRevision}- disabled={!canEditTask}- editable={!lock.lockedByOther && !lock.pending}- editor={editor}- editorData={editorData}- entityId={taskId}- placeholder={t('taskDetail.instructionPlaceholder')}- onContentChange={handleContentChange}- />- <ActionIcon- icon={Paperclip}- size={'small'}- title={t('upload.action.tooltip')}- onClick={handleAttach}- />+ input. Collapsing is pure CSS around the same mounted editor β never a remount, which+ would drop unsaved input. */}+ <CollapsibleContent+ collapsed={!expanded}+ maxHeight={INSTRUCTION_MAX_HEIGHT}+ onCollapsedChange={handleCollapsedChange}+ onOverflowChange={setOverflowing}+ >+ <div onFocus={handleFocus}>+ <EditorCanvas+ contentRevision={instructionRevision}+ disabled={!canEditTask}+ editable={!lock.lockedByOther && !lock.pending}+ editor={editor}+ editorData={editorData}+ entityId={taskId}+ placeholder={t('taskDetail.instructionPlaceholder')}+ onContentChange={handleContentChange}+ />+ </div>+ </CollapsibleContent>+ {showAttach && (+ <ActionIcon+ icon={Paperclip}+ size={'small'}+ title={t('upload.action.tooltip')}+ onClick={handleAttach}+ />+ )}</Flexbox>);});