tide-commander 1.174.0 → 1.176.0

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 (135) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/assets/{BossLogsModal-CsjhF9hQ.js → BossLogsModal-qzLlhqPZ.js} +1 -1
  3. package/dist/assets/{BossSpawnModal-DRgrZpYr.js → BossSpawnModal-Bo5btfZs.js} +1 -1
  4. package/dist/assets/{ControlsModal-zYwhMaaL.js → ControlsModal-CCP1SS-b.js} +1 -1
  5. package/dist/assets/{DockerLogsModal-D7bewBqJ.js → DockerLogsModal-d2Isd330.js} +1 -1
  6. package/dist/assets/{EmbeddedEditor-IxYwI5JV.js → EmbeddedEditor-C2whRCAd.js} +1 -1
  7. package/dist/assets/{GmailOAuthSetup-CfOuUZnu.js → GmailOAuthSetup-BM4xBt67.js} +1 -1
  8. package/dist/assets/{GoogleOAuthSetup-Cw1tGSti.js → GoogleOAuthSetup-BMvbdHEK.js} +1 -1
  9. package/dist/assets/{IframeModal-Bi8MNGZY.js → IframeModal-Diz8yWFu.js} +1 -1
  10. package/dist/assets/{IntegrationsPanel-01iVXM-l.js → IntegrationsPanel-W_8l0DxS.js} +2 -2
  11. package/dist/assets/{LogViewerModal-BXhxgz7Z.js → LogViewerModal-DU64WFDr.js} +1 -1
  12. package/dist/assets/{MonitoringModal-Gf0AkCEl.js → MonitoringModal-BoG0Hr7X.js} +1 -1
  13. package/dist/assets/{PM2LogsModal-BfoL_mEK.js → PM2LogsModal-ZemBmh8q.js} +1 -1
  14. package/dist/assets/{RestoreArchivedAreaModal-Ctss__a9.js → RestoreArchivedAreaModal-CEkL1jB3.js} +1 -1
  15. package/dist/assets/{Scene2DCanvas-BuCW0Zaw.js → Scene2DCanvas-BpX0JWYQ.js} +1 -1
  16. package/dist/assets/{SceneManager-BFnKKU1I.js → SceneManager-CdCkKNKF.js} +2 -2
  17. package/dist/assets/{SkillsPanel-D7kJE7eT.js → SkillsPanel-CcJJoxVd.js} +1 -1
  18. package/dist/assets/{SlackMultiInstanceSetup-Hp7r3YK0.js → SlackMultiInstanceSetup-D0QFzYL8.js} +1 -1
  19. package/dist/assets/{SpawnModal-Dq9P-FdI.js → SpawnModal-C8EMz9dV.js} +1 -1
  20. package/dist/assets/{StatisticsModal-BQOkmrmY.js → StatisticsModal-DBWeBd6u.js} +1 -1
  21. package/dist/assets/{SubordinateAssignmentModal-D2-IpRLn.js → SubordinateAssignmentModal-g2VK-d4p.js} +1 -1
  22. package/dist/assets/{TriggerManagerPanel-BCZhLuoZ.js → TriggerManagerPanel-CybQfvUd.js} +1 -1
  23. package/dist/assets/{WorkflowEditorPanel-BEjublaK.js → WorkflowEditorPanel-Doo1fthh.js} +1 -1
  24. package/dist/assets/{abnfDiagram-VRR7QNED-jjWEEISc.js → abnfDiagram-VRR7QNED-DIzWJ00e.js} +1 -1
  25. package/dist/assets/{arc-xqT5-bwQ.js → arc-DYnuDU5M.js} +1 -1
  26. package/dist/assets/{architectureDiagram-ZJ3FMSHR-BXEbOurL.js → architectureDiagram-ZJ3FMSHR-DcQkZge3.js} +1 -1
  27. package/dist/assets/{area-logos-BH-HM2a-.js → area-logos-CvKL6axv.js} +1 -1
  28. package/dist/assets/{blockDiagram-677ZJIJ3-D-0HVLDv.js → blockDiagram-677ZJIJ3-P9qfYIyd.js} +1 -1
  29. package/dist/assets/{c4Diagram-LMCZKHZV-BK39PXfT.js → c4Diagram-LMCZKHZV-Brvvf8IR.js} +1 -1
  30. package/dist/assets/channel-BjM2BONO.js +1 -0
  31. package/dist/assets/{chunk-2Q5K7J3B-CuW4NYbO.js → chunk-2Q5K7J3B-huNYyvxh.js} +1 -1
  32. package/dist/assets/{chunk-32BRIVSS-eJLo7W-b.js → chunk-32BRIVSS-BPwUeNlq.js} +1 -1
  33. package/dist/assets/{chunk-5VM5RSS4-E2Yaai0b.js → chunk-5VM5RSS4-ClvwfT9j.js} +1 -1
  34. package/dist/assets/{chunk-EX3LRPZG-9uAbQnMb.js → chunk-EX3LRPZG-r7lw8w07.js} +1 -1
  35. package/dist/assets/{chunk-JWPE2WC7-kKtXyMkv.js → chunk-JWPE2WC7-Cg-NNKhK.js} +1 -1
  36. package/dist/assets/{chunk-MOJQB5TN-DPN5ReJ7.js → chunk-MOJQB5TN-D1jRsGiz.js} +1 -1
  37. package/dist/assets/{chunk-RYQCIY6F-d3yFo4Hu.js → chunk-RYQCIY6F-DzLe8Mhn.js} +1 -1
  38. package/dist/assets/{chunk-V7JOEXUC--3A8oVa7.js → chunk-V7JOEXUC-CP3S5ECO.js} +1 -1
  39. package/dist/assets/{chunk-VR4S4FIN-KpHuZy9_.js → chunk-VR4S4FIN-CJsUxduu.js} +1 -1
  40. package/dist/assets/{chunk-XXDRQBXY-hpU30gZQ.js → chunk-XXDRQBXY-CG5BEMYm.js} +1 -1
  41. package/dist/assets/classDiagram-OUVF2IWQ-Bo96wh-7.js +1 -0
  42. package/dist/assets/classDiagram-v2-EOCWNBFH-Bo96wh-7.js +1 -0
  43. package/dist/assets/{cose-bilkent-JH36ORCC-DOhYmYxe.js → cose-bilkent-JH36ORCC-ByxdBNNQ.js} +1 -1
  44. package/dist/assets/{cynefin-VYW2F7L2-UDH0NYTi.js → cynefin-VYW2F7L2-DUAFhLA3.js} +1 -1
  45. package/dist/assets/{cynefinDiagram-TSTJHNR4-DnGUiXaD.js → cynefinDiagram-TSTJHNR4-B2Kk-MGz.js} +1 -1
  46. package/dist/assets/{dagre-VKFMJZFB-BQ6C_GWY.js → dagre-VKFMJZFB-DFCRJf_G.js} +1 -1
  47. package/dist/assets/{diagram-FQU43EPY-CREz1035.js → diagram-FQU43EPY-wYMGeAdu.js} +1 -1
  48. package/dist/assets/{diagram-G47NLZAW-9Jr7GbsE.js → diagram-G47NLZAW-rgjw8pQP.js} +1 -1
  49. package/dist/assets/{diagram-NH7WQ7WH-DtN5x74X.js → diagram-NH7WQ7WH-BpZASdpx.js} +1 -1
  50. package/dist/assets/{diagram-OA4YK3LP-UuOi8FAP.js → diagram-OA4YK3LP-CakEHPj1.js} +1 -1
  51. package/dist/assets/{diagram-WEI45ONY-CWiUGHfM.js → diagram-WEI45ONY-BgF2sKn7.js} +1 -1
  52. package/dist/assets/{ebnfDiagram-CCIWWBDH-3eMfQx1G.js → ebnfDiagram-CCIWWBDH-D0Kf9aJj.js} +1 -1
  53. package/dist/assets/{erDiagram-Q63AITRT-DYzSgp8n.js → erDiagram-Q63AITRT-sKvL1I4l.js} +1 -1
  54. package/dist/assets/{flowDiagram-23GEKE2U-DBLDGx8O.js → flowDiagram-23GEKE2U-DgS4-v6l.js} +1 -1
  55. package/dist/assets/{ganttDiagram-NO4QXBWP-Dv7Uyp2U.js → ganttDiagram-NO4QXBWP-DxkYU6kL.js} +1 -1
  56. package/dist/assets/{gitGraphDiagram-IHSO6WYX-leeHrOrC.js → gitGraphDiagram-IHSO6WYX-BP9sXgF1.js} +1 -1
  57. package/dist/assets/{index-lHF2zw41.js → index-B5rQe41U.js} +1 -1
  58. package/dist/assets/index-BLo9z-jE.js +1 -0
  59. package/dist/assets/{index-CFiAyn9P.js → index-CcSdiUnJ.js} +3 -3
  60. package/dist/assets/index-Cf8OqaQe.js +1 -0
  61. package/dist/assets/{index-Bnk8mX62.js → index-Ct8OBbU_.js} +1 -1
  62. package/dist/assets/{index-fP8UTiVP.js → index-D1S-PYLr.js} +2 -2
  63. package/dist/assets/{index-DY2LUL1D.js → index-DCRtV-sQ.js} +1 -1
  64. package/dist/assets/{index-CtGcfchE.js → index-DSC1km47.js} +1 -1
  65. package/dist/assets/{index-Cpf2LUXa.js → index-MzszL_qp.js} +4 -4
  66. package/dist/assets/{infoDiagram-FWYZ7A6U-B23FL64X.js → infoDiagram-FWYZ7A6U-ODz77wW8.js} +1 -1
  67. package/dist/assets/{ishikawaDiagram-FXEZZL3T-BPsjNXWV.js → ishikawaDiagram-FXEZZL3T-B-zkHET8.js} +1 -1
  68. package/dist/assets/{journeyDiagram-5HDEW3XC-3jqJYemY.js → journeyDiagram-5HDEW3XC-3-0ZxNaY.js} +1 -1
  69. package/dist/assets/{kanban-definition-HUTT4EX6-rHfIfWqi.js → kanban-definition-HUTT4EX6-6TXFrj9B.js} +1 -1
  70. package/dist/assets/{linear-CvofFTBe.js → linear-D4INeZan.js} +1 -1
  71. package/dist/assets/main-BNsRZCIt.css +1 -0
  72. package/dist/assets/{main-ts-uUN3p.js → main-awRasOMk.js} +142 -139
  73. package/dist/assets/{mermaid.core-BuuQCwr7.js → mermaid.core-VfI8B8Nu.js} +4 -4
  74. package/dist/assets/{mindmap-definition-LN4V7U3C-CdMbsouS.js → mindmap-definition-LN4V7U3C-BtnLuWah.js} +1 -1
  75. package/dist/assets/{pegDiagram-2B236MQR-Cl7drnf-.js → pegDiagram-2B236MQR-C7u_WQ8m.js} +1 -1
  76. package/dist/assets/{pieDiagram-ENE6RG2P-CrfvJw6b.js → pieDiagram-ENE6RG2P-FP2oK2aq.js} +1 -1
  77. package/dist/assets/{quadrantDiagram-ABIIQ3AL-D6Z7VqX6.js → quadrantDiagram-ABIIQ3AL-C7R49DqX.js} +1 -1
  78. package/dist/assets/{railroadDiagram-RFXS5EU6-DBhqTpwY.js → railroadDiagram-RFXS5EU6-8Y-09cJG.js} +1 -1
  79. package/dist/assets/{requirementDiagram-TGXJPOKE-DjYygiNl.js → requirementDiagram-TGXJPOKE-CuLFvAIT.js} +1 -1
  80. package/dist/assets/{sankeyDiagram-HTMAVEWB-Cb8su5H6.js → sankeyDiagram-HTMAVEWB-C83wAget.js} +1 -1
  81. package/dist/assets/{sequenceDiagram-DBY2YBRQ-DH326uFa.js → sequenceDiagram-DBY2YBRQ-2bX54qCB.js} +1 -1
  82. package/dist/assets/{sizeCapture-X5ZJPWSS-BA-8zei3.js → sizeCapture-X5ZJPWSS-CwcxMidm.js} +1 -1
  83. package/dist/assets/{stateDiagram-2N3HPSRC-DM412fD5.js → stateDiagram-2N3HPSRC-BRLu0Nh3.js} +1 -1
  84. package/dist/assets/stateDiagram-v2-6OUMAXLB-HDFSwLIz.js +1 -0
  85. package/dist/assets/{swimlanes-5IMT3BWC-BouPQ02z.js → swimlanes-5IMT3BWC-0ZHVD_6W.js} +2 -2
  86. package/dist/assets/swimlanesDiagram-G3AALYLV-DIR86oWK.js +8 -0
  87. package/dist/assets/{timeline-definition-FHXFAJF6-CHbeQn6a.js → timeline-definition-FHXFAJF6-mZxmuno3.js} +1 -1
  88. package/dist/assets/{vennDiagram-L72KCM5P-HSzYjTi7.js → vennDiagram-L72KCM5P-529a4wgg.js} +1 -1
  89. package/dist/assets/{wardleyDiagram-EHGQE667-DvrdmzxK.js → wardleyDiagram-EHGQE667-DsYcsK_D.js} +1 -1
  90. package/dist/assets/{web-BvtZvOK9.js → web-CUfujGZR.js} +1 -1
  91. package/dist/assets/{web-DT7q-yw_.js → web-CzSim3jK.js} +1 -1
  92. package/dist/assets/{web-DwD7eqxR.js → web-VJlfgT9G.js} +1 -1
  93. package/dist/assets/{xychartDiagram-FW5EYKEG-DgSgkHvg.js → xychartDiagram-FW5EYKEG-DImLqIu4.js} +1 -1
  94. package/dist/build-info.json +1 -1
  95. package/dist/index.html +2 -2
  96. package/dist/locales/de/terminal.json +2 -1
  97. package/dist/locales/en/terminal.json +3 -1
  98. package/dist/locales/es/terminal.json +3 -1
  99. package/dist/locales/fr/terminal.json +2 -1
  100. package/dist/locales/hi/terminal.json +2 -1
  101. package/dist/locales/it/terminal.json +2 -1
  102. package/dist/locales/ja/terminal.json +2 -1
  103. package/dist/locales/pt/terminal.json +2 -1
  104. package/dist/locales/ru/terminal.json +2 -1
  105. package/dist/locales/zh-CN/terminal.json +2 -1
  106. package/dist/src/packages/server/claude/backend.js +26 -2
  107. package/dist/src/packages/server/claude/interactive/interactive-backend-args.js +1 -1
  108. package/dist/src/packages/server/claude/interactive/interactive-jsonl-translator.js +20 -0
  109. package/dist/src/packages/server/claude/interactive/interactive-jsonl-watcher.js +9 -1
  110. package/dist/src/packages/server/claude/runner/process-lifecycle.js +3 -1
  111. package/dist/src/packages/server/claude/runner/restart-policy.js +65 -2
  112. package/dist/src/packages/server/claude/runner/stdout-pipeline.js +10 -1
  113. package/dist/src/packages/server/claude/runner/watchdog.js +29 -0
  114. package/dist/src/packages/server/claude/session-loader.js +641 -45
  115. package/dist/src/packages/server/claude/types.js +10 -1
  116. package/dist/src/packages/server/codex/app-server/app-server-event-adapter.js +27 -11
  117. package/dist/src/packages/server/grok/session-watcher.js +60 -0
  118. package/dist/src/packages/server/routes/agents.js +26 -0
  119. package/dist/src/packages/server/routes/sessions.js +9 -4
  120. package/dist/src/packages/server/routes/system.js +16 -0
  121. package/dist/src/packages/server/services/agent-service.js +10 -0
  122. package/dist/src/packages/server/services/codex-usage-service.js +141 -2
  123. package/dist/src/packages/server/services/runtime-service.js +22 -0
  124. package/dist/src/packages/server/websocket/listeners/runtime-listeners.js +27 -0
  125. package/dist/src/packages/shared/model-fallback.js +203 -0
  126. package/dist/src/packages/shared/types.js +1 -0
  127. package/package.json +1 -1
  128. package/dist/assets/channel-BgBFpxsT.js +0 -1
  129. package/dist/assets/classDiagram-OUVF2IWQ-CXHgnAgF.js +0 -1
  130. package/dist/assets/classDiagram-v2-EOCWNBFH-CXHgnAgF.js +0 -1
  131. package/dist/assets/index-BrN1fSea.js +0 -1
  132. package/dist/assets/index-jlRDILHc.js +0 -1
  133. package/dist/assets/main-CZA5Uyu6.css +0 -1
  134. package/dist/assets/stateDiagram-v2-6OUMAXLB-BZJwjeVk.js +0 -1
  135. package/dist/assets/swimlanesDiagram-G3AALYLV-BRQaNmpd.js +0 -8
