Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent-fold): render tool calls with the AI chat's component patterns (#5583)
Eric Hayes7c011c9064d0
diff --git a/.sqlx/query-4a81bb7e2c2dd3a7dc18cb1ac1ce64986824482c7a5f0465e2d2f9394a56ae62.json b/.sqlx/query-284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a.jsonsimilarity index 79%rename from .sqlx/query-4a81bb7e2c2dd3a7dc18cb1ac1ce64986824482c7a5f0465e2d2f9394a56ae62.jsonrename to .sqlx/query-284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a.jsonindex 7a36850d61..62c05ada48 100644--- a/.sqlx/query-4a81bb7e2c2dd3a7dc18cb1ac1ce64986824482c7a5f0465e2d2f9394a56ae62.json+++ b/.sqlx/query-284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at\n FROM agent_session\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY created_at DESC\n LIMIT 1\n ",+ "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE id = $1\n ","describe": {"columns": [{@@ -67,11 +67,15 @@"ordinal": 12,"name": "modified_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 13,+ "name": "thread_channel_id?",+ "type_info": "Uuid"}],"parameters": {"Left": [- "Uuid","Uuid"]},@@ -88,8 +92,9 @@false,true,false,- false+ false,+ null]},- "hash": "4a81bb7e2c2dd3a7dc18cb1ac1ce64986824482c7a5f0465e2d2f9394a56ae62"+ "hash": "284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a"}diff --git a/.sqlx/query-611ccba6439212e9ac2cdf04e77d9733bd60f867d7fd7d6972a41754ce224ed4.json b/.sqlx/query-97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c.jsonsimilarity index 76%rename from .sqlx/query-611ccba6439212e9ac2cdf04e77d9733bd60f867d7fd7d6972a41754ce224ed4.jsonrename to .sqlx/query-97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c.jsonindex 5acdb6654c..3c0198d46e 100644--- a/.sqlx/query-611ccba6439212e9ac2cdf04e77d9733bd60f867d7fd7d6972a41754ce224ed4.json+++ b/.sqlx/query-97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at\n FROM agent_session\n WHERE id = $1\n ",+ "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY created_at DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -67,10 +67,16 @@"ordinal": 12,"name": "modified_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 13,+ "name": "thread_channel_id?",+ "type_info": "Uuid"}],"parameters": {"Left": [+ "Uuid","Uuid"]},@@ -87,8 +93,9 @@false,true,false,- false+ false,+ null]},- "hash": "611ccba6439212e9ac2cdf04e77d9733bd60f867d7fd7d6972a41754ce224ed4"+ "hash": "97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c"}diff --git a/.sqlx/query-f52ab5dea389d06931a7fa43c2ecb8055363f40dcfe1813ac64bf9399b9a9183.json b/.sqlx/query-ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb.jsonsimilarity index 85%rename from .sqlx/query-f52ab5dea389d06931a7fa43c2ecb8055363f40dcfe1813ac64bf9399b9a9183.jsonrename to .sqlx/query-ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb.jsonindex 91d60bf118..8d04514539 100644--- a/.sqlx/query-f52ab5dea389d06931a7fa43c2ecb8055363f40dcfe1813ac64bf9399b9a9183.json+++ b/.sqlx/query-ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, acp_session_id, status, status_event_name\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at\n ",+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, acp_session_id, status, status_event_name\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n ","describe": {"columns": [{@@ -67,6 +67,11 @@"ordinal": 12,"name": "modified_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 13,+ "name": "thread_channel_id?",+ "type_info": "Uuid"}],"parameters": {@@ -97,8 +102,9 @@false,true,false,- false+ false,+ null]},- "hash": "f52ab5dea389d06931a7fa43c2ecb8055363f40dcfe1813ac64bf9399b9a9183"+ "hash": "ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb"}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 80cf59a6e5..a3b3fe411a 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -50,11 +50,11 @@"@fontsource-variable/inter": "^5.2.8","@fontsource-variable/playfair-display": "^5.2.8","@fontsource-variable/roboto-mono": "^5.2.8",- "@inkibra/tauri-plugins": "git+https://github.com/macro-inc/tauri-plugins.git#6ddd6600e20436388f169e936b610fe93944b7b0","@fullcalendar/core": "^6.1.21","@fullcalendar/daygrid": "^6.1.21","@fullcalendar/interaction": "^6.1.21","@fullcalendar/timegrid": "^6.1.21",+ "@inkibra/tauri-plugins": "git+https://github.com/macro-inc/tauri-plugins.git#6ddd6600e20436388f169e936b610fe93944b7b0","@kobalte/core": "^0.13.11","@leeoniya/ufuzzy": "^1.0.19","@lexical/history": "0.45.0",@@ -78,6 +78,7 @@"@normy/query-core": "^0.21.0","@opentelemetry/api": "^1.9.1","@phosphor-icons/core": "^2.1.1",+ "@pierre/diffs": "^1.3.5","@solid-primitives/broadcast-channel": "^0.1.1","@solid-primitives/context": "^0.3.2","@solid-primitives/event-bus": "^1.1.2",@@ -112,6 +113,7 @@"d3-shape": "^3.2.0","date-fns": "^4.1.0","detect-browser": "^5.3.0",+ "diff": "^9.0.0","dinero.js": "2.0.0-alpha.8","email-validator": "^2.0.4","emojibase-data": "^17.0.0",@@ -128,6 +130,7 @@"pdfjs-dist": "github:macro-inc/pdf.js#v2.16.52-web","posthog-js": "^1.387.0","quill": "^2.0.3",+ "shiki": "^4.4.3","short-uuid": "^5.2.0","signature_pad": "^5.0.10","solid-custom-scrollbars": "^0.1.7",diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex 6c90dba8b1..7d8e6dba22 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -689,6 +689,21 @@ if (LOCAL_ONLY) {'dynamic-ui',lazy(() => import('@app/features/dynamic-ui/Gallery')));++ registerComponent(+ 'agent-ui',+ lazy(() => import('@app/features/block-agent/debug/Gallery'))+ );++ registerComponent(+ 'agent-replay',+ lazy(() => import('@app/features/block-agent/debug/replay/Replay'))+ );++ registerComponent(+ 'linked-conversation',+ withAuth(lazy(() => import('@core/linked-conversation/debug/Demo')))+ );}if (DEV_MODE_ENV) {diff --git a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.mdnew file mode 100644index 0000000000..08cca0a23f--- /dev/null+++ b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md@@ -0,0 +1,336 @@+# Channel Block — Reference Notes for the Agent Block++How `block-channel` / `features/channel` is wired, as a template for giving `block-agent`+real state (live updates, send path, scroll, input). All paths relative to `apps/web/src`+unless absolute. Line numbers are as of commit `254b60f339`.++---++## 1. Block entry & composition++```+features/block-channel/definition.ts defineBlock({ name:'channel', component: NewChannelBlockAdapter })+ └─ block-channel/component/NewChannelBlockAdapter.tsx (adapter: tabs, header, persistence, orchestrator)+ └─ features/channel/Channel/Channel.tsx (the actual channel surface, "pure-ish")+```++### definition.ts (`features/block-channel/definition.ts`)+Trivial: `load` accepts a `dss` source and returns `ok({ id })`. `liveTrackingEnabled: true`.+The agent block's `definition.ts` is already the same shape (with `lazy()` component — keep that).++### The adapter layer (`NewChannelBlockAdapter.tsx`)+Everything "block-shaped" lives here, NOT in Channel.tsx:++| Concern | Where | Mechanism |+|---|---|---|+| Hotkey scope ownership | :194–196 | `useHotkeyDOMScope('channel')` → `blockHotkeyScopeSignal.set(scope)` + `useBlockEntityCommands()`. Channel block doesn't render `BlockContainer`, so it owns the scope itself (comment at :190). |+| Block id | :201 | `useBlockId()` — the channel id. |+| Tabs | :242–265, :449–477 | Local `createSignal<ChannelTabId>` + `ChannelTabProvider` (`Channel/ChannelTabContext.tsx`); `<Switch>` mounts one tab at a time. Switching away from `messages` clears the Channel handle (`setMessagesHandle(undefined)`). |+| Header | `NewTop` :125–187 | Rendered *inside* the block via split-layout portals: `ChannelTopLeft`, `SplitHeaderRight` + `HeaderIsland`, `ChannelTopBarLiveIndicators`. |+| Entry-state persistence | :216–218, :408–427 | `splitPanel.handle.registerEntryStateCaptor(CHANNEL_STATE_ENTRY_KEY, () => snapshot)` — the split layout calls this captor on history navigation; on mount the adapter reads `splitPanel.handle.currentEntryState()?.[key]` and hydrates. `onCleanup(dispose)`. Snapshot = `{ activeTab, messages: ChannelMessagesStateSnapshot }`. |+| Orchestrator methods | :354–380 | `createMethodRegistration(blockHandle, { goToLocationFromParams, goToLatest })`. External navigation (mention click, inbox row) lands here. |+| Handle await | :345–350 | `awaitCondition(() => messagesHandle() !== undefined, 10_000)` — the Messages tab may not have mounted yet; orchestrator methods wait for the child handle via a signal. |+| Target-message resolution | :308–341 | `resolveTargetMessage`: cache-first (`findTopLevelMessageInChannelMessages`, `findThreadIdInChannelMessages`), falls back to `fetchResolvedChannelMessage` roundtrip. |+| Permissions | :430 | Wraps everything in `<EntityPermissionsGate entityType="channel" entityId={channelId}>`. |+| Autofocus | :454 | `autofocus={canAutofocusSplitContent && !navigatedFromJK()}` — split layout + j/k navigation decide, not the component. |++### The child-handle pattern (the key adapter↔component contract)+`Channel` exposes an imperative handle instead of the adapter reaching in:++```ts+// Channel.tsx:151–155+export type ChannelHandle = {+ goToMessage: (messageId: string, replyId?: string) => void;+ goToLatest: () => void;+ getMessagesStateSnapshot: () => ChannelMessagesStateSnapshot | undefined;+};+```++- Channel calls `props.onHandleReady(handle)` once `isChannelReady()` (query fetched ++ navigation ready + initial scroll done) — Channel.tsx:694–711.+- Adapter stores it in a signal (`setMessagesHandle`) so `awaitCondition` can wait on it.+- Adapter also keeps `lastMessagesStateSnapshot` so the captor still answers after the+ Messages tab unmounts (:257, :412–415).++### Props crossing the adapter → Channel boundary (`ChannelProps`, Channel.tsx:133–142)+`channelId`, `targetMessageId?`, `targetMessageReplyId?`, `initialMessagesStateSnapshot?`,+`onHandleReady?`, `autofocus?`. That's it — everything else the Channel derives itself.++---++## 2. Context structure++### Consumed (global, cache-backed — Channel does NOT own these)+| Hook | Source | Backing |+|---|---|---|+| `useChannelName` / `useChannelType` / `useChannelActivity` | `lib/core/context/channels.ts:68–81` | `ChannelsContextProvider` — app-level provider over `useListChannelsQuery` + `useChannelsActivityQuery` (whole channel list, memoized `byId` maps). Per-channel hooks are just memos over it. |+| `useUserId` | `@core/context/user` | app-level |+| `useChannelParticipants` | `features/channel/use-channel-participants.ts` | thin memo over `useChannelParticipantsQuery` → `{ users, ids }` accessors |+| `useSplitPanel` / `useSplitLayout` | `@components/app/split-layout` | split-layout contexts (insets, popoverSplit, openWithSplit) |+| `queryClient` | `@queries/client` | module-global TanStack client — all cache surgery goes through it |++### Created by Channel itself (component-local providers, Channel.tsx:713–984)+```+<StaticMarkdownContext> one shared lexical static-markdown editor for all messages+ <SearchHighlightTermsProvider value={findBar.getSearchTermsForMessage}>+ <foldedMessages.Provider> fold lookup context + Suspense gate (see §4)+ <MaybeMessageActionDrawerManager> mobile action drawer+ <ChannelDropZone dragState=...> entity/file drop+```++Rule of thumb the channel follows: **identity/list data is global context; everything+interactive is component-local state created by factories.** The agent block already uses+`StaticMarkdownContext` (Block.tsx:17) — correct instinct.++---++## 3. The `create*` factory pattern (the main thing to copy)++Channel.tsx is ~990 lines but owns almost no logic — it is a *composition root*. Each+factory is a plain function called during setup (component scope, so `onCleanup`/effects+work), taking **accessors + callbacks** in and returning **accessors + methods** out.+Signals are the interface; no factory imports another factory's file — Channel wires them.++| Factory | File | Owns (state) | Takes | Returns | Wired to |+|---|---|---|---|---|---|+| `createTargetMessageController` | `create-target-message-controller.ts:47` | store `{activeTargetMessageId, activeTargetMessageReplyId, loadAroundMessageId, pendingScrollTargetId, pendingTargetReplyId}` + flash timer (1s highlight) | `channelId`, initial target, `messageKeys`, `navigation`, `didInitialScroll` | accessors + `goToMessage/completePendingScroll/clearActiveTarget/reset` | drives `loadAroundMessageId` into the messages query; internal effect executes the scroll via `navigation()` once the key is loaded and initial scroll is done; also swaps the load-around cache back to the default key (`restoreDefaultChannelPaginationAfterTargetLoad`, :214) |+| `useChannelMessagesQuery` + `createMessageIndex` | `@queries/channel/channel-messages.ts:146, :807` | reconciled store `{items, keys, byId}` | query data accessor | oldest-first flat index (pages/items arrive newest-first; dedupe + double reverse); `reconcile()` keeps row identity stable; guards the transient empty-data flash during refetch (:843) | everything renders from `keys`/`byId` |+| `createFoldedMessagesScope` | `create-folded-messages-scope.tsx:40` | delegates to `createFoldedMessages` (§4) | `channelId` | `{ readyLookup, Provider }` — `readyLookup` never suspends; `Provider` = `<AwaitFold/>` (forces Suspense to wait) + context provider | placeholder rows look up their folded body via context |+| `createUnifiedInputManager` | `unified-input-manager.ts:24` | `replyTarget` signal (at most one reply binding channel-wide) | `initialReplyTarget` snapshot, `onReplyThreadReleased` | `replyTarget`, `bindReply(message)`, `closeReply`, `getReplyTargetSnapshot` | bottom input face switching (§6); snapshot goes into entry-state |+| `createThreadManager` | `thread-manager.ts:16` | store of per-thread `ThreadState` (isExpanded, isReplying, replyInputState/El/Handle, focusRequest), lazily created | `initialSnapshot` | `getOrCreateThreadState(threadId)`, `getSnapshot()` | each ThreadList row pulls its state; snapshot → entry-state |+| `createThreadPaginator` | `thread-paginator.ts:41` | per-direction `{pending, is, more}` signals | the infinite query | `isPrepending/isShifting/prependPaginate/shiftPaginate/hasMore*` | `shift` = fetch older (top, virtua `shift` mode), `prepend` = fetch newer (bottom); coalesces re-entrant calls via `pending` do/while loop |+| `createMessageEditor` | `create-message-editor.ts:43` | `editState` signal `{messageId, message, snapshot}` | `channelId`, `participantIds`, `patchMessage` (mutation.mutate), `onEditEnded` | `state/start/update/cancel/save` — `save` diffs content+attachments and no-ops when unchanged | UnifiedEditInput + inline editor + hotkey `e` |+| `createMessageSelection` | `create-message-selection.ts:16` | `selectedId` signal; auto-clears when id leaves `keys` | `keys` accessor | `selectedId/select/clear/selectFirst/selectPrevious/selectNext` | keyboard nav, highlight |+| `createDeleteMessageConfirmation` | `create-delete-message-confirmation.tsx:19` | `pending` signal | `deleteMessage` fn | `{ requestDelete, ConfirmationDialog }` — **returns a component**; mounted once at Channel root (:715) | all delete entry points route through it |+| `createChannelMessageActions` | `create-channel-message-actions.ts:92` | none (pure closure + injectable `effects` for tests) | mutations, `onReply/onEdit/onCreateTask/onChat` callbacks | `(message) => MessageActions` — per-message action set with capability gating (`canEdit/canDelete/...`) | context menus, hotkeys, mobile drawer |+| `createChannelFindBar` | `create-channel-find-bar.ts:46` | wraps `createFindBarController` + search query; active-match memo | `channelId`, `goToMessage`, `clearSelection`, `isMessageLoaded` | FindBarController + `getSearchTermsForMessage` | prefetches next result pages, thread replies, and load-around windows ahead of the cursor |+| `createChannelHotkeys` | `create-channel-hotkeys.ts:47` | two DOM hotkey scopes (message list, input) | selection, navigation, `messageById`, `getMessageActions`, `isEditing`, `isInputEmpty`, callbacks | `{ messageListScopeId, attachMessageListRef, attachInputRef }` — refs attached to DOM in JSX | arrows/enter/e/backspace/escape/shift+g/cmd+f |+| `createChannelKeyboardHandler` | `create-channel-keyboard-handler.ts:47` | pending-reveal signal; **returns void**, pure effect | navigation, `isNearBottom`, `boundMessageId` | — (iOS-only virtual keyboard scroll behavior) | |+| `createStickyScrollEffect` | `sticky-scroll.tsx:29` | none — one `createEffect(on(messages, ...))` | `isNearBottom`, `hasMoreBelow`, `messages`, `scrollToBottom` | void. Scrolls only when a message was *appended at the bottom* AND user was near the true bottom (no more pages below) | the live-follow behavior |+| `createActivityTracker` | `activity-tracker.ts:20` | `newMessagesDismissed` signal; freezes `lastViewedAt`/`openedAt` at first read (so the mark-as-viewed mutation can't hide the "new" divider) | `lastViewedAt`, `userId` | `isNewMessage(message)`, `dismissNewMessages` | new-message divider in list meta |+| `createChannelDragState` | `create-channel-drag-state.ts:27` | plain mutable refs (not signals — never rendered) | `channelId` | drop zone + late-bound setters the input handle fills in `onReady` | `ChannelDropZone` |+| `createInputAttachmentTracker` | `Input/attachment-tracker` (via Channel.tsx:366) | attachment list, persisted | `persistenceKey` | tracker passed into the input | |++**Conventions worth imitating:**+- Options objects with `Accessor<T>` fields; return objects mixing accessors and plain methods.+- Late-bound capabilities as signals: `threadListNavigation`, `threadListScrollState`,+ `channelInputHandle`, `channelInputSnapshot` are all `createSignal<X|undefined>()` filled by+ child `onReady`/`onNavigationReady` callbacks; every factory that needs them takes the+ *accessor* and null-checks (`navigation()?.scrollToBottom()`).+- Factories that need cleanup use `onCleanup` internally (target controller's flash timer,+ keyboard handler's listener) — hence they must be called in component scope.+- Factories that render something return a component (`ConfirmationDialog`, `foldedMessages.Provider`).+- Snapshot/restore is a first-class concern: `getSnapshot()` on any factory whose state+ should survive split-history navigation, and an `initialSnapshot` option to hydrate.++---++## 4. Data layer++### Query (`lib/queries/channel/channel-messages.ts`)+- **Infinite query** keyed by `channelKeys.messages(channelId, loadAroundMessageId)` — the+ load-around id is *part of the key*, so navigating to an old message creates a second+ cache entry (a 50-row window centered on it); `restoreDefaultChannelPaginationAfterTargetLoad`+ later copies that entry over the default key and deletes the variant (create-target-message-controller.ts:214–230).+- Bidirectional cursors: `getNextPageParam` (older) / `getPreviousPageParam` (newer). `staleTime: Infinity` —+ the cache is maintained by hand (mutations + websocket), never by refetch-on-focus.+- `setChannelMessagesData(channelId, updater)` (:194) applies an updater to **every cached+ variant** via key prefix — the core cache-surgery primitive. A big family of pure+ `insert/remove/replace/mark*InChannelMessages(data, ...)` helpers (:255–602) all preserve+ reference equality when nothing changed.+- `createMessageIndex` (:807) — see §3 table.++### Mutations (`lib/queries/channel/message.ts`) — the optimistic send flow+`useSendMessageMutation` (:422):+1. **onMutate**: `registerMessageNonces(optimisticId, ...)` (nonce = the optimisticId);+ `queryClient.cancelQueries(prefix)`; `optimisticInsertChannelMessage` builds a fake+ `ApiChannelMessage` (`id = optimisticId`, `created_at = now`, empty thread) and inserts it+ at the bottom of every cached variant — but **only if the newest page has no+ `previous_cursor`** (i.e. we're actually at the bottom of the conversation, channel-messages.ts:278).+ Returns rollback context.+2. **mutationFn**: `postMessage({ ..., nonce: optimisticId })` — server echoes the nonce in the WS broadcast.+3. **onSuccess**: `replaceOptimisticMessage` swaps `optimisticId → data.id` in place (no refetch);+ refresh soup entity so channel lists re-sort.+4. **onError**: toast + `rollbackInsertChannelMessage` (remove the optimistic row).+5. **onSettled**: `softInvalidateTargetCaches` — `invalidateQueries({ refetchType: 'inactive' })`,+ i.e. mark stale for the *next* mount, don't refetch under the user.++Patch/delete follow the same shape with `createMutationNonce` (`lib/queries/nonce.ts:141`,+prepare-in-onMutate / use-in-mutationFn / cleanup-in-onSettled; 60s TTL). Delete captures a+positional snapshot for rollback; soft-deletes (sets `deleted_at`) when the message has replies.++`reconcile.ts` is the fan-out layer: `resolveMessageTarget` classifies top-level vs thread-reply,+and each `*InTargetCaches` helper applies the change to all three cache families+(paginated channel-messages, thread-replies, by-ids).++### Realtime: socket → cache+- `lib/queries/sync/SyncProvider.tsx` — app-level component using+ `createConnectionWebsocketEffect`, `match(data.type)`:+ - `comms_message` → `handleCommsMessage` (`lib/queries/channel/sync.ts:64`)+ - `agent_session_log` → `handleAgentSessionLog` (`agent-session-stream.ts:220`)+ - `comms_reaction` / `comms_attachment` / `comms_typing` / etc.+- `handleCommsMessage`: `consumeNonce(...)` — if the nonce is ours, the optimistic update+ already applied, so skip the write; otherwise insert/update/delete in cache directly.+ **Always** `softInvalidateTargetCaches` at the end for eventual consistency.+- Adoption: before anything, a payload carrying `agent_session_message` calls+ `adoptAgentSessionPlaceholder` (sync.ts:69–77) so a client-synthesized placeholder row is+ re-keyed to the server row id instead of duplicated.++### The agent-session fold pipeline (already exists — the agent block should reuse it)+- `createFoldedMessages` (`folded-messages.ts:68`): resource + store. Fetches+ `getAgentChannelLog`, opens a fold machine in the worker, then **follows** live WS frames+ through the same machine. Reactivity: a `createStore` keyed+ `bySessionId[sessionId][turn][authorKind] → FoldedMessage`; consumers read through the+ `lookup` closure so only changed rows re-render. Resource resolves once; the store keeps updating.+- `agent-session-stream.ts`: the buffering seam. `beginAgentSessionStream(channelId)`+ **before** the fetch, buffer frames, `followAgentSession` aligns buffer against snapshot+ (`dropOverlap`, :328 — longest buffered-prefix that is a suffix of the fetched log), one+ machine per session shared across split views, refcounted release.+ Also `subscribeAgentSessionLog(sessionId, sink)` (:90) for raw-frame consumers.+- `agent-session-placeholders.ts`: synthesizes a placeholder comms row when the fold derives+ a new message live (`ensureAgentSessionPlaceholder`) and re-keys it when the real row+ arrives (`adoptAgentSessionPlaceholder`). `rememberSessionBot` records sender identity.++---++## 5. Scroll & list (summary)++- **Virtualization**: `virtua/solid` (`Virtualizer` in `Channel/ThreadList.tsx:712`), not a+ hand-rolled list. `itemSize={96}` estimate, `bufferSize={500}`, `shift` prop flips during+ top-pagination so existing items keep their offsets, `keepMounted` pins the target thread's+ row during nested navigation, `cache={snapshot.virtualCache}` restores measured sizes.+- **ThreadList contract**: renders from `keys: Accessor<string[]>` + row render prop; emits+ `onNavigationReady(ThreadListNavigation)` (scrollTo/scrollToId/scrollToBottom/scrollToElementInItem/markUserIntent, :38–61)+ and `onScrollStateChange(ThreadListScrollState)` ({didInitialScroll, isNearBottom, distanceFromTop/Bottom,...}, :63–70).+- **Initial scroll** is a small state machine: preposition to bottom before measurement+ (:538), retry via `onScrollEnd` (:553), RAF fallbacks for "nothing moved". Everything else+ (target scrolls, pagination) is gated on `didInitialScroll`.+- **pinToBottom** (:328): after scroll-to-bottom, re-pin every frame for 1s + ResizeObserver,+ aborted by wheel-up/touch-drag — absorbs late-settling content (images, growing agent output).+ **This is the piece a streaming agent transcript wants most.**+- **Pagination triggers**: `onScrollNearTop/Bottom` fire only with `scrollIntent.isUserInteracting()`+ (:662) so virtualizer-resize scrolls can't fetch pages.+- **Sticky scroll**: `createStickyScrollEffect` (§3) — follow only if appended-at-bottom && near true bottom.+- **Scroll snapshots**: `onScrollSnapshotChange` emits `{scrollOffset, virtualCache, isNearBottom}`+ on every scroll; Channel keeps the latest in a signal; entry-state captor persists it; on+ restore, `isNearBottom` snapshots collapse to "scroll to bottom" (ThreadList.tsx:520–529).+- **Target navigation**: adapter resolves id → Channel `goToMessage` → controller sets+ `loadAroundMessageId` (new query window) + pending scroll ids → effect scrolls when key+ present → row calls `positionTarget`/`onTargetMessageScrolled` to finish → 1s flash then clear.+- `ScrollToBottomOverlay` reads `threadListScrollState`; `handleScrollToBottom` (Channel.tsx:545)+ resets the query to the default bottom window if `hasPreviousPage` (mid-history slice).++---++## 6. Input wiring++- Component stack: `TaskModeChannelInput` (message face + task composer morph,+ `Input/TaskModeChannelInput.tsx`) → `ChannelInput` (`Input/ChannelInput.tsx`, lexical+ markdown editor + mentions tracker + attachment tracker + typing tracker + hotkeys) →+ `Input` primitives.+- **Contract**: `InputSnapshot = { value, mentions, attachments }` (`Input/types.ts:52`);+ `InputHandle = { clear, focus, send, attachFiles, restoreSnapshot, insertEntityMention?, ... }` (:97).+ Channel stores both `onChange`-mirrored snapshot and `onReady` handle in signals (Channel.tsx:204–207).+- **Send** (Channel.tsx:623–648): `buildPostMessageSendPayload({ snapshot, participantIds })`+ (`Input/message-payload.ts:96`) expands mentions (`@here` fan-out, bot re-tagging) and maps+ attachments; then `sendMessageMutation.mutate({ channelID, senderId, optimisticId: crypto.randomUUID(), ...payload }, { onError })`.+ - **Restore-on-error**: the input cleared itself on send; `onError` restores the failed+ snapshot via `handle.restoreSnapshot(snapshot)` — but only if the user hasn't typed new+ sendable content meanwhile (`hasSendableInputContent(current)` check, :643).+- **Persistence**: localStorage-backed draft via `persistenceKey={makeInputValuePersistenceKey({ channelId })}`+ (`Input/utils/persistence.ts` — versioned keys `input-value-channel:<id>[-thread:<id>]`);+ separate keys for attachment tracker, task draft, task mode.+- **Typing indicators**: `ChannelInput` runs `createTypingTracker` (debounced start/stop)+ calling `onStartTyping/onStopTyping` props → `usePostTypingUpdateMutation` (Channel.tsx:961–972).+ Inbound: `comms_typing` WS events feed a module-level signal store (`@queries/channel/typing.ts`), 8s timeout.+- **Input face switching** (Channel.tsx:873–975): `<Switch>` over unified-input mode —+ editing face (`UnifiedEditInput`) > reply face (`UnifiedReplyInput`) > default composer.+ The bottom bar is one surface whose *content* rebinds; state for each face lives in+ messageEditor / unifiedInput / threadManager, not in the input.++---++## 7. Synthesis: what the agent block should take (and skip)++Current agent block (`features/block-agent/`): one-shot `useAgentSessionBlockQuery`+(`data/queries.ts:23` — fetch session + log, `foldSession` once, frozen), plain `<For>` over+messages in a `Scroll` (component/Block.tsx), `AgentInput` with an unwired `onSend`.++### Copy directly++1. **Adapter / component split.** Keep `Block.tsx` as the adapter (header, entry-state+ captor, orchestrator method registration if deep links matter, hotkey scope) and grow an+ `AgentSession.tsx` composition root that takes `{ sessionId, onHandleReady?, initialStateSnapshot?, autofocus? }`+ and exposes a small handle (`goToLatest`, `getStateSnapshot`, maybe `goToTurn`).+2. **The factory decomposition.** Build the stateful surface as `create*` factories with+ accessor-in/accessor-out interfaces, composed in the root:+ - `createAgentSessionFeed` — the analog of `createFoldedMessages` + `createMessageIndex`:+ resource that fetches the log, opens the fold machine, follows live frames, and exposes a+ reconciled *ordered* store of folded messages (the block needs an ordered list, not the+ channel's `(sessionId, turn, author)` lookup — that shape exists in+ `agent-session-stream.ts`'s sink; keep `reconcile()` so streaming appends don't remount rows).+ Reuse `beginAgentSessionStream`/`followAgentSession` (or `subscribeAgentSessionLog`) —+ the buffering seam and one-machine-per-session refcounting are already solved there;+ do NOT refetch-per-frame.+ - `createSessionStatusController` — session status / turn-in-flight / streaming signals+ (derive from the feed's frames; this is our analog of `threadListScrollState` + typing).+ - `createPermissionPrompts` — pending permission requests as a store keyed by request id,+ with `respond(id, outcome)`; model it on `createDeleteMessageConfirmation` (a factory that+ owns pending state *and* returns the UI component) if prompts render as a dialog, or on+ `threadManager` if they render inline per-message.+ - `createComposerController` — the busy/enabled state machine: analog of+ `channelInputSnapshot`/`channelInputHandle` signals + `onSend` in Channel.tsx:623. Own+ `isSending`/`isTurnRunning`, gate `onSend`, and implement **restore-on-error** exactly as+ Channel does (restore snapshot only if input is still empty).+3. **Late-bound handles as signals** for anything the child publishes upward (input handle,+ scroll navigation), with `awaitCondition` in the adapter if orchestrator methods need them.+4. **Optimistic send with nonce-style dedup.** When sending a prompt: append an optimistic+ user-turn row to the feed store immediately, key it by a client id, and adopt/replace when+ the corresponding frame (or server ack) arrives — the exact pattern of+ `optimisticInsertChannelMessage` + `adoptAgentSessionPlaceholder`. The channel's prompt-echo+ problem (`hide-duplicate-prompts.ts`, flagged as a stopgap in Channel.tsx:241–250) is the+ cautionary tale: decide the dedup key (client nonce in the frame?) up front.+5. **Scroll**: at minimum `createStickyScrollEffect`'s exact rule (follow only when appended+ at bottom && near bottom) + a `pinToBottom`-style settle loop, since agent output grows+ after append. If transcripts get long, adopt `ThreadList` itself — it's channel-flavored but+ its props are generic (`keys`, render prop, navigation/scroll-state callbacks); virtua is+ the right tool for a multi-thousand-row session. Persist `{scrollOffset, virtualCache, isNearBottom}`+ in the entry-state captor like the adapter does.+6. **Entry-state captor** (`splitPanel.handle.registerEntryStateCaptor`) for scroll position ++ composer-adjacent state so split history restore doesn't reset the view.+7. **Input**: reuse `ChannelInput` (not `TaskModeChannelInput`) or keep `AgentInput` but adopt+ the `InputSnapshot`/`InputHandle` contract, `persistenceKey` draft persistence+ (`makeInputValuePersistenceKey`-style, keyed by session id), and the send/restore flow.+8. **WS routing**: nothing new needed — `SyncProvider` already routes `agent_session_log`+ frames; subscribe through `agent-session-stream.ts` rather than adding a new socket path.++### Do NOT copy++- **Threads** — thread-manager, thread-paginator's dual direction, thread previews, reply+ inputs, `UnifiedReplyInput`/`UnifiedEditInput` and the whole unified-input-mode face+ switching. Agent sessions are linear.+- **Reactions, message editing, message deletion** — and with them most of+ `create-channel-message-actions` (a slim per-message actions factory for copy-text/copy-link+ is still worth the shape).+- **The multi-variant load-around query machinery** (`loadAroundMessageId` in the query key,+ `restoreDefaultChannelPaginationAfterTargetLoad`, `clearStaleRestoredChannelData`) — the+ session log is fetched whole and folded; there is no cursor pagination to windows. If logs+ ever need windowing, revisit; don't pre-build it.+- **Nonce infrastructure in full** — the channel needs it because every mutation is echoed on+ a shared multi-user socket. A session block likely needs one dedup point (prompt echo), not+ the whole `createMutationNonce` family.+- **Find bar, typing indicators, drag/drop entity mentions, task mode, calls, activity+ tracking / new-message dividers, mobile swipe-to-reply** — channel-specific surface area.+- **`hide-duplicate-prompts`** — explicitly a stopgap; solve prompt identity properly instead.++### Where our extra state slots in (channel-analog map)++| Agent block concern | Channel analog |+|---|---|+| session status / turn running | `threadListScrollState` + typing indicators (derived signal fed by a stream) |+| streaming fold | `createFoldedMessagesScope` + `createFoldedMessages` store (reuse, reshape to ordered list) |+| permission prompts | `createDeleteMessageConfirmation` (pending store + returned dialog component) |+| composer busy state | `channelInputSnapshot`/`channelInputHandle` signals + `onSend` gating (Channel.tsx:204–207, 623) |+| optimistic prompt row | `optimisticInsertChannelMessage` + placeholder adopt (`agent-session-placeholders.ts`) |+| live follow scroll | `createStickyScrollEffect` + `pinToBottom` |+| split restore | entry-state captor + `getStateSnapshot` handle method |diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsxnew file mode 100644index 0000000000..b03a8f8aff--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx@@ -0,0 +1,32 @@+/**+ * The block's composer container: reads the composer controller from the+ * session context and drives the dumb `AgentInput` and `QueuedPromptList`+ * with derived props. All block-level state stays on this side of the+ * boundary.+ */++import { useAgentSession } from '../context/AgentSessionContext';+import { AgentInput, QueuedPromptList } from '../ui';++export function AgentComposer() {+ const { composer, loadFailed } = useAgentSession();++ return (+ <>+ <QueuedPromptList+ prompts={composer.queue()}+ sendingId={composer.sendingId()}+ failed={composer.sendFailed()}+ onRetry={composer.retry}+ onRemove={composer.remove}+ />+ <AgentInput+ placeholder="Message the agent"+ busy={composer.busy()}+ disabled={loadFailed()}+ onSend={composer.send}+ onStop={composer.stop}+ />+ </>+ );+}diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsxnew file mode 100644index 0000000000..994193439b--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx@@ -0,0 +1,73 @@+/**+ * Renders one folded agent-session message. Pure composition: each part kind+ * has its own component under `parts/` (the chat block's handler-per-tool+ * split), user prompts get the chat block's bubble treatment, and thoughts+ * shimmer while the turn is in flight.+ */++import type {+ FoldedMessage,+ MessagePart,+} from '@service-agent-fold/generated/types';+import { For, type JSX, Show } from 'solid-js';+import { match } from 'ts-pattern';+import { Thought } from '../ui';+import { ControlPart } from './parts/ControlPart';+import { PermissionPart } from './parts/PermissionPart';+import { PlanPart } from './parts/PlanPart';+import { TextPart } from './parts/TextPart';+import { ToolCallPart } from './parts/ToolCallPart';++function AgentMessagePart(props: {+ part: MessagePart;+ /** The turn is still in flight — thoughts read "Thinking" and shimmer. */+ inFlight: boolean;+}): JSX.Element {+ return match(props.part)+ .with({ kind: 'text' }, (part) => <TextPart text={part.text} />)+ .with({ kind: 'thought' }, (part) => (+ <Thought text={part.text} active={props.inFlight} />+ ))+ .with({ kind: 'tool_use' }, (part) => <ToolCallPart part={part} />)+ .with({ kind: 'permission' }, (part) => <PermissionPart part={part} />)+ .with({ kind: 'plan' }, (part) => <PlanPart part={part} />)+ .with({ kind: 'control' }, (part) => <ControlPart part={part} />)+ .exhaustive();+}++/**+ * A prompt, in the chat block's user-bubble treatment+ * (`@core/component/AI/component/message/UserMessage.tsx`): right-aligned,+ * rounded gray surface with a hairline border.+ */+function UserMessage(props: { message: FoldedMessage }) {+ return (+ <div class="flex w-full">+ <div class="relative ml-auto max-w-[calc(100%-8rem)] overflow-hidden rounded-lg border border-edge-muted bg-hover px-3 py-2 text-ink">+ <For each={props.message.parts}>+ {(part) => <AgentMessagePart part={part} inFlight={false} />}+ </For>+ </div>+ </div>+ );+}++export function Message(props: { message: FoldedMessage }) {+ const inFlight = () =>+ props.message.author.kind === 'agent' && props.message.stop == null;++ return (+ <Show+ when={props.message.author.kind === 'user'}+ fallback={+ <div class="flex flex-col gap-1 min-w-0">+ <For each={props.message.parts}>+ {(part) => <AgentMessagePart part={part} inFlight={inFlight()} />}+ </For>+ </div>+ }+ >+ <UserMessage message={props.message} />+ </Show>+ );+}diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxnew file mode 100644index 0000000000..c46738ab19--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -0,0 +1,119 @@+import {+ type BlockTool,+ ResponsiveBlockToolbar,+ ToolButton,+} from '@components/app/ResponsiveBlockToolbar';+import { useDrawerControl } from '@components/app/split-layout/components/SplitDrawerContext';+import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';+import {+ SplitHeaderLeft,+ SplitHeaderRight,+} from '@components/app/split-layout/components/SplitHeader';+import { StaticSplitLabel } from '@components/app/split-layout/components/SplitLabel';+import { useBlockId } from '@core/block';+import { toast } from '@core/component/Toast/Toast';+import { isMobile } from '@core/mobile/isMobile';+import { buildSimpleEntityUrl, openExternalUrl } from '@core/util/url';+import GitBranch from '@phosphor/git-branch.svg';+import LinkIcon from '@phosphor/link.svg';+import TreeStructure from '@phosphor/tree-structure.svg';+import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';+import { For, Show } from 'solid-js';+import {+ ORIGIN_THREAD_DRAWER_ID,+ sessionOriginThread,+} from '../context/origin-thread';++/** 'claude-code' → 'Claude Code'; the fallback when the fold has no title. */+export function harnessTitle(harness: string | undefined): string {+ if (!harness) return 'Agent session';+ return harness+ .split(/[-_]/)+ .filter(Boolean)+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join(' ');+}++/**+ * Agent-session identity in the split header chrome plus the standard split+ * toolbar, matching the PR block's shape for non-document blocks: static+ * label (names the split tab), copy-link tool, and a file menu with the+ * session's repository.+ */+export function AgentSplitHeader(props: {+ session: AgentSessionResponse | undefined;+ /** The fold's session title, preferred over the harness fallback. */+ title?: string;+}) {+ const blockId = useBlockId();+ const title = () => props.title ?? harnessTitle(props.session?.harness);+ const originThreadDrawer = useDrawerControl(ORIGIN_THREAD_DRAWER_ID);++ const copyLink = async () => {+ await navigator.clipboard.writeText(+ buildSimpleEntityUrl({ type: 'agent', id: blockId })+ );+ toast.success('Link copied to clipboard');+ };++ const tools: BlockTool[] = [+ {+ label: 'Discussion Thread',+ icon: TreeStructure,+ action: originThreadDrawer.toggle,+ isActive: originThreadDrawer.isOpen,+ condition: () => sessionOriginThread(props.session) !== undefined,+ },+ {+ label: 'Copy link',+ icon: LinkIcon,+ action: copyLink,+ },+ ];++ const ops: FileOperation[] = [+ {+ label: 'Open repository',+ icon: GitBranch,+ action: () => {+ const url = props.session?.repoUrl;+ if (url) openExternalUrl(url);+ },+ },+ ];++ return (+ <>+ <SplitHeaderLeft>+ <StaticSplitLabel iconType="agent" label={title()} />+ </SplitHeaderLeft>++ {/* Tools live on the header row itself — `ResponsiveBlockToolbar`+ would push non-Share tools onto a second toolbar row. Markup+ mirrors its own header-tools branch; on mobile the tools collapse+ into the title menu via `menuTools` below instead. */}+ <Show when={!isMobile()}>+ <SplitHeaderRight>+ <div class="order-[1000] flex items-center gap-1">+ <For each={tools}>+ {(tool) => (+ <Show when={!tool.condition || tool.condition()}>+ <ToolButton tool={tool} />+ </Show>+ )}+ </For>+ </div>+ </SplitHeaderRight>+ </Show>++ <ResponsiveBlockToolbar+ tools={[]}+ menuTools={tools}+ ops={ops}+ id={blockId}+ itemType="foreign"+ name={title()}+ />+ </>+ );+}diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsxnew file mode 100644index 0000000000..53605f10a0--- /dev/null+++ b/apps/web/src/features/block-agent/component/Block.tsx@@ -0,0 +1,69 @@+import { SidePanel } from '@components/app/side-panel';+import { useBlockId } from '@core/block';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { LinkedConversationDrawer } from '@core/linked-conversation';+import { Show } from 'solid-js';++import {+ AgentSessionProvider,+ useAgentSession,+} from '../context/AgentSessionContext';+import {+ ORIGIN_THREAD_DRAWER_ID,+ sessionOriginThread,+} from '../context/origin-thread';+import { AgentComposer } from './AgentComposer';+import { AgentSplitHeader } from './AgentSplitHeader';+import { AgentSidePanelSections } from './sidepanel/AgentSidePanelSections';+import { Transcript } from './Transcript';++function AgentBlockContent() {+ const { session, metadata } = useAgentSession();++ return (+ // One shared static-markdown editor for every text part, rather than one+ // per part — the same scoping the channel does around its message tree.+ <StaticMarkdownContext>+ <div class="size-full overflow-hidden flex">+ {/* Collapsed by default, like the other conversation-shaped blocks —+ the transcript wants the width; `]` or the header button opens it. */}+ <SidePanel.Layout defaultOpen={false}>+ <AgentSidePanelSections />+ <AgentSplitHeader+ session={session()}+ title={metadata()?.title ?? undefined}+ />+ <div class="size-full min-w-0 flex flex-col">+ <Transcript />+ <div class="shrink-0 w-full max-w-3xl mx-auto px-4 pb-4">+ <AgentComposer />+ </div>+ </div>+ <Show when={sessionOriginThread(session())}>+ {(origin) => (+ <LinkedConversationDrawer+ id={ORIGIN_THREAD_DRAWER_ID}+ channelId={origin().channelId}+ messageId={origin().messageId}+ />+ )}+ </Show>+ </SidePanel.Layout>+ </div>+ </StaticMarkdownContext>+ );+}++export default function BlockAgent() {+ const blockId = useBlockId();++ return (+ <Show when={blockId}>+ {(id) => (+ <AgentSessionProvider sessionId={id()}>+ <AgentBlockContent />+ </AgentSessionProvider>+ )}+ </Show>+ );+}diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsxnew file mode 100644index 0000000000..16d74ebb57--- /dev/null+++ b/apps/web/src/features/block-agent/component/Transcript.tsx@@ -0,0 +1,210 @@+/**+ * The message chain: a virtualized transcript that loads pinned to the+ * bottom and follows appends while the reader is near it.+ *+ * The scroll recipe is the channel's `ThreadList` distilled (see+ * CHANNEL_BLOCK_NOTES.md §5): virtua for virtualization, an immediate+ * bottom preposition on mount (virtua overshoots with an unmeasured+ * viewport and the browser clamps — first paint lands at the bottom), then+ * a settle loop that keeps re-pinning while late content (Pierre diffs,+ * markdown) grows the list, aborting on a real scroll-up gesture. opencode+ * solves the same problem by patching @tanstack/virtual-core with+ * `anchorTo: "end"`/`followOnAppend` — virtua plus this loop is the+ * unpatched equivalent.+ *+ * Chrome shared with the channel: the `@ui` `Scroll` thumb (hidden native+ * scrollbar, drag-seekable gutter) and the channel's `ScrollToBottomOverlay`,+ * fed by the same scroll-state shape `ThreadList` emits.+ */++import { ScrollToBottomOverlay } from '@channel/Channel/ScrollToBottomOverlay';+import type { ThreadListScrollState } from '@channel/Channel/ThreadList';+import { Scroll } from '@ui';+import { createSignal, onCleanup, Show } from 'solid-js';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';+import { useAgentSession } from '../context/AgentSessionContext';+import { Message } from './AgentMessage';++/** The channel's `NEAR_BOTTOM_THRESHOLD`: within this, the view follows. */+const NEAR_BOTTOM_PX = 50;+/** How long the bottom pin keeps correcting after a scroll-to-bottom. */+const SETTLE_MS = 1000;+/** The channel's `BASE_ITEM_SIZE` estimate. */+const ITEM_SIZE = 96;++export function Transcript() {+ const { messages, loadFailed } = useAgentSession();++ let scrollRef: HTMLDivElement | undefined;+ let handle: VirtualizerHandle | undefined;+ let cancelPin: (() => void) | undefined;+ let growthObserver: ResizeObserver | undefined;+ let viewportObserver: ResizeObserver | undefined;++ onCleanup(() => {+ cancelPin?.();+ growthObserver?.disconnect();+ viewportObserver?.disconnect();+ });+ // Whether the view should chase the bottom as content grows. True until+ // the reader scrolls away; recomputed on every scroll.+ let follow = true;+ let didInitialScroll = false;+ let lastScrollTop = 0;++ // The scroller's inner height, so short transcripts can bottom-align:+ // the flex spacer needs the content wrapper to be at least viewport-tall.+ const [viewportHeight, setViewportHeight] = createSignal(0);+ const [scrollState, setScrollState] = createSignal<ThreadListScrollState>();++ const distanceFromBottom = () => {+ const el = scrollRef;+ if (!el) return 0;+ return el.scrollHeight - el.scrollTop - el.clientHeight;+ };++ const emitScrollState = () => {+ const el = scrollRef;+ if (!el) return;+ const distance = distanceFromBottom();+ setScrollState({+ didInitialScroll,+ isNearBottom: distance <= NEAR_BOTTOM_PX,+ isScrollingDown: el.scrollTop >= lastScrollTop,+ distanceFromTop: el.scrollTop,+ distanceFromBottom: distance,+ viewportSize: el.clientHeight,+ });+ lastScrollTop = el.scrollTop;+ };++ /**+ * Scroll to the newest message, then keep re-pinning to the true bottom for+ * a short window so late-settling content can't leave the last message cut+ * off. Aborts on a wheel-up or touch drag (a tap is not a scroll) — the+ * channel's `pinToBottom`, without its target machinery.+ */+ const pinToBottom = () => {+ cancelPin?.();+ const el = scrollRef;+ if (!el || !handle) return;+ follow = true;+ handle.scrollToIndex(messages().length - 1, { align: 'end' });++ let rafId = 0;+ const start = performance.now();++ const stop = () => {+ if (rafId) cancelAnimationFrame(rafId);+ el.removeEventListener('wheel', onWheel);+ el.removeEventListener('pointerdown', onPointerDown);+ if (cancelPin === stop) cancelPin = undefined;+ didInitialScroll = true;+ emitScrollState();+ };+ function onWheel(event: WheelEvent) {+ if (event.deltaY < 0) stop();+ }+ function onPointerDown(event: PointerEvent) {+ if (event.pointerType === 'touch') stop();+ }+ el.addEventListener('wheel', onWheel, { passive: true });+ el.addEventListener('pointerdown', onPointerDown, { passive: true });+ cancelPin = stop;++ const tick = () => {+ if (distanceFromBottom() > 1) el.scrollTop = el.scrollHeight;+ if (performance.now() - start >= SETTLE_MS) {+ stop();+ return;+ }+ rafId = requestAnimationFrame(tick);+ };+ rafId = requestAnimationFrame(tick);+ };++ // Follow growth beyond the pin window: whenever the virtualized content+ // resizes (a new turn, a streaming message getting longer) and the reader+ // hasn't scrolled away, snap back to the bottom. This is the sticky-scroll+ // rule — follow only near the bottom — applied to content growth, which is+ // how agent output arrives.+ const observeGrowth = (el: HTMLDivElement) => {+ growthObserver = new ResizeObserver(() => {+ if (follow && distanceFromBottom() > 1) {+ const scroller = scrollRef;+ if (scroller) scroller.scrollTop = scroller.scrollHeight;+ }+ });+ growthObserver.observe(el);+ };++ const attachScroller = (el: HTMLDivElement) => {+ scrollRef = el;+ // `Scroll` owns the element's onScroll; listen alongside it.+ el.addEventListener(+ 'scroll',+ () => {+ follow = distanceFromBottom() <= NEAR_BOTTOM_PX;+ emitScrollState();+ },+ { passive: true }+ );+ viewportObserver = new ResizeObserver(() => {+ setViewportHeight(el.clientHeight);+ emitScrollState();+ });+ viewportObserver.observe(el);+ };++ return (+ <div class="relative flex-1 min-h-0">+ <Scroll scrollRef={attachScroller}>+ <div+ class="flex flex-col [overflow-anchor:none]"+ style={{ 'min-height': `${viewportHeight()}px` }}+ >+ {/* Bottom-align short transcripts, chat-style. */}+ <div aria-hidden style={{ 'flex-grow': 1 }} />+ <Show when={loadFailed()}>+ <div class="w-full max-w-3xl mx-auto px-4 py-4 text-sm text-ink-muted">+ Couldn't load this agent session.+ </div>+ </Show>+ <div ref={observeGrowth}>+ <Virtualizer+ ref={(virtualizer) => {+ if (!virtualizer) return;+ handle = virtualizer;+ // Issue the bottom target immediately, before virtua has a+ // measured viewport — overshoot clamps to the current+ // maximum, so the first painted frame is already at the+ // bottom.+ if (messages().length > 0) pinToBottom();+ }}+ scrollRef={scrollRef}+ data={messages()}+ itemSize={ITEM_SIZE}+ onScrollEnd={() => {+ // The feed fills asynchronously; if rows arrived after mount+ // and we're meant to be following, correct the landing.+ if (follow && distanceFromBottom() > NEAR_BOTTOM_PX) {+ pinToBottom();+ }+ }}+ >+ {(message) => (+ <div class="w-full max-w-3xl mx-auto px-4 pb-4 min-w-0">+ <Message message={message} />+ </div>+ )}+ </Virtualizer>+ </div>+ </div>+ </Scroll>+ <ScrollToBottomOverlay+ scrollState={scrollState}+ onScrollToBottom={pinToBottom}+ />+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/ControlPart.tsx b/apps/web/src/features/block-agent/component/parts/ControlPart.tsxnew file mode 100644index 0000000000..a2903785da--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/ControlPart.tsx@@ -0,0 +1,18 @@+/** A control the user issued mid-session: model switch, compaction, stop. */++import type { MessagePart } from '@service-agent-fold/generated/types';+import { match } from 'ts-pattern';+import { ToolCard } from '../../ui';++export function ControlPart(props: {+ part: Extract<MessagePart, { kind: 'control' }>;+}) {+ const label = () =>+ match(props.part.control)+ .with({ kind: 'set_model' }, (control) => `Model set to ${control.model}`)+ .with({ kind: 'compact' }, () => 'Context compacted')+ .with({ kind: 'stop' }, () => 'Stopped')+ .exhaustive();++ return <ToolCard title={label()} status="completed" />;+}diff --git a/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx b/apps/web/src/features/block-agent/component/parts/EditToolCall.tsxnew file mode 100644index 0000000000..13c6b2fd30--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx@@ -0,0 +1,28 @@+/** File modifications: +/− badge in the row, Pierre-rendered diffs in the body. */++import type { ToolDetail } from '@service-agent-fold/generated/types';+import { Show } from 'solid-js';+import { countDiffChanges } from '../../state/session-summary';+import { DiffChanges, PierreDiff, ToolCard } from '../../ui';+import { pathsSubtitle, type ToolCallCommon } from './shared';++export function EditToolCall(props: {+ detail: Extract<ToolDetail, { kind: 'edit' }>;+ common: ToolCallCommon;+}) {+ const changes = () => countDiffChanges(props.detail.diffs);++ return (+ <ToolCard+ title={props.common.label}+ subtitle={pathsSubtitle(props.detail.diffs.map((diff) => diff.path))}+ trailing={props.common.trailing ?? <DiffChanges {...changes()} />}+ status={props.common.status}+ muted={props.common.muted}+ >+ <Show when={props.detail.diffs.length > 0}>+ <PierreDiff diffs={props.detail.diffs} />+ </Show>+ </ToolCard>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsxnew file mode 100644index 0000000000..1213f4184a--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx@@ -0,0 +1,28 @@+/**+ * The fallback card for fetch, think, and unmodeled tool kinds: label in the+ * row, whatever text the call reported in the body — the chat block's+ * GenericTool analog.+ */++import type { ToolDetail } from '@service-agent-fold/generated/types';+import { Show } from 'solid-js';+import { FoldedOutput, ToolCard } from '../../ui';+import type { ToolCallCommon } from './shared';++export function OutputToolCall(props: {+ detail: Extract<ToolDetail, { kind: 'fetch' | 'think' | 'other' }>;+ common: ToolCallCommon;+}) {+ return (+ <ToolCard+ title={props.common.label}+ status={props.common.status}+ muted={props.common.muted}+ trailing={props.common.trailing}+ >+ <Show when={props.detail.output}>+ {(output) => <FoldedOutput text={output()} />}+ </Show>+ </ToolCard>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx b/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsxnew file mode 100644index 0000000000..3f7fd39562--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx@@ -0,0 +1,25 @@+/** A read, delete, or move: path (or count) in the row, full list in the body. */++import type { ToolDetail } from '@service-agent-fold/generated/types';+import { Show } from 'solid-js';+import { FoldedPathList, ToolCard } from '../../ui';+import { pathsSubtitle, type ToolCallCommon } from './shared';++export function PathsToolCall(props: {+ detail: Extract<ToolDetail, { kind: 'read' | 'delete' | 'move' }>;+ common: ToolCallCommon;+}) {+ return (+ <ToolCard+ title={props.common.label}+ subtitle={pathsSubtitle(props.detail.paths)}+ status={props.common.status}+ muted={props.common.muted}+ trailing={props.common.trailing}+ >+ <Show when={props.detail.paths.length > 1}>+ <FoldedPathList paths={props.detail.paths} />+ </Show>+ </ToolCard>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx b/apps/web/src/features/block-agent/component/parts/PermissionPart.tsxnew file mode 100644index 0000000000..2812a594a4--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/PermissionPart.tsx@@ -0,0 +1,33 @@+/** A permission request, with the outcome (chosen option) as trailing text. */++import type { MessagePart } from '@service-agent-fold/generated/types';+import { Show } from 'solid-js';+import { ToolCard } from '../../ui';++export function PermissionPart(props: {+ part: Extract<MessagePart, { kind: 'permission' }>;+}) {+ const outcome = () => {+ const resolved = props.part.outcome;+ if (!resolved || resolved.kind === 'pending') return undefined;+ if (resolved.kind === 'cancelled') return 'Cancelled';+ if (resolved.kind === 'errored') return 'Failed';+ if (resolved.kind === 'unrecognized') return 'Answered';+ const chosen = props.part.options.find(+ (option) => option.id === resolved.optionId+ );+ return chosen?.name ?? 'Answered';+ };++ return (+ <ToolCard+ title="Permission requested"+ trailing={+ <Show when={outcome()}>+ {(label) => <span class="text-ink">{label()}</span>}+ </Show>+ }+ status="completed"+ />+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/PlanPart.tsx b/apps/web/src/features/block-agent/component/parts/PlanPart.tsxnew file mode 100644index 0000000000..0277dc3c74--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/PlanPart.tsx@@ -0,0 +1,17 @@+/** The agent's working todo list for the turn, in the library's TodoList. */++import type { MessagePart } from '@service-agent-fold/generated/types';+import { TodoList } from '../../ui';++export function PlanPart(props: {+ part: Extract<MessagePart, { kind: 'plan' }>;+}) {+ return (+ <TodoList+ todos={props.part.entries.map((entry) => ({+ content: entry.content,+ status: entry.status,+ }))}+ />+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsxnew file mode 100644index 0000000000..7578c6dc5d--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx@@ -0,0 +1,25 @@+/** A search: scope in the row, reported hits in the body. */++import type { ToolDetail } from '@service-agent-fold/generated/types';+import { Show } from 'solid-js';+import { FoldedOutput, ToolCard } from '../../ui';+import { pathsSubtitle, type ToolCallCommon } from './shared';++export function SearchToolCall(props: {+ detail: Extract<ToolDetail, { kind: 'search' }>;+ common: ToolCallCommon;+}) {+ return (+ <ToolCard+ title={props.common.label}+ subtitle={pathsSubtitle(props.detail.paths)}+ status={props.common.status}+ muted={props.common.muted}+ trailing={props.common.trailing}+ >+ <Show when={props.detail.output}>+ {(output) => <FoldedOutput text={output()} />}+ </Show>+ </ToolCard>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx b/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsxnew file mode 100644index 0000000000..96ad8d215c--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx@@ -0,0 +1,27 @@+/** A shell command: `$ cmd` in the row, ANSI-colored output in the body. */++import type { ToolDetail } from '@service-agent-fold/generated/types';+import { Show } from 'solid-js';+import { FoldedTerminal, ToolCard } from '../../ui';+import type { ToolCallCommon } from './shared';++export function TerminalToolCall(props: {+ detail: Extract<ToolDetail, { kind: 'terminal' }>;+ common: ToolCallCommon;+}) {+ return (+ <ToolCard+ title={props.common.label}+ subtitle={props.detail.command ?? undefined}+ status={props.common.status}+ muted={props.common.muted}+ trailing={props.common.trailing}+ >+ <Show when={props.detail.output}>+ {(output) => (+ <FoldedTerminal output={output()} exitCode={props.detail.exitCode} />+ )}+ </Show>+ </ToolCard>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.tsxnew file mode 100644index 0000000000..80ba92af23--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/TextPart.tsx@@ -0,0 +1,16 @@+/** Prose from the user or the agent, rendered as static markdown. */++import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { channelTheme } from '@core/component/LexicalMarkdown/theme';++export function TextPart(props: { text: string }) {+ return (+ <div class="whitespace-pre-wrap wrap-break-word max-w-full text-sm">+ <StaticMarkdown+ markdown={props.text}+ theme={channelTheme}+ target="internal"+ />+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsxnew file mode 100644index 0000000000..c58d8e249f--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx@@ -0,0 +1,163 @@+/**+ * @vitest-environment jsdom+ */++import type { MessagePart } from '@service-agent-fold/generated/types';+import { render } from '@solidjs/testing-library';+import type { JSX } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import { ToolCallPart } from './ToolCallPart';++// The ui primitives are mocked (the AssistantMessageParts.test.tsx idiom):+// ToolCard pulls in kobalte + svg sprites and PierreDiff pulls in the diff+// engine — the layer under test here is the per-kind card components and the+// dispatcher's routing/common-derivation, which render for real.+vi.mock('../../ui', () => ({+ ToolCard: (props: {+ title: JSX.Element;+ subtitle?: string;+ trailing?: JSX.Element;+ muted?: boolean;+ children?: JSX.Element;+ }) => (+ <div data-muted={String(props.muted ?? false)} data-testid="tool-card">+ <span data-testid="title">{props.title}</span>+ <span data-testid="subtitle">{props.subtitle}</span>+ <span data-testid="trailing">{props.trailing}</span>+ <div data-testid="body">{props.children}</div>+ </div>+ ),+ DiffChanges: (props: { additions: number; deletions: number }) => (+ <span data-testid="diff-changes">+ +{props.additions} −{props.deletions}+ </span>+ ),+ PierreDiff: (props: { diffs: { path: string }[] }) => (+ <div data-testid="pierre-diff">+ {props.diffs.map((diff) => diff.path).join(',')}+ </div>+ ),+ FoldedTerminal: (props: { output: string }) => (+ <pre data-testid="terminal">{props.output}</pre>+ ),+ FoldedOutput: (props: { text: string }) => (+ <pre data-testid="output">{props.text}</pre>+ ),+ FoldedPathList: (props: { paths: string[] }) => (+ <div data-testid="path-list">{props.paths.join(',')}</div>+ ),+}));++type ToolUsePart = Extract<MessagePart, { kind: 'tool_use' }>;++function toolUse(+ detail: ToolUsePart['detail'],+ overrides?: Partial<ToolUsePart>+): ToolUsePart {+ return {+ kind: 'tool_use',+ id: 'call-1',+ label: 'Tool',+ status: 'completed',+ detail,+ ...overrides,+ };+}++describe('ToolCallPart routing', () => {+ it('renders a terminal call with the command as subtitle and output body', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse(+ {+ kind: 'terminal',+ command: 'cargo test -p agent_fold',+ output: 'running 14 tests',+ exitCode: 0,+ },+ { label: 'Bash' }+ )}+ />+ ));+ expect(rendered.getByTestId('title').textContent).toBe('Bash');+ expect(rendered.getByTestId('subtitle').textContent).toBe(+ 'cargo test -p agent_fold'+ );+ expect(rendered.getByTestId('body').textContent).toContain(+ 'running 14 tests'+ );+ });++ it('renders an edit with computed +/− counts and the diff body', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse({+ kind: 'edit',+ diffs: [+ {+ path: 'src/a.rs',+ oldText: 'old\nsame\n',+ newText: 'new\nsame\n',+ },+ ],+ })}+ />+ ));+ expect(rendered.getByTestId('subtitle').textContent).toBe('src/a.rs');+ expect(rendered.getByTestId('diff-changes').textContent).toBe('+1 −1');+ expect(rendered.getByTestId('pierre-diff').textContent).toBe('src/a.rs');+ });++ it('summarizes multi-path reads and lists the paths in the body', () => {+ const rendered = render(() => (+ <ToolCallPart part={toolUse({ kind: 'read', paths: ['a.rs', 'b.rs'] })} />+ ));+ expect(rendered.getByTestId('subtitle').textContent).toBe('2 files');+ expect(rendered.getByTestId('path-list').textContent).toBe('a.rs,b.rs');+ });++ it('routes unmodeled kinds to the output fallback', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse({+ kind: 'other',+ acpKind: 'custom_tool',+ output: 'raw result',+ input: null,+ })}+ />+ ));+ expect(rendered.getByTestId('body').textContent).toContain('raw result');+ });+});++describe('ToolCallPart failed treatment', () => {+ it('fades the row and shows a quiet Failed trailing label', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse(+ { kind: 'terminal', command: 'x', output: null, exitCode: 1 },+ { status: 'failed' }+ )}+ />+ ));+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');+ });++ it('a failed edit shows Failed instead of the +/− badge', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={toolUse(+ {+ kind: 'edit',+ diffs: [{ path: 'src/a.rs', oldText: 'a', newText: 'b' }],+ },+ { status: 'failed' }+ )}+ />+ ));+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');+ expect(rendered.queryByTestId('diff-changes')).toBeNull();+ });+});diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsxnew file mode 100644index 0000000000..46f50b7651--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx@@ -0,0 +1,48 @@+/**+ * Routes a folded tool call to its detail component — the chat block's+ * `RenderTool`/handler-map analog (`tool/handler.tsx`), keyed off the fold's+ * closed `ToolDetail` union instead of tool names. Routing only: every card+ * lives in its own file.+ */++import type { MessagePart } from '@service-agent-fold/generated/types';+import type { JSX } from 'solid-js';+import { match } from 'ts-pattern';+import { EditToolCall } from './EditToolCall';+import { OutputToolCall } from './OutputToolCall';+import { PathsToolCall } from './PathsToolCall';+import { SearchToolCall } from './SearchToolCall';+import type { ToolCallCommon } from './shared';+import { TerminalToolCall } from './TerminalToolCall';++export function ToolCallPart(props: {+ part: Extract<MessagePart, { kind: 'tool_use' }>;+}): JSX.Element {+ const failed = () => props.part.status === 'failed';+ // The chat block's failed-tool treatment: the same row, faded, with a quiet+ // trailing label — not a separate error card.+ const common = (): ToolCallCommon => ({+ label: props.part.label,+ status: props.part.status,+ muted: failed(),+ trailing: failed() ? <span class="text-ink">Failed</span> : undefined,+ });++ return match(props.part.detail)+ .with({ kind: 'terminal' }, (detail) => (+ <TerminalToolCall detail={detail} common={common()} />+ ))+ .with({ kind: 'edit' }, (detail) => (+ <EditToolCall detail={detail} common={common()} />+ ))+ .with({ kind: 'read' }, { kind: 'delete' }, { kind: 'move' }, (detail) => (+ <PathsToolCall detail={detail} common={common()} />+ ))+ .with({ kind: 'search' }, (detail) => (+ <SearchToolCall detail={detail} common={common()} />+ ))+ .with({ kind: 'fetch' }, { kind: 'think' }, { kind: 'other' }, (detail) => (+ <OutputToolCall detail={detail} common={common()} />+ ))+ .exhaustive();+}diff --git a/apps/web/src/features/block-agent/component/parts/shared.ts b/apps/web/src/features/block-agent/component/parts/shared.tsnew file mode 100644index 0000000000..d4a03bdfcf--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/shared.ts@@ -0,0 +1,25 @@+/**+ * Shared vocabulary for the per-part components, mirroring the chat block's+ * tool-handler split (`@core/component/AI/component/tool/handler.tsx`): each+ * detail kind renders in its own file, and the dispatcher passes the+ * row-level facts every card shares.+ */++import type { JSX } from 'solid-js';+import type { ToolStatus } from '../../ui';++/** Row-level facts common to every tool card, derived once by the dispatcher. */+export type ToolCallCommon = {+ label: string;+ status: ToolStatus;+ /** The chat block's failed treatment: faded row, quiet trailing label. */+ muted: boolean;+ trailing: JSX.Element | undefined;+};++/** Subtitle for a call that touched paths: the path, or how many. */+export function pathsSubtitle(paths: string[]): string | undefined {+ if (paths.length === 0) return undefined;+ if (paths.length === 1) return paths[0];+ return `${paths.length} files`;+}diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsxnew file mode 100644index 0000000000..e5ec4d8755--- /dev/null+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx@@ -0,0 +1,202 @@+/**+ * The agent block's side-panel sections, in the repo's+ * `component/sidepanel/<X>SidePanelSections.tsx` convention (the PR block's+ * `PrSidePanelSections` is the template): a fragment of+ * `<SidePanel.Section>` elements that self-register into the enclosing+ * `<SidePanel.Layout>`.+ *+ * Everything rendered here is derived from state the block already holds —+ * the session record, the fold's metadata, and pure summaries over the+ * folded transcript (`state/session-summary.ts`).+ */++import { SidePanel, useSidePanel } from '@components/app/side-panel';+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';+import { registerHotkey } from '@core/hotkey/hotkeys';+import { TOKENS } from '@core/hotkey/tokens';+import { formatDate } from '@core/util/date';+import { openExternalUrl } from '@core/util/url';+import GitBranch from '@phosphor/git-branch.svg';+import { createMemo, For, onCleanup, Show } from 'solid-js';+import { useAgentSession } from '../../context/AgentSessionContext';+import {+ activityCounts,+ changedFiles,+ latestPlan,+} from '../../state/session-summary';+import {+ CountSummary,+ DiffChanges,+ SessionStatusPill,+ TodoList,+} from '../../ui';+import { harnessTitle } from '../AgentSplitHeader';++export function AgentSidePanelSections() {+ const { session, bot, metadata, messages, status } = useAgentSession();++ const plan = createMemo(() => latestPlan(messages()));+ const files = createMemo(() => changedFiles(messages()));+ const activity = createMemo(() => activityCounts(messages()));+ const totals = createMemo(() => ({+ additions: files().reduce((sum, file) => sum + file.additions, 0),+ deletions: files().reduce((sum, file) => sum + file.deletions, 0),+ }));++ // `]` toggles the panel, registered at the split scope so it works from+ // anywhere in the split (the md block's TopBar registration, verbatim).+ const sidePanel = useSidePanel();+ const splitPanel = useSplitPanel();+ if (splitPanel?.splitHotkeyScope) {+ const reg = registerHotkey({+ hotkey: ']',+ scopeId: splitPanel.splitHotkeyScope,+ hotkeyToken: TOKENS.block.toggleSidePanel,+ description: 'Toggle Side Panel',+ keyDownHandler: () => {+ if (!sidePanel) return false;+ if (!sidePanel.hasSections()) return false;+ sidePanel.toggle();+ return true;+ },+ });+ onCleanup(() => reg.dispose());+ }++ return (+ <>+ <SidePanel.Section id="details" title="Details" defaultOpen order={10}>+ <SidePanel.Grid>+ <SidePanel.Row label="Status">+ <SessionStatusPill status={status()} />+ </SidePanel.Row>+ <Show when={bot()?.name}>+ {(name) => (+ <SidePanel.Row label="Agent">+ <SidePanel.Pill>+ <span class="truncate">{name()}</span>+ </SidePanel.Pill>+ </SidePanel.Row>+ )}+ </Show>+ <SidePanel.Row label="Harness">+ <SidePanel.Pill>+ <span class="truncate">{harnessTitle(session()?.harness)}</span>+ </SidePanel.Pill>+ </SidePanel.Row>+ <Show when={metadata()?.model ?? session()?.model}>+ {(model) => (+ <SidePanel.Row label="Model">+ <SidePanel.Pill>+ <span class="truncate">{model()}</span>+ </SidePanel.Pill>+ </SidePanel.Row>+ )}+ </Show>+ <Show when={session()?.repoUrl}>+ {(url) => (+ <SidePanel.Row label="Repository">+ <button+ type="button"+ class={`${SidePanel.pillClass} hover:bg-hover cursor-pointer`}+ onClick={() => openExternalUrl(url())}+ >+ <GitBranch class="size-3 shrink-0" />+ <span class="truncate">{repoName(url())}</span>+ </button>+ </SidePanel.Row>+ )}+ </Show>+ <Show when={session()?.createdAt}>+ {(created) => (+ <SidePanel.Row label="Created">+ <SidePanel.Pill>+ <span class="truncate">+ {formatDate(created(), { showTime: true })}+ </span>+ </SidePanel.Pill>+ </SidePanel.Row>+ )}+ </Show>+ <Show when={session()?.modifiedAt}>+ {(modified) => (+ <SidePanel.Row label="Last updated">+ <SidePanel.Pill>+ <span class="truncate">+ {formatDate(modified(), { showTime: true })}+ </span>+ </SidePanel.Pill>+ </SidePanel.Row>+ )}+ </Show>+ </SidePanel.Grid>+ </SidePanel.Section>++ <Show when={plan()}>+ {(entries) => (+ <SidePanel.Section id="plan" title="Plan" defaultOpen order={15}>+ <TodoList+ todos={entries().map((entry) => ({+ content: entry.content,+ status: entry.status,+ }))}+ />+ </SidePanel.Section>+ )}+ </Show>++ <Show when={files().length > 0}>+ <SidePanel.Section+ id="files"+ title={+ <SidePanel.CountTitle+ label="Changed files"+ count={files().length}+ />+ }+ defaultOpen+ order={20}+ actions={<DiffChanges variant="bars" {...totals()} />}+ >+ <div class="flex flex-col gap-1">+ <For each={files()}>+ {(file) => (+ <div class="flex items-center gap-2 text-xs">+ <span+ class="min-w-0 flex-1 truncate text-ink"+ title={file.path}+ >+ {file.path}+ </span>+ <DiffChanges+ additions={file.additions}+ deletions={file.deletions}+ />+ </div>+ )}+ </For>+ </div>+ </SidePanel.Section>+ </Show>++ <Show when={activity().some((item) => item.count > 0)}>+ <SidePanel.Section id="activity" title="Activity" order={30}>+ <div class="text-xs text-ink-muted">+ <CountSummary items={activity()} />+ </div>+ </SidePanel.Section>+ </Show>+ </>+ );+}++/** `https://github.com/org/repo.git` → `org/repo` for a compact pill. */+function repoName(url: string): string {+ const path = url+ .replace(/\.git$/, '')+ .split('/')+ .filter(Boolean);+ const repo = path.at(-1);+ const org = path.at(-2);+ return org && repo && !org.includes(':') ? `${org}/${repo}` : (repo ?? url);+}diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsxnew file mode 100644index 0000000000..4a9c67b818--- /dev/null+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx@@ -0,0 +1,106 @@+/**+ * Block-level state for the agent block, following the chat block's+ * `ChatInputProvider`/`useChatInputContext` convention: the provider owns the+ * session data and controllers, composer/container components consume them+ * from context, and the `ui/` leaves stay dumb — they only ever receive+ * derived props.+ *+ * The value is assembled from `create*` factories (CHANNEL_BLOCK_NOTES.md §3)+ * so each stateful concern stays a composable unit as wiring grows.+ */++import type {+ FoldedMessage,+ SessionMetadata,+} from '@service-agent-fold/generated/types';+import type {+ AgentSessionResponse,+ SessionBot,+} from '@service-agent-harness/generated/schemas';+import {+ type Accessor,+ createContext,+ type ParentProps,+ useContext,+} from 'solid-js';+import { createAgentSessionFeed } from './create-agent-session-feed';+import {+ type ComposerController,+ createComposerController,+} from './create-composer-controller';+import {+ createSessionStatusController,+ type SessionStatus,+} from './create-session-status-controller';++export type AgentSessionState = {+ sessionId: Accessor<string>;+ /** Session metadata, absent until the load resolves. */+ session: Accessor<AgentSessionResponse | undefined>;+ /** The bot the session runs as, absent until the fold is acquired. */+ bot: Accessor<SessionBot | undefined>;+ /** The fold's session metadata (title, model, …), followed live. */+ metadata: Accessor<SessionMetadata | undefined>;+ /** The folded transcript, ordered by turn, live-following the session. */+ messages: Accessor<FoldedMessage[]>;+ loadFailed: Accessor<boolean>;+ /**+ * The block's one answer to "is the agent working": the fold's+ * turn-in-flight signal, cut off when the runtime is known to be gone.+ * Every consumer — composer, shimmer, header — reads this, never+ * `feed.working` or `status` directly, so the block cannot disagree with+ * itself about whether a turn is running.+ */+ working: Accessor<boolean>;+ /** The runtime's status: the GET snapshot, followed live over the log. */+ status: Accessor<SessionStatus>;+ composer: ComposerController;+};++const AgentSessionCtx = createContext<AgentSessionState>();++export function AgentSessionProvider(+ props: ParentProps & { sessionId: string }+) {+ const sessionId = () => props.sessionId;++ const feed = createAgentSessionFeed(sessionId);+ const status = createSessionStatusController({+ sessionId,+ seed: () => feed.session()?.status,+ });+ // A last message with no stop reason reads as an open turn forever; the+ // status stream knows when the runtime disconnected without closing it.+ // Combining them here is what keeps "working" a single truth.+ const working = () =>+ feed.working() && status.status().kind !== 'disconnected';+ const composer = createComposerController({ sessionId, working });++ return (+ <AgentSessionCtx.Provider+ value={{+ sessionId,+ session: feed.session,+ bot: feed.bot,+ metadata: feed.metadata,+ messages: feed.messages,+ loadFailed: feed.loadFailed,+ working,+ status: status.status,+ composer,+ }}+ >+ {props.children}+ </AgentSessionCtx.Provider>+ );+}++export function useAgentSession(): AgentSessionState {+ const ctx = useContext(AgentSessionCtx);+ if (!ctx) {+ throw new Error(+ 'useAgentSession must be used within <AgentSessionProvider />'+ );+ }+ return ctx;+}diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.tsnew file mode 100644index 0000000000..b3da849677--- /dev/null+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts@@ -0,0 +1,146 @@+/**+ * @vitest-environment jsdom+ *+ * The live path, end to end below the socket: a frame handed to+ * `handleAgentSessionLog` (what `SyncProvider` calls) must reach the feed's+ * ordered store without a refetch.+ */++import type { FoldedMessage } from '@service-agent-fold/generated/types';+import { createRoot } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const worker = vi.hoisted(() => ({+ /** Messages the fold machine reports for the session. */+ messages: [] as FoldedMessage[],+ /** Events the next `pushSessionEntries` resolves with. */+ pushed: [] as { kind: string; message: FoldedMessage }[],+}));++const emptyMetadata = {+ model: null,+ supportedModels: [],+ title: null,+ availableCommands: [],+ status: null,+};++vi.mock('@core/agent-fold/client', () => ({+ openSession: vi.fn(async () => ({+ messages: [],+ metadata: emptyMetadata,+ })),+ closeSession: vi.fn(),+ sessionMessages: vi.fn(async () => ({+ messages: worker.messages,+ metadata: { ...emptyMetadata, title: 'Fixture session' },+ })),+ pushSessionEntries: vi.fn(async () => worker.pushed),+}));++vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: {+ get: vi.fn(async () => ({+ isErr: () => false,+ value: { id: 'session', harness: 'claude-code' },+ })),+ getLog: vi.fn(async () => ({+ isErr: () => false,+ value: { bot: { id: 'bot', name: 'Agent' }, entries: [] },+ })),+ },+}));++function message(+ turn: number,+ author: 'user' | 'agent',+ text: string,+ stop: FoldedMessage['stop'] = null+): FoldedMessage {+ return {+ agentSessionId: 'session',+ requestId: null,+ turn,+ author:+ author === 'user' ? { kind: 'user', userId: null } : { kind: 'agent' },+ parts: [{ kind: 'text', text }],+ stop,+ };+}++const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++describe('createAgentSessionFeed live updates', () => {+ beforeEach(() => {+ worker.messages = [];+ worker.pushed = [];+ vi.resetModules();+ });++ it('applies a streamed frame without refetching', async () => {+ const { createAgentSessionFeed } = await import(+ './create-agent-session-feed'+ );+ const { handleAgentSessionLog } = await import(+ '@queries/agent-session/session-fold'+ );++ worker.messages = [message(0, 'user', 'hi')];++ const feed = createRoot(() => createAgentSessionFeed(() => 'session'));+ await flush();+ await flush();+ expect(feed.messages().map((m) => m.parts)).toHaveLength(1);++ // A live frame arrives: the fold reports a new agent message.+ worker.pushed = [{ kind: 'new', message: message(0, 'agent', 'working') }];+ handleAgentSessionLog({+ agentSessionId: 'session',+ direction: 'to_server',+ content: { type: 'acp' },+ } as never);+ await flush();+ await flush();++ expect(feed.messages()).toHaveLength(2);+ expect(feed.messages()[1]?.parts[0]).toMatchObject({ text: 'working' });+ expect(feed.working()).toBe(true);+ // The acquisition's snapshot metadata and bot land on the feed.+ expect(feed.metadata()?.title).toBe('Fixture session');+ expect(feed.bot()?.name).toBe('Agent');+ });++ it('replaces a streaming message in place as it grows', async () => {+ const { createAgentSessionFeed } = await import(+ './create-agent-session-feed'+ );+ const { handleAgentSessionLog } = await import(+ '@queries/agent-session/session-fold'+ );++ worker.messages = [message(0, 'agent', 'partial')];+ const feed = createRoot(() => createAgentSessionFeed(() => 'session'));+ await flush();+ await flush();++ worker.pushed = [+ {+ kind: 'update',+ message: message(0, 'agent', 'partial then more', { kind: 'end_turn' }),+ },+ ];+ handleAgentSessionLog({+ agentSessionId: 'session',+ direction: 'to_server',+ content: { type: 'acp' },+ } as never);+ await flush();+ await flush();++ expect(feed.messages()).toHaveLength(1);+ expect(feed.messages()[0]?.parts[0]).toMatchObject({+ text: 'partial then more',+ });+ expect(feed.working()).toBe(false);+ });+});diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.tsnew file mode 100644index 0000000000..e729539d11--- /dev/null+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts@@ -0,0 +1,155 @@+/**+ * The block's session feed: session metadata plus the shared live fold,+ * exposed as an *ordered* reactive list of folded messages — the shape a+ * linear transcript renders from.+ *+ * The heavy lifting lives in `@queries/agent-session/session-fold`'s+ * `acquireAgentSessionFold`: it buffers realtime frames before fetching the+ * persisted log, folds through one worker machine per session, and+ * refcounts across surfaces. This factory just orders what the fold reports+ * and keeps rows reconciled so a streaming turn updates in place.+ */++import { acquireAgentSessionFold } from '@queries/agent-session/session-fold';+import type {+ FoldedMessage,+ SessionMetadata,+} from '@service-agent-fold/generated/types';+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import type {+ AgentSessionResponse,+ SessionBot,+} from '@service-agent-harness/generated/schemas';+import {+ type Accessor,+ batch,+ createResource,+ createSignal,+ onCleanup,+} from 'solid-js';+import { createStore, produce, reconcile } from 'solid-js/store';++export type AgentSessionFeed = {+ /** Session metadata, absent until the load resolves. */+ session: Accessor<AgentSessionResponse | undefined>;+ /** The bot the session runs as, absent until the fold is acquired. */+ bot: Accessor<SessionBot | undefined>;+ /** The fold's session metadata (title, model, …), followed live. */+ metadata: Accessor<SessionMetadata | undefined>;+ /** The folded transcript, ordered by turn (prompt before reply). */+ messages: Accessor<FoldedMessage[]>;+ loadFailed: Accessor<boolean>;+ /** The newest turn has no stop reason yet — the agent is working. */+ working: Accessor<boolean>;+};++/** Prompt sorts before reply within a turn. */+function authorRank(message: FoldedMessage): number {+ return message.author.kind === 'user' ? 0 : 1;+}++function compareMessages(a: FoldedMessage, b: FoldedMessage): number {+ if (a.turn !== b.turn) return a.turn - b.turn;+ return authorRank(a) - authorRank(b);+}++function sameMessage(a: FoldedMessage, b: FoldedMessage): boolean {+ return a.turn === b.turn && a.author.kind === b.author.kind;+}++export function createAgentSessionFeed(+ sessionId: Accessor<string>+): AgentSessionFeed {+ const [list, setList] = createStore<FoldedMessage[]>([]);+ const [bot, setBot] = createSignal<SessionBot>();+ const [metadata, setMetadata] = createSignal<SessionMetadata>();++ const upsert = (messages: FoldedMessage[]) =>+ batch(() => {+ for (const message of messages) {+ // The list is short and appends dominate, so scan from the tail+ // rather than binary-searching.+ let index = list.length - 1;+ while (index >= 0 && compareMessages(list[index]!, message) > 0) {+ index--;+ }+ if (index >= 0 && sameMessage(list[index]!, message)) {+ // Path-scoped reconcile: a streaming turn replaces its message+ // hundreds of times; only the changed content re-renders.+ setList(index, reconcile(message));+ } else {+ const at = index + 1;+ setList(+ produce((current: FoldedMessage[]) =>+ current.splice(at, 0, message)+ )+ );+ }+ }+ });++ let release: (() => void) | undefined;++ // A superseded run (session switch, unmount mid-fetch) must release its+ // acquisition or the shared fold leaks a reference.+ let generation = 0;+ let closed = false;+ onCleanup(() => {+ closed = true;+ release?.();+ release = undefined;+ });++ const [resource] = createResource(sessionId, async (id) => {+ const run = ++generation;+ const superseded = () => closed || generation !== run;++ release?.();+ release = undefined;+ batch(() => {+ setList(reconcile([]));+ setBot(undefined);+ setMetadata(undefined);+ });++ const session = await agentHarnessServiceClient.get(id);+ if (session.isErr()) {+ throw new Error(`agent session could not be fetched: ${id}`);+ }+ if (superseded()) return session.value;++ const fold = await acquireAgentSessionFold({+ agentSessionId: id,+ onChange: upsert,+ onMetadata: setMetadata,+ });+ if (superseded()) {+ fold.release();+ return session.value;+ }+ release = fold.release;+ batch(() => {+ setBot(fold.bot);+ setMetadata(fold.metadata);+ upsert(fold.messages);+ });++ return session.value;+ });++ const messages = () => list;+ const working = () => {+ const last = list.at(-1);+ if (!last) return false;+ return last.author.kind === 'user' || last.stop == null;+ };++ return {+ session: () => resource.latest,+ bot,+ metadata,+ messages,+ loadFailed: () => resource.error !== undefined,+ working,+ };+}diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts b/apps/web/src/features/block-agent/context/create-composer-controller.test.tsnew file mode 100644index 0000000000..fb885ed405--- /dev/null+++ b/apps/web/src/features/block-agent/context/create-composer-controller.test.ts@@ -0,0 +1,253 @@+/**+ * @vitest-environment jsdom+ *+ * The controller end to end against a mocked harness client: the drain+ * sends, failures latch and retry, prompts queue behind a running turn and+ * flush when it settles, and `awaiting_turn` cannot wedge — it frees on the+ * fold's signal or on the timeout, whichever comes first.+ */++import { createRoot, createSignal } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ createComposerController,+ TURN_OBSERVE_TIMEOUT_MS,+} from './create-composer-controller';++const control = vi.hoisted(() => ({+ calls: [] as { sessionId: string; action: unknown }[],+ /** What the next `control` calls resolve to. */+ outcome: 'ok' as 'ok' | 'err' | 'reject',+}));++vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: {+ control: vi.fn(async (sessionId: string, action: unknown) => {+ control.calls.push({ sessionId, action });+ if (control.outcome === 'reject') throw new Error('network');+ return { isErr: () => control.outcome === 'err' };+ }),+ },+}));++vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: vi.fn(), success: vi.fn() },+}));++/** Let the drain effect and the awaited POST settle. */+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));++const prompts = () =>+ control.calls+ .filter((c) => (c.action as { type: string }).type === 'prompt')+ .map((c) => (c.action as { prompt: string }).prompt);++function setup(options?: { working?: boolean }) {+ const [working, setWorking] = createSignal(options?.working ?? false);+ const [sessionId, setSessionId] = createSignal('session-1');+ const { controller, dispose } = createRoot((dispose) => ({+ controller: createComposerController({ sessionId, working }),+ dispose,+ }));+ return { controller, setWorking, setSessionId, dispose };+}++beforeEach(() => {+ control.calls = [];+ control.outcome = 'ok';+ vi.useRealTimers();+});++describe('sending while idle', () => {+ it('posts immediately and empties the queue', async () => {+ const { controller, dispose } = setup();+ controller.send('hello');+ await flush();++ expect(prompts()).toEqual(['hello']);+ expect(controller.queue()).toEqual([]);+ dispose();+ });+});++describe('failure', () => {+ it('keeps the failed prompt visible at the head and latches the drain', async () => {+ const { controller, dispose } = setup();+ control.outcome = 'err';+ controller.send('doomed');+ await flush();++ expect(controller.queue().map((p) => p.markdown)).toEqual(['doomed']);+ expect(controller.sendFailed()).toBe(true);+ // The latch holds: no second attempt without user action.+ expect(prompts()).toEqual(['doomed']);+ dispose();+ });++ it('retry() releases the latch and posts the same prompt again', async () => {+ const { controller, dispose } = setup();+ control.outcome = 'err';+ controller.send('doomed');+ await flush();++ control.outcome = 'ok';+ controller.retry();+ await flush();++ expect(prompts()).toEqual(['doomed', 'doomed']);+ expect(controller.queue()).toEqual([]);+ expect(controller.sendFailed()).toBe(false);+ dispose();+ });++ it('a new send also releases the latch, and order is preserved', async () => {+ const { controller, setWorking, dispose } = setup();+ control.outcome = 'err';+ controller.send('first');+ await flush();++ control.outcome = 'ok';+ controller.send('second');+ await flush();+ // The retried 'first' is awaiting its turn; 'second' correctly holds.+ expect(prompts()).toEqual(['first', 'first']);++ setWorking(true); // the fold shows first's turn+ await flush();+ setWorking(false); // ...and it settles+ await flush();++ expect(prompts()).toEqual(['first', 'first', 'second']);+ dispose();+ });++ it('removing the failed prompt clears the failure and unblocks the rest', async () => {+ const { controller, dispose } = setup();+ control.outcome = 'err';+ controller.send('bad');+ await flush();+ control.outcome = 'ok';+ controller.send('good');+ // 'good' releases the latch; make 'bad' fail once more so it latches+ // again with 'good' waiting behind it.+ control.outcome = 'err';+ await flush();++ control.outcome = 'ok';+ const failedId = controller.queue()[0]!.id;+ controller.remove(failedId);+ await flush();++ expect(prompts().at(-1)).toBe('good');+ expect(controller.queue()).toEqual([]);+ dispose();+ });++ it('a rejected promise (network error) behaves like a failure', async () => {+ const { controller, dispose } = setup();+ control.outcome = 'reject';+ controller.send('offline');+ await flush();++ expect(controller.sendFailed()).toBe(true);+ expect(controller.queue().map((p) => p.markdown)).toEqual(['offline']);+ dispose();+ });+});++describe('queueing behind a running turn', () => {+ it('holds while working and sends when the turn settles', async () => {+ const { controller, setWorking, dispose } = setup({ working: true });+ controller.send('queued');+ await flush();++ expect(prompts()).toEqual([]);+ expect(controller.queue().map((p) => p.markdown)).toEqual(['queued']);++ setWorking(false);+ await flush();++ expect(prompts()).toEqual(['queued']);+ expect(controller.queue()).toEqual([]);+ dispose();+ });++ it('sends queued prompts one at a time, in order, across turns', async () => {+ const { controller, setWorking, dispose } = setup({ working: true });+ controller.send('one');+ controller.send('two');+ await flush();++ setWorking(false);+ await flush();+ // 'one' posted; the slot is awaiting_turn, so 'two' holds.+ expect(prompts()).toEqual(['one']);++ setWorking(true); // the fold shows one's turn+ await flush();+ setWorking(false); // ...and it settles+ await flush();++ expect(prompts()).toEqual(['one', 'two']);+ dispose();+ });+});++describe('awaiting_turn cannot wedge', () => {+ it('frees when the fold reports the turn', async () => {+ const { controller, setWorking, dispose } = setup();+ controller.send('hello');+ await flush();+ expect(controller.busy()).toBe(true); // awaiting_turn++ setWorking(true);+ await flush();+ expect(controller.busy()).toBe(true); // now because working+ setWorking(false);+ await flush();+ expect(controller.busy()).toBe(false); // fully idle — no wedge+ dispose();+ });++ it('frees on the timeout when no turn ever appears', async () => {+ vi.useFakeTimers();+ const { controller, dispose } = setup();+ controller.send('hello');+ await vi.advanceTimersByTimeAsync(0);+ expect(controller.busy()).toBe(true);++ await vi.advanceTimersByTimeAsync(TURN_OBSERVE_TIMEOUT_MS);+ expect(controller.busy()).toBe(false);+ dispose();+ });+});++describe('stop', () => {+ it('posts a stop while busy and is a no-op while idle', async () => {+ const { controller, setWorking, dispose } = setup();+ controller.stop();+ await flush();+ expect(control.calls).toEqual([]);++ setWorking(true);+ controller.stop();+ await flush();+ expect(control.calls.at(-1)?.action).toEqual({ type: 'stop' });+ dispose();+ });+});++describe('session switch', () => {+ it('drops the queue — prompts never leak into another session', async () => {+ const { controller, setSessionId, dispose } = setup({ working: true });+ controller.send('for session-1');+ await flush();++ setSessionId('session-2');+ await flush();++ expect(controller.queue()).toEqual([]);+ expect(prompts()).toEqual([]);+ dispose();+ });+});diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.ts b/apps/web/src/features/block-agent/context/create-composer-controller.tsnew file mode 100644index 0000000000..fd2c756089--- /dev/null+++ b/apps/web/src/features/block-agent/context/create-composer-controller.ts@@ -0,0 +1,170 @@+/**+ * The Solid shell around the composer model (`state/composer-state.ts`).+ *+ * One store holds the two facts the controller owns — the prompt queue and+ * the single in-flight POST's phase. The heart is one effect, the drain: on+ * any change it asks `nextAction` what to do and does it. There are no+ * transition events and no phase that waits for a specific event to exit.+ * The one bridge state, `awaiting_turn` (POST accepted, turn not yet visible+ * in the fold), is bounded by a timeout so a turn that never appears cannot+ * wedge the composer.+ *+ * `send` only enqueues. Whether the prompt goes out now or waits for the+ * running turn to settle is entirely the drain's call — the same code path+ * either way, so queueing is not a special case.+ */++import { toast } from '@core/component/Toast/Toast';+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import { type Accessor, batch, createEffect, on, onCleanup } from 'solid-js';+import { createStore } from 'solid-js/store';+import {+ isBusy,+ nextAction,+ type PostPhase,+ type QueuedPrompt,+} from '../state/composer-state';++export type ComposerController = {+ /** Prompts waiting to be sent, oldest first. The head sends next. */+ queue: Accessor<QueuedPrompt[]>;+ /** The prompt currently on the wire or awaiting its turn, if any. */+ sendingId: Accessor<string | undefined>;+ /** The head prompt failed to post and is held for retry. */+ sendFailed: Accessor<boolean>;+ /** A turn is running or a post is starting one — the stop affordance shows. */+ busy: Accessor<boolean>;+ send: (markdown: string) => void;+ /** Release a failed head so the drain tries it again. */+ retry: () => void;+ /** Drop a queued prompt. Dropping the failed head clears the failure. */+ remove: (promptId: string) => void;+ stop: () => void;+};++/**+ * How long `awaiting_turn` waits for the fold to show the posted turn before+ * giving up and freeing the post slot. Normally the prompt frame echoes back+ * within milliseconds of the POST ack; this only fires when the runtime or+ * the socket has genuinely gone quiet.+ */+export const TURN_OBSERVE_TIMEOUT_MS = 10_000;++export function createComposerController(options: {+ sessionId: Accessor<string>;+ /** The block's one working signal — see `AgentSessionContext`. */+ working: Accessor<boolean>;+}): ComposerController {+ const [state, setState] = createStore<{+ queue: QueuedPrompt[];+ post: PostPhase;+ }>({+ queue: [],+ post: { type: 'idle' },+ });++ const postHead = async (prompt: QueuedPrompt) => {+ setState('post', { type: 'posting', promptId: prompt.id });+ const result = await agentHarnessServiceClient+ .control(options.sessionId(), { type: 'prompt', prompt: prompt.markdown })+ .catch(() => undefined);++ if (result === undefined || result.isErr()) {+ // The prompt stays at the head of the queue — visible and retryable,+ // never dropped. The latch stops the drain until the user acts.+ setState('post', { type: 'failed', promptId: prompt.id });+ toast.failure('Message could not be sent');+ return;+ }+ batch(() => {+ setState('queue', (queue) => queue.filter((p) => p.id !== prompt.id));+ setState('post', { type: 'awaiting_turn', promptId: prompt.id });+ });+ };++ const postStop = async () => {+ const result = await agentHarnessServiceClient+ .control(options.sessionId(), { type: 'stop' })+ .catch(() => undefined);+ if (result === undefined || result.isErr()) {+ toast.failure('The agent could not be stopped');+ }+ // Success is observed through the fold: the turn settles and `working`+ // flips false, which re-runs the drain.+ };++ // The drain: whenever any fact changes, ask the model what to do and do+ // it. Deciding from present facts — rather than reacting to event edges —+ // is what makes this wedge-proof: there is no exit event to miss.+ createEffect(() => {+ const action = nextAction({+ post: state.post,+ head: state.queue[0],+ agentWorking: options.working(),+ });+ if (action.type === 'post_head') void postHead(action.prompt);+ });++ // `awaiting_turn` resolves on whichever comes first: the fold reports the+ // turn (`working` flips true), or the timeout gives up. Either way the+ // post slot frees and the drain re-decides from there.+ createEffect(() => {+ if (state.post.type !== 'awaiting_turn') return;+ if (options.working()) {+ setState('post', { type: 'idle' });+ return;+ }+ const timer = setTimeout(+ () => setState('post', { type: 'idle' }),+ TURN_OBSERVE_TIMEOUT_MS+ );+ onCleanup(() => clearTimeout(timer));+ });++ // A session switch resets the composer: queued prompts belong to the+ // session they were typed in, never the next one.+ createEffect(+ on(+ options.sessionId,+ () => setState({ queue: [], post: { type: 'idle' } }),+ { defer: true }+ )+ );++ return {+ queue: () => state.queue,+ sendingId: () =>+ state.post.type === 'posting' || state.post.type === 'awaiting_turn'+ ? state.post.promptId+ : undefined,+ sendFailed: () => state.post.type === 'failed',+ busy: () => isBusy(state.post, options.working()),+ send: (markdown) => {+ batch(() => {+ setState('queue', (queue) => [+ ...queue,+ { id: crypto.randomUUID(), markdown },+ ]);+ // A new message is intent to continue: release a failed head so the+ // drain retries it (in order) rather than holding everything behind+ // a stale failure.+ if (state.post.type === 'failed') setState('post', { type: 'idle' });+ });+ },+ retry: () => {+ if (state.post.type === 'failed') setState('post', { type: 'idle' });+ },+ remove: (promptId) => {+ batch(() => {+ setState('queue', (queue) => queue.filter((p) => p.id !== promptId));+ if (state.post.type === 'failed' && state.post.promptId === promptId) {+ setState('post', { type: 'idle' });+ }+ });+ },+ stop: () => {+ if (!isBusy(state.post, options.working())) return;+ void postStop();+ },+ };+}diff --git a/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts b/apps/web/src/features/block-agent/context/create-session-status-controller.test.tsnew file mode 100644index 0000000000..90dc377379--- /dev/null+++ b/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts@@ -0,0 +1,31 @@+import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';+import { describe, expect, it } from 'vitest';+import { statusFromEntry } from './create-session-status-controller';++function entry(content: unknown): AgentSessionLogEntryDto {+ return { direction: 'to_server', content } as AgentSessionLogEntryDto;+}++describe('statusFromEntry', () => {+ it('projects a system-event frame into an event status', () => {+ expect(entryStatus({ type: 'event', event: 'acp_ready' })).toEqual({+ kind: 'event',+ event: 'acp_ready',+ });+ });++ it('ignores ACP frames', () => {+ expect(+ entryStatus({ type: 'acp', jsonrpc: '2.0', method: 'session/update' })+ ).toBeUndefined();+ });++ it('ignores malformed event frames', () => {+ expect(entryStatus({ type: 'event' })).toBeUndefined();+ expect(entryStatus({ type: 'event', event: 7 })).toBeUndefined();+ });++ function entryStatus(content: unknown) {+ return statusFromEntry(entry(content));+ }+});diff --git a/apps/web/src/features/block-agent/context/create-session-status-controller.ts b/apps/web/src/features/block-agent/context/create-session-status-controller.tsnew file mode 100644index 0000000000..c441664e3b--- /dev/null+++ b/apps/web/src/features/block-agent/context/create-session-status-controller.ts@@ -0,0 +1,77 @@+/**+ * The session's live status: seeded from the GET snapshot, then followed+ * through the same realtime stream the transcript folds.+ *+ * There is no dedicated status feed — status is a projection of the log+ * (`crates/agent_session/src/outbound/postgres/mod.rs`, the log-create+ * transaction), and every appended frame, including the system-event frames+ * that move the status, is published over the one `agent_session_log`+ * gateway event. This controller taps those raw frames and keeps the last+ * system event, exactly as the backend projection does.+ */++import { subscribeAgentSessionLog } from '@queries/agent-session/session-fold';+import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';+import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';++/** Mirrors `SessionStatusDto`, which mirrors the backend's `SessionStatus`. */+export type SessionStatus =+ /** No status updates received. */+ | { kind: 'no_messages' }+ /** The last system event received from the runtime, e.g. `acp_ready`. */+ | { kind: 'event'; event: string }+ /** The session disconnected without sending a closed event. */+ | { kind: 'disconnected' };++/**+ * The status a log frame projects, or undefined for frames that carry none+ * (ACP traffic). The backend's projection rule, applied client-side to the+ * same bytes.+ */+export function statusFromEntry(+ entry: AgentSessionLogEntryDto+): SessionStatus | undefined {+ const content = entry.content as { type?: string; event?: string };+ if (content?.type !== 'event') return undefined;+ if (typeof content.event !== 'string') return undefined;+ return { kind: 'event', event: content.event };+}++export type SessionStatusController = {+ status: Accessor<SessionStatus>;+};++export function createSessionStatusController(options: {+ sessionId: Accessor<string>;+ /** The GET snapshot's status, absent until the session loads. */+ seed: Accessor<SessionStatus | undefined>;+}): SessionStatusController {+ const [status, setStatus] = createSignal<SessionStatus>({+ kind: 'no_messages',+ });++ // A live frame is always newer than the snapshot; once one lands, the+ // (possibly slower) GET must not roll the status back.+ let live = false;++ createEffect(() => {+ const seeded = options.seed();+ if (seeded && !live) setStatus(seeded);+ });++ createEffect(() => {+ live = false;+ const unsubscribe = subscribeAgentSessionLog(+ options.sessionId(),+ (event) => {+ const next = statusFromEntry(event);+ if (!next) return;+ live = true;+ setStatus(next);+ }+ );+ onCleanup(unsubscribe);+ });++ return { status };+}diff --git a/apps/web/src/features/block-agent/context/origin-thread.ts b/apps/web/src/features/block-agent/context/origin-thread.tsnew file mode 100644index 0000000000..4b86dc46f7--- /dev/null+++ b/apps/web/src/features/block-agent/context/origin-thread.ts@@ -0,0 +1,17 @@+import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';++/** Drawer id for the "thread this session was spawned from" drawer. */+export const ORIGIN_THREAD_DRAWER_ID = 'agent-origin-thread';++/** A channel-thread reference: the channel plus the thread's root message. */+export type OriginThreadRef = { channelId: string; messageId: string };++/** The thread this session was spawned from, when renderable. */+export function sessionOriginThread(+ session: AgentSessionResponse | undefined+): OriginThreadRef | undefined {+ const messageId = session?.threadId;+ const channelId = session?.threadChannelId;+ if (!messageId || !channelId) return undefined;+ return { channelId, messageId };+}diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxnew file mode 100644index 0000000000..794364e2d3--- /dev/null+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -0,0 +1,264 @@+/**+ * Debug gallery for the block-agent ui library: every pure component with+ * fixture data, plus a full `AgentMessage` rendered end-to-end. Mounted at+ * `/component/agent-ui`.+ */++import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import type {+ FoldedMessage,+ ToolStatus,+} from '@service-agent-fold/generated/types';+import { createSignal, type JSX, onCleanup } from 'solid-js';+import { Message } from '../component/AgentMessage';+import {+ AgentInput,+ AnimatedNumber,+ CountSummary,+ DiffChanges,+ PierreDiff,+ QuestionAnswers,+ TextShimmer,+ Thought,+ TodoList,+ ToolCard,+ ToolErrorCard,+ ToolStatusTitle,+} from '../ui';++function Item(props: { label: string; children: JSX.Element }) {+ return (+ <section class="flex flex-col gap-2">+ <h2 class="text-xs font-medium uppercase tracking-wide text-ink-extra-muted">+ {props.label}+ </h2>+ <div class="flex flex-col gap-2">{props.children}</div>+ </section>+ );+}++/** Flips every few seconds so the running→done animations stay observable. */+function usePulse(intervalMs = 2500) {+ const [on, setOn] = createSignal(true);+ const timer = setInterval(() => setOn((value) => !value), intervalMs);+ onCleanup(() => clearInterval(timer));+ return on;+}++function useCounter(intervalMs = 1200) {+ const [count, setCount] = createSignal(3);+ const timer = setInterval(+ () => setCount((value) => (value + 1) % 12),+ intervalMs+ );+ onCleanup(() => clearInterval(timer));+ return count;+}++const FIXTURE_DIFF = {+ path: 'crates/agent_fold/src/domain/fold.rs',+ oldText:+ 'fn fold(log: &[Frame]) -> Vec<Message> {\n let mut out = Vec::new();\n for frame in log {\n out.push(frame.into());\n }\n out\n}\n',+ newText:+ 'fn fold(log: &[Frame]) -> Vec<Message> {\n let mut machine = FoldMachine::default();\n for frame in log {\n machine.push(frame);\n }\n machine.finish()\n}\n',+};++const FIXTURE_MESSAGE: FoldedMessage = {+ agentSessionId: 'demo',+ requestId: null,+ turn: 0,+ author: { kind: 'agent' },+ stop: { kind: 'end_turn' },+ parts: [+ {+ kind: 'text',+ text: "I'll look at the fold implementation and tighten it up.",+ },+ {+ kind: 'thought',+ text: 'The batch fold re-derives every message per frame; the incremental machine already handles this.',+ },+ {+ kind: 'tool_use',+ id: 'demo-read',+ label: 'Read',+ status: 'completed',+ detail: { kind: 'read', paths: ['crates/agent_fold/src/domain/fold.rs'] },+ },+ {+ kind: 'tool_use',+ id: 'demo-search',+ label: 'Search',+ status: 'completed',+ detail: {+ kind: 'search',+ paths: ['crates/agent_fold/src'],+ output: 'fold.rs:12: fn fold(log: &[Frame]) -> Vec<Message>',+ },+ },+ {+ kind: 'tool_use',+ id: 'demo-edit',+ label: 'Edit',+ status: 'completed',+ detail: { kind: 'edit', diffs: [FIXTURE_DIFF] },+ },+ {+ kind: 'tool_use',+ id: 'demo-terminal',+ label: 'Bash',+ status: 'running',+ detail: {+ kind: 'terminal',+ command: 'cargo test -p agent_fold',+ output: 'running 14 tests\n[32mtest fold::turns ... ok[0m',+ exitCode: null,+ },+ },+ {+ kind: 'permission',+ toolCall: 'demo-terminal',+ options: [+ { id: 'allow', name: 'Allow', kind: 'allow_once' },+ { id: 'deny', name: 'Deny', kind: 'reject_once' },+ ],+ outcome: { kind: 'selected', optionId: 'allow' },+ },+ ],+};++export default function AgentUiGallery() {+ const pulse = usePulse();+ const status = (): ToolStatus => (pulse() ? 'running' : 'completed');+ const count = useCounter();++ return (+ <StaticMarkdownContext>+ <div class="size-full overflow-auto">+ <div class="mx-auto flex max-w-3xl flex-col gap-8 px-6 py-8">+ <Item label="ToolCard">+ <ToolCard+ title="Bash"+ subtitle="cargo test -p agent_fold"+ status={status()}+ />+ <ToolCard+ title="Read"+ subtitle="crates/agent_fold/src/domain/fold.rs"+ args={{ limit: '200' }}+ status="completed"+ />+ <ToolCard+ title="Edit"+ subtitle={FIXTURE_DIFF.path}+ trailing={<DiffChanges additions={4} deletions={3} />}+ status="completed"+ defaultOpen+ >+ <PierreDiff diffs={[FIXTURE_DIFF]} />+ </ToolCard>+ </Item>++ <Item label="Thought (active / settled)">+ <Thought+ text="The batch fold re-derives every message per frame; the incremental machine already handles this."+ active={pulse()}+ />+ <Thought+ text="The incremental machine is the right default."+ defaultOpen+ />+ </Item>++ <Item label="ToolStatusTitle / TextShimmer">+ <ToolStatusTitle+ active={pulse()}+ activeText="Gathering context"+ doneText="Gathered context"+ />+ <TextShimmer text="Thinking about the fold" active={pulse()} />+ </Item>++ <Item label="AnimatedNumber / CountSummary">+ <div class="text-sm text-ink">+ <AnimatedNumber value={count()} />+ </div>+ <CountSummary+ items={[+ {+ key: 'read',+ count: count(),+ one: 'file read',+ other: 'files read',+ },+ { key: 'search', count: 2, one: 'search', other: 'searches' },+ ]}+ />+ </Item>++ <Item label="TodoList">+ <TodoList+ todos={[+ {+ content: 'Read the fold implementation',+ status: 'completed',+ },+ {+ content: 'Swap batch fold for the machine',+ status: 'in_progress',+ },+ { content: 'Run the crate tests', status: 'pending' },+ {+ content: 'Benchmark against the recording',+ status: 'cancelled',+ },+ ]}+ />+ </Item>++ <Item label="QuestionAnswers">+ <QuestionAnswers+ questions={[+ {+ question: 'Which fold strategy should be the default?',+ answers: ['Incremental machine'],+ },+ { question: 'Keep the batch entry point?', answers: [] },+ ]}+ />+ </Item>++ <Item label="ToolErrorCard">+ <ToolErrorCard+ tool="Bash"+ error="Bash: command timed out after 120s: cargo test -p agent_fold"+ />+ </Item>++ <Item label="DiffChanges">+ <div class="flex items-center gap-4 text-xs">+ <DiffChanges additions={18} deletions={6} />+ <DiffChanges additions={18} deletions={6} variant="bars" />+ <DiffChanges additions={0} deletions={412} variant="bars" />+ </div>+ </Item>++ <Item label="AgentInput (idle / busy)">+ <AgentInput+ onSend={(content) => console.info('[gallery] send', content)}+ />+ <AgentInput+ busy+ onSend={() => {}}+ onStop={() => console.info('[gallery] stop')}+ />+ </Item>++ <Item label="AgentMessage (end-to-end)">+ <Message message={FIXTURE_MESSAGE} />+ </Item>+ </div>+ </div>+ </StaticMarkdownContext>+ );+}diff --git a/apps/web/src/features/block-agent/debug/replay/Replay.tsx b/apps/web/src/features/block-agent/debug/replay/Replay.tsxnew file mode 100644index 0000000000..3a1bd296bf--- /dev/null+++ b/apps/web/src/features/block-agent/debug/replay/Replay.tsx@@ -0,0 +1,273 @@+/**+ * Replay harness: drive the real block-agent stack from a recorded session.+ *+ * Load a `~/.agent_runtime_sessions/<id>.jsonl` recording, choose where the+ * "persisted log" ends, and stream the rest frame by frame through the real+ * realtime path. Everything below the control bar is the production stack —+ * `AgentSessionProvider`, worker fold, `Transcript`, `AgentComposer` —+ * served by `interceptor.ts` instead of the harness service. Mounted at+ * `/component/agent-replay`.+ */++import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';+import { createSignal, onCleanup, Show } from 'solid-js';+import { AgentComposer } from '../../component/AgentComposer';+import { Transcript } from '../../component/Transcript';+import {+ AgentSessionProvider,+ useAgentSession,+} from '../../context/AgentSessionContext';+import { SessionStatusPill } from '../../ui';+import { createReplayDriver, type ReplayDriver } from './driver';+import { registerReplaySession } from './interceptor';+import { parseRecording } from './recording';++type MountedSession = {+ id: string;+ driver: ReplayDriver;+ unregister: () => void;+};++function Knob(props: {+ label: string;+ children: import('solid-js').JSX.Element;+}) {+ return (+ <label class="flex items-center gap-1.5 text-xs text-ink-muted">+ {props.label}+ {props.children}+ </label>+ );+}++function SessionChrome() {+ const { status, working } = useAgentSession();+ return (+ <div class="flex items-center gap-2 border-b border-edge-muted px-4 py-2">+ <SessionStatusPill status={status()} />+ <Show when={working()}>+ <span class="text-xs text-ink-extra-muted">working…</span>+ </Show>+ </div>+ );+}++export default function AgentReplay() {+ const [recording, setRecording] = createSignal<{+ name: string;+ entries: AgentSessionLogEntryDto[];+ }>();+ const [loadError, setLoadError] = createSignal<string>();++ // Applied at (re)mount.+ const [splitPct, setSplitPct] = createSignal(100);+ const [fetchDelayMs, setFetchDelayMs] = createSignal(0);+ const [overlap, setOverlap] = createSignal(0);+ // Read live, per frame / per control call.+ const [frameIntervalMs, setFrameIntervalMs] = createSignal(150);+ const [controlFails, setControlFails] = createSignal(false);++ const [mounted, setMounted] = createSignal<MountedSession>();+ // The driver's cursor/playing signals live inside the mounted session, so+ // reading them through `mounted()` keeps the transport reactive.+ const cursor = () => mounted()?.driver.cursor() ?? 0;+ const playing = () => mounted()?.driver.playing() ?? false;++ const teardown = () => {+ const current = mounted();+ if (!current) return;+ current.driver.dispose();+ current.unregister();+ setMounted(undefined);+ };+ onCleanup(teardown);++ const mount = () => {+ const loaded = recording();+ if (!loaded) return;+ teardown();+ // A real UUID: the fold's wasm side parses the session id, so a+ // `replay-1`-style marker crashes it. The interceptor routes by+ // registration, not by the id's shape.+ const id = crypto.randomUUID();+ const splitIndex = Math.round((loaded.entries.length * splitPct()) / 100);+ const driver = createReplayDriver({+ agentSessionId: id,+ entries: loaded.entries,+ splitIndex,+ overlap: overlap(),+ fetchDelayMs: fetchDelayMs(),+ frameIntervalMs,+ controlFails,+ });+ const unregister = registerReplaySession(id, driver.backend);+ setMounted({ id, driver, unregister });+ };++ const loadFile = async (file: File) => {+ try {+ const entries = parseRecording(await file.text());+ if (entries.length === 0) throw new Error('recording is empty');+ setLoadError(undefined);+ setRecording({ name: file.name, entries });+ } catch (error) {+ setLoadError(error instanceof Error ? error.message : String(error));+ setRecording(undefined);+ }+ teardown();+ };++ return (+ <div+ class="size-full overflow-hidden flex flex-col"+ onDragOver={(event) => event.preventDefault()}+ onDrop={(event) => {+ event.preventDefault();+ const file = event.dataTransfer?.files[0];+ if (file) void loadFile(file);+ }}+ >+ <div class="flex flex-col gap-2 border-b border-edge-muted px-4 py-3">+ <div class="flex flex-wrap items-center gap-3">+ <input+ type="file"+ accept=".jsonl"+ class="text-xs text-ink-muted"+ onChange={(event) => {+ const file = event.currentTarget.files?.[0];+ if (file) void loadFile(file);+ }}+ />+ <Show when={recording()}>+ {(loaded) => (+ <span class="text-xs text-ink-extra-muted">+ {loaded().name} · {loaded().entries.length} frames+ </span>+ )}+ </Show>+ <Show when={loadError()}>+ <span class="text-xs text-failure">{loadError()}</span>+ </Show>+ </div>++ <div class="flex flex-wrap items-center gap-4">+ <Knob label={`log ${splitPct()}%`}>+ <input+ type="range"+ min="0"+ max="100"+ value={splitPct()}+ onInput={(event) =>+ setSplitPct(Number(event.currentTarget.value))+ }+ />+ </Knob>+ <Knob label="frame ms">+ <select+ class="rounded border border-edge-muted bg-transparent px-1 py-0.5"+ value={frameIntervalMs()}+ onChange={(event) =>+ setFrameIntervalMs(Number(event.currentTarget.value))+ }+ >+ <option value="30">30</option>+ <option value="150">150</option>+ <option value="400">400</option>+ <option value="1000">1000</option>+ </select>+ </Knob>+ <Knob label="fetch delay">+ <select+ class="rounded border border-edge-muted bg-transparent px-1 py-0.5"+ value={fetchDelayMs()}+ onChange={(event) =>+ setFetchDelayMs(Number(event.currentTarget.value))+ }+ >+ <option value="0">none</option>+ <option value="1500">1.5s</option>+ </select>+ </Knob>+ <Knob label="overlap">+ <select+ class="rounded border border-edge-muted bg-transparent px-1 py-0.5"+ value={overlap()}+ onChange={(event) =>+ setOverlap(Number(event.currentTarget.value))+ }+ >+ <option value="0">0</option>+ <option value="5">5</option>+ </select>+ </Knob>+ <Knob label="control fails">+ <input+ type="checkbox"+ checked={controlFails()}+ onChange={(event) => setControlFails(event.currentTarget.checked)}+ />+ </Knob>+ <button+ type="button"+ class="rounded border border-edge-muted px-2 py-0.5 text-xs text-ink-muted hover:bg-surface-muted"+ disabled={!recording()}+ onClick={mount}+ >+ {mounted() ? 'restart' : 'mount'}+ </button>+ </div>++ <Show when={mounted()}>+ {(session) => (+ <div class="flex items-center gap-3">+ <button+ type="button"+ class="rounded border border-edge-muted px-2 py-0.5 text-xs text-ink-muted hover:bg-surface-muted"+ onClick={() =>+ playing() ? session().driver.pause() : session().driver.play()+ }+ >+ {playing() ? 'pause' : 'play'}+ </button>+ <button+ type="button"+ class="rounded border border-edge-muted px-2 py-0.5 text-xs text-ink-muted hover:bg-surface-muted"+ onClick={() => session().driver.step()}+ >+ step+ </button>+ <span class="text-xs tabular-nums text-ink-extra-muted">+ {cursor()} / {session().driver.total}+ </span>+ </div>+ )}+ </Show>+ </div>++ <Show+ when={mounted()}+ fallback={+ <div class="flex flex-1 items-center justify-center text-sm text-ink-extra-muted">+ Drop a recording (~/.agent_runtime_sessions/*.jsonl), then mount.+ </div>+ }+ keyed+ >+ {(session) => (+ <AgentSessionProvider sessionId={session.id}>+ <StaticMarkdownContext>+ <div class="flex-1 min-h-0 flex flex-col">+ <SessionChrome />+ <Transcript />+ <div class="shrink-0 w-full max-w-3xl mx-auto px-4 pb-4">+ <AgentComposer />+ </div>+ </div>+ </StaticMarkdownContext>+ </AgentSessionProvider>+ )}+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.tsnew file mode 100644index 0000000000..4d13d37926--- /dev/null+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts@@ -0,0 +1,185 @@+/**+ * Playback engine for one replay session.+ *+ * The driver owns a recording split in two: entries before `splitIndex` are+ * served as the persisted log (`getLog`), the rest stream one at a time+ * through the real realtime entry point, `handleAgentSessionLog` — so+ * buffering, `dropOverlap`, the worker fold, and the status projection all+ * run exactly as they do against the gateway.+ *+ * Two knobs exist purely to provoke the catch-up paths: `fetchDelayMs` holds+ * the `getLog` response open so streamed frames land while the fetch is in+ * flight (they must buffer), and `overlap` rewinds the stream to before the+ * split so the first streamed frames duplicate fetched ones (they must drop).+ */++import type { ResultError } from '@core/util/result';+import { handleAgentSessionLog } from '@queries/agent-session/session-fold';+import type {+ AgentSessionLogEntryDto,+ AgentSessionResponse,+ SessionBot,+} from '@service-agent-harness/generated/schemas';+import { err, ok } from 'neverthrow';+import { type Accessor, createSignal } from 'solid-js';+import type { ReplayBackend } from './interceptor';++export const REPLAY_BOT: SessionBot = { id: 'replay-bot', name: 'Replay' };+export const REPLAY_OWNER = 'macro|[email protected]';++/** POST ack → frame in the log, same ordering the harness produces. */+const PROMPT_ECHO_DELAY_MS = 150;++export type ReplayDriverOptions = {+ agentSessionId: string;+ entries: AgentSessionLogEntryDto[];+ /** How many entries `getLog` returns; the rest stream. */+ splitIndex: number;+ /** Streaming starts this many entries before the split (dedup exercise). */+ overlap: number;+ /** How long `getLog` stays in flight (catch-up buffering exercise). */+ fetchDelayMs: number;+ /** Delay between streamed frames while playing. Read per frame. */+ frameIntervalMs: Accessor<number>;+ /** When true, `control` rejects — the composer's failed/retry path. */+ controlFails: Accessor<boolean>;+};++export type ReplayDriver = {+ backend: ReplayBackend;+ /** Next entry to stream; `total` when the recording is exhausted. */+ cursor: Accessor<number>;+ total: number;+ playing: Accessor<boolean>;+ play: () => void;+ pause: () => void;+ /** Stream exactly one frame. */+ step: () => void;+ dispose: () => void;+};++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function replayFailure(): ResultError<'SERVER_ERROR'> {+ return Object.assign(new Error('replay harness: simulated failure'), {+ code: 'SERVER_ERROR' as const,+ });+}++function sessionFixture(id: string): AgentSessionResponse {+ const now = new Date().toISOString();+ return {+ botId: REPLAY_BOT.id,+ createdAt: now,+ harness: 'replay',+ id,+ model: 'replay',+ modifiedAt: now,+ ownerId: REPLAY_OWNER,+ repoUrl: 'https://example.com/replay.git',+ status: { kind: 'no_messages' },+ };+}++/** The frame the harness would append for a prompt accepted over `control`. */+function promptEcho(prompt: string): AgentSessionLogEntryDto {+ return {+ createdAt: new Date().toISOString(),+ userId: REPLAY_OWNER,+ direction: 'to_runtime',+ content: {+ type: 'acp',+ jsonrpc: '2.0',+ id: crypto.randomUUID(),+ method: 'session/prompt',+ params: { prompt: [{ type: 'text', text: prompt }] },+ },+ };+}++export function createReplayDriver(options: ReplayDriverOptions): ReplayDriver {+ const { agentSessionId, entries } = options;+ const splitIndex = Math.max(0, Math.min(options.splitIndex, entries.length));+ const [cursor, setCursor] = createSignal(+ Math.max(0, splitIndex - options.overlap)+ );+ const [playing, setPlaying] = createSignal(false);+ let disposed = false;+ let timer: ReturnType<typeof setTimeout> | undefined;++ const emit = (entry: AgentSessionLogEntryDto) => {+ handleAgentSessionLog({ agentSessionId, ...entry });+ };++ const pause = () => {+ setPlaying(false);+ if (timer !== undefined) {+ clearTimeout(timer);+ timer = undefined;+ }+ };++ const step = () => {+ const at = cursor();+ const entry = entries[at];+ if (!entry) {+ pause();+ return;+ }+ setCursor(at + 1);+ emit(entry);+ };++ const tick = () => {+ timer = undefined;+ if (disposed || !playing()) return;+ step();+ if (cursor() >= entries.length) {+ setPlaying(false);+ return;+ }+ timer = setTimeout(tick, options.frameIntervalMs());+ };++ const play = () => {+ if (disposed || playing() || cursor() >= entries.length) return;+ setPlaying(true);+ tick();+ };++ const backend: ReplayBackend = {+ get: async () => ok(sessionFixture(agentSessionId)),+ getLog: async () => {+ if (options.fetchDelayMs > 0) await delay(options.fetchDelayMs);+ return ok({ bot: REPLAY_BOT, entries: entries.slice(0, splitIndex) });+ },+ control: async (request) => {+ if (options.controlFails()) return err([replayFailure()]);+ if (request.type === 'prompt') {+ const prompt = request.prompt;+ setTimeout(() => {+ if (!disposed) emit(promptEcho(prompt));+ }, PROMPT_ECHO_DELAY_MS);+ }+ // Every other action — stop, permissions — acks and does nothing:+ // their observable effects come from frames, which playback owns.+ return ok(undefined);+ },+ };++ return {+ backend,+ cursor,+ total: entries.length,+ playing,+ play,+ pause,+ step,+ dispose: () => {+ disposed = true;+ pause();+ },+ };+}diff --git a/apps/web/src/features/block-agent/debug/replay/interceptor.ts b/apps/web/src/features/block-agent/debug/replay/interceptor.tsnew file mode 100644index 0000000000..f83f0c93e8--- /dev/null+++ b/apps/web/src/features/block-agent/debug/replay/interceptor.ts@@ -0,0 +1,56 @@+/**+ * Serve replay sessions through the real `agentHarnessServiceClient`.+ *+ * The client is a plain object, so the first registration wraps its methods+ * in place. Wrapped methods consult a registry keyed by session id and fall+ * through to the captured originals for every id they do not know — live+ * sessions are untouched, and nothing outside the replay debug page imports+ * this module, so the production path never patches.+ */++import { agentHarnessServiceClient } from '@service-agent-harness/client';+import type { ControlRequest } from '@service-agent-harness/generated/schemas';++type Client = typeof agentHarnessServiceClient;++/** The replay driver's answers for one registered session id. */+export type ReplayBackend = {+ get: () => ReturnType<Client['get']>;+ getLog: () => ReturnType<Client['getLog']>;+ control: (request: ControlRequest) => ReturnType<Client['control']>;+};++const backends = new Map<string, ReplayBackend>();++let patched = false;++function ensurePatched(): void {+ if (patched) return;+ patched = true;+ const real: Client = { ...agentHarnessServiceClient };+ agentHarnessServiceClient.get = (sessionId) =>+ backends.get(sessionId)?.get() ?? real.get(sessionId);+ agentHarnessServiceClient.getLog = (sessionId) =>+ backends.get(sessionId)?.getLog() ?? real.getLog(sessionId);+ agentHarnessServiceClient.control = (sessionId, request) => {+ const backend = backends.get(sessionId);+ if (backend) return backend.control(request);+ return real.control(sessionId, request);+ };+ // `delete` stays real: a replay session has nothing behind it to delete.+}++/**+ * Route the client's calls for `sessionId` to `backend`. Returns the+ * unregister function; every other session id keeps its real behavior.+ */+export function registerReplaySession(+ sessionId: string,+ backend: ReplayBackend+): () => void {+ ensurePatched();+ backends.set(sessionId, backend);+ return () => {+ backends.delete(sessionId);+ };+}diff --git a/apps/web/src/features/block-agent/debug/replay/recording.test.ts b/apps/web/src/features/block-agent/debug/replay/recording.test.tsnew file mode 100644index 0000000000..269d7c1de5--- /dev/null+++ b/apps/web/src/features/block-agent/debug/replay/recording.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';+import { isPromptEntry, parseRecording } from './recording';++const LINE = (object: unknown) => JSON.stringify(object);++describe('parseRecording', () => {+ it('re-keys recorder ts to createdAt and keeps the envelope verbatim', () => {+ const entries = parseRecording(+ [+ LINE({+ ts: '2026-08-03T21:04:19.934Z',+ direction: 'to_server',+ content: { type: 'event', event: 'acp_ready' },+ }),+ '',+ LINE({+ ts: '2026-08-03T21:04:20.000Z',+ direction: 'to_runtime',+ content: { type: 'acp', jsonrpc: '2.0', method: 'session/prompt' },+ }),+ ].join('\n')+ );++ expect(entries).toEqual([+ {+ createdAt: '2026-08-03T21:04:19.934Z',+ direction: 'to_server',+ content: { type: 'event', event: 'acp_ready' },+ },+ {+ createdAt: '2026-08-03T21:04:20.000Z',+ direction: 'to_runtime',+ content: { type: 'acp', jsonrpc: '2.0', method: 'session/prompt' },+ },+ ]);+ });++ it('prefers an explicit createdAt and keeps userId when attributed', () => {+ const [entry] = parseRecording(+ LINE({+ ts: '2026-01-01T00:00:00.000Z',+ createdAt: '2026-02-02T00:00:00.000Z',+ userId: 'macro|[email protected]',+ direction: 'to_server',+ content: { type: 'event', event: 'acp_ready' },+ })+ );++ expect(entry).toMatchObject({+ createdAt: '2026-02-02T00:00:00.000Z',+ userId: 'macro|[email protected]',+ });+ });++ it.each([+ ['not JSON', 'nope', /line 1 is not JSON/],+ [+ 'a missing direction',+ LINE({ ts: 't', content: {} }),+ /line 1 has no direction/,+ ],+ [+ 'a missing envelope',+ LINE({ ts: 't', direction: 'to_server' }),+ /line 1 has no content envelope/,+ ],+ ])('throws with the line number on %s', (_name, line, message) => {+ expect(() => parseRecording(line)).toThrow(message);+ });+});++describe('isPromptEntry', () => {+ it('matches only session/prompt frames headed to the runtime', () => {+ const prompt = {+ createdAt: 't',+ direction: 'to_runtime',+ content: { type: 'acp', method: 'session/prompt' },+ } as const;+ expect(isPromptEntry(prompt)).toBe(true);+ expect(isPromptEntry({ ...prompt, direction: 'to_server' })).toBe(false);+ expect(+ isPromptEntry({+ ...prompt,+ content: { type: 'acp', method: 'session/update' },+ })+ ).toBe(false);+ });+});diff --git a/apps/web/src/features/block-agent/debug/replay/recording.ts b/apps/web/src/features/block-agent/debug/replay/recording.tsnew file mode 100644index 0000000000..5180f716f5--- /dev/null+++ b/apps/web/src/features/block-agent/debug/replay/recording.ts@@ -0,0 +1,63 @@+/**+ * Parse a recorded agent session into the wire entries the fold consumes.+ *+ * Recording, DB row, and realtime event share one frame shape+ * (`crates/agent_fold/src/inbound/wasm.rs`): `{direction, content}` plus+ * attribution. The recorder (`~/.agent_runtime_sessions/<id>.jsonl`) writes+ * `ts` where the log row carries `createdAt`; that re-keying is the whole+ * translation.+ */++import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';++type RecordedLine = {+ ts?: string;+ createdAt?: string;+ userId?: string | null;+ direction?: string;+ content?: unknown;+};++/**+ * Parse recorder JSONL into log entries. Throws with a line number on the+ * first malformed line — this feeds a debug page, so a broken recording+ * should fail loudly rather than fold a truncated transcript.+ */+export function parseRecording(jsonl: string): AgentSessionLogEntryDto[] {+ const entries: AgentSessionLogEntryDto[] = [];+ const lines = jsonl.split('\n');+ for (let index = 0; index < lines.length; index++) {+ const line = lines[index]!.trim();+ if (!line) continue;+ let parsed: RecordedLine;+ try {+ parsed = JSON.parse(line) as RecordedLine;+ } catch {+ throw new Error(`recording line ${index + 1} is not JSON`);+ }+ const { direction, content } = parsed;+ if (direction !== 'to_server' && direction !== 'to_runtime') {+ throw new Error(`recording line ${index + 1} has no direction`);+ }+ if (typeof content !== 'object' || content === null) {+ throw new Error(`recording line ${index + 1} has no content envelope`);+ }+ entries.push({+ content: content as AgentSessionLogEntryDto['content'],+ createdAt: parsed.createdAt ?? parsed.ts ?? new Date(0).toISOString(),+ direction,+ ...(parsed.userId ? { userId: parsed.userId } : {}),+ });+ }+ return entries;+}++/** A user prompt on its way to the runtime — the frame a turn starts with. */+export function isPromptEntry(entry: AgentSessionLogEntryDto): boolean {+ const content = entry.content as { type?: string; method?: string };+ return (+ entry.direction === 'to_runtime' &&+ content.type === 'acp' &&+ content.method === 'session/prompt'+ );+}diff --git a/apps/web/src/features/block-agent/definition.ts b/apps/web/src/features/block-agent/definition.tsnew file mode 100644index 0000000000..77b0b5fc9d--- /dev/null+++ b/apps/web/src/features/block-agent/definition.ts@@ -0,0 +1,19 @@+import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';+import { ok } from 'neverthrow';+import { lazy } from 'solid-js';++export const definition = defineBlock({+ name: 'agent',+ description: 'View an agent session',+ component: lazy(() => import('./component/Block')),+ liveTrackingEnabled: false,+ async load(source, _intent) {+ if (source.type === 'dss') {+ return ok({ id: source.id });+ }+ return LoadErrors.MISSING;+ },+ accepted: {},+});++export type AgentData = ExtractLoadType<(typeof definition)['load']>;diff --git a/apps/web/src/features/block-agent/state/composer-state.test.ts b/apps/web/src/features/block-agent/state/composer-state.test.tsnew file mode 100644index 0000000000..c7138c39c2--- /dev/null+++ b/apps/web/src/features/block-agent/state/composer-state.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest';+import {+ type ComposerFacts,+ isBusy,+ nextAction,+ type QueuedPrompt,+} from './composer-state';++const prompt = (id: string): QueuedPrompt => ({ id, markdown: `p-${id}` });++const facts = (overrides: Partial<ComposerFacts>): ComposerFacts => ({+ post: { type: 'idle' },+ head: undefined,+ agentWorking: false,+ ...overrides,+});++describe('nextAction: when the head sends', () => {+ it('idle, agent idle, something queued → post the head', () => {+ const action = nextAction(facts({ head: prompt('a') }));+ expect(action).toEqual({ type: 'post_head', prompt: prompt('a') });+ });++ it('nothing queued → hold', () => {+ expect(nextAction(facts({})).type).toBe('hold');+ });+});++describe('nextAction: every hold, by priority', () => {+ it('a post on the wire holds, even with a head and an idle agent', () => {+ const action = nextAction(+ facts({ post: { type: 'posting', promptId: 'a' }, head: prompt('b') })+ );+ expect(action).toMatchObject({+ type: 'hold',+ reason: 'a post is on the wire',+ });+ });++ it('awaiting the turn holds — the drain must not fire into the same turn', () => {+ const action = nextAction(+ facts({+ post: { type: 'awaiting_turn', promptId: 'a' },+ head: prompt('b'),+ })+ );+ expect(action.type).toBe('hold');+ });++ it('a failed head holds everything behind it — order is preserved', () => {+ const action = nextAction(+ facts({ post: { type: 'failed', promptId: 'a' }, head: prompt('a') })+ );+ expect(action.type).toBe('hold');+ });++ it('a running turn holds a queued prompt until it settles', () => {+ const action = nextAction(facts({ head: prompt('a'), agentWorking: true }));+ expect(action).toMatchObject({+ type: 'hold',+ reason: 'the agent is mid-turn',+ });+ });+});++describe('nextAction: the wedges the old machine allowed', () => {+ it('a prompt queued while idle sends — nothing waits for a turn_settled that will never come', () => {+ // Old bug: post_failed returned to idle with the prompt re-queued, but+ // only working+turn_settled ever flushed the queue.+ const action = nextAction(facts({ head: prompt('stranded') }));+ expect(action.type).toBe('post_head');+ });++ it('the decision is memoryless: the same facts always produce the same action', () => {+ const same = facts({ head: prompt('a') });+ expect(nextAction(same)).toEqual(nextAction(same));+ });+});++describe('isBusy', () => {+ it('working, posting, and awaiting_turn are busy', () => {+ expect(isBusy({ type: 'idle' }, true)).toBe(true);+ expect(isBusy({ type: 'posting', promptId: 'a' }, false)).toBe(true);+ expect(isBusy({ type: 'awaiting_turn', promptId: 'a' }, false)).toBe(true);+ });++ it('idle and failed are not — a failure hands the send button back', () => {+ expect(isBusy({ type: 'idle' }, false)).toBe(false);+ expect(isBusy({ type: 'failed', promptId: 'a' }, false)).toBe(false);+ });+});diff --git a/apps/web/src/features/block-agent/state/composer-state.ts b/apps/web/src/features/block-agent/state/composer-state.tsnew file mode 100644index 0000000000..2c4bb4f7ae--- /dev/null+++ b/apps/web/src/features/block-agent/state/composer-state.ts@@ -0,0 +1,96 @@+/**+ * The composer's queue-and-send model, as pure decisions over present facts.+ *+ * The previous machine (`session-state.ts`) accumulated a phase from events+ * (`turn_started`, `post_succeeded`, ...) and could wedge in a phase whose+ * exit event never arrived. This model keeps no event history. Two facts are+ * owned — the prompt queue and the lifecycle of the single in-flight POST —+ * and `nextAction` derives the one thing to do from what is true *right+ * now*. The Solid shell (`context/create-composer-controller.ts`) re-runs it+ * whenever any fact changes, so nothing can get stuck: if a fact changes,+ * the decision changes. This is opencode's followup-drain shape+ * (`pages/session.tsx` — a guard list, not a transition table).+ *+ * Sending is one prompt at a time, head of the queue first. A failed head+ * stays in the queue behind a `failed` latch — visible, retryable, never+ * silently dropped — and holds everything queued behind it so order is+ * preserved.+ */++import { match, P } from 'ts-pattern';++/** A prompt waiting to be sent. Client-minted id, so rows are stable. */+export type QueuedPrompt = {+ id: string;+ markdown: string;+};++/**+ * The lifecycle of the single in-flight POST. At most one prompt is ever on+ * the wire; everything else waits in the queue.+ */+export type PostPhase =+ /** Nothing on the wire. The drain may send the queue's head. */+ | { type: 'idle' }+ /** The head prompt's POST is on the wire. */+ | { type: 'posting'; promptId: string }+ /**+ * The POST was accepted but the fold has not yet shown the turn it+ * starts. Held so the drain does not fire again into the same turn; freed+ * by the fold reporting the turn — or by a timeout, so a turn that never+ * appears cannot wedge the composer.+ */+ | { type: 'awaiting_turn'; promptId: string }+ /**+ * The head prompt's POST failed. It stays at the head of the queue; this+ * latch stops the drain until the user retries, removes it, or sends a+ * new message (which also retries).+ */+ | { type: 'failed'; promptId: string };++/** Everything `nextAction` is allowed to look at. */+export type ComposerFacts = {+ post: PostPhase;+ /** The queue's head — the only prompt that can send next. */+ head: QueuedPrompt | undefined;+ /** The block's one working signal (fold ∧ not disconnected). */+ agentWorking: boolean;+};++export type ComposerAction =+ | { type: 'post_head'; prompt: QueuedPrompt }+ | { type: 'hold'; reason: string };++const hold = (reason: string): ComposerAction => ({ type: 'hold', reason });++/**+ * The drain decision: given the facts, either send the queue's head or name+ * the reason not to. Every guard is one line; the order is the priority.+ */+export function nextAction(facts: ComposerFacts): ComposerAction {+ return match(facts)+ .with({ post: { type: 'posting' } }, () => hold('a post is on the wire'))+ .with({ post: { type: 'awaiting_turn' } }, () =>+ hold('posted; the fold has not shown the turn yet')+ )+ .with({ post: { type: 'failed' } }, () =>+ hold('the head prompt failed; waiting for retry, edit, or a new send')+ )+ .with({ agentWorking: true }, () => hold('the agent is mid-turn'))+ .with({ head: P.select(P.nonNullable) }, (head) => ({+ type: 'post_head' as const,+ prompt: head,+ }))+ .otherwise(() => hold('nothing queued'));+}++/**+ * Whether the stop affordance shows: a turn is running, or a post is in the+ * middle of starting one. A failed post is *not* busy — the user needs the+ * send button back to retry.+ */+export function isBusy(post: PostPhase, agentWorking: boolean): boolean {+ return (+ agentWorking || post.type === 'posting' || post.type === 'awaiting_turn'+ );+}diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.tsnew file mode 100644index 0000000000..1324b20768--- /dev/null+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts@@ -0,0 +1,120 @@+import type {+ FoldedMessage,+ MessagePart,+} from '@service-agent-fold/generated/types';+import { describe, expect, it } from 'vitest';+import {+ activityCounts,+ changedFiles,+ countDiffChanges,+ latestPlan,+} from './session-summary';++function message(turn: number, parts: MessagePart[]): FoldedMessage {+ return {+ agentSessionId: 'session',+ requestId: null,+ turn,+ author: { kind: 'agent' },+ parts,+ stop: null,+ };+}++function edit(+ diffs: { path: string; oldText: string | null; newText: string }[]+): MessagePart {+ return {+ kind: 'tool_use',+ id: `edit-${diffs[0]?.path}`,+ label: 'Edit',+ status: 'completed',+ detail: { kind: 'edit', diffs },+ };+}++function tool(detail: Extract<MessagePart, { kind: 'tool_use' }>['detail']) {+ return {+ kind: 'tool_use' as const,+ id: 'tool',+ label: 'Tool',+ status: 'completed' as const,+ detail,+ };+}++describe('countDiffChanges', () => {+ it('sums added and removed lines across diffs', () => {+ const { additions, deletions } = countDiffChanges([+ { oldText: 'a\nb\n', newText: 'a\nc\nd\n' },+ { oldText: null, newText: 'new\n' },+ ]);+ expect(additions).toBe(3); // c, d, new+ expect(deletions).toBe(1); // b+ });+});++describe('latestPlan', () => {+ it('returns the last plan in the transcript — later plans replace earlier', () => {+ const early: MessagePart = {+ kind: 'plan',+ entries: [{ content: 'old', priority: 'medium', status: 'pending' }],+ };+ const late: MessagePart = {+ kind: 'plan',+ entries: [{ content: 'new', priority: 'high', status: 'in_progress' }],+ };+ const plan = latestPlan([message(0, [early]), message(1, [late])]);+ expect(plan?.[0]?.content).toBe('new');+ });++ it('is undefined when no turn ever produced a plan', () => {+ expect(latestPlan([message(0, [{ kind: 'text', text: 'hi' }])])).toBe(+ undefined+ );+ });+});++describe('changedFiles', () => {+ it('sums stats per path across edits, in first-touched order', () => {+ const messages = [+ message(0, [+ edit([{ path: 'a.ts', oldText: 'x\n', newText: 'x\ny\n' }]),+ edit([{ path: 'b.ts', oldText: null, newText: 'one\ntwo\n' }]),+ ]),+ message(1, [edit([{ path: 'a.ts', oldText: 'y\n', newText: 'z\n' }])]),+ ];+ expect(changedFiles(messages)).toEqual([+ { path: 'a.ts', additions: 2, deletions: 1 },+ { path: 'b.ts', additions: 2, deletions: 0 },+ ]);+ });++ it('ignores non-edit tools', () => {+ const messages = [message(0, [tool({ kind: 'read', paths: ['a.ts'] })])];+ expect(changedFiles(messages)).toEqual([]);+ });+});++describe('activityCounts', () => {+ it('counts tool calls by kind, keeping zero-count items', () => {+ const messages = [+ message(0, [+ tool({ kind: 'read', paths: ['a.ts'] }),+ tool({ kind: 'read', paths: ['b.ts'] }),+ tool({ kind: 'search', paths: [], output: null }),+ tool({ kind: 'terminal', command: 'ls', output: '', exitCode: 0 }),+ ]),+ ];+ const byKey = Object.fromEntries(+ activityCounts(messages).map((item) => [item.key, item.count])+ );+ expect(byKey).toEqual({+ edit: 0,+ read: 2,+ search: 1,+ terminal: 1,+ fetch: 0,+ });+ });+});diff --git a/apps/web/src/features/block-agent/state/session-summary.ts b/apps/web/src/features/block-agent/state/session-summary.tsnew file mode 100644index 0000000000..e944331fef--- /dev/null+++ b/apps/web/src/features/block-agent/state/session-summary.ts@@ -0,0 +1,105 @@+/**+ * Pure derivations over the folded transcript for session-level summaries —+ * what the side panel shows. Everything here is a plain function of+ * `FoldedMessage[]`; the Solid layer wraps calls in memos.+ */++import type {+ FoldedMessage,+ PlanEntry,+} from '@service-agent-fold/generated/types';+import { diffLines } from 'diff';+import type { CountItem } from '../ui';++/** Sum added/removed lines across file diffs for a +/− badge. */+export function countDiffChanges(+ diffs: { oldText?: string | null; newText: string }[]+) {+ let additions = 0;+ let deletions = 0;+ for (const diff of diffs) {+ for (const change of diffLines(diff.oldText ?? '', diff.newText)) {+ if (change.added) additions += change.count ?? 0;+ if (change.removed) deletions += change.count ?? 0;+ }+ }+ return { additions, deletions };+}++/**+ * The agent's current plan: the last `plan` part in the transcript. Plans are+ * carried whole each time, so later ones replace earlier ones.+ */+export function latestPlan(messages: FoldedMessage[]): PlanEntry[] | undefined {+ for (let m = messages.length - 1; m >= 0; m--) {+ const parts = messages[m]!.parts;+ for (let p = parts.length - 1; p >= 0; p--) {+ const part = parts[p]!;+ if (part.kind === 'plan') return part.entries;+ }+ }+ return undefined;+}++export type ChangedFile = {+ path: string;+ additions: number;+ deletions: number;+};++/**+ * Every file the session's edit tools touched, in first-touched order, with+ * line stats summed across all edits of that file.+ */+export function changedFiles(messages: FoldedMessage[]): ChangedFile[] {+ const byPath = new Map<string, ChangedFile>();+ for (const message of messages) {+ for (const part of message.parts) {+ if (part.kind !== 'tool_use' || part.detail.kind !== 'edit') continue;+ for (const diff of part.detail.diffs) {+ const changes = countDiffChanges([diff]);+ const existing = byPath.get(diff.path);+ if (existing) {+ existing.additions += changes.additions;+ existing.deletions += changes.deletions;+ } else {+ byPath.set(diff.path, { path: diff.path, ...changes });+ }+ }+ }+ }+ return [...byPath.values()];+}++/**+ * Tool-call counts by kind, shaped for `ui/CountSummary` ("3 files read,+ * 2 searches"). Zero-count items are included — the summary component slides+ * them in and out as counts move.+ */+export function activityCounts(messages: FoldedMessage[]): CountItem[] {+ const counts = { edit: 0, read: 0, search: 0, terminal: 0, fetch: 0 };+ for (const message of messages) {+ for (const part of message.parts) {+ if (part.kind !== 'tool_use') continue;+ const kind = part.detail.kind;+ if (kind in counts) counts[kind as keyof typeof counts] += 1;+ }+ }+ return [+ {+ key: 'edit',+ count: counts.edit,+ one: 'file edited',+ other: 'files edited',+ },+ { key: 'read', count: counts.read, one: 'file read', other: 'files read' },+ { key: 'search', count: counts.search, one: 'search', other: 'searches' },+ {+ key: 'terminal',+ count: counts.terminal,+ one: 'command',+ other: 'commands',+ },+ { key: 'fetch', count: counts.fetch, one: 'fetch', other: 'fetches' },+ ];+}diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsxnew file mode 100644index 0000000000..233902c491--- /dev/null+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx@@ -0,0 +1,109 @@+/**+ * The agent block's composer: the chat input's look and its markdown editing+ * surface (`MarkdownShell` over a lean `EditorConfigBuilder`), without the+ * rest of `ChatInput`'s machinery — no mentions, attachments, upload queue,+ * model plumbing, or contexts. Visual chrome mirrors+ * `@core/component/AI/component/input/ChatInput.tsx`.+ */++import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';+import { Button, SendButton, Surface } from '@ui';+import { createSignal, Show } from 'solid-js';++export interface AgentInputProps {+ placeholder?: string;+ /** The agent is working: the send button becomes a stop square. */+ busy?: boolean;+ disabled?: boolean;+ autofocus?: boolean;+ /** Receives the composed markdown. */+ onSend: (markdown: string) => void;+ onStop?: () => void;+}++/** Past this height the controls drop below the text instead of overlaying it. */+const SINGLE_LINE_HEIGHT = 40;++export function AgentInput(props: AgentInputProps) {+ const [markdown, setMarkdown] = createSignal('');+ let bodyRef: HTMLDivElement | undefined;++ // Sending while busy is allowed — the block queues prompts and flushes+ // them when the running turn settles.+ const canSend = () => markdown().trim().length > 0 && !props.disabled;++ // Same content-driven switch as ChatInput: once the editor body wraps past+ // one line, the send button stops overlaying the text and sits below it.+ const isMultiline = () => {+ if (markdown().trim().length === 0) return false;+ if (!bodyRef) return false;+ return bodyRef.scrollHeight > SINGLE_LINE_HEIGHT;+ };++ const send = () => {+ if (!canSend()) return;+ const content = markdown().trim();+ editor.controls.clear();+ props.onSend(content);+ };++ const editor = buildConfig('chat')+ .namespace('agent-input')+ .withEmojis()+ .withLinks({ floatingMenu: true, autoLinkMatchMode: 'common-tlds' })+ .withHistory({ timeGap: 400 })+ .withCode()+ .withRestoreFocus()+ .onEnter(() => {+ send();+ return true;+ })+ .onChange(setMarkdown);++ return (+ <Surface class="rounded-xl" depth={2} solid>+ <div class="relative px-2 py-1.5">+ {/* No vertical padding of its own: the shell is min-h-8 and editor+ paragraphs carry my-1.5, so the row's py-1.5 is the whole frame —+ the same 44px single-line height as ChatInput. */}+ <div+ ref={bodyRef}+ class="pl-1 text-sm text-ink"+ classList={{+ 'pr-10': !isMultiline(),+ 'pb-8': isMultiline(),+ // While empty only the placeholder renders; keep it to one clipped+ // line so it doesn't wrap into the single-line height.+ 'overflow-hidden whitespace-nowrap': markdown().trim().length === 0,+ }}+ >+ <MarkdownShell+ config={editor}+ placeholder={props.placeholder ?? 'Message the agent'}+ autofocus={props.autofocus}+ />+ </div>++ <div class="absolute right-1.5 bottom-1.5">+ <Show+ when={props.busy && props.onStop}+ fallback={+ <SendButton tooltip="Send" disabled={!canSend()} onClick={send} />+ }+ >+ <Button+ variant="ghost"+ size="icon-sm"+ label="Stop"+ onClick={() => props.onStop?.()}+ class="rounded-[11px] size-7.5 text-ink-extra-muted not-disabled:bg-ink/5 not-disabled:hover:bg-ink/10"+ >+ <div class="size-3.5 rounded-sm bg-current" />+ </Button>+ </Show>+ </div>+ </div>+ </Surface>+ );+}diff --git a/apps/web/src/features/block-agent/ui/AnimatedNumber.tsx b/apps/web/src/features/block-agent/ui/AnimatedNumber.tsxnew file mode 100644index 0000000000..fa6ddcb0ae--- /dev/null+++ b/apps/web/src/features/block-agent/ui/AnimatedNumber.tsx@@ -0,0 +1,129 @@+/**+ * Odometer-style rolling number: each digit rides a vertical strip that spins+ * to its new value when the number changes.+ *+ * Ported from opencode's `animated-number.tsx` / `animated-number.css`+ * (github.com/sst/opencode, MIT © 2025 opencode), restyled with Tailwind+ * utilities in place of the original CSS file.+ */+import { createEffect, createMemo, For, Index, on } from 'solid-js';+import { createStore } from 'solid-js/store';++/**+ * Three copies of 0-9 so a strip can overshoot in either direction before the+ * transition-end handler snaps it back to the middle copy.+ */+const TRACK = Array.from({ length: 30 }, (_, index) => index % 10);++/** Map an arbitrary strip position back onto its digit (0-9). */+function normalize(value: number): number {+ return ((value % 10) + 10) % 10;+}++/** How many cells to travel from one digit to another in a fixed direction. */+function spin(from: number, to: number, direction: 1 | -1): number {+ if (from === to) return 0;+ if (direction > 0) return (to - from + 10) % 10;+ return -((from - to + 10) % 10);+}++function Digit(props: { value: number; direction: 1 | -1 }) {+ // Start on the middle copy of the track.+ const [state, setState] = createStore({+ step: props.value + 10,+ animating: false,+ });+ let last = props.value;++ createEffect(+ on(+ () => props.value,+ (next) => {+ const delta = spin(last, next, props.direction);+ last = next;+ if (!delta) {+ setState({ animating: false, step: next + 10 });+ return;+ }++ setState('animating', true);+ setState('step', (value) => value + delta);+ },+ { defer: true }+ )+ );++ return (+ <span class="inline-block h-[1em] w-[1ch] overflow-hidden align-baseline leading-[1em] [mask-image:linear-gradient(to_bottom,transparent_0%,#000_18%,#000_82%,transparent_100%)]">+ <span+ class="inline-flex translate-y-[calc(var(--roll-offset)*-1em)] flex-col transition-transform duration-[600ms] ease-[cubic-bezier(0.22,1,0.36,1)] data-[animating=false]:duration-0 motion-reduce:duration-0"+ data-animating={state.animating ? 'true' : 'false'}+ style={{ '--roll-offset': `${state.step}` }}+ onTransitionEnd={() => {+ // Snap back (without animating) to the equivalent middle-copy cell.+ setState('animating', false);+ setState('step', (value) => normalize(value) + 10);+ }}+ >+ <For each={TRACK}>+ {(digit) => (+ <span class="inline-flex h-[1em] w-[1ch] items-center justify-center leading-[1em]">+ {digit}+ </span>+ )}+ </For>+ </span>+ </span>+ );+}++/** A non-negative integer that rolls odometer-style when its value changes. */+export function AnimatedNumber(props: { value: number; class?: string }) {+ const target = createMemo(() => {+ if (!Number.isFinite(props.value)) return 0;+ return Math.max(0, Math.round(props.value));+ });++ const [state, setState] = createStore({+ value: target(),+ direction: 1 as 1 | -1,+ });++ createEffect(+ on(+ target,+ (next) => {+ if (next === state.value) return;+ setState({ direction: next > state.value ? 1 : -1, value: next });+ },+ { defer: true }+ )+ );++ const label = createMemo(() => state.value.toString());+ // Least-significant digit first; rendered row-reverse so digit identity is+ // stable when the number grows or shrinks a place.+ const digits = createMemo(() =>+ Array.from(label(), (char) => {+ const code = char.charCodeAt(0) - 48;+ if (code < 0 || code > 9) return 0;+ return code;+ }).reverse()+ );++ return (+ <span+ class={`inline-flex items-baseline align-baseline tabular-nums ${props.class ?? ''}`}+ aria-label={label()}+ >+ <span+ class="inline-flex w-[var(--num-width)] flex-row-reverse items-baseline justify-end overflow-hidden transition-[width] duration-[560ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:duration-0"+ style={{ '--num-width': `${digits().length}ch` }}+ >+ <Index each={digits()}>+ {(digit) => <Digit value={digit()} direction={state.direction} />}+ </Index>+ </span>+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/ui/CountSummary.tsx b/apps/web/src/features/block-agent/ui/CountSummary.tsxnew file mode 100644index 0000000000..7c9b2366b9--- /dev/null+++ b/apps/web/src/features/block-agent/ui/CountSummary.tsx@@ -0,0 +1,151 @@+/**+ * A running summary line like "3 files read, 2 searches": each count rolls+ * via {@link AnimatedNumber}, items slide in/out as their counts hit zero, and+ * plural suffixes ("search" → "searches") animate where the words allow it.+ *+ * Ported from opencode's `tool-count-summary.tsx` (`AnimatedCountList`) and+ * `tool-count-label.tsx` (`AnimatedCountLabel`) (github.com/sst/opencode,+ * MIT © 2025 opencode). The original `{{count}}` template interpolation is+ * simplified to `${count} ${count === 1 ? one : other}` composition, and the+ * CSS files are replaced with Tailwind utilities.+ */+import { createMemo, Index, Show } from 'solid-js';+import { AnimatedNumber } from './AnimatedNumber';++/** One countable thing, with its singular and plural labels. */+export interface CountItem {+ /** Stable identity for the item across re-renders. */+ key: string;+ count: number;+ /** Label when count is exactly 1, e.g. "file read". */+ one: string;+ /** Label otherwise, e.g. "files read". */+ other: string;+}++const EASE = 'ease-[cubic-bezier(0.22,1,0.36,1)]';++/** Grid-column reveal: width, opacity, blur, and a small settle transform. */+const REVEAL =+ `inline-grid origin-left translate-y-[0.06em] scale-[0.985] items-baseline overflow-hidden opacity-0 blur-[2px] [grid-template-columns:0fr] transition-[grid-template-columns,opacity,filter,transform] duration-300 ${EASE} ` ++ 'data-[active=true]:translate-y-0 data-[active=true]:scale-100 data-[active=true]:opacity-100 data-[active=true]:blur-none data-[active=true]:[grid-template-columns:1fr] motion-reduce:transition-none';++/** The ", " between visible items, revealed by max-width. */+const SEPARATOR =+ 'inline-flex max-w-0 -translate-x-[0.08em] items-baseline overflow-hidden opacity-0 transition-[max-width,margin,opacity,transform] duration-200 ease-out ' ++ 'data-[active=true]:mr-[0.45ch] data-[active=true]:max-w-[1ch] data-[active=true]:translate-x-0 data-[active=true]:opacity-100 motion-reduce:transition-none';++/** The animated plural suffix inside a label. */+const SUFFIX =+ `inline-grid -translate-x-[0.04em] overflow-hidden opacity-0 blur-[1px] [grid-template-columns:0fr] transition-[grid-template-columns,opacity,filter,transform] duration-[250ms] ${EASE} ` ++ 'data-[active=true]:translate-x-0 data-[active=true]:opacity-100 data-[active=true]:blur-none data-[active=true]:[grid-template-columns:1fr] motion-reduce:transition-none';++/** Split two labels into their shared stem and the diverging tails. */+function splitWords(one: string, other: string) {+ const a = Array.from(one);+ const b = Array.from(other);+ let i = 0;+ while (i < a.length && i < b.length && a[i] === b[i]) i++;+ return {+ stem: a.slice(0, i).join(''),+ oneTail: a.slice(i).join(''),+ otherTail: b.slice(i).join(''),+ };+}++/**+ * "3 searches" with the count rolling and, when one label is a prefix of the+ * other, the extra letters sliding in and out on pluralization. Labels that+ * diverge mid-word ("file read" / "files read") swap without animating.+ */+function CountLabel(props: { count: number; one: string; other: string }) {+ const singular = createMemo(() => Math.round(props.count) === 1);+ const parts = createMemo(() => splitWords(props.one, props.other));+ const animatable = createMemo(+ () => parts().oneTail === '' || parts().otherTail === ''+ );+ // The one non-empty tail (constant text, so it can animate out gracefully).+ const tail = createMemo(() => parts().oneTail || parts().otherTail);+ const showTail = createMemo(() =>+ singular() ? parts().oneTail !== '' : parts().otherTail !== ''+ );++ return (+ <span class="inline-flex items-baseline whitespace-pre">+ <AnimatedNumber value={props.count} />+ <Show+ when={animatable()}+ fallback={+ <span class="whitespace-pre">{` ${+ singular() ? props.one : props.other+ }`}</span>+ }+ >+ <span class="whitespace-pre">{` ${parts().stem}`}</span>+ <span class={SUFFIX} data-active={showTail() ? 'true' : 'false'}>+ <span class="min-w-0 overflow-hidden whitespace-pre">{tail()}</span>+ </span>+ </Show>+ </span>+ );+}++/**+ * The summary line. Items with a zero count collapse away (they stay mounted+ * so they can animate back in); when nothing is visible the `fallback` text+ * shows instead.+ */+export function CountSummary(props: {+ items: CountItem[];+ fallback?: string;+ class?: string;+}) {+ const fallback = createMemo(() => props.fallback ?? '');+ const showEmpty = createMemo(+ () => props.items.every((item) => item.count <= 0) && fallback().length > 0+ );++ return (+ <span+ class={`inline-flex items-baseline whitespace-nowrap ${props.class ?? ''}`}+ >+ <span class={REVEAL} data-active={showEmpty() ? 'true' : 'false'}>+ <span class="min-w-0 overflow-hidden whitespace-nowrap">+ {fallback()}+ </span>+ </span>++ <Index each={props.items}>+ {(item, index) => {+ const active = createMemo(() => item().count > 0);+ const hasPrev = createMemo(() => {+ for (let i = index - 1; i >= 0; i--) {+ if (props.items[i].count > 0) return true;+ }+ return false;+ });++ return (+ <>+ <span+ class={SEPARATOR}+ data-active={active() && hasPrev() ? 'true' : 'false'}+ >+ ,+ </span>+ <span class={REVEAL} data-active={active() ? 'true' : 'false'}>+ <span class="inline-flex min-w-0 items-baseline overflow-hidden whitespace-nowrap">+ <CountLabel+ one={item().one}+ other={item().other}+ count={Math.max(0, Math.round(item().count))}+ />+ </span>+ </span>+ </>+ );+ }}+ </Index>+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/ui/DiffChanges.tsx b/apps/web/src/features/block-agent/ui/DiffChanges.tsxnew file mode 100644index 0000000000..5c656d42cd--- /dev/null+++ b/apps/web/src/features/block-agent/ui/DiffChanges.tsx@@ -0,0 +1,115 @@+/**+ * Additions/deletions badge for a diff: "+18 −6" by default, or a GitHub-style+ * five-block proportional bar with the `bars` variant.+ *+ * Port of opencode's diff-changes — github.com/sst/opencode, MIT © 2025+ * opencode — adapted to Macro tokens and Tailwind.+ */++import { createMemo, For, Match, Show, Switch } from 'solid-js';++const TOTAL_BLOCKS = 5;++export interface DiffChangesProps {+ additions: number;+ deletions: number;+ variant?: 'default' | 'bars';+ class?: string;+}++/**+ * How many of the five bar blocks to paint green / red / neutral, roughly+ * proportional to the diff but capped so tiny diffs never look sweeping.+ */+function blockCounts(adds: number, dels: number) {+ if (adds === 0 && dels === 0) {+ return { added: 0, deleted: 0, neutral: TOTAL_BLOCKS };+ }++ const total = adds + dels;++ if (total < 5) {+ const added = adds > 0 ? 1 : 0;+ const deleted = dels > 0 ? 1 : 0;+ return { added, deleted, neutral: TOTAL_BLOCKS - added - deleted };+ }++ const ratio = adds > dels ? adds / dels : dels / adds;+ let blocksForColors = TOTAL_BLOCKS;++ if (total < 20) {+ blocksForColors = TOTAL_BLOCKS - 1;+ } else if (ratio < 4) {+ blocksForColors = TOTAL_BLOCKS - 1;+ }++ const addedRaw = (adds / total) * blocksForColors;+ const deletedRaw = (dels / total) * blocksForColors;++ let added = adds > 0 ? Math.max(1, Math.round(addedRaw)) : 0;+ let deleted = dels > 0 ? Math.max(1, Math.round(deletedRaw)) : 0;++ // Cap bars based on actual change magnitude.+ if (adds > 0 && adds <= 5) added = Math.min(added, 1);+ if (adds > 5 && adds <= 10) added = Math.min(added, 2);+ if (dels > 0 && dels <= 5) deleted = Math.min(deleted, 1);+ if (dels > 5 && dels <= 10) deleted = Math.min(deleted, 2);++ if (added + deleted > blocksForColors) {+ if (addedRaw > deletedRaw) {+ added = blocksForColors - deleted;+ } else {+ deleted = blocksForColors - added;+ }+ }++ const neutral = Math.max(0, TOTAL_BLOCKS - added - deleted);++ return { added, deleted, neutral };+}++export function DiffChanges(props: DiffChangesProps) {+ const variant = () => props.variant ?? 'default';+ const total = () => props.additions + props.deletions;++ /** Fill class per bar block: additions, then deletions, then neutral. */+ const blocks = createMemo(() => {+ const counts = blockCounts(props.additions, props.deletions);+ return [+ ...Array<string>(counts.added).fill('fill-success'),+ ...Array<string>(counts.deleted).fill('fill-failure'),+ ...Array<string>(counts.neutral).fill('fill-ink-placeholder'),+ ].slice(0, TOTAL_BLOCKS);+ });++ return (+ <Show when={variant() === 'bars' || total() > 0}>+ <div+ class="flex shrink-0 items-center gap-2"+ classList={{ [props.class ?? '']: !!props.class }}+ >+ <Switch>+ <Match when={variant() === 'bars'}>+ <svg+ class="block h-3.5 w-[18px]"+ viewBox="0 0 18 14"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ >+ <For each={blocks()}>+ {(fill, i) => (+ <rect x={i() * 4} width="2" height="14" rx="1" class={fill} />+ )}+ </For>+ </svg>+ </Match>+ <Match when={variant() === 'default'}>+ <span class="font-mono tabular-nums text-success">{`+${props.additions}`}</span>+ <span class="font-mono tabular-nums text-failure">{`−${props.deletions}`}</span>+ </Match>+ </Switch>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/block-agent/ui/FoldedAnsiText.tsx b/apps/web/src/features/block-agent/ui/FoldedAnsiText.tsxnew file mode 100644index 0000000000..a67697e2dc--- /dev/null+++ b/apps/web/src/features/block-agent/ui/FoldedAnsiText.tsx@@ -0,0 +1,105 @@+import { createMemo, For } from 'solid-js';++/** One run of text sharing the same SGR styling. */+interface AnsiSegment {+ text: string;+ fg?: string;+ bold?: boolean;+ dim?: boolean;+}++/** Any CSI sequence, not just SGR - so cursor-movement codes strip too. */+// biome-ignore lint/suspicious/noControlCharactersInRegex: matching ESC (0x1b) is the point+const CSI_PATTERN = /\x1b\[([0-9;]*)([A-Za-z])/g;++/**+ * Standard 16-color ANSI foreground palette. Deliberately fixed rather than+ * drawn from Macro's own semantic tokens (accent/success/failure/...): a+ * tool colored its output on purpose, and that palette means something+ * different from Macro's UI palette - conflating them would misrepresent+ * what the tool actually printed.+ */+const FG_COLORS: Record<number, string> = {+ 30: '#5c5c5c',+ 31: '#e5484d',+ 32: '#30a46c',+ 33: '#f5a623',+ 34: '#3b82f6',+ 35: '#d6409f',+ 36: '#12a4ac',+ 37: '#e5e5e5',+ 90: '#6b7280',+ 91: '#f87171',+ 92: '#4ade80',+ 93: '#fbbf24',+ 94: '#60a5fa',+ 95: '#e879f9',+ 96: '#22d3ee',+ 97: '#ffffff',+};++/**+ * Split ANSI-escaped text into styled runs.+ *+ * Only SGR color/weight codes (0, 1, 2, 22, 39, 30-37, 90-97) affect output;+ * every other CSI sequence (cursor movement, screen clearing) is stripped+ * without effect, since this renders a static log rather than a live+ * terminal.+ */+function parseAnsi(input: string): AnsiSegment[] {+ const segments: AnsiSegment[] = [];+ let fg: string | undefined;+ let bold = false;+ let dim = false;+ let lastIndex = 0;++ for (const match of input.matchAll(CSI_PATTERN)) {+ const text = input.slice(lastIndex, match.index);+ if (text) segments.push({ text, fg, bold, dim });+ lastIndex = match.index + match[0].length;++ if (match[2] !== 'm') continue;+ const codes = match[1].length ? match[1].split(';').map(Number) : [0];+ for (const code of codes) {+ if (code === 0) {+ fg = undefined;+ bold = false;+ dim = false;+ } else if (code === 1) bold = true;+ else if (code === 2) dim = true;+ else if (code === 22) {+ bold = false;+ dim = false;+ } else if (code === 39) fg = undefined;+ else if (code in FG_COLORS) fg = FG_COLORS[code];+ }+ }++ const rest = input.slice(lastIndex);+ if (rest) segments.push({ text: rest, fg, bold, dim });+ return segments;+}++/**+ * Renders ANSI-colored terminal output as styled spans, never `innerHTML` -+ * every segment's text is a plain child, so this is safe over untrusted+ * agent/tool output the same way any other text interpolation is.+ */+export function FoldedAnsiText(props: { text: string }) {+ const segments = createMemo(() => parseAnsi(props.text));+ return (+ <For each={segments()}>+ {(segment) => (+ <span+ style={{+ color: segment.fg,+ 'font-weight': segment.bold ? 600 : undefined,+ opacity: segment.dim ? 0.6 : undefined,+ }}+ >+ {segment.text}+ </span>+ )}+ </For>+ );+}diff --git a/apps/web/src/features/block-agent/ui/FoldedOutput.tsx b/apps/web/src/features/block-agent/ui/FoldedOutput.tsxnew file mode 100644index 0000000000..6d4d18fec1--- /dev/null+++ b/apps/web/src/features/block-agent/ui/FoldedOutput.tsx@@ -0,0 +1,8 @@+/** Free-form text a tool call reported - a search hit, a fetched page, a raw fallback. */+export function FoldedOutput(props: { text: string }) {+ return (+ <pre class="overflow-x-auto rounded bg-surface p-2 font-mono text-xs whitespace-pre-wrap text-ink-muted wrap-break-word">+ {props.text}+ </pre>+ );+}diff --git a/apps/web/src/features/block-agent/ui/FoldedPathList.tsx b/apps/web/src/features/block-agent/ui/FoldedPathList.tsxnew file mode 100644index 0000000000..37664091bf--- /dev/null+++ b/apps/web/src/features/block-agent/ui/FoldedPathList.tsx@@ -0,0 +1,18 @@+import { Tool } from '@core/component/AI/component/tool/Tool';+import FileText from '@phosphor/file-text.svg';+import { For } from 'solid-js';++/** The full path list behind a truncated inline summary. */+export function FoldedPathList(props: { paths: string[] }) {+ return (+ <Tool.List>+ <For each={props.paths}>+ {(path) => (+ <Tool.ListItem icon={<FileText class="size-4" />}>+ <span class="truncate font-mono text-xs">{path}</span>+ </Tool.ListItem>+ )}+ </For>+ </Tool.List>+ );+}diff --git a/apps/web/src/features/block-agent/ui/FoldedTerminal.tsx b/apps/web/src/features/block-agent/ui/FoldedTerminal.tsxnew file mode 100644index 0000000000..7bce95895c--- /dev/null+++ b/apps/web/src/features/block-agent/ui/FoldedTerminal.tsx@@ -0,0 +1,19 @@+import { Show } from 'solid-js';+import { FoldedAnsiText } from './FoldedAnsiText';++/** A terminal call's output, ANSI-colored, plus its exit code when it failed. */+export function FoldedTerminal(props: {+ output: string;+ exitCode?: number | null;+}) {+ return (+ <div class="flex flex-col gap-1">+ <Show when={props.exitCode != null && props.exitCode !== 0}>+ <span class="text-xs text-failure">Exit code {props.exitCode}</span>+ </Show>+ <pre class="overflow-x-auto rounded bg-surface p-2 font-mono text-xs whitespace-pre-wrap text-ink-muted wrap-break-word">+ <FoldedAnsiText text={props.output} />+ </pre>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/PierreDiff.tsx b/apps/web/src/features/block-agent/ui/PierreDiff.tsxnew file mode 100644index 0000000000..f79fb2a316--- /dev/null+++ b/apps/web/src/features/block-agent/ui/PierreDiff.tsx@@ -0,0 +1,217 @@+/**+ * Syntax-highlighted file diffs rendered with @pierre/diffs.+ *+ * Pure component: props in, JSX out. Each file gets a path header and a+ * unified diff rendered by pierre's vanilla `FileDiff` component, which+ * mounts a `<diffs-container>` custom element (shadow DOM) inside our+ * wrapper div and computes the diff from full before/after contents.+ *+ * Choices, for the record:+ * - Entry point: `FileDiff.render({ oldFile, newFile })` — takes raw+ * before/after contents directly (`oldFile: null` marks a new file),+ * matching our wire shape. No patch parsing on our side.+ * - No worker pool: pierre renders fine on the main thread via its shared+ * shiki highlighter (JS regex engine, no wasm fetch). Tradeoff: shiki+ * tokenization of big files runs on the main thread; the+ * MAX_RENDER_LINES fallback bounds that cost. Wire a WorkerPoolManager+ * (see opencode's pierre/worker.ts) only if profiling demands it.+ * - Theme: pierre's built-in `pierre-light`/`pierre-dark` pair (its+ * default). Macro flags dark mode via `html[data-theme-light="false"]`+ * (see features/theme/signals/themeReactive.ts), so we watch that+ * attribute and drive `setThemeType('light' | 'dark')` explicitly+ * instead of pierre's OS-preference "system" mode.+ */++import {+ type FileDiffOptions,+ FileDiff as PierreFileDiffInstance,+ type ThemeTypes,+} from '@pierre/diffs';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ type JSX,+ onCleanup,+ Show,+ untrack,+} from 'solid-js';+import type { FileDiff } from './types';++/**+ * Files whose before or after side exceeds this many lines get a plain+ * placeholder instead of a rendered diff, keeping main-thread highlighting+ * cost bounded.+ */+const MAX_RENDER_LINES = 2000;++/** Options for pierre's diff instance: static, unified, header-less. */+const DIFF_OPTIONS = {+ diffStyle: 'unified',+ diffIndicators: 'bars',+ // We render our own path header per file.+ disableFileHeader: true,+ overflow: 'wrap',+ hunkSeparators: 'line-info-basic',+ lineDiffType: 'none',+ expansionLineCount: 20,+} satisfies FileDiffOptions<undefined>;++/**+ * CSS variables pierre reads inside its shadow DOM, pointed at Macro's+ * typography tokens so the diff matches surrounding font-mono text-xs UI.+ */+const DIFF_STYLE_VARIABLES: JSX.CSSProperties = {+ '--diffs-font-family': 'var(--font-mono)',+ '--diffs-font-size': '0.75rem',+ '--diffs-line-height': '18px',+ '--diffs-tab-size': '2',+ '--diffs-gap-block': '0',+ '--diffs-min-number-column-width': '4ch',+};++function currentThemeType(): 'light' | 'dark' {+ return document.documentElement.dataset.themeLight === 'false'+ ? 'dark'+ : 'light';+}++/**+ * Macro's light/dark state as a signal, tracked off the+ * `data-theme-light` attribute the theme feature keeps on `<html>`.+ */+function createThemeType(): () => 'light' | 'dark' {+ const [themeType, setThemeType] = createSignal(currentThemeType());+ const observer = new MutationObserver(() => setThemeType(currentThemeType()));+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['data-theme-light'],+ });+ onCleanup(() => observer.disconnect());+ return themeType;+}++function lineCount(text: string): number {+ if (text.length === 0) return 0;+ return text.split('\n').length;+}++/** Plain note shown in place of a diff body. */+function DiffNote(props: { children: JSX.Element }) {+ return (+ <div class="rounded border border-edge-muted px-3 py-2 font-mono text-xs text-ink-muted">+ {props.children}+ </div>+ );+}++/** Mounts one pierre diff instance for a single file. */+function PierreFileView(props: {+ diff: FileDiff;+ themeType: () => 'light' | 'dark';+}) {+ let container!: HTMLDivElement;+ let instance: PierreFileDiffInstance | undefined;+ const [failed, setFailed] = createSignal(false);++ onCleanup(() => {+ instance?.cleanUp();+ instance = undefined;+ });++ // Content: (re)render whenever the file's path or texts change.+ createEffect(() => {+ if (failed()) return;+ const name = props.diff.path;+ const oldText = props.diff.oldText;+ const newText = props.diff.newText;+ try {+ instance ??= new PierreFileDiffInstance({+ ...DIFF_OPTIONS,+ themeType: untrack(props.themeType) satisfies ThemeTypes,+ });+ instance.render({+ // `== null` deliberately: the wire declares `oldText: string | null`,+ // but crossing the WASM boundary serde turns `None` into `undefined`.+ oldFile: oldText == null ? null : { name, contents: oldText },+ newFile: { name, contents: newText },+ containerWrapper: container,+ });+ } catch (error) {+ // Pierre throws on inputs it cannot diff (e.g. identical contents+ // slipping through); degrade to a note rather than a broken card.+ console.error('[pierre-diff] render failed', {+ path: props.diff.path,+ newFile: oldText === null,+ error,+ });+ instance?.cleanUp();+ instance = undefined;+ setFailed(true);+ }+ });++ // Theme: flip pierre's light/dark styles alongside Macro's theme.+ createEffect(() => {+ const themeType = props.themeType();+ instance?.setThemeType(themeType);+ });++ return (+ <Show+ when={!failed()}+ fallback={<DiffNote>diff could not be rendered</DiffNote>}+ >+ <div+ ref={container}+ class="overflow-hidden rounded border border-edge-muted"+ style={DIFF_STYLE_VARIABLES}+ />+ </Show>+ );+}++/** One file's block: path header plus diff body (or a size fallback). */+function FileDiffBlock(props: {+ diff: FileDiff;+ themeType: () => 'light' | 'dark';+}) {+ const longestSide = createMemo(() =>+ Math.max(lineCount(props.diff.oldText ?? ''), lineCount(props.diff.newText))+ );++ return (+ <div class="flex flex-col gap-1">+ <span class="truncate font-mono text-xs text-ink-extra-muted">+ {props.diff.path}+ </span>+ <Show+ when={longestSide() <= MAX_RENDER_LINES}+ fallback={+ <DiffNote>+ large diff ({longestSide().toLocaleString()} lines)+ </DiffNote>+ }+ >+ <PierreFileView diff={props.diff} themeType={props.themeType} />+ </Show>+ </div>+ );+}++/**+ * Renders each file's before/after contents as a syntax-highlighted+ * unified diff, one block per file.+ */+export function PierreDiff(props: { diffs: FileDiff[] }): JSX.Element {+ const themeType = createThemeType();++ return (+ <div class="flex flex-col gap-2">+ <For each={props.diffs}>+ {(diff) => <FileDiffBlock diff={diff} themeType={themeType} />}+ </For>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/QuestionAnswers.tsx b/apps/web/src/features/block-agent/ui/QuestionAnswers.tsxnew file mode 100644index 0000000000..a41f80df20--- /dev/null+++ b/apps/web/src/features/block-agent/ui/QuestionAnswers.tsx@@ -0,0 +1,36 @@+/**+ * Body of a "question" tool call: each question the agent asked, with the+ * answer(s) the user chose underneath. Body-only — the caller supplies the+ * card chrome.+ *+ * Port of the question renderer from opencode's message-part.tsx —+ * github.com/sst/opencode, MIT © 2025 opencode — adapted to Macro tokens.+ */++import { For } from 'solid-js';+import type { AnsweredQuestion } from './types';++export interface QuestionAnswersProps {+ questions: AnsweredQuestion[];+}++export function QuestionAnswers(props: QuestionAnswersProps) {+ return (+ <div class="flex flex-col gap-3 py-1">+ <For each={props.questions}>+ {(item) => (+ <div class="flex min-w-0 flex-col gap-0.5">+ <div class="text-xs text-ink-muted">{item.question}</div>+ <div class="text-sm text-ink wrap-break-word">+ {item.answers.length > 0 ? (+ item.answers.join(', ')+ ) : (+ <span class="text-ink-placeholder">No answer</span>+ )}+ </div>+ </div>+ )}+ </For>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/QueuedPromptList.tsx b/apps/web/src/features/block-agent/ui/QueuedPromptList.tsxnew file mode 100644index 0000000000..d856ee9f95--- /dev/null+++ b/apps/web/src/features/block-agent/ui/QueuedPromptList.tsx@@ -0,0 +1,78 @@+/**+ * Prompts waiting to be sent, shown above the composer so a queued message+ * is never invisible: the user can see it, remove it, and — when the send+ * failed — retry it. Pure component: props in, JSX out.+ */++import ArrowClockwise from '@phosphor/arrow-clockwise.svg';+import X from '@phosphor/x.svg';+import { Button } from '@ui';+import { For, Show } from 'solid-js';++export interface QueuedPromptListProps {+ prompts: { id: string; markdown: string }[];+ /** The prompt currently on the wire — its row reads "Sending". */+ sendingId?: string;+ /** The head prompt failed to send — its row reads "Failed" with a retry. */+ failed?: boolean;+ onRetry?: () => void;+ onRemove?: (id: string) => void;+}++/** The first non-empty line, for a one-line preview of a markdown prompt. */+function firstLine(markdown: string): string {+ return (+ markdown+ .split('\n')+ .map((line) => line.trim())+ .find((line) => line.length > 0) ?? markdown+ );+}++export function QueuedPromptList(props: QueuedPromptListProps) {+ return (+ <Show when={props.prompts.length > 0}>+ <div class="flex flex-col gap-1 pb-2">+ <For each={props.prompts}>+ {(prompt, index) => {+ const failed = () => props.failed === true && index() === 0;+ const sending = () => props.sendingId === prompt.id;+ return (+ <div class="flex items-center gap-2 rounded-lg border border-edge-muted bg-hover px-3 py-1.5 text-sm">+ <span class="min-w-0 flex-1 truncate text-ink-muted">+ {firstLine(prompt.markdown)}+ </span>+ <Show when={sending()}>+ <span class="shrink-0 text-xs text-ink-extra-muted">+ Sending+ </span>+ </Show>+ <Show when={failed()}>+ <span class="shrink-0 text-xs text-ink">Failed</span>+ <Button+ variant="ghost"+ size="icon-xs"+ label="Retry"+ onClick={() => props.onRetry?.()}+ >+ <ArrowClockwise />+ </Button>+ </Show>+ <Show when={!sending()}>+ <Button+ variant="ghost"+ size="icon-xs"+ label="Remove"+ onClick={() => props.onRemove?.(prompt.id)}+ >+ <X />+ </Button>+ </Show>+ </div>+ );+ }}+ </For>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/block-agent/ui/SessionStatusPill.tsx b/apps/web/src/features/block-agent/ui/SessionStatusPill.tsxnew file mode 100644index 0000000000..53c3543ebb--- /dev/null+++ b/apps/web/src/features/block-agent/ui/SessionStatusPill.tsx@@ -0,0 +1,63 @@+/**+ * The session's status as a quiet dot + label pill. Pure: the status shape+ * mirrors the wire's `SessionStatusDto`.+ */++import { match } from 'ts-pattern';++export type SessionStatusLike =+ | { kind: 'no_messages' }+ | { kind: 'event'; event: string }+ | { kind: 'disconnected' };++type Presentation = {+ label: string;+ tone: 'positive' | 'neutral' | 'negative';+};++/** `worktree_ready` → `Worktree ready`. */+function prettyEventName(event: string): string {+ const words = event.split(/[_-]/).filter(Boolean).join(' ');+ return words.charAt(0).toUpperCase() + words.slice(1);+}++function presentation(status: SessionStatusLike): Presentation {+ return match(status)+ .with({ kind: 'no_messages' }, (): Presentation => {+ return { label: 'Starting', tone: 'neutral' };+ })+ .with({ kind: 'disconnected' }, (): Presentation => {+ return { label: 'Disconnected', tone: 'negative' };+ })+ .with({ kind: 'event' }, (status): Presentation => {+ if (status.event === 'acp_ready') {+ return { label: 'Ready', tone: 'positive' };+ }+ if (status.event === 'disconnected') {+ return { label: 'Disconnected', tone: 'negative' };+ }+ // An event name the protocol doesn't model yet — show it rather than+ // hide it.+ return { label: prettyEventName(status.event), tone: 'neutral' };+ })+ .exhaustive();+}++export function SessionStatusPill(props: { status: SessionStatusLike }) {+ const current = () => presentation(props.status);++ return (+ <span class="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-edge-muted px-2 py-0.5 text-xs text-ink-muted">+ <span+ aria-hidden="true"+ class="size-1.5 rounded-full"+ classList={{+ 'bg-success': current().tone === 'positive',+ 'bg-ink-placeholder': current().tone === 'neutral',+ 'bg-failure': current().tone === 'negative',+ }}+ />+ {current().label}+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/ui/TextShimmer.tsx b/apps/web/src/features/block-agent/ui/TextShimmer.tsxnew file mode 100644index 0000000000..0af920a6d5--- /dev/null+++ b/apps/web/src/features/block-agent/ui/TextShimmer.tsx@@ -0,0 +1,73 @@+/**+ * A sweeping gradient shimmer over a piece of text while `active`, crossfading+ * back to plain text when it settles.+ *+ * Ported from opencode's `packages/ui/src/components/text-shimmer.tsx`+ * (github.com/sst/opencode, MIT © 2025 opencode). Rewritten against Macro's+ * tokens: the sweep reuses the global `magic-chip-shimmer` keyframes from+ * `index.css` (which already handles `prefers-reduced-motion`) instead of+ * opencode's CSS variable system.+ */++import { createEffect, createSignal, onCleanup } from 'solid-js';++/** How long the crossfade between shimmering and plain text runs. */+const SWAP_MS = 200;++export interface TextShimmerProps {+ text: string;+ active: boolean;+ class?: string;+}++/** Two stacked copies of the text: a plain base and a shimmering overlay. */+export function TextShimmer(props: TextShimmerProps) {+ // Keep the sweep running while the shimmer layer fades out, so deactivation+ // doesn't freeze the gradient mid-swipe.+ const [run, setRun] = createSignal(props.active);+ let timer: ReturnType<typeof setTimeout> | undefined;++ createEffect(() => {+ if (timer !== undefined) {+ clearTimeout(timer);+ timer = undefined;+ }+ if (props.active) {+ setRun(true);+ return;+ }+ timer = setTimeout(() => {+ timer = undefined;+ setRun(false);+ }, SWAP_MS);+ });++ onCleanup(() => {+ if (timer !== undefined) clearTimeout(timer);+ });++ return (+ <span+ class={`inline-grid whitespace-pre align-baseline ${props.class ?? ''}`}+ aria-label={props.text}+ >+ <span+ aria-hidden="true"+ class="col-start-1 row-start-1 transition-opacity duration-200 motion-reduce:transition-none"+ classList={{ 'opacity-0': props.active }}+ >+ {props.text}+ </span>+ <span+ aria-hidden="true"+ class="col-start-1 row-start-1 transition-opacity duration-200 motion-reduce:transition-none"+ classList={{+ 'opacity-0': !props.active,+ 'magic-chip-shimmer': run(),+ }}+ >+ {props.text}+ </span>+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/ui/Thought.tsx b/apps/web/src/features/block-agent/ui/Thought.tsxnew file mode 100644index 0000000000..4d2201112a--- /dev/null+++ b/apps/web/src/features/block-agent/ui/Thought.tsx@@ -0,0 +1,45 @@+/**+ * The agent's reasoning, modeled on the chat block's `ThinkingBlock`+ * (`@core/component/AI/component/message/ThinkingBlock.tsx`): a bare,+ * borderless row — caret, then a "Thinking"/"Thought" label that shimmers+ * while the turn is in flight — expanding to the reasoning text.+ */++import CaretRight from '@phosphor/caret-right.svg';+import { createSignal, Show } from 'solid-js';+import { TextShimmer } from './TextShimmer';++export interface ThoughtProps {+ text: string;+ /** The turn is still in flight: label reads "Thinking" and shimmers. */+ active?: boolean;+ defaultOpen?: boolean;+}++export function Thought(props: ThoughtProps) {+ const [expanded, setExpanded] = createSignal(props.defaultOpen ?? false);++ return (+ <div class="relative text-xs leading-5 text-ink-extra-muted">+ <button+ type="button"+ class="flex min-h-7 cursor-pointer items-center gap-1 py-1 text-left text-ink-extra-muted hover:text-ink-muted"+ onClick={() => setExpanded((prev) => !prev)}+ >+ <CaretRight+ class="size-4 shrink-0 transition-transform motion-reduce:transition-none"+ classList={{ 'rotate-90': expanded() }}+ />+ <TextShimmer+ text={props.active ? 'Thinking' : 'Thought'}+ active={props.active ?? false}+ />+ </button>+ <Show when={expanded()}>+ <div class="pl-5 text-ink-muted whitespace-pre-wrap wrap-break-word">+ {props.text}+ </div>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/TodoList.tsx b/apps/web/src/features/block-agent/ui/TodoList.tsxnew file mode 100644index 0000000000..3acf74faa4--- /dev/null+++ b/apps/web/src/features/block-agent/ui/TodoList.tsx@@ -0,0 +1,96 @@+/**+ * The agent's plan as a checklist: a read-only checkbox visual per item, a+ * pulsing dot while an item is in progress, and content that strikes through+ * and mutes once an item is completed or cancelled.+ *+ * Ported from opencode's inner `TodoList` (`session-todo-dock.tsx`) and its+ * historical `todowrite` card body (`message-part.tsx`)+ * (github.com/sst/opencode, MIT © 2025 opencode). Their kobalte Checkbox is+ * replaced with an inline visual, and their motion-based `TextStrikethrough`+ * with a `text-decoration-color` transition.+ */+import { For } from 'solid-js';+import { match } from 'ts-pattern';+import type { TodoItem } from './types';++function CheckMark() {+ return (+ <svg+ viewBox="0 0 12 12"+ width="10"+ height="10"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ class="block"+ aria-hidden="true"+ >+ <path d="M2.5 6.5 5 9l4.5-5.5" />+ </svg>+ );+}++function PulsingDot() {+ return (+ <svg+ viewBox="0 0 12 12"+ width="12"+ height="12"+ fill="currentColor"+ class="block"+ aria-hidden="true"+ >+ <circle+ cx="6"+ cy="6"+ r="3"+ class="animate-todo-pulse origin-center [transform-box:fill-box] motion-reduce:animate-none"+ />+ </svg>+ );+}++/** The read-only checkbox stand-in: checked, pulsing, or empty. */+function TodoBox(props: { status: TodoItem['status'] }) {+ return (+ <span+ class="mt-[3px] flex size-3.5 shrink-0 items-center justify-center rounded border border-edge-muted transition-colors duration-200"+ classList={{ 'text-ink-muted': props.status === 'completed' }}+ >+ {match(props.status)+ .with('completed', () => <CheckMark />)+ .with('in_progress', () => <PulsingDot />)+ .otherwise(() => undefined)}+ </span>+ );+}++/** A read-only rendering of the agent's todo list. */+export function TodoList(props: { todos: TodoItem[] }) {+ return (+ <div class="flex flex-col gap-1.5">+ <For each={props.todos}>+ {(todo) => {+ const struck = () =>+ todo.status === 'completed' || todo.status === 'cancelled';+ return (+ <div class="flex items-start gap-2 text-xs leading-5">+ <TodoBox status={todo.status} />+ <span+ class="min-w-0 wrap-break-word line-through transition-[color,text-decoration-color] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none"+ classList={{+ 'text-ink decoration-transparent': !struck(),+ 'text-ink-extra-muted decoration-ink-extra-muted': struck(),+ }}+ >+ {todo.content}+ </span>+ </div>+ );+ }}+ </For>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/ToolCard.tsx b/apps/web/src/features/block-agent/ui/ToolCard.tsxnew file mode 100644index 0000000000..c71d9f7d81--- /dev/null+++ b/apps/web/src/features/block-agent/ui/ToolCard.tsx@@ -0,0 +1,121 @@+/**+ * The universal collapsible tool card: one row per tool call, with an optional+ * expandable body.+ *+ * Ported from opencode's+ * `packages/session-ui/src/v2/components/basic-tool-v2.tsx`+ * (github.com/sst/opencode, MIT © 2025 opencode), restyled to Macro's tokens+ * and the `Tool` card idiom.+ */++import { Collapsible } from '@kobalte/core/collapsible';+import CaretRight from '@phosphor/caret-right.svg';+import {+ createMemo,+ For,+ type JSX,+ children as resolveChildren,+ Show,+} from 'solid-js';+import { TextShimmer } from './TextShimmer';+import { isToolActive, type ToolStatus } from './types';++export interface ToolCardProps {+ title: JSX.Element | string;+ /** Mono, truncated detail next to the title (a path, a command, ...). */+ subtitle?: string;+ /** Small `key=value` chips after the subtitle. */+ args?: Record<string, string>;+ /** Right-aligned slot before the chevron (status text, counts, ...). */+ trailing?: JSX.Element;+ status: ToolStatus;+ /** Fade the whole card, the chat block's failed-tool treatment. */+ muted?: boolean;+ /** Controlled open state; omit to let the card manage its own. */+ open?: boolean;+ defaultOpen?: boolean;+ onOpenChange?: (open: boolean) => void;+ /** Expandable body. Without children the row has no collapse affordance. */+ children?: JSX.Element;+}++const ROW_CLASS =+ 'flex min-h-9 w-full items-center gap-2 px-3 py-2 text-left text-xs leading-5';++export function ToolCard(props: ToolCardProps) {+ const active = () => isToolActive(props.status);+ const resolved = resolveChildren(() => props.children);+ const hasChildren = createMemo(() => {+ const body = resolved();+ return Array.isArray(body) ? body.length > 0 : body != null;+ });++ const row = (expandable: boolean) => (+ <>+ <span class="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">+ <span class="shrink-0 text-ink">+ {typeof props.title === 'string' ? (+ <TextShimmer text={props.title} active={active()} />+ ) : (+ props.title+ )}+ </span>+ <Show when={props.subtitle}>+ {(subtitle) => (+ <>+ <span aria-hidden="true" class="shrink-0 text-ink-placeholder">+ ·+ </span>+ <span class="min-w-0 truncate font-mono">{subtitle()}</span>+ </>+ )}+ </Show>+ <For each={Object.entries(props.args ?? {})}>+ {([key, value]) => (+ <span class="shrink-0 rounded bg-hover px-1 font-mono text-ink-extra-muted">+ {key}={value}+ </span>+ )}+ </For>+ </span>+ <Show when={props.trailing || expandable}>+ <span class="flex shrink-0 items-center gap-1.5 whitespace-nowrap">+ {props.trailing}+ <Show when={expandable}>+ <CaretRight+ aria-hidden="true"+ class="size-3 shrink-0 text-ink-extra-muted transition-transform group-data-expanded:rotate-90 motion-reduce:transition-none"+ />+ </Show>+ </span>+ </Show>+ </>+ );++ return (+ <div+ class="overflow-hidden rounded-lg bg-surface text-ink-extra-muted"+ classList={{ 'opacity-50': props.muted }}+ >+ <Show+ when={hasChildren()}+ fallback={<div class={ROW_CLASS}>{row(false)}</div>}+ >+ <Collapsible+ open={props.open}+ defaultOpen={props.defaultOpen}+ onOpenChange={props.onOpenChange}+ >+ <Collapsible.Trigger+ class={`group cursor-pointer hover:bg-hover ${ROW_CLASS}`}+ >+ {row(true)}+ </Collapsible.Trigger>+ <Collapsible.Content class="data-closed:hidden">+ <div class="min-w-0 px-3 pb-2">{resolved()}</div>+ </Collapsible.Content>+ </Collapsible>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx b/apps/web/src/features/block-agent/ui/ToolErrorCard.tsxnew file mode 100644index 0000000000..72e1d57313--- /dev/null+++ b/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx@@ -0,0 +1,135 @@+/**+ * Error card for a failed tool call: a red-edged collapsible row whose header+ * is "Tool · Subtitle" and whose body is the rest of the error, with a+ * copy-error button.+ *+ * Port of opencode's tool-error-card (v2 layout + v1 error parsing and copy+ * button) — github.com/sst/opencode, MIT © 2025 opencode — adapted to Macro+ * tokens and Tailwind.+ */++import { Collapsible } from '@kobalte/core/collapsible';+import CaretRight from '@phosphor/caret-right.svg';+import Check from '@phosphor/check.svg';+import Copy from '@phosphor/copy.svg';+import Prohibit from '@phosphor/prohibit.svg';+import { Button } from '@ui';+import { createMemo, createSignal, Show } from 'solid-js';++/** Display names for well-known tool ids (from opencode's v1 card). */+const TOOL_NAMES: Record<string, string> = {+ read: 'Read',+ list: 'List',+ glob: 'Glob',+ grep: 'Grep',+ task: 'Task',+ webfetch: 'Webfetch',+ websearch: 'Web Search',+ bash: 'Shell',+ shell: 'Shell',+ patch: 'Patch',+ apply_patch: 'Patch',+ question: 'Questions',+};++export interface ToolErrorCardProps {+ /** Tool id the error came from, e.g. "bash". */+ tool: string;+ /** Raw error text, e.g. "Error: bash command failed: exit 1". */+ error: string;+ /** Controlled expanded state; leave unset for uncontrolled. */+ open?: boolean;+ defaultOpen?: boolean;+ onOpenChange?: (open: boolean) => void;+}++export function ToolErrorCard(props: ToolErrorCardProps) {+ const [copied, setCopied] = createSignal(false);++ const title = createMemo(() => TOOL_NAMES[props.tool] ?? props.tool);++ /** Error text minus any leading "Error: ". */+ const cleaned = createMemo(() =>+ props.error.replace(/^Error:\s*/, '').trim()+ );++ /** `cleaned` minus a leading "<tool> " echo of the tool's own name. */+ const tail = createMemo(() => {+ const value = cleaned();+ const prefix = `${props.tool} `;+ return value.startsWith(prefix) ? value.slice(prefix.length) : value;+ });++ /** First "head: rest" segment of the error, capitalized; "Failed" if none. */+ const subtitle = createMemo(() => {+ const parts = tail().split(': ');+ if (parts.length <= 1) return 'Failed';+ const head = (parts[0] ?? '').trim();+ if (!head) return 'Failed';+ return head[0].toUpperCase() + head.slice(1);+ });++ /** Everything after the subtitle; the whole error when there's no split. */+ const body = createMemo(() => {+ const parts = tail().split(': ');+ if (parts.length <= 1) return cleaned();+ return parts.slice(1).join(': ').trim() || cleaned();+ });++ const copy = async () => {+ const text = cleaned();+ if (!text) return;+ try {+ await navigator.clipboard.writeText(text);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch (err) {+ console.error('Failed to copy to clipboard', err);+ }+ };++ return (+ <Collapsible+ open={props.open}+ defaultOpen={props.defaultOpen}+ onOpenChange={props.onOpenChange}+ class="flex w-full min-w-0 flex-col border-l-2 border-failure pl-2.5 text-xs leading-5"+ >+ <Collapsible.Trigger class="group flex min-h-6 w-full min-w-0 items-center gap-2 rounded-xs py-0.5 text-left">+ <Prohibit class="size-4 shrink-0 text-failure" />+ <div class="flex min-w-0 items-center gap-1.5 overflow-hidden">+ <span class="shrink-0 font-medium text-ink">{title()}</span>+ <span class="shrink-0 text-ink-placeholder" aria-hidden="true">+ ·+ </span>+ <span class="min-w-0 truncate text-ink-muted">{subtitle()}</span>+ <CaretRight class="size-3.5 shrink-0 text-ink-extra-muted transition-transform group-data-expanded:rotate-90" />+ </div>+ </Collapsible.Trigger>+ <Collapsible.Content class="min-w-0 data-closed:hidden">+ <div class="flex items-start gap-2 pt-1 pl-6">+ <div class="min-w-0 flex-1 whitespace-pre-wrap wrap-break-word text-ink-extra-muted">+ {body()}+ </div>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ noTouchResize+ class="shrink-0 px-1 text-ink-extra-muted hover:text-ink-muted"+ aria-label={copied() ? 'Copied' : 'Copy error'}+ onMouseDown={(event) => event.preventDefault()}+ onClick={(event) => {+ event.stopPropagation();+ void copy();+ }}+ >+ <Show when={copied()} fallback={<Copy class="size-3.5" />}>+ <Check class="size-3.5 text-success" />+ </Show>+ </Button>+ </div>+ </Collapsible.Content>+ </Collapsible>+ );+}diff --git a/apps/web/src/features/block-agent/ui/ToolStatusTitle.tsx b/apps/web/src/features/block-agent/ui/ToolStatusTitle.tsxnew file mode 100644index 0000000000..58fff8055a--- /dev/null+++ b/apps/web/src/features/block-agent/ui/ToolStatusTitle.tsx@@ -0,0 +1,153 @@+/**+ * An animated swap between an in-progress title ("Running command…",+ * shimmering) and its finished form ("Ran command") when `active` flips.+ * When the two share a prefix of at least two characters, only the differing+ * suffix morphs.+ *+ * Ported from opencode's+ * `packages/session-ui/src/components/tool-status-title.tsx`+ * (github.com/sst/opencode, MIT © 2025 opencode). The spring width animation+ * is replaced with a plain CSS width transition, and the blur/translate+ * flourishes are dropped in favor of a simple opacity crossfade.+ */++import {+ createEffect,+ createMemo,+ createSignal,+ on,+ onCleanup,+ Show,+} from 'solid-js';+import { TextShimmer } from './TextShimmer';++/** Grace period before the width lock is released and text flows naturally. */+const SETTLE_MS = 400;++/** Split two strings into their shared prefix and the differing tails. */+function commonPrefix(active: string, done: string) {+ const a = Array.from(active);+ const b = Array.from(done);+ let i = 0;+ while (i < a.length && i < b.length && a[i] === b[i]) i++;+ return {+ prefix: a.slice(0, i).join(''),+ activeTail: a.slice(i).join(''),+ doneTail: b.slice(i).join(''),+ };+}++function measure(el: HTMLSpanElement | undefined): string | undefined {+ if (!el) return undefined;+ return `${Math.ceil(el.getBoundingClientRect().width)}px`;+}++export interface ToolStatusTitleProps {+ active: boolean;+ activeText: string;+ doneText: string;+ class?: string;+}++export function ToolStatusTitle(props: ToolStatusTitleProps) {+ const split = createMemo(() =>+ commonPrefix(props.activeText, props.doneText)+ );+ const useSuffix = createMemo(+ () =>+ split().prefix.length >= 2 &&+ split().activeTail.length > 0 &&+ split().doneTail.length > 0+ );+ const activeTail = createMemo(() =>+ useSuffix() ? split().activeTail : props.activeText+ );+ const doneTail = createMemo(() =>+ useSuffix() ? split().doneTail : props.doneText+ );++ // What's currently displayed; trails props.active by one effect run so the+ // outgoing width can be measured before the swap.+ const [shown, setShown] = createSignal(props.active);+ const [animating, setAnimating] = createSignal(false);+ const [width, setWidth] = createSignal<string | undefined>(undefined);++ let tailRef: HTMLSpanElement | undefined;+ let activeRef: HTMLSpanElement | undefined;+ let doneRef: HTMLSpanElement | undefined;+ let frame: number | undefined;+ let settle: ReturnType<typeof setTimeout> | undefined;++ const finish = () => {+ if (frame !== undefined) cancelAnimationFrame(frame);+ if (settle !== undefined) clearTimeout(settle);+ frame = undefined;+ settle = undefined;+ setAnimating(false);+ setWidth(undefined);+ };++ createEffect(+ on(+ [() => props.active, activeTail, doneTail],+ ([next]) => {+ const from = measure(tailRef);+ finish();+ setShown(next);+ if (!from) return;+ setAnimating(true);+ setWidth(from);+ frame = requestAnimationFrame(() => {+ frame = undefined;+ const to = measure(next ? activeRef : doneRef);+ if (!to) {+ finish();+ return;+ }+ setWidth(to);+ settle = setTimeout(finish, SETTLE_MS);+ });+ },+ { defer: true }+ )+ );++ onCleanup(finish);++ return (+ <span+ class={`inline-flex items-baseline whitespace-nowrap ${props.class ?? ''}`}+ aria-label={props.active ? props.activeText : props.doneText}+ >+ <Show when={useSuffix()}>+ <span class="shrink-0 whitespace-pre">+ <TextShimmer text={split().prefix} active={shown()} />+ </span>+ </Show>+ <span+ ref={tailRef}+ class="inline-grid justify-items-start overflow-hidden transition-[width] duration-300 ease-out motion-reduce:transition-none"+ style={{ width: width() }}+ >+ <Show when={animating() || shown()}>+ <span+ ref={activeRef}+ class="col-start-1 row-start-1 whitespace-pre transition-opacity duration-200 motion-reduce:transition-none"+ classList={{ 'opacity-0': !shown() }}+ >+ <TextShimmer text={activeTail()} active={shown()} />+ </span>+ </Show>+ <Show when={animating() || !shown()}>+ <span+ ref={doneRef}+ class="col-start-1 row-start-1 whitespace-pre transition-opacity duration-200 motion-reduce:transition-none"+ classList={{ 'opacity-0': shown() }}+ >+ {doneTail()}+ </span>+ </Show>+ </span>+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.tsnew file mode 100644index 0000000000..f9a3d1e281--- /dev/null+++ b/apps/web/src/features/block-agent/ui/index.ts@@ -0,0 +1,42 @@+/**+ * Pure component library for rendering agent sessions.+ *+ * Everything here is props-in, JSX-out — no contexts, no queries. Several+ * components are ports from opencode (github.com/sst/opencode, MIT © 2025+ * opencode); see individual file headers.+ */++export { AgentInput, type AgentInputProps } from './AgentInput';+export { AnimatedNumber } from './AnimatedNumber';+export { type CountItem, CountSummary } from './CountSummary';+export { DiffChanges, type DiffChangesProps } from './DiffChanges';+export { FoldedAnsiText } from './FoldedAnsiText';+export { FoldedOutput } from './FoldedOutput';+export { FoldedPathList } from './FoldedPathList';+export { FoldedTerminal } from './FoldedTerminal';+export { PierreDiff } from './PierreDiff';+export { QuestionAnswers, type QuestionAnswersProps } from './QuestionAnswers';+export {+ QueuedPromptList,+ type QueuedPromptListProps,+} from './QueuedPromptList';+export {+ type SessionStatusLike,+ SessionStatusPill,+} from './SessionStatusPill';+export { TextShimmer, type TextShimmerProps } from './TextShimmer';+export { Thought, type ThoughtProps } from './Thought';+export { TodoList } from './TodoList';+export { ToolCard, type ToolCardProps } from './ToolCard';+export { ToolErrorCard, type ToolErrorCardProps } from './ToolErrorCard';+export {+ ToolStatusTitle,+ type ToolStatusTitleProps,+} from './ToolStatusTitle';+export {+ type AnsweredQuestion,+ type FileDiff,+ isToolActive,+ type TodoItem,+ type ToolStatus,+} from './types';diff --git a/apps/web/src/features/block-agent/ui/types.ts b/apps/web/src/features/block-agent/ui/types.tsnew file mode 100644index 0000000000..68dd29a191--- /dev/null+++ b/apps/web/src/features/block-agent/ui/types.ts@@ -0,0 +1,34 @@+/**+ * Shared vocabulary for the block-agent UI component library.+ *+ * Components in this directory are pure: props in, JSX out. No contexts, no+ * queries, no block signals. Data shapes come from the agent-fold wire types+ * where one exists; anything else is declared here.+ *+ * Several components are ports of opencode's session-ui/ui packages+ * (github.com/sst/opencode, MIT © 2025 opencode), adapted to Macro's tokens+ * and the agent-fold vocabulary.+ */++import type { ToolStatus } from '@service-agent-fold/generated/types';++export type { FileDiff, ToolStatus } from '@service-agent-fold/generated/types';++/** One entry of an agent's plan / todo list. */+export interface TodoItem {+ /** What the agent said it would do. */+ content: string;+ status: 'pending' | 'in_progress' | 'completed' | 'cancelled';+}++/** One question the agent asked the user, with the answer(s) chosen. */+export interface AnsweredQuestion {+ question: string;+ /** Empty when the question went unanswered. */+ answers: string[];+}++/** Whether a tool call is still in flight. */+export function isToolActive(status: ToolStatus): boolean {+ return status === 'pending' || status === 'running';+}diff --git a/apps/web/src/features/entity/utils/buildEntityData.ts b/apps/web/src/features/entity/utils/buildEntityData.tsindex f44f1412e1..27712a6687 100644--- a/apps/web/src/features/entity/utils/buildEntityData.ts+++ b/apps/web/src/features/entity/utils/buildEntityData.ts@@ -178,6 +178,8 @@ export function buildEntityData(.with('company', 'contact', (): undefined => undefined)// PRs are virtual blocks backed by GitHub, not Macro entities..with('pr', (): undefined => undefined)+ // Agent sessions aren't constructed from block args; not soup-listed yet.+ .with('agent', (): undefined => undefined).exhaustive());}diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex ccc8226599..bae31c6ef7 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -370,6 +370,7 @@ body.tauri-ios {--animate-swipe-out: swipeOut 100ms ease-out;--animate-swipe-out-left: swipeOutLeft 100ms ease-out;--animate-indeterminate-bar: indeterminate-bar 1.1s ease-in-out infinite;+ --animate-todo-pulse: todo-pulse 1.6s ease-in-out infinite;/* Z-index scale — the single source of truth for stacking. Classes comefrom these tokens (`--z-index-foo` -> `z-foo`).@@ -658,6 +659,12 @@ body.tauri-ios {100% { transform: translateX(350%); }}+/* Ported from opencode's `--animate-pulse-scale` (github.com/sst/opencode, MIT © 2025 opencode). */+@keyframes todo-pulse {+ 0%, 100% { transform: scale(1); opacity: 1; }+ 50% { transform: scale(0.6); opacity: 0.5; }+}+/* Big hammer fix for cursor pointer. */@utility cursor-pointer {cursor: default;diff --git a/apps/web/src/lib/core/agent-fold/client.ts b/apps/web/src/lib/core/agent-fold/client.tsindex 1540c67ef3..d9784f1388 100644--- a/apps/web/src/lib/core/agent-fold/client.ts+++ b/apps/web/src/lib/core/agent-fold/client.ts@@ -9,10 +9,26 @@import type {FoldedMessage,FoldedStreamEvent,+ SessionMetadata,} from '@service-agent-fold/generated/types';import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';import type { FoldRequest, FoldResponse } from './protocol';+/** A machine-backed read: the fold's messages plus its current metadata. */+export type SessionFoldSnapshot = {+ messages: FoldedMessage[];+ metadata: SessionMetadata;+};++/** What a machine that has folded nothing knows — every field still absent. */+const EMPTY_METADATA: SessionMetadata = {+ model: null,+ supportedModels: [],+ title: null,+ availableCommands: [],+ status: null,+};+interface Pending {resolve: (response: Extract<FoldResponse, { ok: true }>) => void;reject: (error: Error) => void;@@ -102,14 +118,16 @@ export async function foldSession(export async function openSession(sessionId: string,entries: AgentSessionLogEntryDto[]-): Promise<FoldedMessage[]> {+): Promise<SessionFoldSnapshot> {const response = await request((id) => ({id,kind: 'open',sessionId,entries,}));- return response.kind === 'open' ? response.messages : [];+ return response.kind === 'open'+ ? { messages: response.messages, metadata: response.metadata }+ : { messages: [], metadata: EMPTY_METADATA };}/**@@ -143,9 +161,11 @@ export async function pushSessionEntries(*/export async function sessionMessages(sessionId: string-): Promise<FoldedMessage[]> {+): Promise<SessionFoldSnapshot> {const response = await request((id) => ({ id, kind: 'messages', sessionId }));- return response.kind === 'messages' ? response.messages : [];+ return response.kind === 'messages'+ ? { messages: response.messages, metadata: response.metadata }+ : { messages: [], metadata: EMPTY_METADATA };}/** Drop a session's machine once nothing is watching it. */diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.ts b/apps/web/src/lib/core/agent-fold/fold.worker.tsindex 80eb5ac145..4872c50d77 100644--- a/apps/web/src/lib/core/agent-fold/fold.worker.ts+++ b/apps/web/src/lib/core/agent-fold/fold.worker.ts@@ -53,7 +53,14 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {streams.get(sessionId)?.free();const stream = new wasm.FoldStream(sessionId);streams.set(sessionId, stream);- return { id, kind, ok: true as const, messages: stream.extend(entries) };+ const messages = stream.extend(entries);+ return {+ id,+ kind,+ ok: true as const,+ messages,+ metadata: stream.metadata(),+ };}).with({ kind: 'push' }, ({ id, kind, sessionId, entries }) => {const stream = streams.get(sessionId);@@ -70,7 +77,13 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {.with({ kind: 'messages' }, ({ id, kind, sessionId }) => {const stream = streams.get(sessionId);if (!stream) throw new Error(`no open fold for session ${sessionId}`);- return { id, kind, ok: true as const, messages: stream.messages() };+ return {+ id,+ kind,+ ok: true as const,+ messages: stream.messages(),+ metadata: stream.metadata(),+ };}).with({ kind: 'close' }, ({ id, kind, sessionId }) => {streams.get(sessionId)?.free();diff --git a/apps/web/src/lib/core/agent-fold/protocol.ts b/apps/web/src/lib/core/agent-fold/protocol.tsindex 1245663249..558c0c2dd8 100644--- a/apps/web/src/lib/core/agent-fold/protocol.ts+++ b/apps/web/src/lib/core/agent-fold/protocol.ts@@ -15,6 +15,7 @@import type {FoldedMessage,FoldedStreamEvent,+ SessionMetadata,} from '@service-agent-fold/generated/types';import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';@@ -78,11 +79,16 @@ export type FoldRequest =/** What the worker sends back, one per request. */export type FoldResponse =+ | { id: number; ok: true; kind: 'once'; messages: FoldedMessage[] }+ // Machine-backed reads also answer with the machine's current metadata,+ // so a caller catching up (or joining late) does not have to wait for the+ // next `{kind: 'metadata'}` push event to learn the session's title/model.| {id: number;ok: true;- kind: 'open' | 'once' | 'messages';+ kind: 'open' | 'messages';messages: FoldedMessage[];+ metadata: SessionMetadata;}| { id: number; ok: true; kind: 'push'; changes: FoldedStreamEvent[] }| { id: number; ok: true; kind: 'close' }diff --git a/apps/web/src/lib/core/agent-fold/wasm-module.ts b/apps/web/src/lib/core/agent-fold/wasm-module.tsindex c7946e90da..4555e82fe8 100644--- a/apps/web/src/lib/core/agent-fold/wasm-module.ts+++ b/apps/web/src/lib/core/agent-fold/wasm-module.ts@@ -11,6 +11,7 @@import type {FoldedMessage,FoldedStreamEvent,+ SessionMetadata,} from '@service-agent-fold/generated/types';import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';@@ -42,6 +43,12 @@ export interface FoldStream {push: (entry: AgentSessionLogEntryDto) => FoldedStreamEvent[];/** Every message folded so far, oldest first. */messages: () => FoldedMessage[];+ /**+ * The session metadata as it now stands — what the latest+ * `{kind: "metadata"}` event carried, for a caller that caught up with+ * {@link extend} and saw no events.+ */+ metadata: () => SessionMetadata;/** Releases the machine's wasm memory. */free: () => void;}diff --git a/apps/web/src/lib/core/block.ts b/apps/web/src/lib/core/block.tsindex da92add2f2..1c37826290 100644--- a/apps/web/src/lib/core/block.ts+++ b/apps/web/src/lib/core/block.ts@@ -67,6 +67,7 @@ export const BlockRegistry = ['company','automation','pr',+ 'agent',] as const;/** Block names that resolve through another concrete block implementation. */@@ -111,6 +112,7 @@ export const NonDocumentBlockTypes = ['company','automation','pr',+ 'agent',] as const as (BlockName | BlockAlias)[];/**@@ -168,6 +170,7 @@ const _ValidBlockCombinations: BlockCombinationRules = {automation: allBlockNames,csv: allBlockNames,pr: allBlockNames,+ agent: allBlockNames,} as const;// maps block name to valid parents@@ -194,6 +197,7 @@ export const ValidNestingCombinations: BlockCombinationRules = {automation: new Set([]),csv: new Set([]),pr: new Set([]),+ agent: new Set([]),};export const LoadErrors = {diff --git a/apps/web/src/lib/core/blockMethodRegistry.ts b/apps/web/src/lib/core/blockMethodRegistry.tsindex 35ea486f49..78cd0c1d7b 100644--- a/apps/web/src/lib/core/blockMethodRegistry.ts+++ b/apps/web/src/lib/core/blockMethodRegistry.ts@@ -40,6 +40,7 @@ export interface BlockMethodRegistry {task: EmptySpec;automation: EmptySpec;pr: EmptySpec;+ agent: EmptySpec;}// Type helper to get the method spec for a block namediff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsxindex 1ad2f49b3d..f4b14a2b0f 100644--- a/apps/web/src/lib/core/component/EntityIcon.tsx+++ b/apps/web/src/lib/core/component/EntityIcon.tsx@@ -59,6 +59,7 @@ import FolderUser from '@phosphor/folder-user.svg';import GlobeIcon from '@phosphor/globe.svg';import FileImage from '@phosphor/image.svg';import Canvas from '@phosphor/pencil-circle.svg';+import Robot from '@phosphor/robot.svg';import Users from '@phosphor/users.svg';import type { PreviewItem } from '@queries/preview';import type { ChannelType } from '@service-cognition/generated/schemas/channelType';@@ -279,6 +280,12 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {background: 'bg-default/20',prettyName: 'Pull Request',},+ agent: {+ icon: Robot,+ foreground: 'text-default',+ background: 'bg-default/20',+ prettyName: 'Agent',+ },task: {icon: Check,foreground: 'text-task',@@ -382,6 +389,7 @@ const WIDE_ICONS: Record<emailInvite: WideCalendar,githubPullRequest: GithubIcon,pr: GithubIcon,+ agent: Robot,task: WideTask,snippet: WideSnippet,skill: SkillIcon,diff --git a/apps/web/src/lib/core/component/FileList/constants.tsx b/apps/web/src/lib/core/component/FileList/constants.tsxindex 8aa8a6b9f0..858b8c26f2 100644--- a/apps/web/src/lib/core/component/FileList/constants.tsx+++ b/apps/web/src/lib/core/component/FileList/constants.tsx@@ -80,4 +80,5 @@ const _fileTypeColors: Record<BlockName | BlockAlias | 'default', string> = {skill: 'bg-chat/20 group/item',automation: 'bg-chat/20 group/item',pr: defaultFileColor,+ agent: defaultFileColor,};diff --git a/apps/web/src/lib/core/linked-conversation/LinkedConversation.tsx b/apps/web/src/lib/core/linked-conversation/LinkedConversation.tsxnew file mode 100644index 0000000000..8b348aba21--- /dev/null+++ b/apps/web/src/lib/core/linked-conversation/LinkedConversation.tsx@@ -0,0 +1,188 @@+import {+ type GroupableMessage,+ shouldGroupWithPreviousMessage,+} from '@channel/Channel/message-grouping-meta';+import { Message } from '@channel/Message/Message';+import type { MessageData } from '@channel/Message/types';+import { Thread } from '@channel/Thread/Thread';+import { ThreadRail } from '@channel/Thread/ThreadRail';+import {+ DEFAULT_VISIBLE_REPLY_COUNT,+ getCollapsedRepliesCount,+ getThreadLatestReplyAt,+ getUniqueReplyUserIds,+} from '@channel/Thread/utils/thread-reply-indicator-helpers';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { senderFromStorageId } from '@queries/channel/message-sender';+import { cn } from '@ui';+import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';+import type { LinkedConversationSource } from './types';++type LinkedConversationProps = {+ source: LinkedConversationSource;+ /** Navigate-style click handler; message rows get a hover affordance when set. */+ onClickMessage?: (messageId: string, e: MouseEvent) => void;+ class?: string;+};++/**+ * Read-only rendering of a linked conversation — a root message and its reply+ * chain — from a [`LinkedConversationSource`]. Source-agnostic: back it with+ * `createChannelThreadSource` for channel threads, or supply another source.+ * Long reply chains collapse behind a `Thread.CollapsedIndicator` and expand+ * in place.+ */+export function LinkedConversation(props: LinkedConversationProps) {+ const [isExpanded, setIsExpanded] = createSignal(false);++ const replies = () => props.source.replies();+ const hasReplies = () => replies().length > 0;+ const totalReplyCount = () => props.source.replyCount?.() ?? replies().length;++ const displayReplies = () =>+ isExpanded() ? replies() : replies().slice(0, DEFAULT_VISIBLE_REPLY_COUNT);+ const isGroupedById = createMemo(() => buildIsGroupedById(displayReplies()));++ const collapsedRepliesCount = () =>+ getCollapsedRepliesCount(totalReplyCount());+ const showCollapsedIndicator = () =>+ !isExpanded() && collapsedRepliesCount() > 0;+ const collapsedReplyUsers = () =>+ getUniqueReplyUserIds(replies().slice(DEFAULT_VISIBLE_REPLY_COUNT));+ const collapsedLatestReplyAt = () =>+ getThreadLatestReplyAt(undefined, replies());++ const rowClass = () => (props.onClickMessage ? 'hover:bg-hover' : undefined);++ return (+ <StaticMarkdownContext>+ <Suspense>+ <div class={cn('relative', props.class)}>+ <Show when={hasReplies()}>+ <ThreadRail />+ </Show>+ <Show when={props.source.root()}>+ {(rootMessage) => (+ <ConversationMessage+ message={rootMessage()}+ onClick={props.onClickMessage}+ class={rowClass()}+ />+ )}+ </Show>+ <Show when={hasReplies()}>+ <div class="relative w-full">+ <Thread.ReplyRailDecorations+ isReplying={() => false}+ firstThreadReplyNewMessage={false}+ />+ <Thread.RepliesContainer>+ <For each={displayReplies()}>+ {(reply) => (+ <div class="relative">+ <ThreadRail />+ <ConversationMessage+ message={reply}+ grouped={isGroupedById()[reply.id]}+ onClick={props.onClickMessage}+ class={rowClass()}+ />+ </div>+ )}+ </For>+ <Show when={showCollapsedIndicator()}>+ <Thread.ActionsFooter>+ <Thread.CollapsedIndicator+ collapsedRepliesCount={collapsedRepliesCount()}+ participants={collapsedReplyUsers()}+ latestReplyAt={collapsedLatestReplyAt()}+ onClick={() => setIsExpanded(true)}+ />+ </Thread.ActionsFooter>+ </Show>+ </Thread.RepliesContainer>+ </div>+ </Show>+ </div>+ </Suspense>+ </StaticMarkdownContext>+ );+}++function ConversationMessage(props: {+ message: MessageData;+ grouped?: boolean;+ onClick?: (messageId: string, e: MouseEvent) => void;+ class?: string;+}) {+ return (+ <Message.Root+ message={props.message}+ onClick={+ props.onClick+ ? (e: MouseEvent) => props.onClick!(props.message.id, e)+ : undefined+ }+ class={props.class}+ >+ <Message.Layout+ class={props.grouped ? undefined : 'pt-(--regular-message-padding-t)'}+ >+ <Message.Slot placement="icon">+ <Message.SenderIcon hidden={props.grouped} />+ </Message.Slot>+ <Show when={!props.grouped}>+ <Message.Slot+ placement="header"+ class="flex flex-col gap-0.5 min-w-0"+ >+ <div class="flex items-center gap-1 min-w-0">+ <Message.SenderName />+ <Message.AgentBadge />+ <Message.EditedIndicator />+ <Message.Timestamp+ class="ml-auto shrink-0"+ format="dateAndTime"+ />+ </div>+ <Message.FromPill />+ </Message.Slot>+ </Show>+ <Message.Slot placement="content">+ <Message.Content />+ </Message.Slot>+ <Message.Slot placement="footer" class="flex flex-col min-w-0">+ <Message.Attachments />+ <Message.Reactions />+ </Message.Slot>+ </Message.Layout>+ </Message.Root>+ );+}++function toGroupable(message: MessageData): GroupableMessage {+ return {+ id: message.id,+ sender_id: message.sender_id,+ sender: message.sender ?? senderFromStorageId(message.sender_id),+ created_at: message.created_at,+ attachments: message.attachments,+ deleted_at: message.deleted_at ?? null,+ };+}++/**+ * Grouping over `MessageData` rather than `buildThreadReplyListMeta`'s+ * `ApiThreadReply` — linked-conversation messages may come from non-channel+ * sources where `sender` is absent.+ */+function buildIsGroupedById(replies: MessageData[]): Record<string, boolean> {+ const grouped: Record<string, boolean> = {};+ let previous: GroupableMessage | undefined;+ for (const reply of replies) {+ const current = toGroupable(reply);+ grouped[reply.id] = shouldGroupWithPreviousMessage(current, previous);+ previous = current;+ }+ return grouped;+}diff --git a/apps/web/src/lib/core/linked-conversation/LinkedConversationDrawer.tsx b/apps/web/src/lib/core/linked-conversation/LinkedConversationDrawer.tsxnew file mode 100644index 0000000000..3317c85865--- /dev/null+++ b/apps/web/src/lib/core/linked-conversation/LinkedConversationDrawer.tsx@@ -0,0 +1,102 @@+import { navigateToChannelMessage } from '@block-channel/utils/link';+import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';+import { SplitDrawer } from '@components/app/split-layout/components/SplitDrawer';+import { useDrawerControl } from '@components/app/split-layout/components/SplitDrawerContext';+import ArrowSquareOut from '@phosphor/arrow-square-out.svg';+import { Button } from '@ui';+import { Show } from 'solid-js';+import { createChannelThreadSource } from './channel-thread-source';+import { LinkedConversation } from './LinkedConversation';++type LinkedConversationDrawerProps = {+ /**+ * Drawer id, unique within the split. Toggle the drawer from anywhere in+ * the same split (e.g. a toolbar `BlockTool`) with `useDrawerControl(id)`.+ */+ id: string;+ /** Channel containing the linked thread. */+ channelId: string;+ /** Root message of the linked thread — the conversation's parent id. */+ messageId: string;+ /** Target drawer width in px. */+ size?: number;+};++/**+ * A right-hand [`SplitDrawer`] rendering a linked conversation (a channel+ * thread) inside the current split — the "show the thread this came from"+ * affordance. Fully decoupled from any block: it only needs the thread's+ * channel + root message ids. Clicking a message (or the open button in the+ * drawer header) navigates to the referenced thread in its channel and+ * closes the drawer.+ */+export function LinkedConversationDrawer(props: LinkedConversationDrawerProps) {+ const orchestrator = useGlobalBlockOrchestrator();+ const drawer = useDrawerControl(props.id);++ const openInChannel = (clickedMessageId?: string) => {+ const target = clickedMessageId ?? props.messageId;+ const isReply = target !== props.messageId;+ void navigateToChannelMessage(+ orchestrator,+ props.channelId,+ target,+ isReply ? props.messageId : undefined+ );+ drawer.close();+ };++ return (+ <SplitDrawer+ id={props.id}+ side="right"+ size={props.size ?? 420}+ title={+ <Button+ variant="ghost"+ size="icon-sm"+ label="Open thread"+ onClick={() => openInChannel()}+ >+ <ArrowSquareOut />+ </Button>+ }+ >+ <DrawerConversation+ channelId={props.channelId}+ messageId={props.messageId}+ onOpenMessage={openInChannel}+ />+ </SplitDrawer>+ );+}++/**+ * Separate component so the thread queries mount only while the drawer is+ * open — `SplitDrawer` only creates its children then.+ */+function DrawerConversation(props: {+ channelId: string;+ messageId: string;+ onOpenMessage: (messageId: string) => void;+}) {+ const source = createChannelThreadSource({+ channelId: () => props.channelId,+ messageId: () => props.messageId,+ });++ return (+ <Show+ when={source.root()}+ fallback={<p class="px-2 text-sm text-ink-muted">Loading thread…</p>}+ >+ <LinkedConversation+ source={source}+ onClickMessage={(messageId, e) => {+ e.stopPropagation();+ props.onOpenMessage(messageId);+ }}+ />+ </Show>+ );+}diff --git a/apps/web/src/lib/core/linked-conversation/channel-thread-source.ts b/apps/web/src/lib/core/linked-conversation/channel-thread-source.tsnew file mode 100644index 0000000000..e645971905--- /dev/null+++ b/apps/web/src/lib/core/linked-conversation/channel-thread-source.ts@@ -0,0 +1,43 @@+import { useChannelMessagesByIdsQuery } from '@queries/channel/channel-messages';+import { useThreadRepliesQuery } from '@queries/channel/thread-replies';+import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';+import type { Accessor } from 'solid-js';+import type {+ LinkedConversationMessage,+ LinkedConversationSource,+} from './types';++type ChannelThreadSourceProps = {+ channelId: Accessor<string>;+ messageId: Accessor<string>;+ /** Pre-fetched root message; skips the lookup query when provided. */+ data?: Accessor<ApiChannelMessage | undefined>;+};++/**+ * A [`LinkedConversationSource`] backed by a channel thread: the root channel+ * message plus its reply chain. Must be called in a component context — it+ * mounts queries.+ */+export function createChannelThreadSource(+ props: ChannelThreadSourceProps+): LinkedConversationSource {+ const rootQuery = useChannelMessagesByIdsQuery(props.channelId, () =>+ props.data?.() ? [] : [props.messageId()]+ );+ const root = () => props.data?.() ?? rootQuery.data?.[0];+ const replyCount = () => root()?.thread.reply_count;++ const repliesQuery = useThreadRepliesQuery(+ props.channelId,+ props.messageId,+ () => (replyCount() ?? 0) > 0+ );+ const replies = (): LinkedConversationMessage[] =>+ (repliesQuery.data ?? root()?.thread.preview ?? []).map((reply) => ({+ ...reply,+ thread_id: props.messageId(),+ }));++ return { root, replies, replyCount };+}diff --git a/apps/web/src/lib/core/linked-conversation/debug/Demo.tsx b/apps/web/src/lib/core/linked-conversation/debug/Demo.tsxnew file mode 100644index 0000000000..2d9e944495--- /dev/null+++ b/apps/web/src/lib/core/linked-conversation/debug/Demo.tsx@@ -0,0 +1,176 @@+/**+ * Demo for `LinkedConversation`: point it at any channel thread by entering a+ * channel id + message id (or pasting a copied message link). Mounted at+ * `/component/linked-conversation`.+ */++import { URL_PARAMS } from '@channel/Channel/link';+import { useDrawerControl } from '@components/app/split-layout/components/SplitDrawerContext';+import { createSignal, Show, Suspense } from 'solid-js';+import { createChannelThreadSource } from '../channel-thread-source';+import { LinkedConversation } from '../LinkedConversation';+import { LinkedConversationDrawer } from '../LinkedConversationDrawer';++const DEMO_DRAWER_ID = 'linked-conversation-demo';++const STORAGE_KEY = 'linked-conversation-demo-target';++type Target = { channelId: string; messageId: string };++function loadSavedTarget(): Target {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (raw) return JSON.parse(raw) as Target;+ } catch {+ // fall through to the empty target+ }+ return { channelId: '', messageId: '' };+}++/**+ * Parses a copied channel message link+ * (`/app/channel/{channelId}?channel_message_id=…&channel_thread_id=…`).+ * The thread id wins as the root when present, so links copied from replies+ * load the whole conversation.+ */+function parseMessageLink(link: string): Target | undefined {+ try {+ const url = new URL(link);+ const channelId = /\/app\/channel\/([^/?#]+)/.exec(url.pathname)?.[1];+ const messageId =+ url.searchParams.get(URL_PARAMS.thread) ??+ url.searchParams.get(URL_PARAMS.message);+ if (channelId && messageId) return { channelId, messageId };+ } catch {+ // not a URL+ }+ return undefined;+}++export default function LinkedConversationDemo() {+ const saved = loadSavedTarget();+ const [channelIdInput, setChannelIdInput] = createSignal(saved.channelId);+ const [messageIdInput, setMessageIdInput] = createSignal(saved.messageId);+ const [target, setTarget] = createSignal<Target>();++ const load = (event: Event) => {+ event.preventDefault();+ const next = {+ channelId: channelIdInput().trim(),+ messageId: messageIdInput().trim(),+ };+ if (!next.channelId || !next.messageId) return;+ localStorage.setItem(STORAGE_KEY, JSON.stringify(next));+ setTarget(next);+ };++ const handleLinkPaste = (value: string) => {+ const parsed = parseMessageLink(value);+ if (!parsed) return;+ setChannelIdInput(parsed.channelId);+ setMessageIdInput(parsed.messageId);+ };++ const inputClass =+ 'w-80 rounded border border-edge-muted bg-surface px-2 py-1 text-sm text-ink font-mono';++ return (+ <div class="p-8 space-y-6 bg-surface min-h-full overflow-auto">+ <div>+ <h1 class="text-xl font-bold text-ink mb-2">LinkedConversation</h1>+ <p class="text-sm text-ink-muted">+ Read-only rendering of a conversation (root message + reply chain)+ from a <code>LinkedConversationSource</code>, here backed by a channel+ thread via <code>createChannelThreadSource</code>.+ </p>+ </div>++ <form onSubmit={load} class="flex flex-col gap-3">+ <label class="flex flex-col gap-1 text-xs text-ink-muted">+ Paste a message link (fills the ids below)+ <input+ class={inputClass}+ placeholder="https://macro.com/app/channel/…?channel_message_id=…"+ onInput={(e) => handleLinkPaste(e.currentTarget.value)}+ />+ </label>+ <label class="flex flex-col gap-1 text-xs text-ink-muted">+ Channel id+ <input+ class={inputClass}+ value={channelIdInput()}+ onInput={(e) => setChannelIdInput(e.currentTarget.value)}+ />+ </label>+ <label class="flex flex-col gap-1 text-xs text-ink-muted">+ Message id (thread root)+ <input+ class={inputClass}+ value={messageIdInput()}+ onInput={(e) => setMessageIdInput(e.currentTarget.value)}+ />+ </label>+ <button+ type="submit"+ class="w-fit rounded border border-edge-muted bg-surface px-3 py-1 text-sm text-ink hover:bg-hover"+ disabled={!channelIdInput().trim() || !messageIdInput().trim()}+ >+ Load conversation+ </button>+ </form>++ <Show when={target()} keyed>+ {(t) => (+ <>+ <DrawerToggle />+ <div class="max-w-2xl rounded-md border border-edge-muted p-3">+ <Suspense+ fallback={<p class="text-sm text-ink-muted">Loading…</p>}+ >+ <ConversationViewer target={t} />+ </Suspense>+ </div>+ <LinkedConversationDrawer+ id={DEMO_DRAWER_ID}+ channelId={t.channelId}+ messageId={t.messageId}+ />+ </>+ )}+ </Show>+ </div>+ );+}++function DrawerToggle() {+ const drawer = useDrawerControl(DEMO_DRAWER_ID);+ return (+ <button+ type="button"+ class="w-fit rounded border border-edge-muted bg-surface px-3 py-1 text-sm text-ink hover:bg-hover"+ onClick={drawer.toggle}+ >+ Open in drawer+ </button>+ );+}++function ConversationViewer(props: { target: Target }) {+ const source = createChannelThreadSource({+ channelId: () => props.target.channelId,+ messageId: () => props.target.messageId,+ });++ return (+ <Show+ when={source.root()}+ fallback={+ <p class="text-sm text-ink-muted">+ No message found — check the channel id and message id.+ </p>+ }+ >+ <LinkedConversation source={source} />+ </Show>+ );+}diff --git a/apps/web/src/lib/core/linked-conversation/index.ts b/apps/web/src/lib/core/linked-conversation/index.tsnew file mode 100644index 0000000000..9c0d89c8ea--- /dev/null+++ b/apps/web/src/lib/core/linked-conversation/index.ts@@ -0,0 +1,7 @@+export { createChannelThreadSource } from './channel-thread-source';+export { LinkedConversation } from './LinkedConversation';+export { LinkedConversationDrawer } from './LinkedConversationDrawer';+export type {+ LinkedConversationMessage,+ LinkedConversationSource,+} from './types';diff --git a/apps/web/src/lib/core/linked-conversation/types.ts b/apps/web/src/lib/core/linked-conversation/types.tsnew file mode 100644index 0000000000..d98e1b36a1--- /dev/null+++ b/apps/web/src/lib/core/linked-conversation/types.ts@@ -0,0 +1,29 @@+import type { MessageData } from '@channel/Message/types';+import type { Accessor } from 'solid-js';++/**+ * A message in a linked conversation. Structurally the channel `Message`+ * primitive contract, so any plain object matching it renders — sources+ * backed by other systems adapt their records into this shape (see+ * `@core/comments/discussion/messageAdapter.ts` for the precedent).+ */+export type LinkedConversationMessage = MessageData;++/**+ * Backing data for a linked conversation, supplied per backend. The+ * presentational component is agnostic to which source backs it — this is the+ * seam that lets the same UI render channel threads today and other+ * conversation stores later. Read-only for now: contribution actions (reply,+ * react) will be added here when users can participate from the linked view.+ */+export interface LinkedConversationSource {+ /** Root message of the conversation, once loaded. */+ root: Accessor<LinkedConversationMessage | undefined>;+ /** Replies to the root, oldest-first. May be a preview subset — see {@link replyCount}. */+ replies: Accessor<LinkedConversationMessage[]>;+ /**+ * Total reply count when the source knows it ahead of a full load (e.g.+ * channel thread metadata). Falls back to `replies().length` when omitted.+ */+ replyCount?: Accessor<number | undefined>;+}diff --git a/apps/web/src/lib/queries/agent-session/session-fold.test.ts b/apps/web/src/lib/queries/agent-session/session-fold.test.tsindex e99204f588..2b7ee21799 100644--- a/apps/web/src/lib/queries/agent-session/session-fold.test.ts+++ b/apps/web/src/lib/queries/agent-session/session-fold.test.ts@@ -41,11 +41,18 @@ function event(session: string, n: number) {const bot = { id: 'bot-id', name: 'Agent' };const message = { agentSessionId: 'session-a' } as FoldedMessage;+const metadata = {+ model: null,+ supportedModels: [],+ title: null,+ availableCommands: [],+ status: null,+};beforeEach(() => {vi.clearAllMocks();- fold.openSession.mockResolvedValue([message]);- fold.sessionMessages.mockResolvedValue([message]);+ fold.openSession.mockResolvedValue({ messages: [message], metadata });+ fold.sessionMessages.mockResolvedValue({ messages: [message], metadata });fold.pushSessionEntries.mockResolvedValue([]);harness.getLog.mockResolvedValue(ok({ bot, entries: [] }));});@@ -140,6 +147,25 @@ describe('shared session folds', () => {expect(fold.closeSession).toHaveBeenCalledWith('session-a');});+ it('routes metadata push events to metadata sinks, latest wins', async () => {+ const seen: unknown[] = [];+ const acquired = await acquireAgentSessionFold({+ agentSessionId: 'session-a',+ onMetadata: (value) => seen.push(value),+ });+ expect(acquired.metadata).toEqual(metadata);++ fold.pushSessionEntries.mockResolvedValue([+ { kind: 'metadata', metadata: { ...metadata, title: 'First' } },+ { kind: 'metadata', metadata: { ...metadata, title: 'Second' } },+ ]);+ handleAgentSessionLog(event('session-a', 1));+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(seen).toEqual([{ ...metadata, title: 'Second' }]);+ acquired.release();+ });+it('releases a failed acquisition without retaining shared state', async () => {harness.getLog.mockResolvedValueOnce(err([{ code: 'HTTP_ERROR', message: 'nope' }])diff --git a/apps/web/src/lib/queries/agent-session/session-fold.ts b/apps/web/src/lib/queries/agent-session/session-fold.tsindex df978d20ea..78b43302b6 100644--- a/apps/web/src/lib/queries/agent-session/session-fold.ts+++ b/apps/web/src/lib/queries/agent-session/session-fold.ts@@ -4,7 +4,10 @@ import {pushSessionEntries,sessionMessages,} from '@core/agent-fold/client';-import type { FoldedMessage } from '@service-agent-fold/generated/types';+import type {+ FoldedMessage,+ SessionMetadata,+} from '@service-agent-fold/generated/types';import { agentHarnessServiceClient } from '@service-agent-harness/client';import type {AgentSessionLogEntryDto,@@ -15,6 +18,9 @@ import { type AgentSessionLogEvent, entryOf } from './realtime-protocol';/** Receives the folded messages changed by appended frames. */export type FoldedMessageSink = (messages: FoldedMessage[]) => void;+/** Receives the session metadata whenever a frame changes it (latest-wins). */+export type SessionMetadataSink = (metadata: SessionMetadata) => void;+/** Receives raw realtime frames for one session. */export type AgentSessionLogSink = (event: AgentSessionLogEvent) => void;@@ -23,6 +29,7 @@ type SessionState = {bot?: SessionBot;buffered: AgentSessionLogEntryDto[];foldedSinks: Set<FoldedMessageSink>;+ metadataSinks: Set<SessionMetadataSink>;opening?: Promise<void>;ready: boolean;references: number;@@ -56,21 +63,25 @@ export function subscribeAgentSessionLog(export async function acquireAgentSessionFold(args: {agentSessionId: string;onChange?: FoldedMessageSink;+ onMetadata?: SessionMetadataSink;}): Promise<{bot: SessionBot;messages: FoldedMessage[];+ metadata: SessionMetadata;release: () => void;}> {- const { agentSessionId, onChange } = args;+ const { agentSessionId, onChange, onMetadata } = args;const state = sessions.get(agentSessionId) ?? {agentSessionId,buffered: [],foldedSinks: new Set<FoldedMessageSink>(),+ metadataSinks: new Set<SessionMetadataSink>(),ready: false,references: 0,};state.references += 1;if (onChange) state.foldedSinks.add(onChange);+ if (onMetadata) state.metadataSinks.add(onMetadata);sessions.set(agentSessionId, state);let released = false;@@ -78,6 +89,7 @@ export async function acquireAgentSessionFold(args: {if (released) return;released = true;if (onChange) state.foldedSinks.delete(onChange);+ if (onMetadata) state.metadataSinks.delete(onMetadata);state.references -= 1;releaseState(state);};@@ -85,12 +97,15 @@ export async function acquireAgentSessionFold(args: {try {state.opening ??= open(state);await state.opening;- const [messages, bot] = await Promise.all([- sessionMessages(agentSessionId),- Promise.resolve(state.bot),- ]);+ const snapshot = await sessionMessages(agentSessionId);+ const bot = state.bot;if (!bot) throw new Error(`agent session ${agentSessionId} has no bot`);- return { bot, messages, release };+ return {+ bot,+ messages: snapshot.messages,+ metadata: snapshot.metadata,+ release,+ };} catch (error) {release();throw error;@@ -162,20 +177,14 @@ async function push(): Promise<void> {const events = await pushSessionEntries(state.agentSessionId, entries);if (sessions.get(state.agentSessionId) !== state) return;- for (const event of events) {- if (event.kind === 'metadata') {- console.log('[agent-fold] metadata changed', event.metadata);- } else {- console.log(- `[agent-fold] ${event.kind} message`,- event.message.requestId,- event.message- );- }- }const messages = events.flatMap((event) =>event.kind === 'metadata' ? [] : [event.message]);+ // Metadata is carried whole per event, latest-wins — only the last matters.+ const metadata = events.findLast((event) => event.kind === 'metadata');+ if (metadata) {+ for (const sink of state.metadataSinks) sink(metadata.metadata);+ }if (messages.length === 0) return;for (const sink of state.foldedSinks) sink(messages);}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.tsindex 312664e8c1..44d1289c70 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts@@ -6,6 +6,7 @@*/import type { AgentSessionResponseAcpSessionId } from './agentSessionResponseAcpSessionId';import type { AgentSessionResponseOriginatingMessageId } from './agentSessionResponseOriginatingMessageId';+import type { AgentSessionResponseThreadChannelId } from './agentSessionResponseThreadChannelId';import type { AgentSessionResponseThreadId } from './agentSessionResponseThreadId';import type { SessionStatusDto } from './sessionStatusDto';@@ -35,6 +36,9 @@ export interface AgentSessionResponse {repoUrl: string;/** The session's status. */status: SessionStatusDto;+ /** The channel `thread_id` lives in, when the session was spawned from a+thread. */+ threadChannelId?: AgentSessionResponseThreadChannelId;/** The root message of the thread the session was created from, if any. */threadId?: AgentSessionResponseThreadId;}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.tsnew file mode 100644index 0000000000..7ba59613b0--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseThreadChannelId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The channel `thread_id` lives in, when the session was spawned from a+thread.+ */+export type AgentSessionResponseThreadChannelId = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex 8db09b766a..9d3524adbd 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -25,6 +25,7 @@ export * from './agentSessionLogResponse';export * from './agentSessionResponse';export * from './agentSessionResponseAcpSessionId';export * from './agentSessionResponseOriginatingMessageId';+export * from './agentSessionResponseThreadChannelId';export * from './agentSessionResponseThreadId';export * from './agentSetModelAction';export * from './botId';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex 4ca8f07c59..17a21507d3 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -445,6 +445,11 @@"$ref": "#/components/schemas/SessionStatusDto","description": "The session's status."},+ "threadChannelId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The channel `thread_id` lives in, when the session was spawned from a\nthread."+ },"threadId": {"type": ["string", "null"],"format": "uuid",diff --git a/bun.lock b/bun.lockindex 2e5b63ffea..4127130a84 100644--- a/bun.lock+++ b/bun.lock@@ -53,6 +53,7 @@"@normy/query-core": "^0.21.0","@opentelemetry/api": "^1.9.1","@phosphor-icons/core": "^2.1.1",+ "@pierre/diffs": "^1.3.5","@solid-primitives/broadcast-channel": "^0.1.1","@solid-primitives/context": "^0.3.2","@solid-primitives/event-bus": "^1.1.2",@@ -87,6 +88,7 @@"d3-shape": "^3.2.0","date-fns": "^4.1.0","detect-browser": "^5.3.0",+ "diff": "^9.0.0","dinero.js": "2.0.0-alpha.8","email-validator": "^2.0.4","emojibase-data": "^17.0.0",@@ -103,6 +105,7 @@"pdfjs-dist": "github:macro-inc/pdf.js#v2.16.52-web","posthog-js": "^1.387.0","quill": "^2.0.3",+ "shiki": "^4.4.3","short-uuid": "^5.2.0","signature_pad": "^5.0.10","solid-custom-scrollbars": "^0.1.7",@@ -1264,6 +1267,12 @@"@phosphor-icons/core": ["@phosphor-icons/[email protected]", "", {}, "sha512-v4ARvrip4qBCImOE5rmPUylOEK4iiED9ZyKjcvzuezqMaiRASCHKcRIuvvxL/twvLpkfnEODCOJp5dM4eZilxQ=="],+ "@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@pierre/theme": "2.0.0", "@pierre/theming": "1.0.1", "@shikijs/transformers": "^3.0.0 || ^4.0.0", "diff": "9.0.0", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0 || ^4.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-BhaLEiUvR+BdIyOYdogA4JLQjluWPubuwySmmIqEkcE0FwIWRbgJgHNC/r884dlxEr89fO4hTk/sBln0a7NSOw=="],++ "@pierre/theme": ["@pierre/[email protected]", "", {}, "sha512-yNDd9GYLQl1mEUJR8AneJ5e4ohLIHQd/wZLWr4fagt78vS2RwwZNW530vVgHqXFAyFVcFlRmGUD5ramXH46OXw=="],++ "@pierre/theming": ["@pierre/[email protected]", "", { "peerDependencies": { "@pierre/theme": "^1.1.0 || ^2.0.0", "@shikijs/themes": "^3.0.0 || ^4.0.0", "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0", "shiki": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@pierre/theme", "@shikijs/themes", "react", "react-dom", "shiki"] }, "sha512-WCI5Qd7iprDpISL9fBYOLe8RV53+b7mFNA3bPzl60/2CKCSrsKN8zEcep6Y3BAzvARlmca50zGjDodqPGiTUKA=="],+"@pkgjs/parseargs": ["@pkgjs/[email protected]", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],"@playwright/test": ["@playwright/[email protected]", "", { "dependencies": { "playwright": "1.62.0" }, "bin": { "playwright": "cli.js" } }, "sha512-9zOJ6ZQRAena31MpOH9VSzIz8Ou3YJ/wtY/eQm5T2uhfhG7/U3COrMS8xOtUrZrp9OgdmzEnIYODye3nY1VqzA=="],@@ -1356,13 +1365,21 @@"@scarf/scarf": ["@scarf/[email protected]", "", {}, "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ=="],- "@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g=="],+ "@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/primitive": "4.4.3", "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.5" } }, "sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg=="],++ "@shikijs/engine-javascript": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.6" } }, "sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ=="],++ "@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w=="],- "@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0" } }, "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg=="],+ "@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.3" } }, "sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A=="],- "@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0" } }, "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA=="],+ "@shikijs/primitive": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ=="],- "@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="],+ "@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.3" } }, "sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw=="],++ "@shikijs/transformers": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/core": "4.4.3", "@shikijs/types": "4.4.3" } }, "sha512-oJSARV6NaWd+rnNJbtnpAdj3Zg0ZVyzsnMgb3vi3HA+35y8lBWUCpOnWsmyiXZIikY+x1BDqrQUgmxfzWh7Jvw=="],++ "@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g=="],"@shikijs/vscode-textmate": ["@shikijs/[email protected]", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],@@ -1606,6 +1623,8 @@"@types/long": ["@types/[email protected]", "", {}, "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA=="],+ "@types/mdast": ["@types/[email protected]", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="],+"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q=="],"@types/request": ["@types/[email protected]", "", { "dependencies": { "@types/caseless": "*", "@types/node": "*", "@types/tough-cookie": "*", "form-data": "^2.5.5" } }, "sha512-FGJ6udDNUCjd19pp0Q3iTiDkwhYup7J8hpMW9c4k53NrccQFFWKRho6hvtPPEhnXWKvukfwAlB6DbDz4yhH5Gg=="],@@ -1634,6 +1653,8 @@"@typespec/ts-http-runtime": ["@typespec/[email protected]", "", { "dependencies": { "http-proxy-agent": "^7.0.0", "https-proxy-agent": "^7.0.0", "tslib": "^2.6.2" } }, "sha512-jIXhD0eWQ1JA6ln/5Dltyx22UxWNrw0hZmhy2rlv6m6KgF7kplHx3g0fzi09lNmTJQRR91OlemYp3xFnvDK9og=="],+ "@ungap/structured-clone": ["@ungap/[email protected]", "", {}, "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg=="],+"@urql/core": ["@urql/[email protected]", "", { "dependencies": { "@0no-co/graphql.web": "^1.0.13", "wonka": "^6.3.2" } }, "sha512-0F39XWR21+IVLJfsqBvLShvoSzxT6h6wWXwrDhN8j9J+IEVOpQIUNHwpgjsp+2ePzn9aCH+rpDonn3HOAUnn9A=="],"@use-gesture/core": ["@use-gesture/[email protected]", "", {}, "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw=="],@@ -1802,6 +1823,8 @@"caniuse-lite": ["[email protected]", "", {}, "sha512-g/uHREV2ZpK9qMalCsWaxmA6ol+DX8GYhuf3T40RKoP+oL7vhRJh8LNt73PCjpnR6l14FzfPrB5Yux4PKm2meg=="],+ "ccount": ["[email protected]", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],+"chai": ["[email protected]", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="],"chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg=="],@@ -1812,6 +1835,10 @@"change-case-all": ["[email protected]", "", { "dependencies": { "change-case": "^5.2.0", "sponge-case": "^2.0.2", "swap-case": "^3.0.2", "title-case": "^3.0.3" } }, "sha512-v6b0WWWkZUMHVuYk82l+WROgkUm4qEN2w5hKRNWtEOYwWqUGoi8C6xH0l1RLF1EoWqDFK6MFclmN3od6ws3/uw=="],+ "character-entities-html4": ["[email protected]", "", {}, "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA=="],++ "character-entities-legacy": ["[email protected]", "", {}, "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="],+"chardet": ["[email protected]", "", {}, "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA=="],"check-error": ["[email protected]", "", {}, "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA=="],@@ -1842,6 +1869,8 @@"combined-stream": ["[email protected]", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="],+ "comma-separated-tokens": ["[email protected]", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="],+"commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],"common-tags": ["[email protected]", "", {}, "sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA=="],@@ -1960,6 +1989,8 @@"detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],+ "devlop": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],+"dezalgo": ["[email protected]", "", { "dependencies": { "asap": "^2.0.0", "wrappy": "1" } }, "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig=="],"diff": ["[email protected]", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="],@@ -2236,12 +2267,18 @@"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],+ "hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],++ "hast-util-whitespace": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],+"hono": ["[email protected]", "", {}, "sha512-1hNiRjawYrLq/4m3DQQjPGFg0VZkk4RjQJDff/excI6Dm9BiL75qxGrd7/c6YOxPdq6AscP3LiXhQ6fKFC1Waw=="],"html-encoding-sniffer": ["[email protected]", "", { "dependencies": { "whatwg-encoding": "^3.1.1" } }, "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ=="],"html-entities": ["[email protected]", "", {}, "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA=="],+ "html-void-elements": ["[email protected]", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="],+"http-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="],"http2-client": ["[email protected]", "", {}, "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA=="],@@ -2544,6 +2581,8 @@"lru-cache": ["[email protected]", "", {}, "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA=="],+ "lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],+"lunr": ["[email protected]", "", {}, "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow=="],"lz-string": ["[email protected]", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="],@@ -2558,6 +2597,8 @@"math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],+ "mdast-util-to-hast": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="],+"mdn-data": ["[email protected]", "", {}, "sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA=="],"mdurl": ["[email protected]", "", {}, "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w=="],@@ -2572,6 +2613,16 @@"methods": ["[email protected]", "", {}, "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w=="],+ "micromark-util-character": ["[email protected]", "", { "dependencies": { "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q=="],++ "micromark-util-encode": ["[email protected]", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="],++ "micromark-util-sanitize-uri": ["[email protected]", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-symbol": "^2.0.0" } }, "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ=="],++ "micromark-util-symbol": ["[email protected]", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="],++ "micromark-util-types": ["[email protected]", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="],+"micromatch": ["[email protected]", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],"mime": ["[email protected]", "", { "bin": { "mime": "cli.js" } }, "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg=="],@@ -2652,6 +2703,10 @@"onetime": ["[email protected]", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],+ "oniguruma-parser": ["[email protected]", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="],++ "oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="],+"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],"openai": ["[email protected]", "", { "peerDependencies": { "@aws-sdk/credential-provider-node": ">=3.972.0 <4", "@smithy/hash-node": ">=4.3.0 <5", "@smithy/signature-v4": ">=5.4.0 <6", "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["@aws-sdk/credential-provider-node", "@smithy/hash-node", "@smithy/signature-v4", "ws", "zod"] }, "sha512-aYCc0C6L864eR6WSYIwQGyXriw/nIyZx0ObvhzOEVuk0zoBDpynjSbrionWI7q65B5H8jJX0DXR9snEzM6bfPg=="],@@ -2754,6 +2809,8 @@"process-nextick-args": ["[email protected]", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],+ "property-information": ["[email protected]", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="],+"proto3-json-serializer": ["[email protected]", "", { "dependencies": { "protobufjs": "^7.2.5" } }, "sha512-SAzp/O4Yh02jGdRc+uIrGoe87dkN/XtwxfZ4ZyafJHymd79ozp5VG5nyZ7ygqPM5+cpLDjjGnYFUkngonyDPOQ=="],"protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="],@@ -2812,6 +2869,12 @@"reftools": ["[email protected]", "", {}, "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w=="],+ "regex": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],++ "regex-recursion": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],++ "regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],+"regexp.prototype.flags": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-errors": "^1.3.0", "get-proto": "^1.0.1", "gopd": "^1.2.0", "set-function-name": "^2.0.2" } }, "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA=="],"remedial": ["[email protected]", "", {}, "sha512-/62tYiOe6DzS5BqVsNpH/nkGlX45C/Sp6V+NtiN6JQNS1Viay7cWkazmRkrQrdFj2eshDe96SIQNIoMxqhzBOg=="],@@ -2898,7 +2961,7 @@"shell-quote": ["[email protected]", "", {}, "sha512-Iov+JwFv/2HcTpcwNMKd8+IWNb8tboQJNQTkAY/LLVK7gGH9jy+LGkVqPxfekHl+yMmiqXszdGWXgkfml7hjqA=="],- "shiki": ["[email protected]", "", { "dependencies": { "jsonc-parser": "^3.0.0", "vscode-oniguruma": "^1.6.1", "vscode-textmate": "5.2.0" } }, "sha512-VsY7QJVzU51j5o1+DguUd+6vmCmZ5v/6gYu4vyYAhzjuNQU6P/vmSy4uQaOhvje031qQMiW0d2BwgMH52vqMng=="],+ "shiki": ["[email protected]", "", { "dependencies": { "@shikijs/core": "4.4.3", "@shikijs/engine-javascript": "4.4.3", "@shikijs/engine-oniguruma": "4.4.3", "@shikijs/langs": "4.4.3", "@shikijs/themes": "4.4.3", "@shikijs/types": "4.4.3", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g=="],"short-uuid": ["[email protected]", "", { "dependencies": { "any-base": "^1.1.0", "uuid": "^9.0.1" } }, "sha512-296/Nzi4DmANh93iYBwT4NoYRJuHnKEzefrkSagQbTH/A6NTaB68hSPDjm5IlbI5dx9FXdmtqPcj6N5H+CPm6w=="],@@ -2970,6 +3033,8 @@"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],+ "space-separated-tokens": ["[email protected]", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],+"sponge-case": ["[email protected]", "", {}, "sha512-i4h9ZGRfxV6Xw3mpZSFOfbXjf0cQcYmssGWutgNIfFZ2VM+YIWfD71N/kjjwK6X/AAHzBr+rciEcn/L34S8TGw=="],"sprintf-js": ["[email protected]", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="],@@ -3004,6 +3069,8 @@"string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],+ "stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],+"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],"strip-ansi-cjs": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],@@ -3098,6 +3165,8 @@"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],+ "trim-lines": ["[email protected]", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],+"ts-log": ["[email protected]", "", {}, "sha512-esq6hx2lM66sQV1YcFkIYTqrWWabmqBqobKHyn1CswdI5FgfQhkmiKiRWVGBNlIbdjBxEIkNvMIwLKKPgRYZLQ=="],"ts-pattern": ["[email protected]", "", {}, "sha512-6s5V71mX8qBUmlgbrfL33xDUwO0fq48rxAu2LBE11WBeGdpCPOsXksQbZJHvHwhrd3QjUusd3mAOM5Gg0mFBLg=="],@@ -3150,6 +3219,16 @@"unicode-emoji-json": ["[email protected]", "", {}, "sha512-3wDXXvp6YGoKGhS2O2H7+V+bYduOBydN1lnI0uVfr1cIdY02uFFiEH1i3kE5CCE4l6UqbLKVmEFW9USxTAMD1g=="],+ "unist-util-is": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],++ "unist-util-position": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],++ "unist-util-stringify-position": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="],++ "unist-util-visit": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg=="],++ "unist-util-visit-parents": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="],+"universalify": ["[email protected]", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="],"unixify": ["[email protected]", "", { "dependencies": { "normalize-path": "^2.1.1" } }, "sha512-6bc58dPYhCMHHuwxldQxO3RRNZ4eCogZ/st++0+fcC1nr0jiGUtAdBJ2qzmLQWSxbtz42pWt4QQMiZ9HvZf5cg=="],@@ -3172,6 +3251,10 @@"validator": ["[email protected]", "", {}, "sha512-4yoz1kEWqUjzi5zsPbAS/903QXSYp0UOtHsPpp7p9rHAw/W+dkInskAE386Fat3oKRROwO98d9ZB0G4cObgUyw=="],+ "vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],++ "vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],+"virtua": ["[email protected]", "", { "peerDependencies": { "react": ">=16.14.0", "react-dom": ">=16.14.0", "solid-js": ">=1.0", "svelte": ">=5.0", "vue": ">=3.2" }, "optionalPeers": ["react", "react-dom", "solid-js", "svelte", "vue"] }, "sha512-jpsxOw5V4B6hg44JePRLo9DL0TV7N1lBEVtPjKpAJebXyhI2s9lfiXJESaLapNtr3vtiSk/pWHiLf7B2a6UcgQ=="],"vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A=="],@@ -3280,6 +3363,8 @@"zone.js": ["[email protected]", "", {}, "sha512-Eky7p2Z1Ig3NnbfodSPoARCjKBSTFMnE/ACsP1L/XJEfY4SdOFce19BsUCWVwL6K5ABZFy5J3bjcMWffX+YM3Q=="],+ "zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],+"@antfu/install-pkg/tinyexec": ["[email protected]", "", {}, "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg=="],"@apidevtools/swagger-parser/@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw=="],@@ -3310,6 +3395,14 @@"@datadog/datadog-ci-plugin-synthetics/ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA=="],+ "@gerrit0/mini-shiki/@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g=="],++ "@gerrit0/mini-shiki/@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0" } }, "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg=="],++ "@gerrit0/mini-shiki/@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.23.0" } }, "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA=="],++ "@gerrit0/mini-shiki/@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ=="],+"@google-cloud/common/google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="],"@google-cloud/common/html-entities": ["[email protected]", "", {}, "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ=="],@@ -3644,6 +3737,8 @@"tsx/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.1", "@esbuild/android-arm": "0.28.1", "@esbuild/android-arm64": "0.28.1", "@esbuild/android-x64": "0.28.1", "@esbuild/darwin-arm64": "0.28.1", "@esbuild/darwin-x64": "0.28.1", "@esbuild/freebsd-arm64": "0.28.1", "@esbuild/freebsd-x64": "0.28.1", "@esbuild/linux-arm": "0.28.1", "@esbuild/linux-arm64": "0.28.1", "@esbuild/linux-ia32": "0.28.1", "@esbuild/linux-loong64": "0.28.1", "@esbuild/linux-mips64el": "0.28.1", "@esbuild/linux-ppc64": "0.28.1", "@esbuild/linux-riscv64": "0.28.1", "@esbuild/linux-s390x": "0.28.1", "@esbuild/linux-x64": "0.28.1", "@esbuild/netbsd-arm64": "0.28.1", "@esbuild/netbsd-x64": "0.28.1", "@esbuild/openbsd-arm64": "0.28.1", "@esbuild/openbsd-x64": "0.28.1", "@esbuild/openharmony-arm64": "0.28.1", "@esbuild/sunos-x64": "0.28.1", "@esbuild/win32-arm64": "0.28.1", "@esbuild/win32-ia32": "0.28.1", "@esbuild/win32-x64": "0.28.1" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw=="],+ "typedoc/shiki": ["[email protected]", "", { "dependencies": { "jsonc-parser": "^3.0.0", "vscode-oniguruma": "^1.6.1", "vscode-textmate": "5.2.0" } }, "sha512-VsY7QJVzU51j5o1+DguUd+6vmCmZ5v/6gYu4vyYAhzjuNQU6P/vmSy4uQaOhvje031qQMiW0d2BwgMH52vqMng=="],+"typedoc-plugin-coverage/typedoc": ["[email protected]", "", { "dependencies": { "@gerrit0/mini-shiki": "^3.23.0", "lunr": "^2.3.9", "markdown-it": "^14.3.0", "minimatch": "^10.2.5", "yaml": "^2.9.0" }, "peerDependencies": { "typescript": "5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x" }, "bin": { "typedoc": "bin/typedoc" } }, "sha512-uSKqkh8Cr48vllnEy+jdaAgOeR6Y+QCBW7usgUsKj7gJEfR7stw9U/fE49LBnj2tPRKPY0c0EBJSWe9Appmplg=="],"typedoc-plugin-markdown/typedoc": ["[email protected]", "", { "dependencies": { "@gerrit0/mini-shiki": "^3.23.0", "lunr": "^2.3.9", "markdown-it": "^14.3.0", "minimatch": "^10.2.5", "yaml": "^2.9.0" }, "peerDependencies": { "typescript": "5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x" }, "bin": { "typedoc": "bin/typedoc" } }, "sha512-uSKqkh8Cr48vllnEy+jdaAgOeR6Y+QCBW7usgUsKj7gJEfR7stw9U/fE49LBnj2tPRKPY0c0EBJSWe9Appmplg=="],diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rsindex cd555af592..cc1115c079 100644--- a/crates/agent_fold/src/domain/fold.rs+++ b/crates/agent_fold/src/domain/fold.rs@@ -53,7 +53,7 @@ use std::borrow::Cow;use crate::domain::error::FoldError;use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};-use crate::domain::meta::{claude_code, command_from_raw_input};+use crate::domain::meta::{claude_code, command_from_raw_input, file_edit_from_raw_input};use crate::domain::model::{AnsiText, Author, AvailableCommand, Control, ControlOutcome, FileDiff, FoldEvent,FoldedMessage, MessagePart, ModelOption, PermissionOption, PermissionOptionKind,@@ -1137,7 +1137,7 @@ fn tool_detail(exit_code: claude_code::terminal_exit_code(meta),},ToolKind::Edit => ToolDetail::Edit {- diffs: diffs(content),+ diffs: edit_diffs(content, raw_input),},ToolKind::Read => ToolDetail::Read {paths: location_paths(locations),@@ -1199,6 +1199,13 @@ fn patch_detail(*existing = found;}}+ // A call that never reports a diff block (Claude Code's `Write`)+ // may still deliver its raw input on a later update.+ if existing.is_empty()+ && let Some(found) = synthesized_edit_diff(raw_input)+ {+ *existing = vec![found];+ }}ToolDetail::Read { paths } | ToolDetail::Delete { paths } | ToolDetail::Move { paths } => {if let Some(found) = locations.map(location_paths)@@ -1233,6 +1240,28 @@ fn patch_detail(}}+/// An edit call's diffs: the reported diff blocks, or — for calls that never+/// report one, like Claude Code's `Write` — a whole-file diff synthesized+/// from the raw input.+fn edit_diffs(content: &[ToolCallContent], raw_input: Option<&serde_json::Value>) -> Vec<FileDiff> {+ let found = diffs(content);+ if !found.is_empty() {+ return found;+ }+ synthesized_edit_diff(raw_input).into_iter().collect()+}++/// A whole-file diff from `{filePath, content}` raw input. The prior contents+/// are not on the wire, so the file reads as new.+fn synthesized_edit_diff(raw_input: Option<&serde_json::Value>) -> Option<FileDiff> {+ let (path, content) = file_edit_from_raw_input(raw_input)?;+ Some(FileDiff {+ path: path.into(),+ old_text: None,+ new_text: content,+ })+}+/// The diffs among a tool call's content blocks.fn diffs(content: &[ToolCallContent]) -> Vec<FileDiff> {contentdiff --git a/crates/agent_fold/src/domain/meta.rs b/crates/agent_fold/src/domain/meta.rsindex 043614ad22..ce525adb74 100644--- a/crates/agent_fold/src/domain/meta.rs+++ b/crates/agent_fold/src/domain/meta.rs@@ -69,3 +69,19 @@ pub mod claude_code {pub fn command_from_raw_input(raw_input: Option<&serde_json::Value>) -> Option<String> {raw_input?.get("command")?.as_str().map(ToOwned::to_owned)}++/// The whole-file edit an edit tool's raw input describes, as+/// `(path, new contents)`.+///+/// Claude Code's `Write` (and whole-file `Edit`) calls carry+/// `{"filePath", "content"}` in `rawInput` and never report an ACP diff+/// content block, so this is the only material a fold has for their diff. The+/// prior contents are not on the wire at all — a reader treats the file as+/// new.+#[must_use]+pub fn file_edit_from_raw_input(raw_input: Option<&serde_json::Value>) -> Option<(String, String)> {+ let input = raw_input?;+ let path = input.get("filePath")?.as_str()?;+ let content = input.get("content")?.as_str()?;+ Some((path.to_owned(), content.to_owned()))+}diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rsindex ae05a9787d..fad5631afc 100644--- a/crates/agent_fold/src/domain/test/fold.rs+++ b/crates/agent_fold/src/domain/test/fold.rs@@ -313,6 +313,59 @@ fn folds_every_official_tool_kind() {insta::assert_debug_snapshot!(agent.parts);}+/// An edit call that never reports a diff content block — Claude Code's+/// `Write` — synthesizes a whole-file diff from `rawInput`'s+/// `{filePath, content}`, on the opening frame or a later patch.+#[test]+fn synthesizes_a_write_diff_from_raw_input() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"hi"}]}}}"#,+ "\n",+ // Opened with the raw input already present, no diff content ever.+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"w","title":"write","kind":"edit","status":"in_progress","rawInput":{"filePath":"/repo/readme.md","content":"hello\n"}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"w","status":"completed"}}}}"#,+ ));++ let messages = fold(log);+ let MessagePart::ToolUse { detail, .. } = &messages[1].parts[0] else {+ panic!("first part is the write: {:?}", messages[1].parts);+ };+ let ToolDetail::Edit { diffs } = detail else {+ panic!("write folds to an edit: {detail:?}");+ };+ assert_eq!(diffs.len(), 1);+ assert_eq!(diffs[0].path, std::path::PathBuf::from("/repo/readme.md"));+ assert_eq!(+ diffs[0].old_text, None,+ "prior contents are not on the wire"+ );+ assert_eq!(diffs[0].new_text, "hello\n");+}++/// A reported diff block wins over the synthesized raw-input diff.+#[test]+fn reported_diffs_beat_the_synthesized_write_diff() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"hi"}]}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"e","title":"edit","kind":"edit","status":"in_progress","rawInput":{"filePath":"/repo/a.rs","content":"whole file"}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"e","status":"completed","content":[{"type":"diff","path":"/repo/a.rs","oldText":"old","newText":"new"}]}}}}"#,+ ));++ let messages = fold(log);+ let MessagePart::ToolUse { detail, .. } = &messages[1].parts[0] else {+ panic!("first part is the edit: {:?}", messages[1].parts);+ };+ let ToolDetail::Edit { diffs } = detail else {+ panic!("edit folds to diffs: {detail:?}");+ };+ assert_eq!(diffs.len(), 1);+ assert_eq!(diffs[0].old_text.as_deref(), Some("old"));+ assert_eq!(diffs[0].new_text, "new");+}+/// A patch for a tool call that was never opened is logged, not fatal.#[test]fn reports_a_patch_before_open() {diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 0a6c801c76..c1634d6e2d 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -55,6 +55,10 @@ pub struct AgentSession {pub owner_id: MacroUserIdStr<'static>,/// The root message where the bot was originally invoked, if any.pub thread_id: Option<Uuid>,+ /// The channel `thread_id` lives in, when the session was spawned from a+ /// thread. Derived from the thread root's message row rather than+ /// stored — the message's channel is authoritative.+ pub thread_channel_id: Option<Uuid>,/// The exact message that originally invoked the bot, if any.pub originating_message_id: Option<Uuid>,/// the bot id of the bot running the agentdiff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 33e57411e9..ab254c0d04 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -276,6 +276,9 @@ pub struct AgentSessionResponse {pub owner_id: String,/// The root message of the thread the session was created from, if any.pub thread_id: Option<Uuid>,+ /// The channel `thread_id` lives in, when the session was spawned from a+ /// thread.+ pub thread_channel_id: Option<Uuid>,/// The exact message that invoked the bot, if any.pub originating_message_id: Option<Uuid>,/// The bot running the agent.@@ -302,6 +305,7 @@ impl From<AgentSession> for AgentSessionResponse {id: session.id.as_uuid(),owner_id: session.owner_id.to_string(),thread_id: session.thread_id,+ thread_channel_id: session.thread_channel_id,originating_message_id: session.originating_message_id,bot_id: session.bot_id.as_uuid(),model: session.model,diff --git a/crates/agent_session/src/outbound/postgres/mod.rs b/crates/agent_session/src/outbound/postgres/mod.rsindex c4c5c3c361..621ea28f98 100644--- a/crates/agent_session/src/outbound/postgres/mod.rs+++ b/crates/agent_session/src/outbound/postgres/mod.rs@@ -91,6 +91,7 @@ struct AgentSessionRow {id: Uuid,owner_id: String,thread_id: Option<Uuid>,+ thread_channel_id: Option<Uuid>,originating_message_id: Option<Uuid>,bot_id: Uuid,model: String,@@ -113,6 +114,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {owner_id: MacroUserIdStr::try_from(row.owner_id).context("agent session has an unparseable owner")?,thread_id: row.thread_id,+ thread_channel_id: row.thread_channel_id,originating_message_id: row.originating_message_id,bot_id: BotId::new_from_uuid(row.bot_id),model: row.model,@@ -160,7 +162,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {RETURNINGid, owner_id, thread_id, originating_message_id, bot_id,model, harness, repo_url, acp_session_id, status, status_event_name,- created_at, modified_at+ created_at, modified_at,+ (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)+ AS "thread_channel_id?""#,id.as_uuid(),owner_id.as_ref(),@@ -233,7 +237,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {SELECTid, owner_id, thread_id, originating_message_id, bot_id,model, harness, repo_url, acp_session_id, status, status_event_name,- created_at, modified_at+ created_at, modified_at,+ (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)+ AS "thread_channel_id?"FROM agent_sessionWHERE id = $1"#,@@ -264,7 +270,9 @@ impl AgentSessionRepo for PgAgentSessionRepo {SELECTid, owner_id, thread_id, originating_message_id, bot_id,model, harness, repo_url, acp_session_id, status, status_event_name,- created_at, modified_at+ created_at, modified_at,+ (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)+ AS "thread_channel_id?"FROM agent_sessionWHERE thread_id = $1 AND bot_id = $2ORDER BY created_at DESCdiff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 94410bc665..fdade07443 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -317,7 +317,7 @@ async fn find_for_channel_matches_the_originating_thread_and_bot(pool: PgPool) {let repo = PgAgentSessionRepo::new(pool.clone());let bot_a = create_test_bot(&pool).await;let bot_b = create_test_bot(&pool).await;- let (_originating_channel, thread, originating_message) =+ let (originating_channel, thread, originating_message) =insert_originating_thread_fixture(&pool).await;let session = create_session(@@ -325,6 +325,9 @@ async fn find_for_channel_matches_the_originating_thread_and_bot(pool: PgPool) {new_session(bot_b, Some(thread), Some(originating_message)),).await;+ // The create response must already resolve the thread's channel: linked+ // -thread navigation renders from this row without a second lookup.+ assert_eq!(session.thread_channel_id, Some(originating_channel));// A session from some other context must not shadow the lookup.create_session(&repo, new_session(bot_a, None, None)).await;@@ -337,6 +340,7 @@ async fn find_for_channel_matches_the_originating_thread_and_bot(pool: PgPool) {};assert_eq!(matched.id, session.id);assert_eq!(matched.originating_message_id, Some(originating_message));+ assert_eq!(matched.thread_channel_id, Some(originating_channel));let wrong_bot = repo.find_for_channel(Some(thread), Some(bot_a))diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex 92e8bf77b3..e8dd6db641 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -102,6 +102,8 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {id: params.id,owner_id: params.owner_id,thread_id: params.thread_id,+ // The in-memory repo has no comms rows to derive a channel from.+ thread_channel_id: None,originating_message_id: params.originating_message_id,bot_id: params.bot_id,model: params.model,@@ -290,6 +292,7 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {owner_id: macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").expect("valid macro user id"),thread_id: None,+ thread_channel_id: None,originating_message_id: None,bot_id: BotId::new_from_uuid(Uuid::from_u128(0xb07)),model: "claude-sonnet-5".to_string(),diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 7d6af328ea..40b12882c3 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -47,6 +47,7 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {id,owner_id: MacroUserIdStr::try_from_email("[email protected]").expect("valid macro user id"),thread_id: None,+ thread_channel_id: None,originating_message_id: None,bot_id,model: "model".to_owned(),diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.jsonindex 4db10355a1..a04f4aac97 100644--- a/nix-support/node_modules-hashes.json+++ b/nix-support/node_modules-hashes.json@@ -1,6 +1,6 @@{"nodeModules": {- "aarch64-darwin": "sha256-62zvY4Lt3mpN9bl42m2T0k9ndedLGUBkWFQlR5qBvXs=",- "x86_64-linux": "sha256-MBea1zLaAa/2dTSWmkfDUp/RtWK9SURmMpiGWQ7fKdg="+ "aarch64-darwin": "sha256-1twYQYOzR/LZ6S5zM0eCXyKttn0B66wQoeW4w712o/c=",+ "x86_64-linux": "sha256-2SoOzP1lzRlIvwkgJxfl5CxkLB48L36U1X65wMatImU="}}