@happyvertical/smrt-chat 0.51.5 → 0.51.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/AGENTS.md +19 -0
  2. package/dist/index.js +1 -1
  3. package/dist/manifest.json +1 -1
  4. package/dist/smrt-knowledge.json +5 -5
  5. package/dist/svelte/components/agent/ToolCallDisplay.svelte +103 -7
  6. package/dist/svelte/components/agent/ToolCallDisplay.svelte.d.ts +18 -0
  7. package/dist/svelte/components/agent/ToolCallDisplay.svelte.d.ts.map +1 -1
  8. package/dist/svelte/components/agent/__tests__/ToolCallDisplay.test.js +100 -9
  9. package/dist/svelte/components/assistant/AssistantComposer.svelte +354 -0
  10. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts +20 -0
  11. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts.map +1 -0
  12. package/dist/svelte/components/assistant/AssistantDock.svelte +534 -0
  13. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts +30 -0
  14. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts.map +1 -0
  15. package/dist/svelte/components/assistant/AssistantThreadList.svelte +136 -0
  16. package/dist/svelte/components/assistant/AssistantThreadList.svelte.d.ts +15 -0
  17. package/dist/svelte/components/assistant/AssistantThreadList.svelte.d.ts.map +1 -0
  18. package/dist/svelte/components/assistant/__tests__/AssistantComposer.test.js +75 -0
  19. package/dist/svelte/components/assistant/__tests__/AssistantDock.test.js +395 -0
  20. package/dist/svelte/components/assistant/__tests__/AssistantThreadList.test.js +45 -0
  21. package/dist/svelte/components/assistant/__tests__/action-status.test.js +25 -0
  22. package/dist/svelte/components/assistant/__tests__/assistant-transport.test.js +253 -0
  23. package/dist/svelte/components/assistant/__tests__/attachment-href.test.js +31 -0
  24. package/dist/svelte/components/assistant/__tests__/create-assistant-dock-controller.test.js +2492 -0
  25. package/dist/svelte/components/assistant/action-status.d.ts +14 -0
  26. package/dist/svelte/components/assistant/action-status.d.ts.map +1 -0
  27. package/dist/svelte/components/assistant/action-status.js +7 -0
  28. package/dist/svelte/components/assistant/assistant-transport.d.ts +239 -0
  29. package/dist/svelte/components/assistant/assistant-transport.d.ts.map +1 -0
  30. package/dist/svelte/components/assistant/assistant-transport.js +306 -0
  31. package/dist/svelte/components/assistant/attachment-href.d.ts +23 -0
  32. package/dist/svelte/components/assistant/attachment-href.d.ts.map +1 -0
  33. package/dist/svelte/components/assistant/attachment-href.js +36 -0
  34. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts +172 -0
  35. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts.map +1 -0
  36. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.js +0 -0
  37. package/dist/svelte/components/shared/ModelPicker.svelte +84 -0
  38. package/dist/svelte/components/shared/ModelPicker.svelte.d.ts +26 -0
  39. package/dist/svelte/components/shared/ModelPicker.svelte.d.ts.map +1 -0
  40. package/dist/svelte/components/shared/__tests__/ModelPicker.test.js +36 -0
  41. package/dist/svelte/i18n.d.ts +21 -0
  42. package/dist/svelte/i18n.d.ts.map +1 -1
  43. package/dist/svelte/i18n.js +25 -0
  44. package/dist/svelte/index.d.ts +7 -0
  45. package/dist/svelte/index.d.ts.map +1 -1
  46. package/dist/svelte/index.js +12 -0
  47. package/package.json +11 -11
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-chat",
5
- "packageVersion": "0.51.5",
5
+ "packageVersion": "0.51.6",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-chat:AgentSessionCollection": {
8
8
  "name": "agentsessioncollection",
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-chat",
6
- "packageVersion": "0.51.5",
6
+ "packageVersion": "0.51.6",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "f595007a8fec0375b6d1432ad715313ac532fc8c300fd0033ec94c93cddce31d",
11
- "packageJson": "aebde1a796c8d61bfafe9c29879a4224674094c5530481f086e0f0d41068bee1",
12
- "agents": "8d016963502a7cb53247cc366c5265c6b4d3240bc9c352242485b24a3644677c"
10
+ "manifest": "d7afc478c46521adbe6d0306efbb20915aa4bb518c2c8aa38c8518cb37ba82d3",
11
+ "packageJson": "636f5772d37b9810860eb1cb040836fb19171832de1677ff805c2484ceb1dc29",
12
+ "agents": "09fd59894602d9ff76216fdec92ef2e4eb20d63e0a9a469ba9217af3ed8efca2"
13
13
  },
