@vellumai/assistant 0.11.0-dev.202607301449.cefb1f3 → 0.11.0-dev.202607301636.699c1c8

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 (46) hide show
  1. package/ARCHITECTURE.md +1 -0
  2. package/docs/stt-provider-onboarding.md +10 -7
  3. package/openapi.yaml +15 -1
  4. package/package.json +1 -1
  5. package/src/__tests__/gemini-provider.test.ts +78 -1
  6. package/src/__tests__/guardian-card-rehydration.test.ts +210 -0
  7. package/src/__tests__/guardian-card-withdrawal.test.ts +37 -2
  8. package/src/__tests__/host-bash-routes.test.ts +66 -0
  9. package/src/__tests__/host-cu-routes-targeted.test.ts +87 -0
  10. package/src/__tests__/host-file-routes-targeted.test.ts +60 -0
  11. package/src/__tests__/stt-language-catalog-parity.test.ts +131 -0
  12. package/src/__tests__/voice-config-update.test.ts +254 -1
  13. package/src/a2a/__tests__/agent-card.test.ts +5 -21
  14. package/src/a2a/agent-card.ts +11 -17
  15. package/src/api/events/contact-request.ts +1 -0
  16. package/src/approvals/guardian-card-withdrawal.ts +30 -11
  17. package/src/cli/commands/contacts.help.ts +5 -0
  18. package/src/cli/commands/contacts.ts +2 -0
  19. package/src/config/bundled-skills/settings/TOOLS.json +4 -3
  20. package/src/config/bundled-skills/settings/tools/voice-config-update.ts +226 -2
  21. package/src/config/schemas/__tests__/stt.test.ts +27 -0
  22. package/src/config/schemas/stt.ts +20 -1
  23. package/src/daemon/conversation-error.ts +8 -0
  24. package/src/live-voice/__tests__/live-voice-stt.test.ts +321 -0
  25. package/src/live-voice/live-voice-session.ts +129 -15
  26. package/src/providers/gemini/client.ts +54 -2
  27. package/src/providers/speech-to-text/__tests__/deepgram.test.ts +27 -0
  28. package/src/providers/speech-to-text/__tests__/provider-catalog.test.ts +25 -0
  29. package/src/providers/speech-to-text/__tests__/resolve.test.ts +195 -1
  30. package/src/providers/speech-to-text/deepgram-realtime.ts +9 -1
  31. package/src/providers/speech-to-text/deepgram.ts +117 -1
  32. package/src/providers/speech-to-text/provider-catalog.ts +17 -0
  33. package/src/providers/speech-to-text/resolve.ts +64 -5
  34. package/src/providers/speech-to-text/xai.test.ts +43 -0
  35. package/src/providers/speech-to-text/xai.ts +48 -7
  36. package/src/runtime/routes/__tests__/conversation-query-routes.test.ts +116 -1
  37. package/src/runtime/routes/__tests__/stt-routes.test.ts +13 -0
  38. package/src/runtime/routes/contact-prompt-routes.ts +8 -1
  39. package/src/runtime/routes/conversation-query-routes.ts +34 -0
  40. package/src/runtime/routes/host-bash-routes.ts +31 -22
  41. package/src/runtime/routes/host-cu-routes.ts +26 -36
  42. package/src/runtime/routes/host-file-routes.ts +29 -40
  43. package/src/runtime/routes/stt-routes.ts +3 -0
  44. package/src/stt/__tests__/daemon-batch-transcriber.test.ts +136 -2
  45. package/src/stt/daemon-batch-transcriber.ts +39 -22
  46. package/src/util/errors.ts +1 -0
package/ARCHITECTURE.md CHANGED
@@ -717,6 +717,7 @@ The web client implements these flows in `clients/web/src/domains/chat/voice/`:
717
717
  **Cross-boundary notes:**
718
718
 