@@ -2,4 +2,13 @@
2
2
  * Claude Backend Types
3
3
  * Modular abstraction for CLI backend communication
4
4
  */
5
- export {};
5
+ /** Shape a tracker transition as the event the runner pipeline renders. */
6
+ export function toModelFallbackEvent(transition) {
7
+ return {
8
+ type: 'model_fallback',
9
+ requestedModel: transition.requestedModel,
10
+ servedModel: transition.servedModel,
11
+ text: transition.label,
12
+ ...(transition.restored ? { fallbackRestored: true } : {}),
13
+ };
14
+ }
@@ -90,8 +90,15 @@ export class CodexAppServerEventAdapter {
90
90
  const ids = item.id ? { uuid: item.id, toolUseId: item.id } : {};
91
91
  return [{ type: 'tool_start', toolName: 'Bash', toolInput: { command, status: item.status }, ...ids }];
92
92
  }
93
- case 'webSearch':
94
- return [{ type: 'tool_start', toolName: 'web_search', toolInput: this.webSearchInput(item) }];
93
+ case 'webSearch': {
94
+ // Same id on start + result (like commandExecution) so the client
95
+ // attaches the completed search onto this card. Without it the result
96
+ // — which carries the ONLY useful data, since itemStarted fires before
97
+ // the query/action are known — had nowhere to land and the row was
98
+ // stuck showing an all-empty input.
99
+ const ids = item.id ? { uuid: item.id, toolUseId: item.id } : {};
100
+ return [{ type: 'tool_start', toolName: 'web_search', toolInput: this.webSearchInput(item), ...ids }];
101
+ }
95
102
  // agentMessage / reasoning: deltas carry the content; fileChange diff lands