14
14
  "exports": [
15
15
  ".",
@@ -5108,5 +5108,5 @@
5108
5108
  "polymorphicAssociations": 0,
5109
5109
  "uuidColumns": 76
5110
5110
  },
5111
- "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute is an interactive chat surface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root workbench also has a dev-only voice conversation mode. It reads voice\ngateway connection details through `/api/dev-voice/config`, streams browser mic\naudio to `WS /ws/voice` as PCM16 mono, appends gateway transcripts/responses to\nthe chat, and plays returned TTS audio. Exposing\n`SMRT_CHAT_DEV_VOICE_GATEWAY_TOKEN` to the browser requires\n`SMRT_CHAT_DEV_VOICE_GATEWAY_EXPOSE_TOKEN=true`; keep that local-only.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for accidental mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (string ref, not FK), `allowedTools` (JSON string array), `sessionContext` (JSON), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentId`, accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Conversational Harness (L3, #1891)\n\nThe `AgentSession` runtime depends on personas, agents, and users. Keep those\nedges acyclic: none of those packages may depend back on chat.\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by a max-steps ceiling (`DEFAULT_MAX_STEPS = 8`): on the ceiling it disables tools for one final completion so the turn always terminates with text.\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge.\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token Streaming (SSE, #1936)\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n"
5111
+ "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute is an interactive chat surface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root workbench also has a dev-only voice conversation mode. It reads voice\ngateway connection details through `/api/dev-voice/config`, streams browser mic\naudio to `WS /ws/voice` as PCM16 mono, appends gateway transcripts/responses to\nthe chat, and plays returned TTS audio. Exposing\n`SMRT_CHAT_DEV_VOICE_GATEWAY_TOKEN` to the browser requires\n`SMRT_CHAT_DEV_VOICE_GATEWAY_EXPOSE_TOKEN=true`; keep that local-only.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for accidental mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (string ref, not FK), `allowedTools` (JSON string array), `sessionContext` (JSON), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentId`, accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Conversational Harness (L3, #1891)\n\nThe `AgentSession` runtime depends on personas, agents, and users. Keep those\nedges acyclic: none of those packages may depend back on chat.\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by a max-steps ceiling (`DEFAULT_MAX_STEPS = 8`): on the ceiling it disables tools for one final completion so the turn always terminates with text.\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge.\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token Streaming (SSE, #1936)\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`) is a\nshell-mounted, route-aware assistant surface: it discovers currently-mounted\n`DataSurfaceDescriptor`s from a host-supplied `DataSurfaceRegistry`\n(`@happyvertical/smrt-ui/data-surface`) and fails closed to plain chat when\nnone are mounted. Action proposals flow through\n`normalizeDataSurfaceActionRequest` → a host-supplied `AssistantActionClient`\n(preview/apply against a server-hosted `DataSurfaceActionAdapter`, not through\nthe `data-surface-bridge.ts` live-collaboration command channel) →\n`ToolCallDisplay`'s additive `actionResult` rendering. `AssistantTransport`\n(`assistant-transport.ts`) is a narrower, separate contract from\n`ChatClientBackend` (`client.ts`): `ChatThread`/`ChatMessage` only expose\ngenerated `list`/`get` REST (`api: { include: ['list', 'get'] }`,\n`models/ChatThread.ts:16`, `models/ChatMessage.ts:26`), so writes need a host-\nsupplied `writeEndpoint`. See [`docs/assistant-dock.md`](../../docs/assistant-dock.md)\nfor the full design, the anytown `PortalChatTool.svelte` polling/stale-send\nreconnaissance, and open gaps.\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n"
5112
5112
  }
@@ -4,23 +4,59 @@
4
4
  * Collapsible card showing tool name, arguments (as JSON), status indicator,
5
5
  * and result/error. Color-coded by status (pending, running, success, error).