719
719
  - The `services.stt` config block is the single source of truth for STT provider selection across the daemon batch boundary, the conversation streaming boundary, the client service-first boundary, and the telephony boundary. The batch and streaming resolvers (`resolveBatchTranscriber()`, `resolveStreamingTranscriber()`) both read from `services.stt.provider` and resolve credentials through the same catalog; the telephony boundary's media-stream STT session uses these same resolvers — it selects streaming vs batch transcription via `resolveStreamingTranscriber()`/`resolveBatchTranscriber()` under the `calls.voice.telephonyStreaming` flag, gated by `resolveTelephonySttCapability()`, while call placement/TwiML is gated by `resolveTelephonyCredentialReadiness()`. The daemon provider catalog (`src/providers/speech-to-text/provider-catalog.ts`) is the authoritative registry of supported providers. Native clients fetch display metadata via `GET /v1/stt/providers`.
720
+ - **Spoken language** is a second axis on the same block: `services.stt.language` is read by `resolveStreamingTranscriber()` and `resolveBatchTranscriber()` and forwarded to the adapters that accept one (Deepgram, xAI, and the managed relay, which passes it to Deepgram server-side). Callers may override it per streaming session, but none need to: reading it in the resolvers means every boundary inherits the setting. Gemini and Whisper take no language option and auto-detect natively, so they ignore it. Leaving it unset is **not** auto-detection on Deepgram or the managed relay: Deepgram's default is English, so non-English speech transcribes as English-sounding nonsense. `"multi"` selects nova-3 code-switching across English, Spanish, French, German, Hindi, Russian, Portuguese, Japanese, Italian, and Dutch, the mode to use when a speaker mixes languages inside one utterance. BYOK Deepgram pins `model=nova-3` for **any** explicitly configured language, not just `"multi"`: the curated roster is verified against nova-3 (the default nova-2 supports only a subset, and rejects `"multi"` outright), and `deepgramLanguageOptions()` owns the model+language pairing so every call site inherits the rule; leaving the language unset keeps the adapter default model with no language param. `"multi"` is never forwarded to xAI (it is not a BCP-47 code; xAI auto-handles multilingual audio). The managed relay pins nova-3 and allowlists `language`, so streaming needs no platform-side change; managed **batch** goes through the platform speech proxy, which accepts no language parameter, so forwarding it there is deferred pending a platform-side change.
720
721
  - Conversation streaming does not replace the client service-first batch path. When streaming is available, it runs concurrently during recording and provides real-time partials and finals. The batch path remains the fallback for providers that do not support streaming, when streaming fails mid-session, or when streaming produces no final transcript.
721
722
  - Credential mapping is catalog-driven: `provider-secret-catalog.ts` derives STT API-key provider names from the daemon catalog via `listCredentialProviderNames()`, deduplicating against the LLM/search provider list. Adding a provider to the catalog automatically includes its credential name in `API_KEY_PROVIDERS`.
722
723
  - Terminology: "STT", "transcription", and "speech recognition" all refer to the same operation (converting audio to text).
@@ -30,6 +30,8 @@ This ensures the exhaustive switch in `daemon-batch-transcriber.ts` produces a c
30
30
 
31
31
  The `services.stt.providers` map uses a sparse `z.record(z.string(), ...)` schema, so adding a new provider does **not** require a workspace migration to seed a `services.stt.providers.<id>` entry. Users only need to set `services.stt.provider` to the new ID and supply credentials.
32
32
 
33
+ **Language handling.** `services.stt.language` is resolved centrally in `resolveStreamingTranscriber()` (and in `resolveBatchTranscriber()` for the daemon-batch boundary), so a new adapter inherits it for free: accept a `language` option in the adapter's constructor and forward it to the provider. If the provider auto-detects natively and has no language parameter (as Gemini and Whisper do), accept nothing and let the resolver's value be ignored; document that choice in the adapter, because "no language param" means auto-detect for some providers and _English_ for others (Deepgram), and that difference is an easy source of silent wrong-language transcription. A provider that supports both batch and streaming must forward the language on **both** paths, not just the streaming one.
34
+
33
35
  ## 4. Adapter wiring
34
36
 
35
37
  **File:** `src/stt/daemon-batch-transcriber.ts`
