arco-workbench 0.1.5 → 0.1.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 (188) hide show
  1. package/CONTRIBUTING.md +9 -0
  2. package/README.md +17 -5
  3. package/client/dist/assets/{PhosphorBackdrop-D6cbmLNY.js → PhosphorBackdrop-DVQdBrTw.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-2dyerOi4.js → ThemedBackgroundShaderImpl-BfSs2tB4.js} +1 -1
  5. package/client/dist/assets/{XtermView-AIwo7O3D.js → XtermView-DaMjC8Ny.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-DXAuxS8D.js → galleryEditor-BCQnXj7R.js} +1 -1
  7. package/client/dist/assets/{index-8j6p-pmQ.js → index-COfbHCYv.js} +245 -243
  8. package/client/dist/index.html +1 -1
  9. package/client/src/alerts/desktopAlerts.ts +13 -0
  10. package/client/src/buildCheck.ts +3 -1
  11. package/client/src/components/AppUpdateNotice.tsx +2 -1
  12. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +46 -11
  13. package/client/src/components/ClusterRightPanel/MemberRow.tsx +1 -1
  14. package/client/src/components/ClusterRightPanel/index.tsx +2 -1
  15. package/client/src/components/ClusterTaskBoardTab.tsx +54 -3
  16. package/client/src/components/ContextMeter.tsx +7 -0
  17. package/client/src/components/HeaderVersionBox.tsx +7 -4
  18. package/client/src/components/Home/HomeView.tsx +1 -1
  19. package/client/src/components/NeedsYouBadge.tsx +31 -16
  20. package/client/src/components/OperatorQuestionNotice.tsx +10 -1
  21. package/client/src/components/ProvidersPopover.tsx +23 -12
  22. package/client/src/components/TabBar.tsx +11 -8
  23. package/client/src/components/TabStatusChip.tsx +8 -7
  24. package/client/src/components/UpdateAction.tsx +18 -4
  25. package/client/src/components/UpdateResultNotice.tsx +3 -1
  26. package/client/src/components/clusterNeedsYou.ts +27 -8
  27. package/client/src/help/content/cluster.tsx +50 -27
  28. package/client/src/help/content/composer.tsx +8 -1
  29. package/client/src/help/content/header.tsx +25 -14
  30. package/client/src/help/content/misc.tsx +8 -0
  31. package/client/src/help/content/rightPanel.tsx +1 -1
  32. package/client/src/help/content/settings.tsx +1 -1
  33. package/client/src/help/content/tabbar.tsx +2 -1
  34. package/client/src/help/manualSections/clusters.tsx +78 -19
  35. package/client/src/help/manualSections/configuration.tsx +20 -4
  36. package/client/src/help/manualSections/gettingStarted.tsx +10 -0
  37. package/client/src/help/manualSections/maintenance.tsx +50 -8
  38. package/client/src/help/manualSections/plans.tsx +5 -1
  39. package/client/src/help/manualSections/providers.tsx +10 -3
  40. package/client/src/help/manualSections/reference.tsx +1 -1
  41. package/client/src/help/manualSections/workflows.tsx +20 -0
  42. package/client/src/help/manualSections/workspace.tsx +7 -1
  43. package/client/src/questions/waitingQuestion.ts +3 -2
  44. package/client/src/stores/appStore.ts +1 -1
  45. package/client/src/stores/appStore.types.ts +1 -0
  46. package/client/src/stores/appUpdateStore.ts +29 -8
  47. package/client/src/stores/notificationStore.ts +2 -0
  48. package/client/src/utils/activityPresentation.ts +1 -1
  49. package/client/src/utils/tabStatus.ts +8 -0
  50. package/client/src/utils/wsSession.ts +2 -1
  51. package/client/src/voice/commands.ts +4 -3
  52. package/client/src/voice/executor.ts +3 -3
  53. package/client/src/ws/handleServerMessage.ts +22 -2
  54. package/client/src/ws/operatorQuestions.ts +2 -0
  55. package/docs/CLIENT.md +3 -3
  56. package/docs/FEATURES.md +1 -1
  57. package/docs/GETTING_STARTED.md +16 -6
  58. package/docs/GLOSSARY.md +6 -2
  59. package/docs/GOTCHAS.md +17 -5
  60. package/docs/OPERATIONS.md +207 -5
  61. package/docs/PERSISTENCE.md +22 -1
  62. package/docs/PRIMITIVES.md +1 -1
  63. package/docs/PROTOCOL.md +1 -1
  64. package/docs/PROTOCOL_CLUSTER.md +18 -7
  65. package/docs/PROVIDERS.md +10 -5
  66. package/docs/SETTINGS.md +4 -2
  67. package/docs/TASK_LEDGER.md +6 -0
  68. package/docs/VOICE.md +2 -0
  69. package/native/darwin-arm64/manifest.json +1 -1
  70. package/native/win32-arm64/manifest.json +1 -1
  71. package/node_modules/@arco/shared/dist/clusterRolePresets.d.ts +1 -1
  72. package/node_modules/@arco/shared/dist/clusterRolePresets.js +10 -0
  73. package/node_modules/@arco/shared/dist/protocol/autoPickup.d.ts +3 -0
  74. package/node_modules/@arco/shared/dist/protocol/autoPickup.js +9 -1
  75. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +2 -2
  76. package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -0
  77. package/node_modules/@arco/shared/dist/protocol/notifications.d.ts +4 -0
  78. package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +12 -0
  79. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +9 -3
  80. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  81. package/node_modules/@arco/shared/package.json +1 -1
  82. package/package.json +2 -2
  83. package/scripts/packaging/arco.mjs +1 -0
  84. package/scripts/packaging/native-repair.mjs +46 -8
  85. package/scripts/packaging/update.mjs +5 -1
  86. package/server/dist/attention.d.ts +1 -1
  87. package/server/dist/attention.js +6 -4
  88. package/server/dist/capabilities.d.ts +9 -8
  89. package/server/dist/capabilities.js +71 -102
  90. package/server/dist/cliUpdateDecision.d.ts +34 -0
  91. package/server/dist/cliUpdateDecision.js +152 -0
  92. package/server/dist/clusterAutoTurn.d.ts +4 -0
  93. package/server/dist/clusterAutoTurn.js +29 -25
  94. package/server/dist/clusterBusyReminder.js +1 -1
  95. package/server/dist/clusterDirector.js +1 -0
  96. package/server/dist/clusterPeerOps.js +2 -2
  97. package/server/dist/clusterStore.d.ts +3 -0
  98. package/server/dist/clusterStore.js +22 -0
  99. package/server/dist/defaults/models.md +1 -1
  100. package/server/dist/fileAccessPolicy.js +7 -5
  101. package/server/dist/http/workflowDataRoutes.js +1 -1
  102. package/server/dist/index.js +5 -1
  103. package/server/dist/primitives/seedWorker.d.ts +1 -0
  104. package/server/dist/primitives/seedWorker.js +2 -1
  105. package/server/dist/providerConversation.d.ts +9 -0
  106. package/server/dist/providerConversation.js +80 -0
  107. package/server/dist/providers/claude-native/retainedContext.d.ts +4 -0
  108. package/server/dist/providers/claude-native/retainedContext.js +20 -0
  109. package/server/dist/providers/claude-native/worker.d.ts +1 -0
  110. package/server/dist/providers/claude-native/worker.js +34 -6
  111. package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -0
  112. package/server/dist/providers/codex-appserver/operatorQuestions.js +30 -0
  113. package/server/dist/providers/codex-appserver/worker.js +9 -4
  114. package/server/dist/providers/ollama.js +2 -3
  115. package/server/dist/server/broadcast.d.ts +1 -1
  116. package/server/dist/smartPickup.d.ts +2 -1
  117. package/server/dist/smartPickup.js +28 -1
  118. package/server/dist/smartPickupAdapters.d.ts +1 -0
  119. package/server/dist/smartPickupAdapters.js +18 -5
  120. package/server/dist/smartPickupLedger.js +6 -4
  121. package/server/dist/smartPickupObserver.d.ts +1 -0
  122. package/server/dist/smartPickupObserver.js +69 -23
  123. package/server/dist/workers/WorkerManager.d.ts +1 -0
  124. package/server/dist/workers/WorkerManager.js +1 -0
  125. package/server/dist/workers/limits.js +6 -2
  126. package/server/dist/workflowMeta.d.ts +11 -1
  127. package/server/dist/workflowMeta.js +132 -6
  128. package/server/dist/workflows/types.d.ts +1 -0
  129. package/server/dist/ws/clusterHandlers.d.ts +1 -0
  130. package/server/dist/ws/clusterHandlers.js +2 -1
  131. package/server/dist/ws/compactHandlers.d.ts +1 -1
  132. package/server/dist/ws/compactHandlers.js +11 -4
  133. package/server/dist/ws/handoffHandlers.js +16 -6
  134. package/server/dist/ws/operatorQuestionHandlers.d.ts +2 -1
  135. package/server/dist/ws/operatorQuestionHandlers.js +9 -1
  136. package/server/dist/ws/turnEngine.d.ts +2 -4
  137. package/server/dist/ws/turnEngine.js +88 -129
  138. package/server/package.json +1 -1
  139. package/server/src/attention.ts +5 -4
  140. package/server/src/capabilities.ts +70 -111
  141. package/server/src/cliUpdateDecision.ts +159 -0
  142. package/server/src/clusterAutoTurn.ts +26 -21
  143. package/server/src/clusterBusyReminder.ts +1 -1
  144. package/server/src/clusterDirector.ts +1 -0
  145. package/server/src/clusterPeerOps.ts +2 -2
  146. package/server/src/clusterStore.ts +26 -1
  147. package/server/src/defaults/models.md +1 -1
  148. package/server/src/fileAccessPolicy.ts +7 -5
  149. package/server/src/http/workflowDataRoutes.ts +1 -1
  150. package/server/src/index.ts +5 -1
  151. package/server/src/primitives/seedWorker.ts +3 -1
  152. package/server/src/providerConversation.ts +71 -0
  153. package/server/src/providers/claude-native/retainedContext.ts +22 -0
  154. package/server/src/providers/claude-native/worker.ts +33 -5
  155. package/server/src/providers/codex-appserver/operatorQuestions.ts +24 -0
  156. package/server/src/providers/codex-appserver/worker.ts +8 -4
  157. package/server/src/providers/ollama.ts +2 -3
  158. package/server/src/smartPickup.ts +27 -3
  159. package/server/src/smartPickupAdapters.ts +19 -5
  160. package/server/src/smartPickupLedger.ts +6 -4
  161. package/server/src/smartPickupObserver.ts +51 -17
  162. package/server/src/workers/WorkerManager.ts +2 -0
  163. package/server/src/workers/limits.ts +7 -2
  164. package/server/src/workflowMeta.ts +139 -5
  165. package/server/src/workflows/types.ts +1 -0
  166. package/server/src/ws/clusterHandlers.ts +3 -2
  167. package/server/src/ws/compactHandlers.ts +9 -3
  168. package/server/src/ws/handoffHandlers.ts +13 -6
  169. package/server/src/ws/operatorQuestionHandlers.ts +10 -2
  170. package/server/src/ws/turnEngine.ts +80 -135
  171. package/shared/dist/clusterRolePresets.d.ts +1 -1
  172. package/shared/dist/clusterRolePresets.js +10 -0
  173. package/shared/dist/protocol/autoPickup.d.ts +3 -0
  174. package/shared/dist/protocol/autoPickup.js +9 -1
  175. package/shared/dist/protocol/clientMessages.d.ts +2 -2
  176. package/shared/dist/protocol/models.d.ts +6 -0
  177. package/shared/dist/protocol/notifications.d.ts +4 -0
  178. package/shared/dist/protocol/operatorQuestions.d.ts +12 -0
  179. package/shared/dist/protocol/serverMessages.d.ts +9 -3
  180. package/shared/dist/protocol/workflows.d.ts +1 -0
  181. package/shared/src/clusterRolePresets.ts +11 -1
  182. package/shared/src/protocol/autoPickup.ts +14 -1
  183. package/shared/src/protocol/clientMessages.ts +2 -1
  184. package/shared/src/protocol/models.ts +5 -2
  185. package/shared/src/protocol/notifications.ts +5 -0
  186. package/shared/src/protocol/operatorQuestions.ts +13 -0
  187. package/shared/src/protocol/serverMessages.ts +12 -2
  188. package/shared/src/protocol/workflows.ts +4 -0
