@deep-podder/dsh-remote-mobile 0.0.6 → 0.0.7

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 (45) hide show
  1. package/PROTOCOL.md +97 -9
  2. package/README.md +44 -9
  3. package/SECURITY.md +8 -0
  4. package/auth.js +16 -0
  5. package/bridge.js +336 -9
  6. package/docs/api-notes.md +12 -4
  7. package/docs/engineering-audit.md +252 -0
  8. package/docs/reference-chat-demo.md +41 -0
  9. package/docs/screenshots/chat-light.png +0 -0
  10. package/docs/screenshots/commands-dark.png +0 -0
  11. package/docs/screenshots/pairing-light.png +0 -0
  12. package/docs/screenshots/sessions-light.png +0 -0
  13. package/docs/verification.md +40 -4
  14. package/index.js +1 -1
  15. package/mobile/README.md +81 -35
  16. package/mobile/app.js +4268 -906
  17. package/mobile/index.html +28 -17
  18. package/mobile/lib/away.js +45 -0
  19. package/mobile/lib/constants.js +5 -0
  20. package/mobile/lib/errors.js +42 -0
  21. package/mobile/lib/format.js +94 -0
  22. package/mobile/lib/lock.js +21 -0
  23. package/mobile/manifest.webmanifest +24 -0
  24. package/mobile/mock-server.js +442 -17
  25. package/mobile/model/history.js +119 -0
  26. package/mobile/model/question.js +318 -0
  27. package/mobile/model/turns.js +57 -0
  28. package/mobile/styles/base.css +143 -0
  29. package/mobile/{styles.css → styles/components.css} +1170 -826
  30. package/mobile/styles/overrides.css +269 -0
  31. package/mobile/styles/tokens.css +169 -0
  32. package/mobile/sw.js +28 -4
  33. package/package.json +34 -20
  34. package/protocol.js +87 -0
  35. package/push-policy.js +58 -0
  36. package/server/frames/activity.js +110 -0
  37. package/server/frames/connection.js +21 -0
  38. package/server/frames/history.js +23 -0
  39. package/server/frames/interactions.js +77 -0
  40. package/server/frames/prompts.js +29 -0
  41. package/server/frames/queue.js +58 -0
  42. package/server/frames/sessions.js +201 -0
  43. package/server/frames/settings.js +38 -0
  44. package/server/frames/subagents.js +50 -0
  45. package/server.js +341 -423
@@ -9,8 +9,10 @@
9
9
  It implements, with Node built-ins only (no npm dependencies):
10
10
 
11
11
  GET / the SPA shell