@@ -52,13 +54,14 @@ If the new provider **shares** an existing credential name (e.g. reuses `"openai
52
54
 
53
55
  All client-facing metadata is part of the daemon's provider catalog entry (`src/providers/speech-to-text/provider-catalog.ts`). When adding a new provider, include these fields in the catalog entry:
54
56
 
55
- | Field | Description |
56
- | ------------------ | ------------------------------------------------------------------------- |
57
- | `displayName` | Human-readable name shown in client settings UI. |
58
- | `subtitle` | Short description displayed below the provider selector. |
59
- | `setupMode` | `"api-key"` (inline key field) or `"cli"` (instructions-only). |
60
- | `setupHint` | Brief guidance shown during setup. |
61
- | `credentialsGuide` | Object with `description`, `url`, and `linkLabel` for the key mgmt page. |
57
+ | Field | Description |
58
+ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
+ | `displayName` | Human-readable name shown in client settings UI. |
60
+ | `subtitle` | Short description displayed below the provider selector. |
61
+ | `setupMode` | `"api-key"` (inline key field) or `"cli"` (instructions-only). |
62
+ | `setupHint` | Brief guidance shown during setup. |
63
+ | `languageSelection` | `"manual"` (provider takes a language parameter, clients show a picker) or `"auto"` (native detection, picker hidden). See the "Language handling" paragraph in step 3. |
64
+ | `credentialsGuide` | Object with `description`, `url`, and `linkLabel` for the key mgmt page. |
62
65
 
63
66
  Native clients fetch this metadata at launch via `GET /v1/stt/providers`. No separate client-side file updates are needed.
64
67
 
package/openapi.yaml CHANGED
@@ -6126,6 +6126,9 @@ paths:
6126
6126
  placeholder:
6127
6127
  description: Placeholder text for the address input field.
6128
6128
  type: string
6129
+ defaultValue:
6130
+ description: Suggested address to pre-fill the input with (e.g. a known email). The user can edit it before submitting.
6131
+ type: string
6129
6132
  label:
6130
6133
  description: Display label shown in the prompt UI.
6131
6134
  type: string
@@ -13719,13 +13722,17 @@ paths:
13719
13722
  properties:
13720
13723
  requestId:
13721
13724
  type: string
13725
+ minLength: 1
13722
13726
  description: Pending bash request ID
13723
13727
  stdout:
13724
13728
  type: string
13725
13729
  stderr:
13726
13730
  type: string
13727
13731
  exitCode:
13728
- type: number
13732
+ anyOf:
13733
+ - type: number
13734
+ - type: "null"
13735
+ description: Process exit status, or null when terminated by a signal
13729
13736
  timedOut:
13730
13737
  type: boolean
13731
13738
  required:
@@ -13888,6 +13895,7 @@ paths:
13888
13895
  properties:
13889
13896
  requestId:
13890
13897
  type: string
13898
+ minLength: 1
13891
13899
  description: Pending CU request ID
13892
13900
  axTree:
13893
13901
  type: string
@@ -13955,6 +13963,7 @@ paths:
13955
13963
  properties:
13956
13964
  requestId:
13957
13965
  type: string
13966
+ minLength: 1
13958
13967
  description: Pending request ID to resolve
13959
13968
  content:
13960
13969
  type: string
@@ -29518,6 +29527,11 @@ paths:
29518
29527
  type: string
29519
29528
  conversationStreamingMode:
29520
29529
  type: string
29530
+ languageSelection:
29531
+ type: string
29532
+ enum:
29533
+ - manual
29534
+ - auto
29521
29535
  credentialsGuide:
29522
29536
  type: string
29523
29537
  required:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.0-dev.202607301449.cefb1f3",
3
+ "version": "0.11.0-dev.202607301636.699c1c8",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -46,6 +46,7 @@ let fakeChunks: FakeChunk[] = [];
46
46
  let lastStreamParams: Record<string, unknown> | null = null;
47
47
  let lastConstructorOpts: Record<string, unknown> | null = null;
48
48
  let shouldThrow: Error | null = null;
49
+ let listShouldThrow: Error | null = null;
49
50
 
50
51
  class FakeApiError extends Error {
51
52
  status: number;
@@ -76,6 +77,12 @@ mock.module("@google/genai", () => ({
76
77
  },
77
78
  };
78
79
  },
80
+ list: async () => {
81
+ if (listShouldThrow) {
82
+ throw listShouldThrow;
83
+ }
84
+ return { models: [] };
85
+ },
79
86
  };
80
87
  },
81
88
  ApiError: FakeApiError,
@@ -88,7 +95,10 @@ mock.module("@google/genai", () => ({
88
95
  }));
89
96
 
90
97
  // Import after mocking
91
- import { GeminiProvider } from "../providers/gemini/client.js";
98
+ import {
99
+ GeminiProvider,
100
+ validateGeminiApiKey,
101
+ } from "../providers/gemini/client.js";
92
102
 
93
103
  // ---------------------------------------------------------------------------
94
104
  // Helpers
@@ -1474,6 +1484,48 @@ describe("GeminiProvider", () => {
1474
1484
  ).toBe("model_not_found");
1475
1485
  });
1476
1486
 
1487
+ test("maps 404 with empty message to network_error (proxy interception)", async () => {
1488
+ const reason = await reasonForApiError(404, "");
1489
+ expect(reason).toBe("network_error");
1490
+ });
1491
+
1492
+ test("maps 403 with empty message to network_error (proxy interception)", async () => {
1493
+ const reason = await reasonForApiError(403, "");
1494
+ expect(reason).toBe("network_error");
1495
+ });
1496
+
1497
+ test("surfaces actionable network/proxy message for 404 with empty body", async () => {
1498
+ shouldThrow = new FakeApiError(404, "");
1499
+ try {
1500
+ await provider.sendMessage([
1501
+ { role: "user", content: [{ type: "text", text: "Hi" }] },
1502
+ ]);
1503
+ throw new Error("expected sendMessage to throw");
1504
+ } catch (error) {
1505
+ expect(error).toBeInstanceOf(ProviderError);
1506
+ const msg = (error as Error).message;
1507
+ expect(msg).toContain("no response body");
1508
+ expect(msg).toContain("network proxy or egress filter");
1509
+ expect(msg).not.toContain("Gemini API error (404):");
1510
+ }
1511
+ });
1512
+
1513
+ test("preserves existing message format for 404 with a real body", async () => {
1514
+ shouldThrow = new FakeApiError(404, "NOT_FOUND: model does not exist");
1515
+ try {
1516
+ await provider.sendMessage([
1517
+ { role: "user", content: [{ type: "text", text: "Hi" }] },
1518
+ ]);
1519
+ throw new Error("expected sendMessage to throw");
1520
+ } catch (error) {
1521
+ expect(error).toBeInstanceOf(ProviderError);
1522
+ const msg = (error as Error).message;
1523
+ expect(msg).toBe(
1524
+ "Gemini API error (404): NOT_FOUND: model does not exist",
1525
+ );
1526
+ }
1527
+ });
1528
+
1477
1529
  test("maps a plain 429 (no token signal) to rate_limited, not context overflow", async () => {
1478
1530
  shouldThrow = new FakeApiError(
1479
1531
  429,
@@ -1709,3 +1761,28 @@ describe("GeminiProvider", () => {
1709
1761
  });
1710
1762
  });
1711
1763
  });
1764
+
1765
+ // ---------------------------------------------------------------------------
1766
+ // validateGeminiApiKey — empty-body 403 handling (proxy interception)
1767
+ // ---------------------------------------------------------------------------
1768
+ describe("validateGeminiApiKey", () => {
1769
+ beforeEach(() => {
1770
+ shouldThrow = null;
1771
+ listShouldThrow = null;
1772
+ });
1773
+
1774
+ test("returns valid for 403 with empty message (proxy interception)", async () => {
1775
+ listShouldThrow = new FakeApiError(403, "");
1776
+ const result = await validateGeminiApiKey("test-key");
1777
+ expect(result.valid).toBe(true);
1778
+ });
1779
+
1780
+ test("returns invalid for 403 with a real message", async () => {
1781
+ listShouldThrow = new FakeApiError(403, "PERMISSION_DENIED");
1782
+ const result = await validateGeminiApiKey("test-key");
1783
+ expect(result.valid).toBe(false);
1784
+ if (!result.valid) {
1785
+ expect(result.reason).toContain("Gemini API error (403)");
1786
+ }
1787
+ });
1788
+ });
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Rehydration coverage for in-app guardian decision cards (LUM-2919).
3
+ *
4
+ * Selecting Trust / Leave unverified / Block on a message-reaction card resolves
5
+ * the request server-side and the acting client completes its own card
6
+ * optimistically. That optimistic completion is in-memory only, so the terminal
7
+ * state must also reach the conversation's persisted `ui_surface` block, or
8
+ * re-entering the conversation rebuilds history from a card that still looks
9
+ * undecided and re-renders the raw button group.
10
+ *
11
+ * This exercises the real withdrawal → `markSurfaceCompleted` → history-render
12
+ * chain, asserting on what a returning client actually reads back.
13
+ */
14
+
15
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
16
+
17
+ import type { AssistantEvent } from "../api/index.js";
18
+
19
+ const broadcasts: AssistantEvent[] = [];
20
+ const realEventHub = await import("../runtime/assistant-event-hub.js");
21
+ mock.module("../runtime/assistant-event-hub.js", () => ({
22
+ ...realEventHub,
23
+ broadcastMessage: (msg: AssistantEvent) => {
24
+ broadcasts.push(msg);
25
+ },
26
+ }));
27
+
28
+ // Stand in for the messages table: `markSurfaceCompleted` scans it for the
29
+ // block carrying the surface id and writes the patched content back.
30
+ let rows: Array<{
31
+ id: string;
32
+ conversationId: string;
33
+ role: string;
34
+ content: unknown;
35
+ createdAt: number;
36
+ metadata: string | null;
37
+ }> = [];
38
+
39
+ const realCrud = await import("../persistence/conversation-crud.js");
40
+ mock.module("../persistence/conversation-crud.js", () => ({
41
+ ...realCrud,
42
+ getMessages: (conversationId: string) =>
43
+ rows.filter((r) => r.conversationId === conversationId),
44
+ updateMessageContent: (id: string, content: string) => {
45
+ const row = rows.find((r) => r.id === id);
46
+ if (row) {
47
+ row.content = JSON.parse(content);
48
+ }
49
+ },
50
+ }));
51
+
52
+ import {
53
+ bridgeState,
54
+ gatewayGuardianRequestsStoreBridge,
55
+ } from "./helpers/gateway-guardian-requests-store-bridge.js";
56
+
57
+ mock.module(
58
+ "../channels/gateway-guardian-requests.js",
59
+ () => gatewayGuardianRequestsStoreBridge,
60
+ );
61
+
62
+ const { withdrawGuardianRequestCards } =
63
+ await import("../approvals/guardian-card-withdrawal.js");
64
+ const { renderHistoryContent } = await import("../daemon/handlers/shared.js");
65
+
66
+ import type { SimGuardianRequest } from "./guardian-gateway-sim.js";
67
+
68
+ const CONVERSATION_ID = "conv-rehydration-1";
69
+
70
+ /** The three-button trust decision card as it is first persisted. */
71
+ function seedUndecidedCard(requestId: string): void {
72
+ rows = [
73
+ {
74
+ id: "msg-card",
75
+ conversationId: CONVERSATION_ID,
76
+ role: "assistant",
77
+ content: [
78
+ {
79
+ type: "ui_surface",
80
+ surfaceId: `access-request-${requestId}`,
81
+ surfaceType: "card",
82
+ title: "Access Request",
83
+ data: {
84
+ title: "Alice",
85
+ subtitle: "Requesting access to the assistant",
86
+ body: "",
87
+ },
88
+ actions: [
89
+ { id: `apr:${requestId}:trust`, label: "Trust", style: "primary" },
90
+ {
91
+ id: `apr:${requestId}:leave_unverified`,
92
+ label: "Leave unverified",
93
+ },
94
+ {
95
+ id: `apr:${requestId}:block`,
96
+ label: "Block",
97
+ style: "destructive",
98
+ },
99
+ ],
100
+ },
101
+ ],
102
+ createdAt: 0,
103
+ metadata: null,
104
+ },
105
+ ];
106
+ }
107
+
108
+ /** The surface a returning client reads off the rehydrated history row. */
109
+ function rehydratedSurface() {
110
+ const row = rows.find((r) => r.id === "msg-card")!;
111
+ return renderHistoryContent(row.content).surfaces[0];
112
+ }
113
+
114
+ /** A pending access request whose in-app card sits in the conversation. */
115
+ function seedPendingRequest(): SimGuardianRequest {
116
+ const request = bridgeState.seedRequest({
117
+ kind: "access_request",
118
+ sourceType: "channel",
119
+ sourceChannel: "slack",
120
+ guardianPrincipalId: "rehydration-test-principal",
121
+ });
122
+ bridgeState.seedDelivery({
123
+ requestId: request.id,
124
+ destinationChannel: "vellum",
125
+ destinationConversationId: CONVERSATION_ID,
126
+ });
127
+ seedUndecidedCard(request.id);
128
+ return request;
129
+ }
130
+
131
+ describe("in-app trust decision rehydration", () => {
132
+ beforeEach(() => {
133
+ bridgeState.reset();
134
+ broadcasts.length = 0;
135
+ });
136
+
137
+ test("an undecided card still carries its action buttons", () => {
138
+ seedPendingRequest();
139
+
140
+ const surface = rehydratedSurface();
141
+ expect(surface?.completed).toBeUndefined();
142
+ expect(surface?.actions).toHaveLength(3);
143
+ });
144
+
145
+ test("a decision made in-app rehydrates as completed, not as the button group", async () => {
146
+ const request = seedPendingRequest();
147
+
148
+ await withdrawGuardianRequestCards({
149
+ request,
150
+ status: "denied",
151
+ originChannel: "vellum",
152
+ decidedAction: "leave_unverified",
153
+ });
154
+
155
+ const surface = rehydratedSurface();
156
+ expect(surface?.completed).toBe(true);
157
+ // The neutral park label, not "Denied": the client infers the completion
158
+ // tone from this string.
159
+ expect(surface?.completionSummary).toBe("Left unverified");
160
+ // The card keeps its content for the audit trail; only the live
161
+ // affordances stop rendering, which the client drives off `completed`.
162
+ expect(surface?.data).toMatchObject({ title: "Alice" });
163
+ });
164
+
165
+ test("a trust decision made in-app rehydrates as approved", async () => {
166
+ const request = seedPendingRequest();
167
+
168
+ await withdrawGuardianRequestCards({
169
+ request,
170
+ status: "approved",
171
+ originChannel: "vellum",
172
+ decidedAction: "trust",
173
+ });
174
+
175
+ const surface = rehydratedSurface();
176
+ expect(surface?.completed).toBe(true);
177
+ expect(surface?.completionSummary).toBe("Approved");
178
+ });
179
+
180
+ test("an in-app decision does not re-broadcast over the acting client's own summary", async () => {
181
+ const request = seedPendingRequest();
182
+
183
+ await withdrawGuardianRequestCards({
184
+ request,
185
+ status: "approved",
186
+ originChannel: "vellum",
187
+ decidedAction: "trust",
188
+ });
189
+
190
+ expect(
191
+ broadcasts.filter((m) => m.type === "ui_surface_complete"),
192
+ ).toHaveLength(0);
193
+ });
194
+
195
+ test("a decision made on another surface both persists and broadcasts", async () => {
196
+ const request = seedPendingRequest();
197
+
198
+ await withdrawGuardianRequestCards({
199
+ request,
200
+ status: "denied",
201
+ originChannel: "slack",
202
+ decidedAction: "block",
203
+ });
204
+
205
+ expect(rehydratedSurface()?.completionSummary).toBe("Denied");
206
+ expect(
207
+ broadcasts.filter((m) => m.type === "ui_surface_complete"),
208
+ ).toHaveLength(1);
209
+ });
210
+ });
@@ -1,8 +1,10 @@
1
1
  import { beforeEach, describe, expect, mock, test } from "bun:test";
2
2
 
3
3
  const completeSurfaceAndNotify = mock(() => {});
4
+ const markSurfaceCompleted = mock(() => {});
4
5
  mock.module("../daemon/conversation-surfaces.js", () => ({
5
6
  completeSurfaceAndNotify,
7
+ markSurfaceCompleted,
6
8
  }));
7
9
 
8
10
  const withdrawSlackApprovalCard = mock(
@@ -56,6 +58,7 @@ describe("withdrawGuardianRequestCards", () => {
56
58
  beforeEach(() => {
57
59
  bridgeState.reset();
58
60
  completeSurfaceAndNotify.mockClear();
61
+ markSurfaceCompleted.mockClear();
59
62
  withdrawSlackApprovalCard.mockClear();
60
63
  });
61
64
 
@@ -81,7 +84,7 @@ describe("withdrawGuardianRequestCards", () => {
81
84
  );
82
85
  });
83
86
 
84
- test("skips the in-app card when the decision originated in-app", async () => {
87
+ test("persists the in-app card's completion without broadcasting when the decision originated in-app", async () => {
85
88
  const req = makeRequest();
86
89
  bridgeState.seedDelivery({
87
90
  requestId: req.id,
@@ -95,10 +98,42 @@ describe("withdrawGuardianRequestCards", () => {
95
98
  originChannel: "vellum",
96
99
  });
97
100
 
98
- // The acting in-app client already completed its own card optimistically.
101
+ // The acting client's optimistic completion is in-memory only, so the
102
+ // terminal state still has to reach history or a re-entry re-renders the
103
+ // undecided button group (LUM-2919).
104
+ expect(markSurfaceCompleted).toHaveBeenCalledTimes(1);
105
+ expect(markSurfaceCompleted).toHaveBeenCalledWith(
106
+ { conversationId: "conv-1" },
107
+ `access-request-${req.id}`,
108
+ "Approved",
109
+ );
110
+ // No broadcast: it would replace the resolver's reply text already on
111
+ // screen with the canonical status label.
99
112
  expect(completeSurfaceAndNotify).not.toHaveBeenCalled();
100
113
  });
101
114
 
115
+ test("persists a park decided in-app under its neutral label", async () => {
116
+ const req = makeRequest();
117
+ bridgeState.seedDelivery({
118
+ requestId: req.id,
119
+ destinationChannel: "vellum",
120
+ destinationConversationId: "conv-1",
121
+ });
122
+
123
+ await withdrawGuardianRequestCards({
124
+ request: req,
125
+ status: "denied",
126
+ originChannel: "vellum",
127
+ decidedAction: "leave_unverified",
128
+ });
129
+
130
+ expect(markSurfaceCompleted).toHaveBeenCalledWith(
131
+ { conversationId: "conv-1" },
132
+ `access-request-${req.id}`,
133
+ "Left unverified",
134
+ );
135
+ });
136
+
102
137
  test("withdraws the Slack card with decider and decision time", async () => {
103
138
  const req = makeRequest({ decidedByExternalUserId: "U-guardian" });
104
139
  bridgeState.seedDelivery({
@@ -448,3 +448,69 @@ describe("handleHostBashResult", () => {
448
448
  );
449
449
  });
450
450
  });
451
+
452
+ // ── Request body validation ──────────────────────────────────────────
453
+
454
+ describe("handleHostBashResult: request body validation", () => {
455
+ beforeEach(() => {
456
+ pendingStore.clear();
457
+ resolvedIds.length = 0;
458
+ resolveSpy.length = 0;
459
+ clientActorPrincipals.clear();
460
+ });
461
+
462
+ test("rejects a body that is not an object", () => {
463
+ expect(() => handleHostBashResult({ body: undefined })).toThrow(
464
+ BadRequestError,
465
+ );
466
+ });
467
+
468
+ test("rejects an empty-string requestId", () => {
469
+ expect(() => handleHostBashResult({ body: bashBody("") })).toThrow(
470
+ BadRequestError,
471
+ );
472
+ });
473
+
474
+ test("rejects a wrongly typed field before the interaction is consumed", () => {
475
+ const requestId = "req-bash-bad-exit-code";
476
+ registerPending(requestId);
477
+
478
+ expect(() =>
479
+ handleHostBashResult({
480
+ body: { ...bashBody(requestId), exitCode: "0" },
481
+ }),
482
+ ).toThrow(BadRequestError);
483
+
484
+ expect(resolveSpy).toHaveLength(0);
485
+ expect(pendingStore.has(requestId)).toBe(true);
486
+ });
487
+
488
+ test("accepts a null exitCode (process terminated by a signal)", async () => {
489
+ const requestId = "req-bash-signal-kill";
490
+ registerPending(requestId);
491
+
492
+ const result = await handleHostBashResult({
493
+ body: { ...bashBody(requestId), exitCode: null, timedOut: true },
494
+ });
495
+
496
+ expect(result).toEqual({ accepted: true });
497
+ expect(resolveSpy[0].result.exitCode).toBeNull();
498
+ });
499
+
500
+ test("tolerates unknown keys", async () => {
501
+ const requestId = "req-bash-unknown-keys";
502
+ registerPending(requestId);
503
+
504
+ const result = await handleHostBashResult({
505
+ body: { ...bashBody(requestId), somethingNew: "ignored" },
506
+ });
507
+
508
+ expect(result).toEqual({ accepted: true });
509
+ expect(resolveSpy[0].result).toEqual({
510
+ stdout: "hello\n",
511
+ stderr: "",
512
+ exitCode: 0,
513
+ timedOut: false,
514
+ });
515
+ });
516
+ });
@@ -419,3 +419,90 @@ describe("handleHostCuResult — Phase 2 targetClientId guard", () => {
419
419
  });
420
420
  });
421
421
  });
422
+
423
+ // ── Request body validation ──────────────────────────────────────────────────
424
+
425
+ describe("handleHostCuResult: request body validation", () => {
426
+ beforeEach(() => {
427
+ pendingStore.clear();
428
+ conversationStore.clear();
429
+ actorPrincipalByClient.clear();
430
+ resolvedIds.length = 0;
431
+ cuResolveSpy.length = 0;
432
+ registerConversation("conv-cu-1");
433
+ });
434
+
435
+ test("rejects a body that is not an object", () => {
436
+ expect(() => handleHostCuResult({ body: undefined })).toThrow(
437
+ BadRequestError,
438
+ );
439
+ });
440
+
441
+ test("rejects an empty-string requestId", () => {
442
+ expect(() => handleHostCuResult({ body: cuBody("") })).toThrow(
443
+ BadRequestError,
444
+ );
445
+ });
446
+
447
+ test("rejects a wrongly typed field before the interaction is consumed", () => {
448
+ const requestId = "req-cu-bad-screenshot-width";
449
+ registerPending(requestId);
450
+
451
+ expect(() =>
452
+ handleHostCuResult({
453
+ body: { ...cuBody(requestId), screenshotWidthPx: "800" },
454
+ }),
455
+ ).toThrow(BadRequestError);
456
+
457
+ expect(cuResolveSpy).toHaveLength(0);
458
+ expect(pendingStore.has(requestId)).toBe(true);
459
+ });
460
+
461
+ test("forwards a full observation payload unchanged", async () => {
462
+ const requestId = "req-cu-full-observation";
463
+ registerPending(requestId);
464
+
465
+ const result = await handleHostCuResult({
466
+ body: {
467
+ requestId,
468
+ axTree: "Button [1]",
469
+ axDiff: "+Button [1]",
470
+ screenshot: "base64png",
471
+ screenshotWidthPx: 1600,
472
+ screenshotHeightPx: 1000,
473
+ screenWidthPt: 800,
474
+ screenHeightPt: 500,
475
+ executionResult: "Clicked",
476
+ executionError: undefined,
477
+ secondaryWindows: "none",
478
+ userGuidance: "look here",
479
+ },
480
+ });
481
+
482
+ expect(result).toEqual({ accepted: true });
483
+ expect(cuResolveSpy[0].payload).toMatchObject({
484
+ axTree: "Button [1]",
485
+ axDiff: "+Button [1]",
486
+ screenshot: "base64png",
487
+ screenshotWidthPx: 1600,
488
+ screenshotHeightPx: 1000,
489
+ screenWidthPt: 800,
490
+ screenHeightPt: 500,
491
+ executionResult: "Clicked",
492
+ secondaryWindows: "none",
493
+ userGuidance: "look here",
494
+ });
495
+ });
496
+
497
+ test("tolerates unknown keys", async () => {
498
+ const requestId = "req-cu-unknown-keys";
499
+ registerPending(requestId);
500
+
501
+ const result = await handleHostCuResult({
502
+ body: { ...cuBody(requestId), somethingNew: "ignored" },
503
+ });
504
+
505
+ expect(result).toEqual({ accepted: true });
506
+ expect(cuResolveSpy[0].payload).not.toHaveProperty("somethingNew");
507
+ });
508
+ });