@@ -11,6 +11,7 @@
11
11
  // the session or mode changed while it was running.
12
12
  import {
13
13
  isSmartPickupMode,
14
+ isAutoPickupAcknowledgement,
14
15
  presetForText,
15
16
  sanitizeSmartPickupLimits,
16
17
  type SmartPickupAction,
@@ -129,7 +130,7 @@ function armed(clusterId: string): { sessionId: string; mode: 'smart-observe' |
129
130
  if (!state) return null;
130
131
  const mode = clusterStore.autoPickupModeOf(state);
131
132
  const session = state.smartPickup?.session;
132
- if (!isSmartPickupMode(mode) || !session || !state.smartPickup?.evaluator) return null;
133
+ if (state.autoPickupPausedAt !== undefined || !isSmartPickupMode(mode) || !session || !state.smartPickup?.evaluator) return null;
133
134
  if (deps.now() >= session.expiresAt) return null;
134
135
  return { sessionId: session.id, mode };
135
136
  }
@@ -138,9 +139,9 @@ function armed(clusterId: string): { sessionId: string; mode: 'smart-observe' |
138
139
  // evaluation per recipient at a time; a trigger during a run schedules one
139
140
  // more pass afterwards.
140
141
  export function onSmartPickupMail(clusterId: string, workflowId: string, chainDepth = 0): Promise<void> {
141
- if (!armed(clusterId)) return Promise.resolve();
142
142
  const k = key(clusterId, workflowId);
143
143
  if (chainDepth > (depthSeen.get(k) ?? 0)) depthSeen.set(k, chainDepth);
144
+ if (!armed(clusterId)) return Promise.resolve();
144
145
  const current = running.get(k);
145
146
  if (current) { rerun.add(k); return current; }
146
147
  const run = (async () => {
@@ -181,7 +182,10 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
181
182
  if (prior && prior.sessionId === arm.sessionId && prior.fingerprint === snapshot.fingerprint) {
182
183
  // An admitted-in-principle wake that was blocked by a passing condition
183
184
  // (busy, cooldown) is retried without asking the evaluator again.
184
- if (prior.wakeOwed && arm.mode === 'smart-auto') return gateAndRecord({ ...base, action: 'wake', reason: 'retry', outcome: 'pending' }, arm);
185
+ if (prior.wakeOwed && arm.mode === 'smart-auto') {
186
+ const fallback = prior.action === null;
187
+ return gateAndRecord({ ...base, action: fallback ? null : 'wake', reason: fallback ? prior.reason! : 'retry', outcome: 'pending' }, arm);
188
+ }
185
189
  // A defer lapses after deferMs so unchanged mail is looked at again; an
186
190
  // evaluation refused by a passing limit is attempted again.
187
191
  const deferLapsed = prior.action === 'defer' && prior.deferUntil !== undefined && deps.now() >= prior.deferUntil;
@@ -201,6 +205,7 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
201
205
  return d;
202
206
  }
203
207
  const evaluator = state.smartPickup!.evaluator!;
208
+ if (armed(clusterId)?.sessionId !== arm.sessionId) return null;
204
209
  const slot = await reserveSmartPickup(clusterId, { kind: 'evaluator', memberId: workflowId, sessionId: arm.sessionId, limits, now: deps.now() }).catch(() => ({ ok: false as const, reason: 'ledger_unreadable' }));
205
210
  if (!slot.ok) {
206
211
  const d = { ...base, action: null, reason: slot.reason, outcome: 'skipped' };
@@ -215,6 +220,10 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
215
220
  }
216
221
  let raw: string | null = null;
217
222
  let failure: string | null = null;
223
+ if (armed(clusterId)?.sessionId !== arm.sessionId) {
224
+ await settleSmartPickup(clusterId, slot.id, 'session_changed', deps.now()).catch(() => undefined);
225
+ return null;
226
+ }
218
227
  try {
219
228
  raw = await evaluatorAdapter(evaluator.provider).evaluate({
220
229
  model: evaluator.model,
@@ -236,21 +245,30 @@ export async function evaluateOnce(clusterId: string, workflowId: string): Promi
236
245
  }
237
246
  if (failure !== null) {
238
247
  const d = { ...base, action: null, reason: `evaluator_error:${failure}`.slice(0, 64), outcome: 'none' };
239
- // A failure before the evaluator session was ready (a cold agent start)
240
- // says nothing about this mail: evaluate the same mail once more, with a
241
- // new reservation counted against the limits. Any other failure, or a
242
- // second start-up failure, stands until the mail changes.
248
+ // Preserve the established one retry for a failure before the evaluator
249
+ // session was ready: the model has not seen this mail yet. The retry
250
+ // spends its own reservation. A second startup failure or any other
251
+ // failure then takes the guarded fallback path without another request.
243
252
  const sameMail = prior?.fingerprint === snapshot.fingerprint && prior.sessionId === arm.sessionId;
244
253
  if (isStartupFailure(failure) && !(sameMail && prior?.startupRetried)) {
245
254
  await record(d, { retryEvaluation: true, startupRetried: true });
246
255
  return d;
247
256
  }
257
+ if (failure === 'cancelled') {
258
+ d.outcome = 'discarded';
259
+ await record(d);
260
+ return d;
261
+ }
262
+ if (still.mode === 'smart-auto') return gateAndRecord(d, still);
263
+ d.outcome = 'fallback_observed';
248
264
  await record(d);
249
265
  return d;
250
266
  }
251
267
  const parsed = parseEvaluatorAnswer(raw);
252
268
  if (!parsed.ok) {
253
269
  const d = { ...base, action: null, reason: `invalid_answer:${parsed.problem}`, outcome: 'none' };
270
+ if (still.mode === 'smart-auto') return gateAndRecord(d, still);
271
+ d.outcome = 'fallback_observed';
254
272
  await record(d);
255
273
  return d;
256
274
  }
@@ -268,7 +286,10 @@ const TRANSIENT = new Set(['busy', 'cooldown', 'rate_capped', 'limit_wakes_membe
268
286
 
269
287
  async function gateAndRecord(proposal: ObservedDecision, arm: { sessionId: string; mode: 'smart-observe' | 'smart-auto' }): Promise<ObservedDecision> {
270
288
  const result = await gateWake(proposal, arm);
271
- const d = { ...proposal, outcome: result.outcome, ...(result.reason ? { reason: proposal.reason === 'retry' ? result.reason : `${proposal.reason}:${result.reason}` } : {}) };
289
+ const fallback = proposal.action === null;
290
+ const d = fallback
291
+ ? { ...proposal, outcome: `fallback_${result.outcome}${result.reason ? `:${result.reason}` : ''}` }
292
+ : { ...proposal, outcome: result.outcome, ...(result.reason ? { reason: proposal.reason === 'retry' ? result.reason : `${proposal.reason}:${result.reason}` } : {}) };
272
293
  const owed = result.outcome !== 'woke' && result.reason !== undefined && TRANSIENT.has(result.reason);
273
294
  await record(d, owed ? { wakeOwed: true } : {});
274
295
  return d;
@@ -302,6 +323,15 @@ async function gateWake(p: ObservedDecision, arm: { sessionId: string }): Promis
302
323
  let ids: string[];
303
324
  try { ids = await clusterMailbox.pendingIdsStrict(clusterId, wfid); } catch { refusal = 'unverifiable'; return false; }
304
325
  if (mailFingerprint(ids) !== p.fingerprint) { refusal = 'mail_changed'; return false; }
326
+ if (p.action === null) {
327
+ // Ordinary pickup ignores bare acknowledgements. Re-read the same
328
+ // exact mailbox under its lock; unreadable or empty mail cannot
329
+ // authorise fallback, and attachments retain their normal exception.
330
+ let pending: Awaited<ReturnType<typeof clusterMailbox.peek>>;
331
+ try { pending = await clusterMailbox.peek(wfid); } catch { refusal = 'unverifiable'; return false; }
332
+ if (ids.length === 0 || pending.length !== ids.length || pending.some((m) => !ids.includes(m.msgId))) { refusal = 'unverifiable'; return false; }
333
+ if (pending.every((m) => !m.artifacts?.length && isAutoPickupAcknowledgement(m.content))) { refusal = 'ack_only'; return false; }
334
+ }
305
335
  if (await smartPickupHoldActive(clusterId, wfid, ids, deps.now()).catch(() => true)) { refusal = 'stop_hold'; return false; }
306
336
  if (sharedGuardProblem(clusterId, wfid, depth, deps.now())) { refusal = 'rate_capped'; return false; }
307
337
  if (!claim()) { refusal = 'busy'; return false; }
@@ -336,21 +366,25 @@ export async function sweepSmartPickupMail(): Promise<void> {
336
366
  sweeping = true;
337
367
  try {
338
368
  for (const clusterId of clusterStore.listKnownClusterIds().sort()) {
339
- if (!armed(clusterId)) continue;
340
- const members = [...(clusterStore.getClusterCached(clusterId)?.members ?? [])].sort();
341
- // One member at a time per cluster, in a stable order, so the
342
- // in-flight limit is respected and no mailbox starves another.
343
- for (const wfid of members) {
344
- if (deps.isBusy(wfid)) continue;
345
- const depth = await clusterMailbox.depthFor(wfid).catch(() => 0);
346
- if (depth > 0) await onSmartPickupMail(clusterId, wfid).catch(() => undefined);
347
- }
369
+ await pickupSmartWaitingMail(clusterId);
348
370
  }
349
371
  } finally {
350
372
  sweeping = false;
351
373
  }
352
374
  }
353
375
 
376
+ export async function pickupSmartWaitingMail(clusterId: string): Promise<void> {
377
+ if (!armed(clusterId)) return;
378
+ const members = [...(clusterStore.getClusterCached(clusterId)?.members ?? [])].sort();
379
+ // One member at a time per cluster, in a stable order, so the
380
+ // in-flight limit is respected and no mailbox starves another.
381
+ for (const wfid of members) {
382
+ if (deps.isBusy(wfid)) continue;
383
+ const depth = await clusterMailbox.depthFor(wfid).catch(() => 0);
384
+ if (depth > 0) await onSmartPickupMail(clusterId, wfid).catch(() => undefined);
385
+ }
386
+ }
387
+
354
388
  let mailTimer: NodeJS.Timeout | null = null;
355
389
  const MAIL_SWEEP_MS = (() => {
356
390
  const raw = Number(process.env.ARCO_SMART_PICKUP_MAIL_SWEEP_MS);
@@ -150,6 +150,7 @@ export class WorkerManager {
150
150
  // and the next API round-trip to drain any pending mid-turn steer
151
151
  // queue entries. See WorkerConfig.drainSteer.
152
152
  drainSteer?: WorkerConfig['drainSteer'];
153
+ peekSteer?: WorkerConfig['peekSteer'];
153
154
  // Phase 6b — paired with drainSteer for the Codex app-server worker.
154
155
  // Called when `turn/steer` round-trip fails and the drained items
155
156
  // need to land back in a queue. Bucket determines whether items
@@ -289,6 +290,7 @@ export class WorkerManager {
289
290
  voiceOperator: options?.voiceOperator,
290
291
  incognito: options?.incognito,
291
292
  drainSteer: options?.drainSteer,
293
+ peekSteer: options?.peekSteer,
292
294
  requeueSteer: options?.requeueSteer,
293
295
  onSteerDelivered: options?.onSteerDelivered,
294
296
  // Phase 6 — workflowId is required for per-workflow-lifetime providers
@@ -23,7 +23,7 @@ function formatCapMb(bytes: number): string {
23
23
  export const OUTPUT_TRUNCATION_NOTICE =
24
24
  `\n\n[OUTPUT TRUNCATED — Arco enforced ${formatCapMb(MAX_WORKER_OUTPUT_BYTES)} worker-output cap. ` +
25
25
  'For reports larger than this, instruct the worker to write the full ' +
26
- 'output to a markdown file in the workflow artifacts directory and return only a brief summary + path.]';
26
+ 'output to a markdown file in the workflow artifacts directory and return only a brief summary + path, unless the operator wants it kept in the project.]';
27
27
 
28
28
  function parseRssEnv(): number {
29
29
  const raw = process.env.ARCO_RSS_KILL_BYTES;
@@ -68,6 +68,11 @@ export function buildWorkerSafetyFooter(cwd?: string, wfid?: string): string {
68
68
  ? `- For report-shaped outputs (deep dives, inventories, audits, multi-section findings), write a markdown file into \`${dir}/\` (this directory already exists) and return a brief summary that names the file in backticks (for example \`audit-spawns.md\`) so it is clickable in chat. Do NOT write report files at the project root — Arco tracks artifacts per-workflow and surfaces them inline in chat. For ordinary prose responses — even detailed ones — return the full text inline; the operator reads it in chat.`
69
69
  : `- For report-shaped outputs (deep dives, inventories, audits, multi-section findings), write a markdown file in the cwd and return a brief summary + absolute path. For ordinary prose responses — even detailed ones — return the full text inline; the operator reads it in chat.`;
70
70
 
71
+ const projectStateLine = `Never commit, force-add or add an ignore exception for \`.arco/\`, which is local state, except a skill shared through SHARE WITH REPOSITORY.`;
72
+ const projectFilesLine = dir
73
+ ? `\n- Put files the operator wants kept in the project (documentation, a README or notes to commit) in the project tree, for example \`docs/\`, not in artifacts. ${projectStateLine}`
74
+ : `\n- ${projectStateLine}`;
75
+
71
76
  const scratchLine = dir
72
77
  ? `\n- Put large intermediate files (builds, disk images, downloads, datasets) in \`${path.join(path.dirname(dir), 'scratch')}/\` (create it if missing), not in artifacts. Keep only finished deliverables in artifacts. The operator empties scratch with EMPTY SCRATCH; nothing there is deleted automatically.`
73
78
  : '';
@@ -79,7 +84,7 @@ export function buildWorkerSafetyFooter(cwd?: string, wfid?: string): string {
79
84
  - No \`find /\` / \`du -sh /\` without \`-maxdepth\` and exclusions for \`/proc /sys /dev /run\`. Skip \`~/.cache\`, \`node_modules\`, \`.git/objects\`, \`/var/cache\`, \`/snap\`.
80
85
  - No reads of \`/proc/kcore\`, \`/proc/*/mem\`, \`/dev/{kmem,mem,zero,urandom}\` past first KB. No unbounded \`journalctl\` or \`while true\` loops.
81
86
  - No \`cat\` of files >10MB; use \`head -c 100K\` instead. \`xargs\` always with explicit limits.
82
- ${bigOutputLine}${scratchLine}
87
+ ${bigOutputLine}${projectFilesLine}${scratchLine}
83
88
  - Arco will hard-kill your process tree at 32GB RSS or ${formatCapMb(MAX_WORKER_OUTPUT_BYTES)} returned output. These are the floor, not the budget.
84
89
  `;
85
90
  }
@@ -1,6 +1,7 @@
1
+ import type { PrimaryConfig } from './primitives/seedWorker.js';
1
2
  import { beginConversationWrite } from './conversationActivity.js';
2
3
  import { ensureProjectStateIgnore } from './projectStateIgnore.js';
3
- import { normalizeAutoHandoff, normalizeOutputStyle, retiredProviderReason, resolveAutoCompactionPolicy } from '@arco/shared';
4
+ import { isAutoCompactionPolicy, storedOutputStyle, normalizeAutoHandoff, normalizeOutputStyle, retiredProviderReason, resolveAutoCompactionPolicy } from '@arco/shared';
4
5
  // Slot 9 — per-workflow identity + session ledger (meta.json).
5
6
  //
6
7
  // Lives at <cwd>/.arco/workflows/<wfid>/meta.json alongside Slot 5's
@@ -80,6 +81,8 @@ export interface WorkflowMeta {
80
81
  // Append-only ledger of every CLI session bound to this workflow. Newest
81
82
  // entry last.
82
83
  cliSessions: WorkflowCliSession[];
84
+ // A replacement external conversation has not supplied its own context reading.
85
+ providerConversationPendingReading?: boolean;
83
86
  // Phase 6 Lite — session rotations archived by Handoff land here. Not the
84
87
  // same as `cliSessions[]`: a session can appear in both (it was live at
85
88
  // some point, then later archived). The history entry carries the handoff
@@ -470,8 +473,8 @@ export async function updateMeta(
470
473
  }
471
474
 
472
475
  // Ensure a meta.json exists — write one from `seed` if missing. Used by the
473
- // rehydrate path so pre-Slot-9 workflows (no meta.json on disk) get one
474
- // lazily the next time their client reconnects.
476
+ // creation, reconnect and turn paths. Existing metadata is preserved, including
477
+ // updates that land while the caller is constructing its authoritative seed.
475
478
  export async function ensureMeta(cwd: string, seed: WorkflowMeta): Promise<WorkflowMeta> {
476
479
  if (!cwd) return seed;
477
480
  validateWfid(seed.workflowId);
@@ -519,16 +522,21 @@ export async function appendCliSession(
519
522
  // with Arco's placeholder id. Update that provider's latest entry in place
520
523
  // rather than appending a second row; when the ids already match, only refresh
521
524
  // lastActiveAt. This keeps resume lookup aligned with the live CLI session
522
- // after initial binding or session rotation.
525
+ // after initial binding or session rotation. An authoritative seed repairs a
526
+ // missing file inside the same lock; generic updateMeta remains update-only.
523
527
  export async function reconcileLatestCliSession(
524
528
  cwd: string,
525
529
  wfid: string,
526
530
  provider: ProviderName,
527
531
  liveSessionId: string,
528
532
  providerAccountRef?: string,
533
+ seed?: WorkflowMeta,
529
534
  ): Promise<void> {
530
535
  if (!cwd || !liveSessionId) return;
531
- await updateMeta(cwd, wfid, (meta) => {
536
+ validateWfid(wfid);
537
+ await withFileLock(metaPath(cwd, wfid), async () => {
538
+ const meta = await readMeta(cwd, wfid) ?? seed;
539
+ if (!meta) throw new Error('Workflow metadata is missing; the provider conversation was not saved.');
532
540
  // Find the latest entry for this provider (not strictly the last overall —
533
541
  // a cross-provider workflow might have interleaved entries).
534
542
  let latestIdx = -1;
@@ -544,6 +552,11 @@ export async function reconcileLatestCliSession(
544
552
  meta.cliSessions[latestIdx].providerAccountRef = providerAccountRef;
545
553
  }
546
554
  meta.lastActiveAt = now;
555
+ if (seed) {
556
+ if (seed.providerConversationPendingReading) meta.providerConversationPendingReading = true;
557
+ else delete meta.providerConversationPendingReading;
558
+ }
559
+ await writeMeta(cwd, meta);
547
560
  });
548
561
  }
549
562
 
@@ -683,3 +696,124 @@ export async function listWorkflowMetas(cwd: string): Promise<WorkflowMetaSummar
683
696
  out.sort((a, b) => b.lastActiveAt - a.lastActiveAt);
684
697
  return out;
685
698
  }
699
+
700
+ export function workflowMetaSeed(
701
+ cwd: string, workflowId: string, config: WorkflowConfig,
702
+ primary: Pick<PrimaryConfig, 'provider' | 'model' | 'effort'>,
703
+ opts?: { parentWorkflowId?: string },
704
+ ): WorkflowMeta {
705
+ const now = Date.now();
706
+ return {
707
+ workflowId,
708
+ name: config.name,
709
+ cwd,
710
+ ...(config.kind === 'chat' ? { kind: 'chat' as const } : {}),
711
+ ...(config.kind === 'chat' && config.voiceOperator === true ? { voiceOperator: true } : {}),
712
+ createdAt: now,
713
+ lastActiveAt: now,
714
+ primaryProvider: primary.provider,
715
+ primaryModel: primary.model,
716
+ primaryEffort: primary.effort,
717
+ ...(config.providerAccountRef ? { providerAccountRef: config.providerAccountRef } : {}),
718
+ cliSessions: [],
719
+ operator: 'local',
720
+ lastEventSeq: null,
721
+ lastTranscriptSeq: null,
722
+ compactedAt: null,
723
+ ...(config.pinnedSkills?.length
724
+ ? { pinnedSkills: config.pinnedSkills.map((s) => ({ scope: s.scope, slug: s.slug })) }
725
+ : {}),
726
+ ...(opts?.parentWorkflowId ? { parentWorkflowId: opts.parentWorkflowId } : {}),
727
+ // docs/PROVIDERS.md / docs/PROVIDERS.md - when the New-tab
728
+ // picker (or Spawn-from-here parent inheritance) provided a non-default
729
+ // value, persist it to disk on the very first meta write so a server
730
+ // restart before the operator's first turn doesn't lose the pick.
731
+ // Sanitized one more time at write-site against unknown values reaching
732
+ // disk via a hand-edited cascade default.
733
+ ...(config.efficiencyToolFilter === 'off' || config.efficiencyToolFilter === 'conservative' || config.efficiencyToolFilter === 'aggressive'
734
+ ? { efficiencyToolFilter: config.efficiencyToolFilter }
735
+ : {}),
736
+ // docs/PROVIDERS.md - persist the stamped new-tab default or
737
+ // an explicit operator choice on the first meta write.
738
+ ...(config.efficiencyFactForce === 'on' || config.efficiencyFactForce === 'off'
739
+ ? { efficiencyFactForce: config.efficiencyFactForce }
740
+ : {}),
741
+ // Persist an explicit config-protection choice to disk on first meta-write
742
+ // so an operator opt-out survives a restart. Absent ⇒ gate ON by default.
743
+ ...(config.efficiencyConfigProtection === 'on' || config.efficiencyConfigProtection === 'off'
744
+ ? { efficiencyConfigProtection: config.efficiencyConfigProtection }
745
+ : {}),
746
+ ...(typeof config.claudeNativeCompact === 'boolean'
747
+ ? {
748
+ claudeNativeCompact: config.claudeNativeCompact,
749
+ ...(config.claudeNativeCompact === true ? { claudeNativeCompactUserSetAt: now } : {}),
750
+ }
751
+ : {}),
752
+ ...(typeof config.claudeNativeForceInterleavedThinkingBeta === 'boolean'
753
+ ? { claudeNativeForceInterleavedThinkingBeta: config.claudeNativeForceInterleavedThinkingBeta }
754
+ : {}),
755
+ nativeSubagents: config.nativeSubagents,
756
+ claudeNativeTaskDisabled: config.claudeNativeTaskDisabled,
757
+ ...(config.claudeNativeThinkingDisplay === 'omitted' || config.claudeNativeThinkingDisplay === 'summarized' || config.claudeNativeThinkingDisplay === 'updates'
758
+ ? { claudeNativeThinkingDisplay: config.claudeNativeThinkingDisplay }
759
+ : {}),
760
+ ...(config.codexTransport === 'exec' || config.codexTransport === 'appserver'
761
+ ? { codexTransport: config.codexTransport }
762
+ : {}),
763
+ ...(config.codexContextPolicy === 'max' || config.codexContextPolicy === 'standard'
764
+ ? { codexContextPolicy: config.codexContextPolicy }
765
+ : {}),
766
+ ...(config.claudeTransport === 'cli' || config.claudeTransport === 'native'
767
+ ? { claudeTransport: config.claudeTransport }
768
+ : {}),
769
+ // Persist the seeded auto-handoff default on the first meta-write so a
770
+ // server restart before the operator's first turn keeps the global
771
+ // default (handleCreateWorkflow bakes it into config for new tabs). The
772
+ // savedMeta restore in handleCreateWorkflow reads this back.
773
+ ...(isAutoCompactionPolicy(config.autoCompaction) ? { autoCompaction: { ...config.autoCompaction } } : {}),
774
+ ...(config.autoHandoff ? { autoHandoff: { ...config.autoHandoff } } : {}),
775
+ // docs/PROVIDERS.md - persist the sandbox toggle on the
776
+ // first meta-write when the cascade default supplied a non-undefined
777
+ // value. Default is 'off'; only the explicit on/off pair lands here so
778
+ // a stale cascade doesn't accidentally turn the sandbox on for tabs
779
+ // that were never asked.
780
+ ...(config.efficiencySandbox === 'on' || config.efficiencySandbox === 'off'
781
+ ? { efficiencySandbox: config.efficiencySandbox }
782
+ : {}),
783
+ // docs/PROVIDERS.md - persist the review-gate toggle on the first meta-write
784
+ // when the cascade default supplied an explicit value, so an operator opt-in
785
+ // survives a restart before the first turn. Default 'off'.
786
+ ...(config.reviewSafeMode === 'on' || config.reviewSafeMode === 'off'
787
+ ? { reviewSafeMode: config.reviewSafeMode }
788
+ : {}),
789
+ // Only a style other than the default is written; unset means
790
+ // DEFAULT_OUTPUT_STYLE. Legacy `lite` / `caveman` from a stale client are
791
+ // written as `plain` / `terse` (plain being the default, it stays unset).
792
+ ...(storedOutputStyle(config.outputStyle) ? { outputStyle: storedOutputStyle(config.outputStyle) } : {}),
793
+ // docs/GOTCHAS.md - persist a north-star seeded before the first turn
794
+ // (e.g. a Spawn-from-here that inherited the parent's) so it survives a
795
+ // restart even if the operator never re-sets it. Blank ⇒ omitted.
796
+ ...(config.goal && config.goal.trim() ? { goal: config.goal } : {}),
797
+ // docs/PROVIDERS.md - persist sticky ultracode on the first meta-write so a
798
+ // tab left in ultracode survives a restart (the rehydrate read in
799
+ // workflowHandlers.ts expects saved.ultracode). Without this the flag lives
800
+ // only in-memory and the tab silently drops out of ultracode on restart.
801
+ ...(config.ultracode === true ? { ultracode: true } : {}),
802
+ ...(typeof config.webSearchMaxUses === 'number' ? { webSearchMaxUses: config.webSearchMaxUses } : {}),
803
+ ...(config.managedWorktreeSourceCwd
804
+ ? { managedWorktreeSourceCwd: config.managedWorktreeSourceCwd }
805
+ : {}),
806
+ };
807
+ }
808
+
809
+ export async function persistInitialMeta(
810
+ cwd: string, workflowId: string, config: WorkflowConfig,
811
+ primary: Pick<PrimaryConfig, 'provider' | 'model' | 'effort'>,
812
+ opts?: { parentWorkflowId?: string; sessionId?: string; pendingReading?: boolean },
813
+ ): Promise<void> {
814
+ if (config.incognito) return;
815
+ const seed = workflowMetaSeed(cwd, workflowId, config, primary, opts);
816
+ if (opts?.pendingReading) seed.providerConversationPendingReading = true;
817
+ if (opts?.sessionId) seed.cliSessions.push({ provider: primary.provider, sessionId: opts.sessionId, createdAt: Date.now(), providerAccountRef: config.providerAccountRef });
818
+ await ensureMeta(cwd, seed);
819
+ }
@@ -38,6 +38,7 @@ export interface WorkflowState {
38
38
  manager: WorkerManager;
39
39
  primary: PrimaryConfig;
40
40
  primarySessionId?: string;
41
+ providerConversation?: 'unavailable' | 'awaiting-reading';
41
42
  // Owned by the user-message loop; interrupt only its worker, never reviewers
42
43
  // or compaction. Keep the claim until cancellation has actually settled.
43
44
  primaryTurn?: { token: number; workerId?: string; holdSteer: boolean; clusterDispatch?: { clusterId?: string }; interruption?: Promise<boolean | void> };
@@ -2517,14 +2517,15 @@ export async function handleClusterAutoTurnToggle(
2517
2517
  // Operator chose an AUTO-PICKUP mode in the cluster dialog. Smart modes need
2518
2518
  // an evaluator from an enabled provider and start a new session; Off and
2519
2519
  // Rule-based end any Smart session. Pushes cluster_state on success.
2520
+ // A pause-only request keeps the current mode, session and budgets.
2520
2521
  export async function handleClusterAutoPickupSet(
2521
2522
  ws: WebSocket,
2522
- msg: { clusterId: string; mode: unknown; evaluator?: unknown; limits?: unknown; ruleLimits?: unknown; resumeRule?: boolean; remindBusy?: boolean },
2523
+ msg: { clusterId: string; mode: unknown; paused?: unknown; evaluator?: unknown; limits?: unknown; ruleLimits?: unknown; resumeRule?: boolean; remindBusy?: boolean },
2523
2524
  ): Promise<void> {
2524
2525
  const settings = await readSettings().catch(() => null);
2525
2526
  const result = await applyAutoPickup(
2526
2527
  msg.clusterId,
2527
- { mode: msg.mode, evaluator: msg.evaluator, limits: msg.limits, ruleLimits: msg.ruleLimits, resumeRule: msg.resumeRule },
2528
+ { mode: msg.mode, paused: msg.paused, evaluator: msg.evaluator, limits: msg.limits, ruleLimits: msg.ruleLimits, resumeRule: msg.resumeRule },
2528
2529
  (provider) => settings?.enabledProviders?.[provider] !== false,
2529
2530
  );
2530
2531
  if (!result.ok) {
@@ -1,3 +1,4 @@
1
+ import { hasConversationHistory } from '../providerConversation.js';
1
2
  import { supportsManualCompact } from '../manualCompactCapability.js';
2
3
  // `compact_workflow` handler — operator-triggered native compaction. One WS
3
4
  // message, provider-routed:
@@ -30,6 +31,7 @@ import {
30
31
  releaseBusy,
31
32
  refreshCodexTokenSnapshot,
32
33
  resetCodexContextAfterCompact,
34
+ resetAutoCompactionCycle,
33
35
  } from './turnEngine.js';
34
36
  import { send, broadcastWorkflow, broadcastTransient, notifyClusterStateForWorkflow } from '../server/broadcast.js';
35
37
  import { workflows, workflowCwds } from '../server/state.js';
@@ -43,7 +45,7 @@ import { readSettings } from '../settings.js';
43
45
  import * as clusterStore from '../clusterStore.js';
44
46
 
45
47
  export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg: CompactWorkflowMessage,
46
- claimGuard?: (claim: () => number) => Promise<number | false>, autoDetail?: string): Promise<void> {
48
+ claimGuard?: (claim: () => number) => Promise<number | false>, autoDetail?: string, onSuccess?: () => void): Promise<void> {
47
49
  const workflowId = msg.workflowId;
48
50
  const wf = workflows.get(workflowId);
49
51
  if (!wf) {
@@ -153,7 +155,7 @@ export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg
153
155
  if (codexTransport !== 'appserver') {
154
156
  result = { ok: false, error: 'Compact needs the Codex app-server transport (CONFIG → TRANSPORT). On Codex exec, use Handoff.' };
155
157
  } else if (!wf.primarySessionId) {
156
- result = { ok: false, error: 'no saved Codex thread for this workflow — run a turn first' };
158
+ result = { ok: false, error: await hasConversationHistory(cwd!, workflowId) ? 'The previous Codex conversation cannot be resumed because its saved thread id is unavailable. The next message starts a new conversation; earlier messages remain in this tab.' : 'no saved Codex thread for this workflow — run a turn first' };
157
159
  } else {
158
160
  const account = await resolveProviderAccount('codex', wf.config.providerAccountRef, cwd).catch(() => null);
159
161
  const turnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
@@ -183,7 +185,7 @@ export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg
183
185
  } else if (provider === 'cursor') {
184
186
  compactedVia = 'cursor-acp';
185
187
  if (!wf.primarySessionId) {
186
- result = { ok: false, error: 'no saved Cursor session for this workflow — run a turn first' };
188
+ result = { ok: false, error: await hasConversationHistory(cwd!, workflowId) ? 'The previous Cursor conversation cannot be resumed because its saved session id is unavailable. The next message starts a new conversation; earlier messages remain in this tab.' : 'no saved Cursor session for this workflow — run a turn first' };
187
189
  } else {
188
190
  const turnClusterId = clusterStore.getClusterIdForWorkflow(workflowId);
189
191
  result = await compactCursorAcpThread(workflowId, {
@@ -240,6 +242,10 @@ export async function handleCompactWorkflow(ws: WebSocket, session: Session, msg
240
242
  // busy now) — report the outcome but leave busy + the queue alone.
241
243
  const owned = releaseBusy(wf, busyToken, 'interrupted', false);
242
244
 
245
+ if (result.ok && owned) {
246
+ if (autoDetail) onSuccess?.();
247
+ else resetAutoCompactionCycle(wf);
248
+ }
243
249
  if (result.ok && owned && autoDetail) {
244
250
  if (provider === 'codex') resetCodexContextAfterCompact(workflowId, wf);
245
251
  else wf.lastContextPercent = 0;
@@ -1,3 +1,4 @@
1
+ import { ensureWorkflowMetadata, providerConversationState, saveProviderSession } from '../providerConversation.js';
1
2
  import { isClaudeNativeTaskActive } from '../providers/claude-native/index.js';
2
3
  import { appendHandoffNotice } from '../handoffHistoryTool.js';
3
4
  import { unsettledTaskStatuses } from './taskLifecycle.js';
@@ -78,7 +79,6 @@ import {
78
79
  appendHistoryEntry,
79
80
  readMeta,
80
81
  workflowConfigFromMeta,
81
- reconcileLatestCliSession,
82
82
  writeMeta,
83
83
  } from '../workflowMeta.js';
84
84
  import {
@@ -492,6 +492,7 @@ export async function handleHandoffRequest(
492
492
  // Clear the pinned session id so the next primary turn mints fresh.
493
493
  if (!handoffOwned()) return;
494
494
  wf.primarySessionId = undefined;
495
+ wf.providerConversation = undefined;
495
496
 
496
497
  // Retire every cached transport before the new seed, so Codex app-server
497
498
  // and Cursor ACP bootstrap their MCP children with the new history grant.
@@ -680,7 +681,7 @@ export async function handleHandoffRequest(
680
681
  // extras filter excludes non-streaming assistants when sessionChat is
681
682
  // non-empty from the pre-handoff session). No-op for non-Claude.
682
683
  startSessionWatcher(msg.workflowId, wf, cwd, ws);
683
- reconcileLatestCliSession(cwd, msg.workflowId, 'claude', primaryTurn.initialSessionId).catch((err) => {
684
+ saveProviderSession(cwd, msg.workflowId, wf, 'claude', primaryTurn.initialSessionId).catch((err) => {
684
685
  console.error(`[arco] handoff ${handle.handoffId} meta reconcile failed:`, err);
685
686
  });
686
687
  }
@@ -694,7 +695,7 @@ export async function handleHandoffRequest(
694
695
  startSessionWatcher(msg.workflowId, wf, cwd, ws);
695
696
  }
696
697
 
697
- reconcileLatestCliSession(cwd, msg.workflowId, wf.primary.provider, sid, handoffAccount?.profile.id).catch((err) => {
698
+ saveProviderSession(cwd, msg.workflowId, wf, wf.primary.provider, sid, handoffAccount?.profile.id).catch((err) => {
698
699
  console.error(`[arco] handoff ${handle.handoffId} meta reconcile (${wf.primary.provider}) failed:`, err);
699
700
  });
700
701
  });
@@ -1323,7 +1324,7 @@ export async function handleSpawnFromHere(
1323
1324
  // the usual watcher-start call never runs. Start it here once the new
1324
1325
  // session's id is known — same reasoning as the handoff fix above.
1325
1326
  startSessionWatcher(newWorkflowId, spawnedWf, newCwd, ws);
1326
- reconcileLatestCliSession(newCwd, newWorkflowId, 'claude', primaryTurn.initialSessionId).catch((err) => {
1327
+ saveProviderSession(newCwd, newWorkflowId, spawnedWf, 'claude', primaryTurn.initialSessionId).catch((err) => {
1327
1328
  console.error(`[arco] spawn meta reconcile failed:`, err);
1328
1329
  });
1329
1330
  }
@@ -1334,7 +1335,8 @@ export async function handleSpawnFromHere(
1334
1335
  wf.primarySessionId = sid;
1335
1336
  startSessionWatcher(newWorkflowId, wf, newCwd, ws);
1336
1337
  }
1337
- reconcileLatestCliSession(newCwd, newWorkflowId, newPrimary.provider, sid, spawnAccount?.profile.id).catch((err) => {
1338
+ if (!wf) return;
1339
+ saveProviderSession(newCwd, newWorkflowId, wf, newPrimary.provider, sid, spawnAccount?.profile.id).catch((err) => {
1338
1340
  console.error(`[arco] spawn meta reconcile (${newPrimary.provider}) failed:`, err);
1339
1341
  });
1340
1342
  });
@@ -1480,6 +1482,7 @@ export async function handleRehydrateWorkflows(
1480
1482
  // Read meta.json to restore primarySessionId so the next user_message
1481
1483
  // continues the prior CLI session instead of starting a fresh one.
1482
1484
  try {
1485
+ await ensureWorkflowMetadata(cwd, entry.workflowId, wf);
1483
1486
  const meta = await readMeta(cwd, entry.workflowId);
1484
1487
  if (meta) {
1485
1488
  const latestForProvider = [...meta.cliSessions].reverse().find((s) => s.provider === wf.primary.provider);
@@ -1752,6 +1755,7 @@ export async function rehydrateOneWorkflow(
1752
1755
  opts: { tail?: boolean } = {},
1753
1756
  ): Promise<void> {
1754
1757
  const cwd = wf.config.incognito ? '' : wf.config.workingDirectory;
1758
+ if (cwd) await ensureWorkflowMetadata(cwd, workflowId, wf);
1755
1759
  let latestNativeLastPromptTokens: number | undefined;
1756
1760
  const captureReplayTokens = (events: ServerMessage[]): void => {
1757
1761
  for (const event of events) {
@@ -1882,9 +1886,12 @@ export async function rehydrateOneWorkflow(
1882
1886
  : null;
1883
1887
  const codexSnapshotWindow = codexSnapshot?.modelContextWindow;
1884
1888
  const computerState = isComputer(wf) ? await computerContextState(workflowId, wf) : undefined;
1889
+ const conversationState = cwd ? await providerConversationState(cwd, workflowId, wf) : undefined;
1890
+ wf.providerConversation = conversationState;
1885
1891
  const msg: ServerMessage = {
1886
1892
  type: 'workflow_state_snapshot',
1887
1893
  workflowId,
1894
+ ...(conversationState ? { providerConversation: conversationState } : {}),
1888
1895
  workers: {},
1889
1896
  busy: wf.busy,
1890
1897
  ...(wf.busy && Number.isFinite(wf.turnStartedAt) ? { turnStartedAt: wf.turnStartedAt } : {}),
@@ -1925,7 +1932,7 @@ export async function rehydrateOneWorkflow(
1925
1932
 
1926
1933
  // Phase 2 — emit a context estimate immediately so the client has a fill
1927
1934
  // reading as soon as the snapshot arrives (not only after the next turn).
1928
- if (cwd && wf.primary.provider === 'claude' && typeof latestNativeLastPromptTokens === 'number' && latestNativeLastPromptTokens > 0) {
1935
+ if (cwd && !conversationState && wf.primary.provider === 'claude' && typeof latestNativeLastPromptTokens === 'number' && latestNativeLastPromptTokens > 0) {
1929
1936
  const estimate = nativeContextEstimate(wf.primary.model, latestNativeLastPromptTokens);
1930
1937
  if (estimate && ws.readyState === WebSocket.OPEN) {
1931
1938
  const usage = { type: 'context_usage' as const, workflowId, ...estimate };
@@ -1,8 +1,8 @@
1
1
  import { WebSocket } from 'ws';
2
- import type { OperatorQuestionReplyMessage } from '@arco/shared';
2
+ import type { OperatorQuestionReplyMessage, OperatorQuestionDismissMessage } from '@arco/shared';
3
3
  import type { Session } from '../workflows/types.js';
4
4
  import { workflows } from '../server/state.js';
5
- import { replyToOperatorQuestion } from '../providers/codex-appserver/operatorQuestions.js';
5
+ import { replyToOperatorQuestion, dismissOperatorQuestion } from '../providers/codex-appserver/operatorQuestions.js';
6
6
  import { handleUserMessage } from './turnEngine.js';
7
7
  import { broadcastWorkflow } from '../server/broadcast.js';
8
8
 
@@ -25,3 +25,11 @@ export async function handleOperatorQuestionReply(ws: WebSocket, session: Sessio
25
25
  // publisher; failed/stale reply attempts do not become transcript events.
26
26
  if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'operator_question_reply_result', workflowId: msg.workflowId, requestId: msg.requestId, ...result }));
27
27
  }
28
+
29
+ export function handleOperatorQuestionDismiss(ws: WebSocket, session: Session, msg: OperatorQuestionDismissMessage): void {
30
+ const wf = workflows.get(msg.workflowId);
31
+ const result = !wf || !wf.observers.has(ws) || !session.workflowIds.has(msg.workflowId)
32
+ ? { ok: false, error: 'Subscribe to this workflow before dismissing.' }
33
+ : dismissOperatorQuestion(msg.workflowId, msg.requestId);
34
+ if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'operator_question_dismiss_result', workflowId: msg.workflowId, requestId: msg.requestId, ...result }));
35
+ }