12
- GET /app.js the SPA bundle
13
- GET /styles.css the stylesheet
12
+ GET /app.js the SPA module root
13
+ GET /protocol.js shared wire constants/catalog
14
+ GET /lib/*, /model/* SPA helper modules
15
+ GET /styles/*.css cascade-ordered stylesheets
14
16
  GET /api/state { paired, device, version }
15
17
  POST /api/pair { pin } or { token } -> Set-Cookie: rm_session
16
18
  POST /api/rotate-pin rotates the demo PIN
@@ -30,16 +32,24 @@ import { createHash, createECDH, randomBytes } from 'node:crypto';
30
32
  import { fileURLToPath } from 'node:url';
31
33
  import { dirname, extname, join } from 'node:path';
32
34
  import { networkInterfaces } from 'node:os';
35
+ import {
36
+ HISTORY_DEFAULT_LIMIT,
37
+ HISTORY_MAX_LIMIT,
38
+ MAX_UPLOAD_BYTES as DEFAULT_MAX_UPLOAD_BYTES
39
+ } from '../protocol.js';
33
40
 
34
41
  const HERE = dirname(fileURLToPath(import.meta.url));
35
42
  const PORT = Number(process.env.PORT || process.argv[2] || 3456);
36
43
  const HOST = process.env.HOST || '0.0.0.0';
37
- const VERSION = '0.0.6';
44
+ const VERSION = '0.0.7';
38
45
  const PAIRING_TOKEN = randomBytes(24).toString('base64url');
39
46
  const RATE_WINDOW_MS = Number(process.env.RM_RATE_WINDOW_MS || 5 * 60 * 1000);
40
47
  const RATE_MAX = Number(process.env.RM_RATE_MAX || 5);
41
- const MAX_UPLOAD_BYTES = Number(process.env.RM_MAX_UPLOAD_BYTES || 32 * 1024 * 1024);
48
+ const MAX_UPLOAD_BYTES = Number(process.env.RM_MAX_UPLOAD_BYTES || DEFAULT_MAX_UPLOAD_BYTES);
42
49
  const UPLOAD_DELAY_MS = Number(process.env.RM_UPLOAD_DELAY_MS || 0);
50
+ const UPLOAD_FAIL_FIRST = process.env.RM_UPLOAD_FAIL_FIRST === '1';
51
+ let uploadFailedOnce = false;
52
+ let rejectedPromptOnce = false;
43
53
  const UPLOAD_FILE_LIMIT = 10;
44
54
  const SESSION_COOKIE = 'rm_session';
45
55
  const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
@@ -61,7 +71,19 @@ const STATIC_FILES = {
61
71
  '/': 'index.html',
62
72
  '/index.html': 'index.html',
63
73
  '/app.js': 'app.js',
64
- '/styles.css': 'styles.css',
74
+ '/protocol.js': '../protocol.js',
75
+ '/lib/constants.js': 'lib/constants.js',
76
+ '/lib/errors.js': 'lib/errors.js',
77
+ '/lib/away.js': 'lib/away.js',
78
+ '/lib/lock.js': 'lib/lock.js',
79
+ '/lib/format.js': 'lib/format.js',
80
+ '/model/question.js': 'model/question.js',
81
+ '/model/history.js': 'model/history.js',
82
+ '/model/turns.js': 'model/turns.js',
83
+ '/styles/tokens.css': 'styles/tokens.css',
84
+ '/styles/base.css': 'styles/base.css',
85
+ '/styles/components.css': 'styles/components.css',
86
+ '/styles/overrides.css': 'styles/overrides.css',
65
87
  '/manifest.webmanifest': 'manifest.webmanifest',
66
88
  '/sw.js': 'sw.js',
67
89
  '/favicon.svg': 'favicon.svg',
@@ -94,7 +116,14 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
94
116
  const PUSH_ECDH = createECDH('prime256v1');
95
117
  PUSH_ECDH.generateKeys();
96
118
  const PUSH_PUBLIC_KEY = PUSH_ECDH.getPublicKey().toString('base64url');
97
- const pushSubscriptions = new Map(); // endpoint -> { endpoint, deviceId, subscription }
119
+ const pushSubscriptions = new Map();
120
+ let mockPushPrefs = {
121
+ muted: false,
122
+ decisionsOnly: false,
123
+ quietStart: null,
124
+ quietEnd: null,
125
+ utcOffsetMinutes: 0
126
+ }; // endpoint -> { endpoint, deviceId, subscription }
98
127
  const deviceVisibility = new Map(); // deviceId -> boolean
99
128
 
100
129
  function log(...args) {
@@ -430,6 +459,60 @@ function seed() {
430
459
  'Want me to run the checks now?'
431
460
  ].join('\n'),
432
461
  ts: now - 5 * 60 * 1000
462
+ },
463
+ {
464
+ id: 'seq:3u',
465
+ kind: 'user',
466
+ text: 'Run the checks before I tag the release.',
467
+ ts: now - 4 * 60 * 1000
468
+ },
469
+ /* The Host records tool rows before the assistant message that closes the
470
+ turn; this fixture keeps that ordering so the transcript must still fold
471
+ the three calls into one turn (regression: they rendered as three cards). */
472
+ {
473
+ id: 'tool:2',
474
+ kind: 'tool',
475
+ callId: 'call-history-2',
476
+ name: 'pwsh',
477
+ title: 'Run command',
478
+ argsPreview: 'node dev/release-check.mjs',
479
+ ok: true,
480
+ output: 'PASS release packaging check',
481
+ diff: null,
482
+ durationMs: 1200,
483
+ ts: now - 3.5 * 60 * 1000
484
+ },
485
+ {
486
+ id: 'tool:3',
487
+ kind: 'tool',
488
+ callId: 'call-history-3',
489
+ name: 'pwsh',
490
+ title: 'Run command',
491
+ argsPreview: 'node dev/protocol-check.mjs',
492
+ ok: true,
493
+ output: 'PASS protocol parity',
494
+ diff: null,
495
+ durationMs: 800,
496
+ ts: now - 3 * 60 * 1000
497
+ },
498
+ {
499
+ id: 'tool:4',
500
+ kind: 'tool',
501
+ callId: 'call-history-4',
502
+ name: 'read',
503
+ title: 'Read file',
504
+ argsPreview: 'docs/verification.md',
505
+ ok: true,
506
+ output: 'verification log…',
507
+ diff: null,
508
+ durationMs: 60,
509
+ ts: now - 2.7 * 60 * 1000
510
+ },
511
+ {
512
+ id: 'seq:3r',
513
+ kind: 'assistant',
514
+ text: 'All three checks pass — the release checklist is clear to tag.',
515
+ ts: now - 2.5 * 60 * 1000
433
516
  }
