switchroom 0.18.9 → 0.18.11

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 (65) hide show
  1. package/dist/agent-scheduler/index.js +1 -0
  2. package/dist/auth-broker/index.js +198 -13
  3. package/dist/cli/notion-write-pretool.mjs +1 -0
  4. package/dist/cli/switchroom.js +214 -83
  5. package/dist/cli/ui/apple-touch-icon.png +0 -0
  6. package/dist/cli/ui/favicon-32.png +0 -0
  7. package/dist/cli/ui/favicon.ico +0 -0
  8. package/dist/host-control/main.js +760 -257
  9. package/dist/vault/approvals/kernel-server.js +3 -1
  10. package/dist/vault/broker/server.js +3 -1
  11. package/package.json +1 -1
  12. package/profiles/_base/start.sh.hbs +119 -37
  13. package/profiles/_shared/dev-protocol.md.hbs +42 -0
  14. package/skills/dev-protocol/SKILL.md +131 -0
  15. package/telegram-plugin/README.md +2 -1
  16. package/telegram-plugin/admin-commands/dispatch.test.ts +40 -2
  17. package/telegram-plugin/admin-commands/index.ts +6 -1
  18. package/telegram-plugin/bridge/bridge.ts +23 -1
  19. package/telegram-plugin/bridge/crash-breadcrumb.ts +42 -0
  20. package/telegram-plugin/chat-lock.ts +13 -0
  21. package/telegram-plugin/dist/bridge/bridge.js +24 -1
  22. package/telegram-plugin/dist/gateway/gateway.js +1832 -263
  23. package/telegram-plugin/dist/server.js +29 -2
  24. package/telegram-plugin/fallback-card-collapse.ts +131 -0
  25. package/telegram-plugin/gateway/bridge-dead-watchdog.ts +546 -0
  26. package/telegram-plugin/gateway/effort-command.ts +47 -3
  27. package/telegram-plugin/gateway/gateway.ts +1435 -211
  28. package/telegram-plugin/gateway/model-command.ts +94 -8
  29. package/telegram-plugin/gateway/pending-session-command.ts +365 -0
  30. package/telegram-plugin/gateway/permission-timeout.ts +25 -0
  31. package/telegram-plugin/gateway/resume-inbound-builder.ts +23 -3
  32. package/telegram-plugin/gateway/session-model-file.ts +166 -23
  33. package/telegram-plugin/gateway/stop-command.ts +56 -0
  34. package/telegram-plugin/photo-precheck.ts +201 -0
  35. package/telegram-plugin/quota-watch.ts +141 -2
  36. package/telegram-plugin/registry/subagents-schema.ts +26 -3
  37. package/telegram-plugin/registry/subagents.test.ts +67 -0
  38. package/telegram-plugin/retry-api-call.ts +31 -0
  39. package/telegram-plugin/subagent-watcher.ts +392 -1
  40. package/telegram-plugin/tests/bridge-dead-watchdog.test.ts +576 -0
  41. package/telegram-plugin/tests/buffer-gate-broadened.test.ts +11 -5
  42. package/telegram-plugin/tests/chat-lock-unhandled-rejection.test.ts +101 -0
  43. package/telegram-plugin/tests/crash-breadcrumb.test.ts +57 -0
  44. package/telegram-plugin/tests/effort-command.test.ts +59 -2
  45. package/telegram-plugin/tests/fallback-card-collapse.test.ts +104 -0
  46. package/telegram-plugin/tests/gateway-pending-command-wiring.test.ts +124 -0
  47. package/telegram-plugin/tests/gateway-secret-detect.test.ts +7 -1
  48. package/telegram-plugin/tests/gateway-session-model-relaunch.test.ts +19 -11
  49. package/telegram-plugin/tests/model-command.test.ts +46 -3
  50. package/telegram-plugin/tests/pending-session-command.test.ts +322 -0
  51. package/telegram-plugin/tests/permission-timeout.test.ts +26 -0
  52. package/telegram-plugin/tests/permission-verdict-resume-guard.test.ts +16 -0
  53. package/telegram-plugin/tests/photo-dimension-fallback.test.ts +129 -0
  54. package/telegram-plugin/tests/photo-precheck.test.ts +240 -0
  55. package/telegram-plugin/tests/photo-reroute-wiring.test.ts +85 -0
  56. package/telegram-plugin/tests/quota-watch.test.ts +225 -0
  57. package/telegram-plugin/tests/session-model-file.test.ts +101 -2
  58. package/telegram-plugin/tests/stop-command.test.ts +234 -0
  59. package/telegram-plugin/tests/subagent-watcher-env-thresholds.test.ts +27 -9
  60. package/telegram-plugin/tests/subagent-watcher-resurrection.test.ts +398 -0
  61. package/telegram-plugin/tests/subagent-watcher-stall-terminal.test.ts +172 -0
  62. package/telegram-plugin/tests/worker-activity-feed.test.ts +37 -0
  63. package/telegram-plugin/tests/worker-visibility-prose-silent-harness.test.ts +18 -4
  64. package/telegram-plugin/welcome-text.ts +4 -3
  65. package/telegram-plugin/worker-activity-feed.ts +27 -0
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Contract pins for the mid-turn ack-queue-apply-confirm slots (#3017/#3018)
3
+ * that back `/model` + `/effort` when the agent is busy.
4
+ *
5
+ * The gateway wiring (busy-gate enqueue, idle-gate drain, reaper drain-cap,
6
+ * shutdown resolution) is exercised end-to-end by the UAT harness and pinned
7
+ * structurally in gateway-pending-command-wiring.test.ts; these lock the PURE
8
+ * contract the gateway relies on:
9
+ *
10
+ * - one slot PER KIND (model, effort): same-kind last-write-wins (a rapid
11
+ * re-issue queues only the latest and REPORTS the displaced one so it's
12
+ * never silently lost); cross-kind requests COEXIST (#3018 finding 2)
13
+ * - take(kind)/takeAll() are the atomic drain reads (empty the slots)
14
+ * - size mirrors the `pendingRestarts.size` gate shape (0..2)
15
+ * - the reaper's drainCapDecision DEFERS while a turn is in flight — the
16
+ * 60s cap must never force a mid-turn drain (#3018 finding 1)
17
+ * - shutdownResolutionActions empties the slots and yields, per queued
18
+ * command, the durable persist the gateway should perform so the choice
19
+ * still applies across the bounce (#3039) — with a re-issue fallback only
20
+ * for the unresolvable menu-tag case
21
+ * - the ack / superseded / restart-superseded text names the target so the
22
+ * operator always sees their choice was captured, replaced, or deferred —
23
+ * never dropped.
24
+ */
25
+
26
+ import { describe, it, expect } from 'vitest'
27
+ import {
28
+ createPendingSessionCommandSlots,
29
+ drainCapDecision,
30
+ shutdownResolutionActions,
31
+ resolveForRestart,
32
+ drainTakenCommands,
33
+ type DrainIo,
34
+ ackText,
35
+ supersededText,
36
+ restartSupersededText,
37
+ type PendingSessionCommand,
38
+ } from '../gateway/pending-session-command.js'
39
+
40
+ const ident = (s: string) => s
41
+
42
+ function cmd(overrides: Partial<PendingSessionCommand> = {}): PendingSessionCommand {
43
+ return {
44
+ kind: 'model',
45
+ origin: 'typed',
46
+ arg: 'fable',
47
+ targetLabel: 'fable',
48
+ chatId: '100',
49
+ threadId: undefined,
50
+ ackChatId: '100',
51
+ ackMessageId: 42,
52
+ requestedAt: 1_000,
53
+ ...overrides,
54
+ }
55
+ }
56
+
57
+ describe('pending-session-command slots', () => {
58
+ it('start empty (size 0, get null, take null, takeAll empty)', () => {
59
+ const slots = createPendingSessionCommandSlots()
60
+ expect(slots.size).toBe(0)
61
+ expect(slots.get('model')).toBeNull()
62
+ expect(slots.get('effort')).toBeNull()
63
+ expect(slots.take('model')).toBeNull()
64
+ expect(slots.takeAll()).toEqual([])
65
+ expect(slots.list()).toEqual([])
66
+ })
67
+
68
+ it('set on an empty slot displaces nothing and becomes gettable', () => {
69
+ const slots = createPendingSessionCommandSlots()
70
+ const a = cmd({ arg: 'opus', targetLabel: 'opus' })
71
+ expect(slots.set(a)).toBeNull()
72
+ expect(slots.size).toBe(1)
73
+ expect(slots.get('model')).toBe(a)
74
+ })
75
+
76
+ it('SAME-KIND last-write-wins: a second set returns the displaced command', () => {
77
+ const slots = createPendingSessionCommandSlots()
78
+ const first = cmd({ arg: 'fable', targetLabel: 'fable', ackMessageId: 1 })
79
+ const second = cmd({ arg: 'opus', targetLabel: 'opus', ackMessageId: 2 })
80
+ expect(slots.set(first)).toBeNull()
81
+ const displaced = slots.set(second)
82
+ expect(displaced).toBe(first) // caller edits THIS ack card to "superseded"
83
+ expect(slots.get('model')).toBe(second) // only the latest is queued
84
+ expect(slots.size).toBe(1)
85
+ })
86
+
87
+ it('CROSS-KIND commands coexist: /effort never displaces a queued /model (#3018 finding 2)', () => {
88
+ const slots = createPendingSessionCommandSlots()
89
+ const model = cmd({ kind: 'model', arg: 'fable', targetLabel: 'fable', ackMessageId: 1 })
90
+ const effort = cmd({ kind: 'effort', arg: 'high', targetLabel: 'high', ackMessageId: 2 })
91
+ expect(slots.set(model)).toBeNull()
92
+ expect(slots.set(effort)).toBeNull() // NOT a displacement
93
+ expect(slots.size).toBe(2)
94
+ expect(slots.get('model')).toBe(model)
95
+ expect(slots.get('effort')).toBe(effort)
96
+ // …and vice versa: a later model re-issue displaces only the model slot.
97
+ const model2 = cmd({ kind: 'model', arg: 'opus', targetLabel: 'opus', ackMessageId: 3 })
98
+ expect(slots.set(model2)).toBe(model)
99
+ expect(slots.get('effort')).toBe(effort)
100
+ expect(slots.size).toBe(2)
101
+ })
102
+
103
+ it('take(kind) atomically empties only that slot (the per-kind drain read)', () => {
104
+ const slots = createPendingSessionCommandSlots()
105
+ const model = cmd({ kind: 'model' })
106
+ const effort = cmd({ kind: 'effort', arg: 'high', targetLabel: 'high' })
107
+ slots.set(model)
108
+ slots.set(effort)
109
+ expect(slots.take('model')).toBe(model)
110
+ expect(slots.size).toBe(1)
111
+ expect(slots.get('model')).toBeNull()
112
+ expect(slots.get('effort')).toBe(effort)
113
+ expect(slots.take('model')).toBeNull() // second drain is a no-op
114
+ })
115
+
116
+ it('takeAll() empties everything in enqueue order; a same-kind re-enqueue moves to the back', () => {
117
+ const slots = createPendingSessionCommandSlots()
118
+ const model1 = cmd({ kind: 'model', targetLabel: 'fable', ackMessageId: 1 })
119
+ const effort = cmd({ kind: 'effort', arg: 'high', targetLabel: 'high', ackMessageId: 2 })
120
+ const model2 = cmd({ kind: 'model', targetLabel: 'opus', ackMessageId: 3 })
121
+ slots.set(model1)
122
+ slots.set(effort)
123
+ slots.set(model2) // displaces model1 AND moves the model slot behind effort
124
+ const all = slots.takeAll()
125
+ expect(all).toEqual([effort, model2])
126
+ expect(slots.size).toBe(0)
127
+ expect(slots.takeAll()).toEqual([])
128
+ })
129
+
130
+ it('clear() drops every queued command without returning them', () => {
131
+ const slots = createPendingSessionCommandSlots()
132
+ slots.set(cmd({ kind: 'model' }))
133
+ slots.set(cmd({ kind: 'effort', arg: 'high', targetLabel: 'high' }))
134
+ slots.clear()
135
+ expect(slots.size).toBe(0)
136
+ expect(slots.get('model')).toBeNull()
137
+ expect(slots.get('effort')).toBeNull()
138
+ })
139
+ })
140
+
141
+ describe('drainCapDecision (#3018 finding 1: the cap must never force mid-turn)', () => {
142
+ const CAP = 60_000
143
+
144
+ it('waits when nothing is queued', () => {
145
+ expect(drainCapDecision([], 1_000_000, CAP, false)).toBe('wait')
146
+ expect(drainCapDecision([], 1_000_000, CAP, true)).toBe('wait')
147
+ })
148
+
149
+ it('waits while the queued command is younger than the cap', () => {
150
+ const q = [cmd({ requestedAt: 100_000 })]
151
+ expect(drainCapDecision(q, 100_000 + CAP, CAP, false)).toBe('wait')
152
+ })
153
+
154
+ it('forces once overdue AND the session is idle (missed idle gate)', () => {
155
+ const q = [cmd({ requestedAt: 100_000 })]
156
+ expect(drainCapDecision(q, 100_000 + CAP + 1, CAP, false)).toBe('force')
157
+ })
158
+
159
+ it('DEFERS (keeps waiting) when overdue but a turn is in flight — a forced mid-turn drain would destroy the queued command', () => {
160
+ const q = [cmd({ requestedAt: 100_000 })]
161
+ expect(drainCapDecision(q, 100_000 + CAP + 1, CAP, true)).toBe('defer-turn-in-flight')
162
+ // …even hours overdue: the idle gate at turn end is the drain point.
163
+ expect(drainCapDecision(q, 100_000 + 100 * CAP, CAP, true)).toBe('defer-turn-in-flight')
164
+ })
165
+
166
+ it('any one overdue command trips the cap (mixed ages)', () => {
167
+ const q = [
168
+ cmd({ kind: 'model', requestedAt: 100_000 }),
169
+ cmd({ kind: 'effort', requestedAt: 100_000 + CAP }),
170
+ ]
171
+ expect(drainCapDecision(q, 100_000 + CAP + 1, CAP, false)).toBe('force')
172
+ })
173
+ })
174
+
175
+ describe('shutdownResolutionActions (#3018 finding 3 + #3039: SIGTERM persists the queued choice)', () => {
176
+ it('empties the slots and yields a persist action per queued command', () => {
177
+ const slots = createPendingSessionCommandSlots()
178
+ slots.set(cmd({ kind: 'model', targetLabel: 'fable', arg: 'fable', ackChatId: '100', ackMessageId: 7 }))
179
+ slots.set(cmd({ kind: 'effort', targetLabel: 'high', arg: 'high', ackChatId: '100', ackMessageId: 9 }))
180
+ const actions = shutdownResolutionActions(slots, ident)
181
+ expect(actions).toHaveLength(2)
182
+ expect(slots.size).toBe(0) // the queue is RESOLVED, not left behind
183
+ const model = actions.find(a => a.cmd.ackMessageId === 7)!
184
+ expect(model.persist).toBe('model')
185
+ expect(model.arg).toBe('fable')
186
+ expect(model.persistedText).toContain('`fable`')
187
+ expect(model.persistedText).toContain('saved')
188
+ // The fallback (persist failed) still names the choice + how to recover.
189
+ expect(model.reissueText).toContain('re-issue')
190
+ const effort = actions.find(a => a.cmd.ackMessageId === 9)!
191
+ expect(effort.persist).toBe('effort')
192
+ expect(effort.arg).toBe('high')
193
+ })
194
+
195
+ it('typed /model default → clear-model; typed /effort default → clear-effort', () => {
196
+ expect(resolveForRestart(cmd({ kind: 'model', arg: 'default', targetLabel: 'default' }), ident).persist).toBe('clear-model')
197
+ expect(resolveForRestart(cmd({ kind: 'effort', arg: 'default', targetLabel: 'default' }), ident).persist).toBe('clear-effort')
198
+ })
199
+
200
+ it('menu model selection (mdl:s:<tag>) is not offline-resolvable → persist null, re-issue fallback', () => {
201
+ const a = resolveForRestart(cmd({ kind: 'model', origin: 'menu', arg: 'mdl:s:abcd1234', targetLabel: 'the selected model' }), ident)
202
+ expect(a.persist).toBeNull()
203
+ expect(a.reissueText).toContain('re-issue')
204
+ })
205
+
206
+ it('menu effort tap (eff:s:<level>) IS resolvable → persist effort with the level', () => {
207
+ const a = resolveForRestart(cmd({ kind: 'effort', origin: 'menu', arg: 'eff:s:xhigh', targetLabel: 'xhigh' }), ident)
208
+ expect(a.persist).toBe('effort')
209
+ expect(a.arg).toBe('xhigh')
210
+ })
211
+
212
+ it('returns no actions when nothing is queued', () => {
213
+ expect(shutdownResolutionActions(createPendingSessionCommandSlots(), ident)).toEqual([])
214
+ })
215
+ })
216
+
217
+ describe('ackText', () => {
218
+ it('names the model target with a mid-turn framing', () => {
219
+ const t = ackText('model', 'fable', ident)
220
+ expect(t).toContain('mid-turn')
221
+ expect(t).toContain('`fable`')
222
+ expect(t).toContain('switch to')
223
+ })
224
+
225
+ it('uses the effort verb for effort commands', () => {
226
+ const t = ackText('effort', 'high', ident)
227
+ expect(t).toContain('set effort to')
228
+ expect(t).toContain('`high`')
229
+ })
230
+
231
+ it('routes the label through escapeHtml', () => {
232
+ const seen: string[] = []
233
+ ackText('model', 'sr-glm-5', (s) => { seen.push(s); return s })
234
+ expect(seen).toContain('sr-glm-5')
235
+ })
236
+ })
237
+
238
+ describe('supersededText', () => {
239
+ it('names BOTH the replaced and the new target', () => {
240
+ const displaced = cmd({ kind: 'model', targetLabel: 'fable' })
241
+ const next = cmd({ kind: 'model', targetLabel: 'opus' })
242
+ const t = supersededText(displaced, next, ident)
243
+ expect(t).toContain('`opus`')
244
+ expect(t).toContain('`fable`')
245
+ expect(t).toContain('replaced')
246
+ })
247
+ })
248
+
249
+ describe('restartSupersededText', () => {
250
+ it('tells the operator to re-issue after the restart', () => {
251
+ const t = restartSupersededText(cmd({ kind: 'effort', targetLabel: 'max' }), ident)
252
+ expect(t).toContain('restarting')
253
+ expect(t).toContain('/effort max')
254
+ expect(t).toContain('`max`')
255
+ })
256
+ })
257
+
258
+
259
+ // ─── #3042 blocker 1: drain loss-safety across a two-command batch ───────────
260
+
261
+ describe('drainTakenCommands (#3042 blocker 1: an early stop must not drop the rest of the batch)', () => {
262
+ function makeIo(overrides: Partial<DrainIo> = {}) {
263
+ const events: string[] = []
264
+ const io: DrainIo = {
265
+ restartPending: () => false,
266
+ turnInFlight: () => false,
267
+ apply: async c => { events.push(`apply:${c.kind}`); return `✅ ${c.kind} done` },
268
+ isBusyRefusal: t => t.includes('BUSY'),
269
+ resolveForRestartText: c => `persisted:${c.kind}`,
270
+ editCard: async (c, text) => { events.push(`edit:${c.kind}:${text}`) },
271
+ reEnqueue: c => { events.push(`requeue:${c.kind}`) },
272
+ failureText: (c, err) => `fail:${c.kind}:${(err as Error).message}`,
273
+ ...overrides,
274
+ }
275
+ return { io, events }
276
+ }
277
+ const batch = () => [cmd({ kind: 'model' }), cmd({ kind: 'effort', arg: 'high', targetLabel: 'high' })]
278
+
279
+ it('happy path applies and confirms both commands in order', async () => {
280
+ const { io, events } = makeIo()
281
+ await drainTakenCommands(batch(), io)
282
+ expect(events).toEqual(['apply:model', 'edit:model:✅ model done', 'apply:effort', 'edit:effort:✅ effort done'])
283
+ })
284
+
285
+ it('turn races in before the FIRST command → BOTH are re-enqueued, none applied or confirmed', async () => {
286
+ const { io, events } = makeIo({ turnInFlight: () => true })
287
+ await drainTakenCommands(batch(), io)
288
+ expect(events).toEqual(['requeue:model', 'requeue:effort'])
289
+ })
290
+
291
+ it('turn races in before the SECOND command → first applied, second re-enqueued (not lost)', async () => {
292
+ let calls = 0
293
+ const { io, events } = makeIo({ turnInFlight: () => ++calls > 1 })
294
+ await drainTakenCommands(batch(), io)
295
+ expect(events).toEqual(['apply:model', 'edit:model:✅ model done', 'requeue:effort'])
296
+ })
297
+
298
+ it('handler busy-refusal on the FIRST command → the refusal never reaches the ack card and BOTH are re-enqueued', async () => {
299
+ const { io, events } = makeIo({
300
+ apply: async c => (c.kind === 'model' ? 'BUSY — mid-turn' : '✅ effort done'),
301
+ })
302
+ await drainTakenCommands(batch(), io)
303
+ expect(events).toEqual(['requeue:model', 'requeue:effort'])
304
+ })
305
+
306
+ it('apply throwing on the first command does NOT stop the second (failure is per-command)', async () => {
307
+ const { io, events } = makeIo({
308
+ apply: async c => {
309
+ if (c.kind === 'model') throw new Error('boom')
310
+ return '✅ effort done'
311
+ },
312
+ })
313
+ await drainTakenCommands(batch(), io)
314
+ expect(events).toEqual(['edit:model:fail:model:boom', 'edit:effort:✅ effort done'])
315
+ })
316
+
317
+ it('restart pending → every command is resolved via the carriers, none applied live', async () => {
318
+ const { io, events } = makeIo({ restartPending: () => true })
319
+ await drainTakenCommands(batch(), io)
320
+ expect(events).toEqual(['edit:model:persisted:model', 'edit:effort:persisted:effort'])
321
+ })
322
+ })
@@ -19,6 +19,8 @@ import {
19
19
  HOSTD_PERMISSION_TTL_MS,
20
20
  ttlForTool,
21
21
  buildTimedOutCardEdits,
22
+ buildCancelledCardEdits,
23
+ CANCELLED_FOOTER,
22
24
  isStaleTap,
23
25
  STALE_TAP_NOTICE,
24
26
  TIMED_OUT_FOOTER,
@@ -178,6 +180,30 @@ describe('buildTimedOutCardEdits (Bug 2 fix #1 — strip stale keyboard)', () =>
178
180
  })
179
181
  })
180
182
 
183
+ describe('buildCancelledCardEdits (#3020 — halt cancels pending cards)', () => {
184
+ it('marks every recorded card for keyboard-strip and appends the cancelled footer', () => {
185
+ const cards = [
186
+ { chatId: '111', messageId: 5 },
187
+ { chatId: '222', messageId: 9 },
188
+ ]
189
+ const edits = buildCancelledCardEdits('🔐 **Overlord** wants to roll the fleet', cards)
190
+ expect(edits).toHaveLength(2)
191
+ for (const [i, edit] of edits.entries()) {
192
+ // Same contract as the timeout path: a live Approve after the halt
193
+ // would dispatch a verdict into an idle session.
194
+ expect(edit.stripKeyboard).toBe(true)
195
+ expect(edit.chatId).toBe(cards[i]!.chatId)
196
+ expect(edit.messageId).toBe(cards[i]!.messageId)
197
+ expect(edit.text).toContain('roll the fleet')
198
+ expect(edit.text.endsWith(CANCELLED_FOOTER)).toBe(true)
199
+ }
200
+ })
201
+
202
+ it('returns no edits when there were no recorded cards', () => {
203
+ expect(buildCancelledCardEdits('body', [])).toEqual([])
204
+ })
205
+ })
206
+
181
207
  describe('isStaleTap (Bug 2 fix #3 — do not dispatch a verdict for a dead id)', () => {
182
208
  it('is stale when no pending entry exists for the tapped request_id', () => {
183
209
  // hasPending=false ⇒ the reaper already auto-denied + deleted it.
@@ -79,6 +79,18 @@ const isSilentNoCardVerdict = (idx: number): boolean =>
79
79
  const isCardFoldedResume = (idx: number): boolean =>
80
80
  LINES.slice(idx, idx + POST_WINDOW + 1).some((l) => /card-folded-resume/.test(l))
81
81
 
82
+ // A HALTED-TURN verdict (#3020 `executeHaltNow` → `cancelPendingPermissionsForHalt`)
83
+ // denies the pending call because the operator is KILLING the turn (/stop,
84
+ // bare "stop", empty `!`). There is nothing to resume — the turn is about to
85
+ // be C-c'd and its busy state torn down — so neither the glyph flip nor the
86
+ // "got it, continuing" message applies. The card is still visibly terminal:
87
+ // the halt path edits it to "⏹ Cancelled" with the keyboard stripped, and the
88
+ // /stop reply acks the operator. Such callsites carry the
89
+ // `halted-turn-verdict` sentinel within the 5 lines above the dispatch and
90
+ // are exempt from BOTH pairings.
91
+ const isHaltedTurnVerdict = (idx: number): boolean =>
92
+ LINES.slice(Math.max(0, idx - 5), idx + 1).some((l) => /halted-turn-verdict/.test(l))
93
+
82
94
  // How far below the dispatch the resume call is allowed to live. The
83
95
  // widest real gap today is ~9 lines (the slash-command path); 15 gives
84
96
  // refactor headroom without letting an unrelated resume "cover" a
@@ -99,6 +111,8 @@ describe('permission verdict → resume reaction wiring', () => {
99
111
  const unpaired: number[] = []
100
112
  for (const idx of dispatchCallsites) {
101
113
  if (isSilentNoCardVerdict(idx)) continue
114
+ // Exempt: the halt path kills the turn — nothing resumes (#3020).
115
+ if (isHaltedTurnVerdict(idx)) continue
102
116
  const window = LINES.slice(idx, idx + RESUME_WINDOW + 1).join('\n')
103
117
  if (!/\bresumeReactionAfterVerdict\s*\(\s*\)/.test(window)) {
104
118
  // 1-based line number for a human-readable failure.
@@ -125,6 +139,8 @@ describe('permission verdict → resume reaction wiring', () => {
125
139
  const unpaired: number[] = []
126
140
  for (const idx of dispatchCallsites) {
127
141
  if (isSilentNoCardVerdict(idx)) continue
142
+ // Exempt: the halt path kills the turn — nothing resumes (#3020).
143
+ if (isHaltedTurnVerdict(idx)) continue
128
144
  // Exempt: card-ux fix 3 folds the resume line into the card edit
129
145
  // instead of a separate message (still visibly resumes the operator).
130
146
  if (isCardFoldedResume(idx)) continue
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Covers the photo→document graceful fallback contract (#klanker
3
+ * 2026-07-10 incident: a tall phone screenshot sent via the reply tool's
4
+ * `files` param threw PHOTO_INVALID_DIMENSIONS).
5
+ *
6
+ * Two production pieces make the gateway's fallback work:
7
+ * 1. `isPhotoDimensionRejectError` classifies the 400s that mean "not
8
+ * usable AS a photo" (dimensions / save-file / too-large).
9
+ * 2. `retryApiCall` must NOT swallow or retry those 400s — they have to
10
+ * reach the caller's catch so it can re-send as a document.
11
+ *
12
+ * The final block exercises the EXACT try/catch shape the gateway's reply
13
+ * file-send loop uses (`retryWithThreadFallback` + the predicate), proving
14
+ * the file is still delivered as a document.
15
+ */
16
+
17
+ import { describe, it, expect, vi } from 'vitest'
18
+ import {
19
+ createRetryApiCall,
20
+ retryWithThreadFallback,
21
+ isPhotoDimensionRejectError,
22
+ } from '../retry-api-call.js'
23
+ import { errors } from './fake-bot-api.js'
24
+
25
+ describe('isPhotoDimensionRejectError', () => {
26
+ it('is true for PHOTO_INVALID_DIMENSIONS', () => {
27
+ expect(isPhotoDimensionRejectError(errors.badRequest('PHOTO_INVALID_DIMENSIONS', 'sendPhoto'))).toBe(true)
28
+ })
29
+
30
+ it('is true for PHOTO_SAVE_FILE_INVALID', () => {
31
+ expect(isPhotoDimensionRejectError(errors.badRequest('PHOTO_SAVE_FILE_INVALID', 'sendPhoto'))).toBe(true)
32
+ })
33
+
34
+ it('is true for the mediagroup-wrapped variant', () => {
35
+ const err = errors.badRequest(
36
+ 'failed to send message #2 with the error message "PHOTO_INVALID_DIMENSIONS"',
37
+ 'sendMediaGroup',
38
+ )
39
+ expect(isPhotoDimensionRejectError(err)).toBe(true)
40
+ })
41
+
42
+ it('is true for photo-too-big size rejections', () => {
43
+ expect(isPhotoDimensionRejectError(errors.badRequest('PHOTO_SAVE_FILE_INVALID: photo is too big', 'sendPhoto'))).toBe(true)
44
+ expect(isPhotoDimensionRejectError(errors.badRequest('Image is too big', 'sendPhoto'))).toBe(true)
45
+ })
46
+
47
+ it('is false for unrelated 400s', () => {
48
+ expect(isPhotoDimensionRejectError(errors.badRequest('chat not found', 'sendPhoto'))).toBe(false)
49
+ expect(isPhotoDimensionRejectError(errors.threadNotFound('sendPhoto'))).toBe(false)
50
+ })
51
+
52
+ it('is false for non-400 and non-grammy errors', () => {
53
+ expect(isPhotoDimensionRejectError(errors.forbidden('sendPhoto'))).toBe(false)
54
+ expect(isPhotoDimensionRejectError(errors.floodWait(3, 'sendPhoto'))).toBe(false)
55
+ expect(isPhotoDimensionRejectError(new Error('PHOTO_INVALID_DIMENSIONS'))).toBe(false)
56
+ expect(isPhotoDimensionRejectError(null)).toBe(false)
57
+ })
58
+ })
59
+
60
+ describe('retryApiCall does not swallow photo-dimension rejects', () => {
61
+ it('rethrows PHOTO_INVALID_DIMENSIONS so the caller can fall back', async () => {
62
+ const retry = createRetryApiCall()
63
+ const err = errors.badRequest('PHOTO_INVALID_DIMENSIONS', 'sendPhoto')
64
+ await expect(retry(() => Promise.reject(err))).rejects.toBe(err)
65
+ })
66
+
67
+ it('propagates through retryWithThreadFallback (not treated as THREAD_NOT_FOUND)', async () => {
68
+ const retry = createRetryApiCall()
69
+ const err = errors.badRequest('PHOTO_INVALID_DIMENSIONS', 'sendPhoto')
70
+ await expect(
71
+ retryWithThreadFallback(retry, () => Promise.reject(err), {
72
+ threadId: 42,
73
+ chat_id: '123',
74
+ verb: 'sendPhoto',
75
+ }),
76
+ ).rejects.toBe(err)
77
+ })
78
+ })
79
+
80
+ describe('photo→document fallback (gateway reply-loop shape)', () => {
81
+ it('re-sends as a document when sendPhoto is rejected for dimensions', async () => {
82
+ const retry = createRetryApiCall()
83
+ const err = errors.badRequest('PHOTO_INVALID_DIMENSIONS', 'sendPhoto')
84
+ const sendPhoto = vi.fn(() => Promise.reject(err))
85
+ const sendDocument = vi.fn(() => Promise.resolve({ message_id: 555 }))
86
+
87
+ // Mirror gateway.ts executeReply's per-file try/catch.
88
+ let sent: { message_id: number }
89
+ try {
90
+ sent = await retryWithThreadFallback(retry, () => sendPhoto(), {
91
+ threadId: undefined,
92
+ chat_id: '123',
93
+ verb: 'sendPhoto',
94
+ })
95
+ } catch (caught) {
96
+ expect(isPhotoDimensionRejectError(caught)).toBe(true)
97
+ sent = await retryWithThreadFallback(retry, () => sendDocument(), {
98
+ threadId: undefined,
99
+ chat_id: '123',
100
+ verb: 'sendDocument',
101
+ })
102
+ }
103
+
104
+ expect(sendPhoto).toHaveBeenCalledTimes(1)
105
+ expect(sendDocument).toHaveBeenCalledTimes(1)
106
+ expect(sent!.message_id).toBe(555)
107
+ })
108
+
109
+ it('does NOT fall back for non-dimension errors (they propagate)', async () => {
110
+ const retry = createRetryApiCall()
111
+ const err = errors.forbidden('sendPhoto')
112
+ const sendDocument = vi.fn(() => Promise.resolve({ message_id: 1 }))
113
+
114
+ let threw = false
115
+ try {
116
+ await retryWithThreadFallback(retry, () => Promise.reject(err), {
117
+ threadId: undefined,
118
+ chat_id: '123',
119
+ verb: 'sendPhoto',
120
+ })
121
+ } catch (caught) {
122
+ threw = true
123
+ // The gateway only falls back when this predicate holds.
124
+ expect(isPhotoDimensionRejectError(caught)).toBe(false)
125
+ }
126
+ expect(threw).toBe(true)
127
+ expect(sendDocument).not.toHaveBeenCalled()
128
+ })
129
+ })