96
103
  // on completion. Everything else stays silent on start.
97
104
  default:
@@ -123,8 +130,10 @@ export class CodexAppServerEventAdapter {
123
130
  }
124
131
  case 'fileChange':
125
132
  return this.handleFileChange(item);
126
- case 'webSearch':
127
- return [{ type: 'tool_result', toolName: 'web_search', toolOutput: JSON.stringify(this.webSearchInput(item)) }];
133
+ case 'webSearch': {
134
+ const ids = item.id ? { uuid: item.id, toolUseId: item.id } : {};
135
+ return [{ type: 'tool_result', toolName: 'web_search', toolOutput: JSON.stringify(this.webSearchInput(item)), ...ids }];
136
+ }
128
137
  case 'collabAgentToolCall': {
129
138
  const toolName = item.tool || 'collab_tool';
130
139
  const toolInput = { tool: item.tool, status: item.status };
@@ -165,14 +174,21 @@ export class CodexAppServerEventAdapter {
165
174
  }
166
175
  return events;
167
176
  }
177
+ /** Only the fields Codex actually populated — an all-null payload renders as
178
+ * a row of noise ({"query":"","actionType":null,…}) instead of nothing. */
168
179
  webSearchInput(item) {
169
- return {
170
- query: item.query,
171
- actionType: item.action?.type,
172
- actionQuery: item.action?.query,
173
- actionQueries: item.action?.queries,
174
- actionUrl: item.action?.url,
175
- };
180
+ const out = {};
181
+ if (item.query)
182
+ out.query = item.query;
183
+ if (item.action?.type)
184
+ out.actionType = item.action.type;
185
+ if (item.action?.query)
186
+ out.actionQuery = item.action.query;
187
+ if (item.action?.queries?.length)
188
+ out.actionQueries = item.action.queries;
189
+ if (item.action?.url)
190
+ out.actionUrl = item.action.url;
191
+ return out;
176
192
  }