434
517
  ]);
435
518
 
@@ -485,6 +568,20 @@ function seed() {
485
568
  ts: now - 26 * 60 * 60 * 1000
486
569
  }
487
570
  ]);
571
+
572
+ /* Long-history fixture for the paged "Load earlier messages" check. */
573
+ if (process.env.RM_LONG_HISTORY === '1') {
574
+ const filler = [];
575
+ for (let i = 0; i < 120; i += 1) {
576
+ filler.push({
577
+ id: 'filler:' + i,
578
+ kind: i % 2 === 0 ? 'user' : 'assistant',
579
+ text: 'Earlier message ' + (i + 1),
580
+ ts: now - (200 - i) * 1000
581
+ });
582
+ }
583
+ histories.set(release.id, filler.concat(histories.get(release.id) || []));
584
+ }
488
585
  }
489
586
 
490
587
  seed();
@@ -495,6 +592,11 @@ function findSession(id) {
495
592
  return serverState.sessions.find((session) => session.id === id) || null;
496
593
  }
497
594
 
595
+ function findWorkspace(id) {
596
+ if (typeof id !== 'string' || id.length === 0) return null;
597
+ return WORKSPACES.find((workspace) => workspace.id === id) || null;
598
+ }
599
+
498
600
  function publicSession(session) {
499
601
  return {
500
602
  id: session.id,
@@ -655,8 +757,23 @@ function splitChunks(text) {
655
757
  return text.match(/\s*\S+/g) || [text];
656
758
  }
657
759
 
658
- async function streamAssistant(sessionId, turn, step, text, runToken) {
760
+ async function streamAssistant(sessionId, turn, step, text, runToken, reasoning) {
659
761
  broadcast({ type: 'assistant.start', sessionId, turn, step });
762
+ /* A short reasoning phase for prompts that ask for it, including a pause so
763
+ the live "Thinking · Ns" timer is observable in a browser check. */
764
+ if (reasoning) {
765
+ for (const chunk of splitChunks(reasoning)) {
766
+ if (runToken.cancelled) break;
767
+ broadcast({
768
+ type: 'assistant.delta',
769
+ sessionId,
770
+ text: '',
771
+ reasoning: chunk
772
+ });
773
+ await sleep(35);
774
+ }
775
+ if (!runToken.cancelled) await sleep(900);
776
+ }
660
777
  const chunks = splitChunks(text);
661
778
  let accumulated = '';
662
779
  for (const chunk of chunks) {
@@ -707,7 +824,7 @@ function deployQuestions() {
707
824
  detail: 'Staging is safe to retry; production carries live traffic.',
708
825
  multiSelect: false,
709
826
  options: [
710
- { label: 'Staging', description: 'Shared staging slot' },
827
+ { label: 'Staging (recommended)', description: 'Shared staging slot' },
711
828
  { label: 'Production', description: 'Live traffic — use with care' }
712
829
  ]
713
830
  },
@@ -725,6 +842,25 @@ function deployQuestions() {
725
842
  ];
726
843
  }
727
844
 
845
+ /* The plan-review presentation intent: one decision over one plan. */
846
+ function planReviewQuestion() {
847
+ return {
848
+ id: 'plan',
849
+ question: 'Approve this plan?',
850
+ header: 'Plan review',
851
+ detail:
852
+ '# Ship the question-card parity fix\n\n' +
853
+ 'Bring the phone card in line with the desktop composer.\n\n' +
854
+ '## Steps\n\n- Paged questions\n- Recommended options\n- Per-question skip\n',
855
+ multiSelect: false,
856
+ options: [
857
+ { label: 'Approve plan', description: 'Start implementing the plan' },
858
+ { label: 'Revise plan' }
859
+ ],
860
+ intent: { kind: 'plan-review', approve: 'Approve plan' }
861
+ };
862
+ }
863
+
728
864
  /* Ask a batch through the full tool shape: tool.start (with question) +
729
865
  question.request, then question.resolved + tool.end once the phone answers. */
730
866
  async function askQuestions(sessionId, callId, questions, runToken, opts = {}) {
@@ -988,6 +1124,76 @@ function emitCrossSessionFixtures(activeSessionId) {
988
1124
  }, 350);
989
1125
  }
990
1126
 
1127
+
1128
+ function mockSubagents(sessionId) {
1129
+ const now = Date.now();
1130
+ return [
1131
+ {
1132
+ id: sessionId + '-sub-research',
1133
+ parentId: sessionId,
1134
+ depth: 1,
1135
+ label: 'research',
1136
+ mode: 'continuable',
1137
+ title: 'Research the workspace API',
1138
+ running: true,
1139
+ status: 'running',
1140
+ createdAt: now - 42000,
1141
+ updatedAt: now - 2000,
1142
+ model: { provider: 'deepseek', model: 'deepseek-chat' }
1143
+ },
1144
+ {
1145
+ id: sessionId + '-sub-tests',
1146
+ parentId: sessionId,
1147
+ depth: 1,
1148
+ label: 'tests',
1149
+ mode: 'one-shot',
1150
+ title: 'Run focused checks',
1151
+ running: false,
1152
+ status: 'idle',
1153
+ createdAt: now - 180000,
1154
+ updatedAt: now - 95000,
1155
+ model: { provider: 'deepseek', model: 'deepseek-chat' }
1156
+ },
1157
+ {
1158
+ id: sessionId + '-sub-external',
1159
+ parentId: sessionId,
1160
+ depth: 1,
1161
+ label: 'external',
1162
+ mode: 'external',
1163
+ title: 'External reviewer',
1164
+ running: false,
1165
+ status: 'unknown',
1166
+ createdAt: now - 240000,
1167
+ updatedAt: now - 200000,
1168
+ model: null
1169
+ }
1170
+ ];
1171
+ }
1172
+
1173
+ function mockSubagentHistory(subagentId) {
1174
+ const now = Date.now();
1175
+ return [
1176
+ { id: 'sub-u-1', kind: 'user', text: 'Inspect the workspace API and report the risky seams.', ts: now - 40000 },
1177
+ {
1178
+ id: 'sub-a-1',
1179
+ kind: 'assistant',
1180
+ text: 'I checked the workspace registry and found two seams worth reporting: cold-session projection reads and the archive gate.',
1181
+ ts: now - 36000
1182
+ },
1183
+ {
1184
+ id: 'sub-t-1',
1185
+ kind: 'tool',
1186
+ callId: 'sub-tool-1',
1187
+ name: 'read',
1188
+ title: 'Read workspace docs',
1189
+ ok: true,
1190
+ output: 'docs/api-notes-v2.md\n- cold-safe reads\n- archive gate',
1191
+ durationMs: 240,
1192
+ ts: now - 34000
1193
+ }
1194
+ ];
1195
+ }
1196
+
991
1197
  async function runTurn(sessionId, promptText, attachments) {
992
1198
  const session = findSession(sessionId);
993
1199
  if (!session) return;
@@ -1008,7 +1214,10 @@ async function runTurn(sessionId, promptText, attachments) {
1008
1214
  turn,
1009
1215
  1,
1010
1216
  firstStepText(promptText, attachments),
1011
- runToken
1217
+ runToken,
1218
+ /think|reason/i.test(promptText)
1219
+ ? 'Weighing the next step before answering.\n\n- check the workspace state\n- confirm the target'
1220
+ : null
1012
1221
  );
1013
1222
  appendHistory(sessionId, {
1014
1223
  id: nextHistoryId('assistant'),
@@ -1064,7 +1273,7 @@ async function runTurn(sessionId, promptText, attachments) {
1064
1273
  argsPreview,
1065
1274
  detail: { command: argsPreview, cwd: 'C:\\workspace\\demo' }
1066
1275
  });
1067
- await sleep(850);
1276
+ await sleep(2600);
1068
1277
  if (runToken.cancelled) return;
1069
1278
  broadcast({
1070
1279
  type: 'tool.end',
@@ -1102,6 +1311,19 @@ async function runTurn(sessionId, promptText, attachments) {
1102
1311
  if (runToken.cancelled) return;
1103
1312
  }
1104
1313
 
1314
+ /* A plan prompt exercises the plan-review presentation intent. */
1315
+ if (!wantsQuestion && /plan/i.test(promptText)) {
1316
+ const planCallId = 'call-' + randomBytes(4).toString('hex');
1317
+ asked = await askQuestions(
1318
+ sessionId,
1319
+ planCallId,
1320
+ [planReviewQuestion()],
1321
+ runToken,
1322
+ { toolTitle: 'Review plan' }
1323
+ );
1324
+ if (runToken.cancelled) return;
1325
+ }
1326
+
1105
1327
  let denied = false;
1106
1328
  const wantsApproval = /deploy/i.test(promptText);
1107
1329
  if (wantsApproval) {
@@ -1435,6 +1657,16 @@ function handleClientFrame(conn, frame) {
1435
1657
  serverState.presets.presets.some((entry) => entry.id === frame.preset)
1436
1658
  ? frame.preset
1437
1659
  : serverState.presets.current;
1660
+ /* Mirror the Host: a project files the Session under that Workspace,
1661
+ while a bare directory leaves it ungrouped. */
1662
+ const workspace =
1663
+ typeof frame.workspaceId === 'string' ? findWorkspace(frame.workspaceId) : null;
1664
+ if (typeof frame.workspaceId === 'string' && frame.workspaceId && !workspace) {
1665
+ conn.sendText(
1666
+ JSON.stringify(errorFrame('not-found', 'That project does not exist.'))
1667
+ );
1668
+ return;
1669
+ }
1438
1670
  const session = {
1439
1671
  id: 'sess-' + randomBytes(3).toString('hex'),
1440
1672
  title: 'New session',
@@ -1450,9 +1682,11 @@ function handleClientFrame(conn, frame) {
1450
1682
  turn: 0,
1451
1683
  agentAvailable: true,
1452
1684
  pinned: false,
1453
- archived: false
1685
+ archived: false,
1686
+ workspaceId: workspace ? workspace.id : null
1454
1687
  };
1455
1688
  serverState.sessions.unshift(session);
1689
+ if (workspace) workspace.sessionIds.unshift(session.id);
1456
1690
  histories.set(session.id, []);
1457
1691
  queues.set(session.id, []);
1458
1692
  serverState.activeSessionId = session.id;
@@ -1468,13 +1702,43 @@ function handleClientFrame(conn, frame) {
1468
1702
  return;
1469
1703
  }
1470
1704
 
1705
+ case 'session.attach': {
1706
+ const session = findSession(frame.sessionId);
1707
+ if (!session) {
1708
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1709
+ return;
1710
+ }
1711
+ const workspace =
1712
+ typeof frame.workspaceId === 'string' ? findWorkspace(frame.workspaceId) : null;
1713
+ if (!workspace) {
1714
+ conn.sendText(
1715
+ JSON.stringify(errorFrame('not-found', 'That project does not exist.'))
1716
+ );
1717
+ return;
1718
+ }
1719
+ for (const entry of WORKSPACES) {
1720
+ entry.sessionIds = entry.sessionIds.filter((id) => id !== session.id);
1721
+ }
1722
+ workspace.sessionIds.unshift(session.id);
1723
+ session.workspaceId = workspace.id;
1724
+ conn.sendText(
1725
+ JSON.stringify({
1726
+ type: 'session.attached',
1727
+ sessionId: session.id,
1728
+ workspaceId: workspace.id
1729
+ })
1730
+ );
1731
+ broadcastSessions();
1732
+ return;
1733
+ }
1734
+
1471
1735
  case 'history.load': {
1472
1736
  const session = findSession(frame.sessionId);
1473
1737
  if (!session) {
1474
1738
  conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1475
1739
  return;
1476
1740
  }
1477
- const limit = clampLimit(frame.limit, 200);
1741
+ const limit = clampLimit(frame.limit, HISTORY_MAX_LIMIT);
1478
1742
  const all = historyOf(session.id);
1479
1743
  conn.sendText(
1480
1744
  JSON.stringify({
@@ -1640,9 +1904,11 @@ function handleClientFrame(conn, frame) {
1640
1904
  conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
1641
1905
  return;
1642
1906
  }
1907
+ const atSeq = Number.isInteger(frame.atSeq) && frame.atSeq >= 0 ? frame.atSeq : null;
1643
1908
  const fork = {
1644
1909
  id: 'sess-' + randomBytes(3).toString('hex'),
1645
- title: session.title + ' (fork)',
1910
+ title:
1911
+ session.title + (atSeq === null ? ' (fork)' : ' (fork@' + atSeq + ')'),
1646
1912
  running: false,
1647
1913
  updatedAt: Date.now(),
1648
1914
  preset: session.preset || null,
@@ -1650,10 +1916,23 @@ function handleClientFrame(conn, frame) {
1650
1916
  turn: 0,
1651
1917
  agentAvailable: true,
1652
1918
  pinned: false,
1653
- archived: false
1919
+ archived: false,
1920
+ /* The Host attaches a fork to the source Session's Workspace. */
1921
+ workspaceId: session.workspaceId || null
1654
1922
  };
1655
1923
  serverState.sessions.unshift(fork);
1656
- histories.set(fork.id, historyOf(session.id).slice());
1924
+ const forkWorkspace = session.workspaceId ? findWorkspace(session.workspaceId) : null;
1925
+ if (forkWorkspace) forkWorkspace.sessionIds.unshift(fork.id);
1926
+ let forkHistory = historyOf(session.id).slice();
1927
+ if (atSeq !== null) {
1928
+ /* Keep the durable rows up to the requested event, mirroring a Host
1929
+ fork at that sequence (non-sequenced fixture ids are kept). */
1930
+ forkHistory = forkHistory.filter((item) => {
1931
+ const match = /^(?:seq|tool):(\d+)$/.exec(String(item.id || ''));
1932
+ return match === null || Number(match[1]) <= atSeq;
1933
+ });
1934
+ }
1935
+ histories.set(fork.id, forkHistory);
1657
1936
  queues.set(fork.id, []);
1658
1937
  serverState.activeSessionId = fork.id;
1659
1938
  broadcastSessions();
@@ -1898,6 +2177,40 @@ function handleClientFrame(conn, frame) {
1898
2177
  return;
1899
2178
  }
1900
2179
 
2180
+ case 'subagents.list': {
2181
+ const session = findSession(frame.sessionId);
2182
+ if (!session) {
2183
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown session.')));
2184
+ return;
2185
+ }
2186
+ conn.sendText(
2187
+ JSON.stringify({
2188
+ type: 'subagents',
2189
+ sessionId: session.id,
2190
+ items: mockSubagents(session.id)
2191
+ })
2192
+ );
2193
+ return;
2194
+ }
2195
+
2196
+ case 'subagents.history': {
2197
+ const subagentId = typeof frame.subagentId === 'string' ? frame.subagentId : '';
2198
+ const session = findSession(frame.sessionId);
2199
+ if (!session || !subagentId) {
2200
+ conn.sendText(JSON.stringify(errorFrame('not-found', 'Unknown subagent.')));
2201
+ return;
2202
+ }
2203
+ conn.sendText(
2204
+ JSON.stringify({
2205
+ type: 'subagent.history',
2206
+ sessionId: session.id,
2207
+ subagentId,
2208
+ items: mockSubagentHistory(subagentId)
2209
+ })
2210
+ );
2211
+ return;
2212
+ }
2213
+
1901
2214
  case 'prompt': {
1902
2215
  const session = findSession(frame.sessionId);
1903
2216
  if (!session) {
@@ -1934,6 +2247,20 @@ function handleClientFrame(conn, frame) {
1934
2247
  );
1935
2248
  return;
1936
2249
  }
2250
+ /* One-shot rejection fixture: the phone should keep the message with a
2251
+ retry instead of dropping it. The retry (same text) then succeeds. */
2252
+ if (/^reject once/i.test(promptText) && !rejectedPromptOnce) {
2253
+ rejectedPromptOnce = true;
2254
+ conn.sendText(
2255
+ JSON.stringify({
2256
+ type: 'error',
2257
+ code: 'bad-request',
2258
+ message: 'Prompt rejected by fixture.',
2259
+ ...(frame.requestId ? { requestId: String(frame.requestId) } : {})
2260
+ })
2261
+ );
2262
+ return;
2263
+ }
1937
2264
  const mode = frame.mode === 'steer' ? 'steer' : 'queue';
1938
2265
  if (mode === 'steer') {
1939
2266
  if (!session.running) {
@@ -2001,6 +2328,23 @@ function handleClientFrame(conn, frame) {
2001
2328
  return;
2002
2329
  }
2003
2330
 
2331
+ case 'question.cancel': {
2332
+ const question = frame.requestId
2333
+ ? pendingQuestions.get(frame.requestId)
2334
+ : null;
2335
+ if (!question || question.done) {
2336
+ conn.sendText(
2337
+ JSON.stringify(
2338
+ errorFrame('not-found', 'Question is unknown or already resolved.')
2339
+ )
2340
+ );
2341
+ return;
2342
+ }
2343
+ question.done = true;
2344
+ question.resolve({ answers: [], cancelled: true });
2345
+ return;
2346
+ }
2347
+
2004
2348
  case 'question.answer': {
2005
2349
  let question = frame.requestId
2006
2350
  ? pendingQuestions.get(frame.requestId)
@@ -2028,6 +2372,24 @@ function handleClientFrame(conn, frame) {
2028
2372
  return;
2029
2373
  }
2030
2374
 
2375
+ case 'pending.list': {
2376
+ conn.sendText(
2377
+ JSON.stringify({
2378
+ type: 'pending',
2379
+ approvals: [...pendingApprovals.values()].map((entry) => ({
2380
+ requestId: entry.requestId,
2381
+ sessionId: entry.sessionId || null
2382
+ })),
2383
+ questions: [...pendingQuestions.values()].map((entry) => ({
2384
+ requestId: entry.requestId,
2385
+ callId: entry.callId || null,
2386
+ sessionId: entry.sessionId || null
2387
+ }))
2388
+ })
2389
+ );
2390
+ return;
2391
+ }
2392
+
2031
2393
  case 'approval.answer': {
2032
2394
  const approval = pendingApprovals.get(frame.requestId);
2033
2395
  if (!approval || approval.done) {
@@ -2161,7 +2523,7 @@ function handleClientFrame(conn, frame) {
2161
2523
 
2162
2524
  function clampLimit(value, max) {
2163
2525
  const n = Number(value);
2164
- if (!isFinite(n) || n <= 0) return 50;
2526
+ if (!isFinite(n) || n <= 0) return HISTORY_DEFAULT_LIMIT;
2165
2527
  return Math.min(Math.floor(n), max);
2166
2528
  }
2167
2529
 
@@ -2377,6 +2739,44 @@ async function handleRequest(req, res) {
2377
2739
  return;
2378
2740
  }
2379
2741
 
2742
+ if (path === '/api/devices' && req.method === 'GET') {
2743
+ const current = deviceForRequest(req);
2744
+ if (!current) {
2745
+ sendJson(res, 401, { error: 'unauthenticated' });
2746
+ return;
2747
+ }
2748
+ sendJson(res, 200, {
2749
+ devices: devices.map((entry) => ({
2750
+ id: entry.id,
2751
+ name: entry.name,
2752
+ createdAt: entry.createdAt,
2753
+ lastSeenAt: entry.lastSeenAt || entry.createdAt,
2754
+ canApprove: true,
2755
+ current: entry.id === current.id
2756
+ }))
2757
+ });
2758
+ return;
2759
+ }
2760
+
2761
+ if (path === '/api/devices/name' && req.method === 'POST') {
2762
+ const current = deviceForRequest(req);
2763
+ if (!current) {
2764
+ sendJson(res, 401, { error: 'unauthenticated' });
2765
+ return;
2766
+ }
2767
+ const body = await readJsonBody(req, 4 * 1024);
2768
+ const name = String(body?.name || '').replace(/\s+/g, ' ').trim().slice(0, 40);
2769
+ if (!name) {
2770
+ sendJson(res, 400, { error: 'bad-request' });
2771
+ return;
2772
+ }
2773
+ current.name = name;
2774
+ sendJson(res, 200, {
2775
+ device: { id: current.id, name: current.name, createdAt: current.createdAt }
2776
+ });
2777
+ return;
2778
+ }
2779
+
2380
2780
  if (path === '/api/state' && req.method === 'GET') {
2381
2781
  const device = deviceForRequest(req);
2382
2782
  sendJson(res, 200, {
@@ -2437,7 +2837,25 @@ async function handleRequest(req, res) {
2437
2837
  sendJson(res, 200, { ok: true });
2438
2838
  return;
2439
2839
  }
2440
- if (path === '/api/push/report') {
2840
+ if (path === '/api/push/prefs') {
2841
+ if (req.method === 'GET') {
2842
+ sendJson(res, 200, { prefs: mockPushPrefs });
2843
+ return;
2844
+ }
2845
+ if (req.method === 'POST') {
2846
+ const body = await readJsonBody(req, 4 * 1024);
2847
+ mockPushPrefs = {
2848
+ muted: body?.muted === true,
2849
+ decisionsOnly: body?.decisionsOnly === true,
2850
+ quietStart: Number.isInteger(body?.quietStart) ? body.quietStart : null,
2851
+ quietEnd: Number.isInteger(body?.quietEnd) ? body.quietEnd : null,
2852
+ utcOffsetMinutes: Number.isFinite(body?.utcOffsetMinutes) ? body.utcOffsetMinutes : 0
2853
+ };
2854
+ sendJson(res, 200, { prefs: mockPushPrefs });
2855
+ return;
2856
+ }
2857
+ }
2858
+ if (path === '/api/push/report') {
2441
2859
  /* Service-worker/SPA diagnostics are a bounded no-op in the mock. */
2442
2860
  sendJson(res, 200, { ok: true });
2443
2861
  return;
@@ -2497,6 +2915,12 @@ async function handleRequest(req, res) {
2497
2915
  });
2498
2916
  return;
2499
2917
  }
2918
+ if (UPLOAD_FAIL_FIRST && !uploadFailedOnce) {
2919
+ uploadFailedOnce = true;
2920
+ req.resume();
2921
+ sendJson(res, 500, { ok: false, error: 'upload-failed' });
2922
+ return;
2923
+ }
2500
2924
  const declared = Number(req.headers['content-length'] || 0);
2501
2925
  if (declared > MAX_UPLOAD_BYTES) {
2502
2926
  req.resume();
@@ -2798,3 +3222,4 @@ function shutdown() {
2798
3222
 
2799
3223
  process.on('SIGINT', shutdown);
2800
3224
  process.on('SIGTERM', shutdown);
3225
+