6
6
  */
7
+ import type { DataSurfaceActionResult } from '@happyvertical/smrt-ui/data-surface';
7
8
  import { useI18n } from '@happyvertical/smrt-ui/i18n';
9
+ import { Button } from '@happyvertical/smrt-ui/ui';
8
10
  import { M } from '../../i18n.js';
9
11
  import type { ToolCallDisplayData } from '../../types.js';
10
12
 
11
13
  export interface Props {
12
14
  /** Tool call data */
13
15
  toolCall: ToolCallDisplayData;
16
+ /**
17
+ * Data-surface action preview/apply outcome (#2904, AssistantDock). Additive:
18
+ * when present, the body renders a preview/applied/failed panel for the
19
+ * action alongside the generic tool-call rendering above; existing callers
20
+ * that never pass this prop see no change.
21
+ */
22
+ actionResult?: DataSurfaceActionResult;
23
+ /** Fired by the Confirm button, shown only while
24
+ * `actionResult.phase === 'preview' && actionResult.ok`. */
25
+ onconfirmaction?: () => void;
26
+ /** Fired by the Reject button, shown alongside `onconfirmaction`. */
27
+ onrejectaction?: () => void;
14
28
  }
15
29
 
16
- const { toolCall }: Props = $props();
30
+ const { toolCall, actionResult, onconfirmaction, onrejectaction }: Props =
31
+ $props();
17
32
 
18
33
  const { t } = useI18n();
19
34
 
20
- let isExpanded = $state(false);
35
+ // When an actionResult is present it overrides the generic tool-call status
36
+ // for both the pill and the outer card's color: a preview that's still
37
+ // awaiting Confirm/Reject must never read "Completed" (#2904 review fix) —
38
+ // only an applied action reads that way.
39
+ const effectiveStatus = $derived.by(() => {
40
+ if (!actionResult) return toolCall.status;
41
+ if (!actionResult.ok) return 'error';
42
+ return actionResult.phase === 'preview' ? 'awaiting-confirmation' : 'applied';
43
+ });
44
+
45
+ // A pending preview (awaiting Confirm/Reject), a running tool call, or a
46
+ // failed action starts expanded so the action buttons / live output /
47
+ // failure reason are visible without a click; the user's own toggle always
48
+ // wins after that.
49
+ let userToggledExpanded = $state<boolean | null>(null);
50
+ const autoExpanded = $derived(
51
+ effectiveStatus === 'awaiting-confirmation' ||
52
+ effectiveStatus === 'applied' ||
53
+ toolCall.status === 'running' ||
54
+ (Boolean(actionResult) && effectiveStatus === 'error'),
55
+ );
56
+ const isExpanded = $derived(userToggledExpanded ?? autoExpanded);
21
57
 