177
193
  captureTokenUsage(tokenUsage) {
178
194
  if (typeof tokenUsage !== 'object' || tokenUsage === null)
@@ -19,6 +19,13 @@ const DISCOVER_INTERVAL_MS = 250;
19
19
  const TAIL_INTERVAL_MS = 200;
20
20
  /** Accept sessions created up to this long before process start (slow disk / clock skew). */
21
21
  const DISCOVER_GRACE_MS = 5_000;
22
+ /**
23
+ * How long after `turn_ended` to wait for the CLI's own stdout terminator before
24
+ * synthesizing step_complete. Long enough that the normal exit path always wins,
25
+ * far below the idle watchdog's 180s "stuck mid-turn" kill. Read per use so the
26
+ * env override applies without depending on module-load order.
27
+ */
28
+ const forceFinalizeGraceMs = () => Number.parseInt(process.env.TIDE_GROK_FORCE_FINALIZE_MS ?? '', 10) || 15_000;
22
29
  /**
23
30
  * Session dir (absolute) → agentId that attached it. Grok keeps every session
24
31
  * for a cwd under ONE shared root, so newest-first discovery could attach
@@ -195,6 +202,10 @@ export function startGrokSessionWatcher(opts) {
195
202
  let lastSignalsUsageKey = '';
196
203
  /** mtime+size of signals.json at last read — skip the 200ms-tick read+parse when unchanged. */
197
204
  let lastSignalsStatKey = '';
205
+ /** Pending synthetic step_complete for a turn whose CLI outlived its own turn_ended. */
206
+ let forceFinalizeTimer = null;
207
+ /** Guard so at most one synthetic step_complete is emitted per turn. */
208
+ let forcedFinalizeThisTurn = false;
198
209
  const emittedToolStarts = new Set();
199
210
  const emittedToolResults = new Set();
200
211
  /**
@@ -239,6 +250,46 @@ export function startGrokSessionWatcher(opts) {
239
250
  return;
240
251
  opts.onEvent(event);
241
252
  };
253
+ /**
254
+ * Force-finalize fallback for a turn that ended without the CLI exiting.
255
+ *
256
+ * Grok signals the end of a turn twice: `end` on stdout (which the parser
257
+ * turns into step_complete) and `turn_ended` in the session's events.jsonl.
258
+ * Normally the process exits right after, so the stdout path wins and this
259
+ * timer is torn down before it fires. But grok sometimes finishes the turn
260
+ * and then lingers forever — a background task it spawned is still alive, or
261
+ * it simply never exits. Then stdout never carries the terminator, turnState
262
+ * stays 'processing' for good, and the agent shows "working" with its answer
263
+ * already written: new messages queue behind a turn that will never end, the
264
+ * idle watchdog eventually kills the CLI as if it had wedged mid-turn, and
265
+ * the resulting resume of a session killed mid-turn deadlocks permanently.
266
+ *
267
+ * `turn_started`/`turn_ended` are paired 1:1 per turn, so arming on
268
+ * turn_ended and disarming on turn_started emits at most one synthetic
269
+ * step_complete per turn, and only when the CLI outlived its own turn.
270
+ */
271
+ const disarmForceFinalize = () => {
272
+ if (forceFinalizeTimer) {
273
+ clearTimeout(forceFinalizeTimer);
274
+ forceFinalizeTimer = null;
275
+ }
276
+ };
277
+ const armForceFinalize = () => {
278
+ if (stopped || forcedFinalizeThisTurn)
279
+ return;
280
+ disarmForceFinalize();
281
+ const graceMs = forceFinalizeGraceMs();
282
+ forceFinalizeTimer = setTimeout(() => {
283
+ forceFinalizeTimer = null;
284
+ if (stopped || forcedFinalizeThisTurn)
285
+ return;
286
+ forcedFinalizeThisTurn = true;
287
+ log.warn(`[agentId=${opts.agentId}] turn_ended seen but the CLI never emitted stdout 'end' `
288
+ + `within ${graceMs / 1000}s — synthesizing step_complete so the turn closes`);
289
+ emit({ type: 'step_complete', sessionId });
290
+ }, graceMs);
291
+ forceFinalizeTimer.unref?.();
292
+ };
242
293
  const pollSignalsUsage = () => {
243
294
  if (!sessionDirPath)
244
295
  return;
@@ -338,9 +389,17 @@ export function startGrokSessionWatcher(opts) {
338
389
  pollSignalsUsage();
339
390
  return;
340
391
  }
392
+ // A new turn began — any pending force-finalize belongs to the previous
393
+ // turn and is void, and the next turn_ended gets a fresh single shot.
394
+ if (line.type === 'turn_started') {
395
+ disarmForceFinalize();
396
+ forcedFinalizeThisTurn = false;
397
+ return;
398
+ }
341
399
  // End of model turn is a good moment to refresh context stats.
342
400
  if (line.type === 'turn_ended') {
343
401
  pollSignalsUsage();
402
+ armForceFinalize();
344
403
  }
345
404
  };
346
405
  const handleChatLine = (raw) => {
@@ -524,6 +583,7 @@ export function startGrokSessionWatcher(opts) {
524
583
  if (stopped)
525
584
  return;
526
585
  stopped = true;
586
+ disarmForceFinalize();
527
587
  if (discoverTimer)
528
588
  clearInterval(discoverTimer);
529
589
  if (tailTimer)
@@ -1279,6 +1279,32 @@ router.post('/:id/collapse-context', async (req, res) => {
1279
1279
  res.status(500).json({ error: err?.message || 'Failed to collapse context' });
1280
1280
  }
1281
1281
  });
1282
+ // POST /api/agents/:id/simulate-model-fallback - Render a model swap without waiting for one.
1283
+ //
1284
+ // The API decides server-side whether to substitute a model, so no prompt can
1285
+ // force a real fallback on demand. This drives the same code path a real one
1286
+ // takes (terminal row + header chip + activity) so the UI can be verified.
1287
+ // Simulation only — the agent keeps running on whatever model it always was.
1288
+ router.post('/:id/simulate-model-fallback', (req, res) => {
1289
+ try {
1290
+ const agentId = req.params.id;
1291
+ const agent = agentService.getAgent(agentId);
1292
+ if (!agent) {
1293
+ res.status(404).json({ error: `Agent not found: ${agentId}` });
1294
+ return;
1295
+ }
1296
+ const body = (req.body ?? {});
1297
+ const requestedModel = body.requestedModel || agent.model || 'claude-fable-5';
1298
+ const servedModel = body.servedModel || 'claude-opus-4-8';
1299
+ const emitted = runtimeService.simulateModelFallback(agentId, requestedModel, servedModel);
1300
+ log.log(`API simulate-model-fallback for ${agentId}: ${requestedModel} -> ${servedModel} (emitted=${emitted})`);
1301
+ res.json({ success: true, agentId, requestedModel, servedModel, emitted, simulated: true });
1302
+ }
1303
+ catch (err) {
1304
+ log.error(' Failed to simulate model fallback:', err);
1305
+ res.status(500).json({ error: err?.message || 'Failed to simulate model fallback' });
1306
+ }
1307
+ });
1282
1308
  // POST /api/agents/:id/report-task - Subordinate reports task completion to its boss
1283
1309
  router.post('/:id/report-task', async (req, res) => {
1284
1310
  try {
@@ -7,7 +7,7 @@
7
7
  * an optional `cwd` to support cross-project attach.
8
8
  */
9
9
  import { Router } from 'express';
10
- import { listAllSessions, searchAllSessions, loadSession } from '../claude/session-loader.js';
10
+ import { listAllSessions, searchAllSessions, loadSession, loadSessionAroundMatch } from '../claude/session-loader.js';
11
11
  import { createLogger } from '../utils/logger.js';
12
12
  const log = createLogger('Routes');
13
13
  const router = Router();
@@ -63,7 +63,9 @@ router.get('/search', async (req, res) => {
63
63
  res.status(500).json({ error: err.message });
64
64
  }
65
65
  });
66
- // GET /api/sessions/preview?cwd=...&sessionId=...&limit=30
66
+ // GET /api/sessions/preview?cwd=...&sessionId=...&limit=30&q=...
67
+ // With `q`, the returned window is anchored on the most recent matching
68
+ // message instead of the tail, so the preview actually shows the hit.
67
69
  router.get('/preview', async (req, res) => {
68
70
  try {
69
71
  const cwd = req.query.cwd || '';
@@ -72,8 +74,11 @@ router.get('/preview', async (req, res) => {
72
74
  res.status(400).json({ error: 'Both "cwd" and "sessionId" query parameters are required' });
73
75
  return;
74
76
  }
75
- const limit = Math.max(1, Math.min(parseInt(req.query.limit) || 30, 200));
76
- const history = await loadSession(cwd, sessionId, limit, 0);
77
+ const limit = Math.max(1, Math.min(parseInt(req.query.limit) || 30, 500));
78
+ const q = (req.query.q || '').trim();
79
+ const history = q
80
+ ? await loadSessionAroundMatch(cwd, sessionId, limit, q)
81
+ : await loadSession(cwd, sessionId, limit, 0);
77
82
  if (!history) {
78
83
  res.status(404).json({ error: 'Session not found' });
79
84
  return;
@@ -14,6 +14,7 @@ import { getAutoUpdateStatus, setAutoUpdateEnabled } from '../services/auto-upda
14
14
  import { isDevInstall, maybeTriggerWebBundleRebuild } from '../services/web-bundle-builder.js';
15
15
  import { deleteClaudeCredentialProfile, getClaudeCredentialProfilesUsage, listClaudeCredentialProfiles, renameClaudeCredentialProfile, saveActiveClaudeCredentialProfile, switchClaudeCredentialProfile, } from '../services/claude-credentials-service.js';
16
16
  import { deleteProviderCredentialProfile, listProviderCredentialProfiles, renameProviderCredentialProfile, saveActiveProviderCredentialProfile, switchProviderCredentialProfile, } from '../services/provider-credentials-service.js';
17
+ import { getCodexCredentialProfilesUsage } from '../services/codex-usage-service.js';
17
18
  const log = createLogger('SystemRoutes');
18
19
  const router = Router();
19
20
  const PACKAGE_NAME = 'tide-commander';
@@ -672,4 +673,19 @@ function mountProviderCredentialRoutes(provider, basePath) {
672
673
  }
673
674
  mountProviderCredentialRoutes('grok', '/grok-credentials');
674
675
  mountProviderCredentialRoutes('codex', '/codex-credentials');
676
+ /**
677
+ * Daily + weekly rate-limit gauges per stored Codex credential profile — same
678
+ * admin model as /claude-credentials/usage. Dormant profiles are read through
679
+ * a temporary CODEX_HOME so the live ~/.codex/auth.json is never touched.
680
+ */
681
+ router.get('/codex-credentials/usage', async (_req, res) => {
682
+ try {
683
+ res.json(await getCodexCredentialProfilesUsage());
684
+ }
685
+ catch (err) {
686
+ const message = err.message;
687
+ log.error(`Failed to fetch Codex credentials usage: ${message}`);
688
+ res.status(500).json({ error: message });
689
+ }
690
+ });
675
691
  export default router;
@@ -472,6 +472,16 @@ export function updateAgent(id, updates, updateActivity = true) {
472
472
  pendingPropertyUpdates.set(id, pending);
473
473
  }
474
474
  const nextStatus = normalizedUpdates.status ?? agent.status;
475
+ // Server-observed work stamp: moves ONLY on status transitions into/out of
476
+ // an active state — never on selection/metric updates (status unchanged), so
477
+ // it neither breaks the quiet-broadcast filter nor reintroduces the
478
+ // every-click-reshuffles bug. The client dock (dockRoster.settleWorkRecency)
479
+ // trusts it to keep the recent-agents bar in sync across browsers/APK that
480
+ // never observed the work live.
481
+ const isActiveWorkStatus = (status) => status === 'working' || status === 'waiting' || status === 'waiting_permission';
482
+ if (agent.status !== nextStatus && (isActiveWorkStatus(agent.status) || isActiveWorkStatus(nextStatus))) {
483
+ normalizedUpdates.lastWorkedAt = Date.now();
484
+ }
475
485
  const hasExplicitTrackingStatus = Object.prototype.hasOwnProperty.call(normalizedUpdates, 'trackingStatus');
476
486
  const explicitTrackingStatus = normalizedUpdates.trackingStatus;
477
487
  const shouldPreserveExplicitTrackingStatus = explicitTrackingStatus !== undefined
@@ -1,5 +1,11 @@
1
1
  import { spawn } from 'child_process';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
2
5
  import { getCodexBinaryPath } from './system-prompt-service.js';
6
+ import { listProviderCredentialProfiles } from './provider-credentials-service.js';
7
+ import { createLogger } from '../utils/logger.js';
8
+ const log = createLogger('CodexUsage');
3
9
  export function classifyCodexRateLimits(raw) {
4
10
  const result = { daily: null, weekly: null };
5
11
  for (const value of [raw?.primary, raw?.secondary]) {
@@ -21,9 +27,10 @@ export function classifyCodexRateLimits(raw) {
21
27
  }
22
28
  return result;
23
29
  }
24
- function readNativeRateLimits() {
30
+ function readNativeRateLimits(codexHome) {
25
31
  return new Promise((resolve, reject) => {
26
- const child = spawn(getCodexBinaryPath(), ['app-server'], { stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
32
+ const env = codexHome ? { ...process.env, CODEX_HOME: codexHome } : process.env;
33
+ const child = spawn(getCodexBinaryPath(), ['app-server'], { stdio: ['pipe', 'pipe', 'pipe'], env });
27
34
  let stdout = '';
28
35
  let stderr = '';
29
36
  let settled = false;
@@ -91,3 +98,135 @@ export async function buildCodexUsageSnapshot(_agent) {
91
98
  cache = { expiresAt: Date.now() + 60_000, snapshot };
92
99
  return snapshot;
93
100
  }
101
+ const PROFILE_USAGE_TTL_OK_MS = 2 * 60 * 1000;
102
+ const PROFILE_USAGE_TTL_ERR_MS = 45 * 1000;
103
+ const profileUsageCache = new Map();
104
+ const profileUsageInFlight = new Map();
105
+ let nativeReaderOverride = null;
106
+ export function setCodexNativeRateLimitsReaderForTests(reader) {
107
+ nativeReaderOverride = reader;
108
+ }
109
+ export function resetCodexProfileUsageCacheForTests() {
110
+ profileUsageCache.clear();
111
+ profileUsageInFlight.clear();
112
+ }
113
+ function readRateLimits(codexHome) {
114
+ return (nativeReaderOverride ?? readNativeRateLimits)(codexHome);
115
+ }
116
+ /** Atomic write with restrictive permissions (credentials are secrets). */
117
+ function writeAuthAtomic(filePath, content) {
118
+ const dir = path.dirname(filePath);
119
+ const tmp = path.join(dir, `.auth.tmp.${process.pid}.${Date.now()}`);
120
+ fs.writeFileSync(tmp, content, { encoding: 'utf-8', mode: 0o600 });
121
+ fs.renameSync(tmp, filePath);
122
+ try {
123
+ fs.chmodSync(filePath, 0o600);
124
+ }
125
+ catch {
126
+ // best-effort
127
+ }
128
+ }
129
+ function persistRefreshedAuth(group, seededRaw, refreshedRaw) {
130
+ for (const filePath of group.paths) {
131
+ try {
132
+ // Skip copies that changed while the read was in flight — never clobber
133
+ // a newer on-disk grant with our response.
134
+ if (fs.readFileSync(filePath, 'utf-8') !== seededRaw)
135
+ continue;
136
+ writeAuthAtomic(filePath, refreshedRaw);
137
+ }
138
+ catch (err) {
139
+ log.warn(`Refreshed Codex tokens but failed to persist to ${filePath}: ${err}`);
140
+ }
141
+ }
142
+ log.log(`Refreshed dormant Codex credentials for profile(s): ${group.ids.join(', ')}`);
143
+ }
144
+ async function readDormantProfileRateLimits(group) {
145
+ const sourcePath = group.paths[0];
146
+ const seededRaw = fs.readFileSync(sourcePath, 'utf-8');
147
+ const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'tc-codex-usage-'));
148
+ try {
149
+ fs.writeFileSync(path.join(tmpHome, 'auth.json'), seededRaw, { encoding: 'utf-8', mode: 0o600 });
150
+ // Custom config can affect auth flows (enterprise base URLs, auth prefs).
151
+ const configPath = path.join(path.dirname(sourcePath), 'config.toml');
152
+ if (fs.existsSync(configPath))
153
+ fs.copyFileSync(configPath, path.join(tmpHome, 'config.toml'));
154
+ const rateLimits = classifyCodexRateLimits(await readRateLimits(tmpHome));
155
+ try {
156
+ const refreshedRaw = fs.readFileSync(path.join(tmpHome, 'auth.json'), 'utf-8');
157
+ if (refreshedRaw !== seededRaw)
158
+ persistRefreshedAuth(group, seededRaw, refreshedRaw);
159
+ }
160
+ catch {
161
+ // refresh write-back is best-effort; the gauges are still valid
162
+ }
163
+ return rateLimits;
164
+ }
165
+ finally {
166
+ fs.rmSync(tmpHome, { recursive: true, force: true });
167
+ }
168
+ }
169
+ function fetchUsageForCodexGroup(fingerprint, group) {
170
+ const cached = profileUsageCache.get(fingerprint);
171
+ if (cached && Date.now() < cached.validUntil)
172
+ return Promise.resolve(cached);
173
+ const inFlight = profileUsageInFlight.get(fingerprint);
174
+ if (inFlight)
175
+ return inFlight;
176
+ const promise = (async () => {
177
+ let rateLimits = null;
178
+ let error = null;
179
+ try {
180
+ rateLimits = group.includesActive
181
+ ? classifyCodexRateLimits(await readRateLimits())
182
+ : await readDormantProfileRateLimits(group);
183
+ }
184
+ catch (err) {
185
+ error = err instanceof Error ? err.message : String(err);
186
+ }
187
+ const entry = {
188
+ rateLimits,
189
+ error,
190
+ fetchedAt: Date.now(),
191
+ validUntil: Date.now() + (error ? PROFILE_USAGE_TTL_ERR_MS : PROFILE_USAGE_TTL_OK_MS),
192
+ };
193
+ profileUsageCache.set(fingerprint, entry);
194
+ return entry;
195
+ })().finally(() => profileUsageInFlight.delete(fingerprint));
196
+ profileUsageInFlight.set(fingerprint, promise);
197
+ return promise;
198
+ }
199
+ /**
200
+ * Daily + weekly rate-limit gauges for every stored Codex credential profile,
201
+ * keyed by profile id ("active" or name). One native read per distinct
202
+ * account (profiles sharing a fingerprint share the fetch), cached briefly.
203
+ */
204
+ export async function getCodexCredentialProfilesUsage() {
205
+ const list = listProviderCredentialProfiles('codex');
206
+ const candidates = [...(list.active ? [list.active] : []), ...list.profiles];
207
+ const groups = new Map();
208
+ const usage = [];
209
+ for (const meta of candidates) {
210
+ if (!meta.valid || !meta.fingerprint) {
211
+ usage.push({ id: meta.id, rateLimits: null, error: 'Invalid credentials file', fetchedAt: Date.now() });
212
+ continue;
213
+ }
214
+ const existing = groups.get(meta.fingerprint);
215
+ if (existing) {
216
+ existing.ids.push(meta.id);
217
+ if (!existing.paths.includes(meta.path))
218
+ existing.paths.push(meta.path);
219
+ existing.includesActive = existing.includesActive || meta.id === 'active';
220
+ }
221
+ else {
222
+ groups.set(meta.fingerprint, { ids: [meta.id], paths: [meta.path], includesActive: meta.id === 'active' });
223
+ }
224
+ }
225
+ await Promise.all(Array.from(groups.entries()).map(async ([fingerprint, group]) => {
226
+ const entry = await fetchUsageForCodexGroup(fingerprint, group);
227
+ for (const id of group.ids) {
228
+ usage.push({ id, rateLimits: entry.rateLimits, error: entry.error, fetchedAt: entry.fetchedAt });
229
+ }
230
+ }));
231
+ return { usage };
232
+ }
@@ -4,6 +4,8 @@
4
4
  */
5
5
  import { isClaudeProcessRunningInCwd, isCodexProcessRunningInCwd, isOpencodeProcessRunningInCwd, isGrokProcessRunningInCwd, killClaudeProcessInCwd, killCodexProcessInCwd, killOpencodeProcessInCwd, killGrokProcessInCwd, findClaudeProcessPidInCwd, findCodexProcessPidInCwd, findOpencodeProcessPidInCwd, findGrokProcessPidInCwd, } from '../claude/session-loader.js';
6
6
  import * as agentService from './agent-service.js';
7
+ import { ModelFallbackTracker } from '../../shared/model-fallback.js';
8
+ import { toModelFallbackEvent } from '../claude/types.js';
7
9
  import { loadRunningProcesses, isProcessRunning } from '../data/index.js';
8
10
  import { logger } from '../utils/logger.js';
9
11
  import { createClaudeRuntimeProvider, createCodexRuntimeProvider, createOpencodeRuntimeProvider, createGrokRuntimeProvider, } from '../runtime/index.js';
@@ -127,6 +129,26 @@ const statusSync = createRuntimeStatusSync({
127
129
  // Combined interval for status sync + orphan polling (20 seconds)
128
130
  const STATUS_POLL_INTERVAL = 20000;
129
131
  let statusPollTimer = null;
132
+ /**
133
+ * Push a synthetic model-fallback through the exact path a real one takes
134
+ * (terminal row + agent badge + activity line), for verifying the UI.
135
+ *
136
+ * There is no prompt that can trigger a real fallback on demand — the API
137
+ * decides server-side — so this is the only way to see the rendering without
138
+ * waiting for one to happen. Simulation only: it changes nothing about which
139
+ * model actually answers.
140
+ */
141
+ export function simulateModelFallback(agentId, requestedModel, servedModel) {
142
+ // Seeded from the agent record exactly like the real backend, so passing the
143
+ // requested model back as the served one produces the "restored" edge and
144
+ // clears the badge — the same call clears what it set.
145
+ const tracker = new ModelFallbackTracker(requestedModel, agentService.getAgent(agentId)?.modelFallback?.servedModel ?? null);
146
+ const transition = tracker.observe(servedModel);
147
+ if (!transition)
148
+ return false;
149
+ runtimeEvents.handleEvent(agentId, toModelFallbackEvent(transition));
150
+ return true;
151
+ }
130
152
  export function init() {
131
153
  const claudeCallbacks = {
132
154
  onEvent: runtimeEvents.handleEvent,
@@ -1,6 +1,7 @@
1
1
  import { execFileSync } from 'child_process';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
+ import { detectModelFallback, formatModelName } from '../../../shared/model-fallback.js';
4
5
  import { parseContextOutput } from '../../claude/backend.js';
5
6
  import { parseAllFormats } from '../handlers/agent-handler.js';
6
7
  import { agentService, runtimeService } from '../../services/index.js';
@@ -125,6 +126,32 @@ export function setupRuntimeListeners(ctx) {
125
126
  bossAccumulatedText.set(agentId, prev + event.text);
126
127
  }
127
128
  }
129
+ // The API served a different model than the agent is configured with (or
130
+ // stopped doing so). Park it on the agent record: the terminal already got
131
+ // a chat row from the runner, this is what keeps the header chip honest
132
+ // after a page reload.
133
+ if (event.type === 'model_fallback') {
134
+ if (event.fallbackRestored) {
135
+ agentService.updateAgent(agentId, { modelFallback: undefined }, false);
136
+ ctx.sendActivity(agentId, `Back on ${formatModelName(event.requestedModel)}`);
137
+ }
138
+ else if (event.requestedModel && event.servedModel) {
139
+ const detection = detectModelFallback(event.requestedModel, event.servedModel);
140
+ if (detection) {
141
+ agentService.updateAgent(agentId, {
142
+ modelFallback: {
143
+ requestedModel: detection.from,
144
+ servedModel: detection.to,
145
+ requestedLabel: detection.fromLabel,
146
+ servedLabel: detection.toLabel,
147
+ tierChanged: detection.tierChanged,
148
+ detectedAt: Date.now(),
149
+ },
150
+ }, false);
151
+ ctx.sendActivity(agentId, `Served by ${detection.toLabel} (asked for ${detection.fromLabel})`);
152
+ }
153
+ }
154
+ }
128
155
  if (event.type === 'compacting') {
129
156
  compactingAgents.add(agentId);
130
157
  ctx.broadcast({