22
58
  const statusLabel = $derived.by(() => {
23
- switch (toolCall.status) {
59
+ switch (effectiveStatus) {
24
60
  case 'pending':
25
61
  return 'Pending';
26
62
  case 'running':
@@ -28,9 +64,13 @@ const statusLabel = $derived.by(() => {
28
64
  case 'success':
29
65
  return 'Completed';
30
66
  case 'error':
31
- return 'Error';
67
+ return actionResult ? 'Failed' : 'Error';
68
+ case 'awaiting-confirmation':
69
+ return 'Awaiting confirmation';
70
+ case 'applied':
71
+ return 'Applied';
32
72
  default:
33
- return toolCall.status;
73
+ return effectiveStatus;
34
74
  }
35
75
  });
36
76
 
@@ -49,12 +89,12 @@ function formatDuration(ms: number | undefined): string {
49
89
  }
50
90
  </script>
51
91
 
52
- <div class="tool-call tool-call--{toolCall.status}" aria-label={t(M['chat.tool_call_display.tool_call'], { toolName: toolCall.toolName })}>
92
+ <div class="tool-call tool-call--{effectiveStatus}" aria-label={t(M['chat.tool_call_display.tool_call'], { toolName: toolCall.toolName })}>
53
93
  <!-- raw-primitive-allow: full-width disclosure trigger with aria-expanded and aria-controls toggling an externally-rendered collapsible panel, wrapping rich content (status dot, name, duration, status label, rotating chevron); structural accordion header no Button primitive owns -->
54
94
  <button
55
95
  class="tool-call__header"
56
96
  type="button"
57
- onclick={() => isExpanded = !isExpanded}
97
+ onclick={() => userToggledExpanded = !isExpanded}
58
98
  aria-expanded={isExpanded}
59
99
  aria-controls="tool-call-body-{toolCall.toolCallId}"
60
100
  >
@@ -110,6 +150,40 @@ function formatDuration(ms: number | undefined): string {
110
150
  <span>Executing...</span>
111
151
  </div>
112
152
  {/if}
153
+
154
+ {#if actionResult}
155
+ <div class="tool-call__section tool-call__data-surface-action" data-phase={actionResult.phase} data-ok={actionResult.ok}>
156
+ <span class="tool-call__section-label">
157
+ {actionResult.phase === 'preview' ? 'Proposed change' : 'Applied change'}
158
+ </span>
159
+ {#if actionResult.ok}
160
+ {#if actionResult.details}
161
+ <pre class="tool-call__json">{formatJson(actionResult.details)}</pre>
162
+ {:else if actionResult.phase === 'apply'}
163
+ <p class="tool-call__applied-fallback">
164
+ {t(M['chat.tool_call_display.applied_successfully'])}
165
+ </p>
166
+ {/if}
167
+ {#if actionResult.phase === 'preview'}
168
+ <div class="tool-call__data-surface-action-buttons">
169
+ <Button type="button" size="sm" onclick={() => onconfirmaction?.()}>
170
+ {t(M['chat.tool_call_display.confirm'])}
171
+ </Button>
172
+ <Button
173
+ type="button"
174
+ variant="secondary"
175
+ size="sm"
176
+ onclick={() => onrejectaction?.()}
177
+ >
178
+ {t(M['chat.tool_call_display.reject'])}
179
+ </Button>
180
+ </div>
181
+ {/if}
182
+ {:else}
183
+ <pre class="tool-call__json tool-call__json--error">{actionResult.reason ?? 'Action failed'}</pre>
184
+ {/if}
185
+ </div>
186
+ {/if}
113
187
  </div>
114
188
  {/if}
115
189
  </div>
@@ -138,6 +212,14 @@ function formatDuration(ms: number | undefined): string {
138
212
  border-left: 3px solid var(--smrt-color-error, #b3261e);
139
213
  }
140
214
 
215
+ .tool-call--awaiting-confirmation {
216
+ border-left: 3px solid var(--smrt-color-tertiary, #7d5260);
217
+ }
218
+
219
+ .tool-call--applied {
220
+ border-left: 3px solid var(--smrt-color-success, #1e8e3e);
221
+ }
222
+
141
223
  .tool-call__header {
142
224
  display: flex;
143
225
  align-items: center;
@@ -186,6 +268,20 @@ function formatDuration(ms: number | undefined): string {
186
268
  background: var(--smrt-color-error, #b3261e);
187
269
  }
188
270
 
271
+ .tool-call--awaiting-confirmation .tool-call__status-dot {
272
+ background: var(--smrt-color-tertiary, #7d5260);
273
+ }
274
+
275
+ .tool-call--applied .tool-call__status-dot {
276
+ background: var(--smrt-color-success, #1e8e3e);
277
+ }
278
+
279
+ .tool-call__applied-fallback {
280
+ margin: 0;
281
+ font: var(--smrt-typography-body-small-font, 0.8125rem/1.4 sans-serif);
282
+ color: var(--smrt-color-on-surface-variant, #43474e);
283
+ }
284
+
189
285
  .tool-call__name {
190
286
  font: var(--smrt-typography-label-large-font, 500 0.875rem/1.25 sans-serif);
191
287
  font-family: var(--smrt-font-family-mono, 'SF Mono', 'Fira Code', 'Cascadia Code', monospace);
@@ -1,7 +1,25 @@
1
+ /**
2
+ * ToolCallDisplay - Inline tool call/result display
3
+ * Collapsible card showing tool name, arguments (as JSON), status indicator,
4
+ * and result/error. Color-coded by status (pending, running, success, error).
5
+ */
6
+ import type { DataSurfaceActionResult } from '@happyvertical/smrt-ui/data-surface';
1
7
  import type { ToolCallDisplayData } from '../../types.js';
2
8
  export interface Props {
3
9
  /** Tool call data */
4
10
  toolCall: ToolCallDisplayData;
11
+ /**
12
+ * Data-surface action preview/apply outcome (#2904, AssistantDock). Additive:
13
+ * when present, the body renders a preview/applied/failed panel for the
14
+ * action alongside the generic tool-call rendering above; existing callers
15
+ * that never pass this prop see no change.
16
+ */
17
+ actionResult?: DataSurfaceActionResult;
18
+ /** Fired by the Confirm button, shown only while
19
+ * `actionResult.phase === 'preview' && actionResult.ok`. */
20
+ onconfirmaction?: () => void;
21
+ /** Fired by the Reject button, shown alongside `onconfirmaction`. */
22
+ onrejectaction?: () => void;
5
23
  }
6
24
  declare const ToolCallDisplay: import("svelte").Component<Props, {}, "">;
7
25
  type ToolCallDisplay = ReturnType<typeof ToolCallDisplay>;
@@ -1 +1 @@
1
- {"version":3,"file":"ToolCallDisplay.svelte.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/agent/ToolCallDisplay.svelte.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAG1D,MAAM,WAAW,KAAK;IACpB,qBAAqB;IACrB,QAAQ,EAAE,mBAAmB,CAAC;CAC/B;AAmGD,QAAA,MAAM,eAAe,2CAAwC,CAAC;AAC9D,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;AAC1D,eAAe,eAAe,CAAC"}
1
+ {"version":3,"file":"ToolCallDisplay.svelte.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/agent/ToolCallDisplay.svelte.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAInF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAG1D,MAAM,WAAW,KAAK;IACpB,qBAAqB;IACrB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,uBAAuB,CAAC;IACvC;gEAC4D;IAC5D,eAAe,CAAC,EAAE,MAAM,IAAI,CAAC;IAC7B,qEAAqE;IACrE,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;CAC7B;AA4JD,QAAA,MAAM,eAAe,2CAAwC,CAAC;AAC9D,KAAK,eAAe,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;AAC1D,eAAe,eAAe,CAAC"}
@@ -1,13 +1,5 @@
1
- // @vitest-environment jsdom
2
- /**
3
- * Component coverage for ToolCallDisplay via the shared S11 harness (#1416).
4
- *
5
- * Locks the T2 #1391 dead-code removal: the unused `statusIcon` $derived (which
6
- * returned '...'/'' for every branch and was never rendered) was removed. The
7
- * component must still render the tool name and status, and expand on click.
8
- */
9
1
  import { expectNoA11yViolations, render, screen, userEvent, } from '@happyvertical/smrt-vitest/svelte';
10
- import { describe, expect, it } from 'vitest';
2
+ import { describe, expect, it, vi } from 'vitest';
11
3
  import ToolCallDisplay from '../ToolCallDisplay.svelte';
12
4
  function makeToolCall(overrides = {}) {
13
5
  return {
@@ -26,6 +18,19 @@ describe('ToolCallDisplay', () => {
26
18
  expect(screen.getByText('search')).toBeInTheDocument();
27
19
  expect(screen.getByText('Completed')).toBeInTheDocument();
28
20
  });
21
+ // #2904 review, Copilot PR #2919 jAwua/jAwtb: AssistantDock/the demo route
22
+ // map an in-flight preview/apply action to this 'running' toolCall status
23
+ // (see action-status.test.ts) — assert it actually renders "Running", not
24
+ // "Completed".
25
+ it('renders "Running" for a running tool call', () => {
26
+ render(ToolCallDisplay, {
27
+ props: {
28
+ toolCall: makeToolCall({ status: 'running', result: undefined }),
29
+ },
30
+ });
31
+ expect(screen.getByText('Running')).toBeInTheDocument();
32
+ expect(screen.queryByText('Completed')).not.toBeInTheDocument();
33
+ });
29
34
  it('expands to reveal arguments and result on click', async () => {
30
35
  render(ToolCallDisplay, { props: { toolCall: makeToolCall() } });
31
36
  const header = screen.getByRole('button');
@@ -41,4 +46,90 @@ describe('ToolCallDisplay', () => {
41
46
  });
42
47
  await expectNoA11yViolations(container);
43
48
  });
49
+ // #2904: additive DataSurfaceActionResult rendering, used by AssistantDock.
50
+ function makeActionResult(overrides = {}) {
51
+ return {
52
+ version: 1,
53
+ requestId: 'req-1',
54
+ identity: {
55
+ surfaceId: 'orders',
56
+ kind: 'table',
57
+ subject: { type: 'tenant', id: 'tenant-a' },
58
+ },
59
+ actionId: 'archive',
60
+ phase: 'preview',
61
+ ok: true,
62
+ ...overrides,
63
+ };
64
+ }
65
+ it('a pending preview reads "Awaiting confirmation", starts expanded, and exposes Confirm/Reject', async () => {
66
+ const onconfirmaction = vi.fn();
67
+ const onrejectaction = vi.fn();
68
+ render(ToolCallDisplay, {
69
+ props: {
70
+ toolCall: makeToolCall(),
71
+ actionResult: makeActionResult(),
72
+ onconfirmaction,
73
+ onrejectaction,
74
+ },
75
+ });
76
+ // #2904 review fix: a preview must never read "Completed" and must be
77
+ // expanded by default so Confirm/Reject are visible without a click.
78
+ expect(screen.queryByText('Completed')).not.toBeInTheDocument();
79
+ expect(screen.getByText('Awaiting confirmation')).toBeInTheDocument();
80
+ const header = screen.getByRole('button', { name: /search/i });
81
+ expect(header).toHaveAttribute('aria-expanded', 'true');
82
+ expect(screen.getByText('Proposed change')).toBeInTheDocument();
83
+ await userEvent.click(screen.getByRole('button', { name: 'Confirm' }));
84
+ expect(onconfirmaction).toHaveBeenCalledOnce();
85
+ await userEvent.click(screen.getByRole('button', { name: 'Reject' }));
86
+ expect(onrejectaction).toHaveBeenCalledOnce();
87
+ });
88
+ it('the header toggle still collapses an awaiting-confirmation card', async () => {
89
+ render(ToolCallDisplay, {
90
+ props: { toolCall: makeToolCall(), actionResult: makeActionResult() },
91
+ });
92
+ const header = screen.getByRole('button', { name: /search/i });
93
+ expect(header).toHaveAttribute('aria-expanded', 'true');
94
+ await userEvent.click(header);
95
+ expect(header).toHaveAttribute('aria-expanded', 'false');
96
+ });
97
+ it('renders "Applied" with a result body and no Confirm/Reject once applied', async () => {
98
+ render(ToolCallDisplay, {
99
+ props: {
100
+ toolCall: makeToolCall(),
101
+ actionResult: makeActionResult({
102
+ phase: 'apply',
103
+ details: { rowId: 'order-2', status: 'shipped' },
104
+ }),
105
+ },
106
+ });
107
+ expect(screen.getByText('Applied')).toBeInTheDocument();
108
+ const header = screen.getByRole('button', { name: /search/i });
109
+ expect(header).toHaveAttribute('aria-expanded', 'true');
110
+ expect(screen.getByText('Applied change')).toBeInTheDocument();
111
+ expect(screen.getByText(/order-2/)).toBeInTheDocument();
112
+ expect(screen.queryByRole('button', { name: 'Confirm' })).not.toBeInTheDocument();
113
+ });
114
+ it('falls back to a plain confirmation line when an applied result has no details', () => {
115
+ render(ToolCallDisplay, {
116
+ props: {
117
+ toolCall: makeToolCall(),
118
+ actionResult: makeActionResult({ phase: 'apply' }),
119
+ },
120
+ });
121
+ expect(screen.getByText('Change applied successfully.')).toBeInTheDocument();
122
+ });
123
+ it('renders "Failed" with the reason when the action result is not ok', async () => {
124
+ render(ToolCallDisplay, {
125
+ props: {
126
+ toolCall: makeToolCall(),
127
+ actionResult: makeActionResult({ ok: false, reason: 'stale_revision' }),
128
+ },
129
+ });
130
+ expect(screen.getByText('Failed')).toBeInTheDocument();
131
+ const header = screen.getByRole('button', { name: /search/i });
132
+ expect(header).toHaveAttribute('aria-expanded', 'true');
133
+ expect(screen.getByText('stale_revision')).toBeInTheDocument();
134
+ });
44
135
  });