@zergai/ztc 0.23.0-beta.1 → 0.24.0-beta.1

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 (146) hide show
  1. package/README.md +299 -13
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/agent/agent.js +57 -14
  8. package/dist/agent/backends/http_error.d.ts +2 -0
  9. package/dist/agent/backends/http_error.js +2 -0
  10. package/dist/agent/backends/router_gate.d.ts +3 -2
  11. package/dist/agent/backends/router_gate.js +5 -4
  12. package/dist/agent/backends/router_keys.d.ts +14 -0
  13. package/dist/agent/backends/router_keys.js +19 -0
  14. package/dist/agent/backends/router_refusal.d.ts +5 -3
  15. package/dist/agent/backends/router_refusal.js +28 -6
  16. package/dist/agent/backends/types.d.ts +1 -1
  17. package/dist/agent/backends/zrouter_stream.js +10 -6
  18. package/dist/agent/commands/agent_cli.d.ts +11 -1
  19. package/dist/agent/commands/agent_cli.js +295 -38
  20. package/dist/agent/commands/diff.js +4 -1
  21. package/dist/agent/commands/help.js +4 -1
  22. package/dist/agent/commands/plan.js +3 -1
  23. package/dist/agent/commands/session_redaction.d.ts +16 -0
  24. package/dist/agent/commands/session_redaction.js +77 -0
  25. package/dist/agent/commands/settings.js +144 -0
  26. package/dist/agent/commands/types.d.ts +5 -0
  27. package/dist/agent/commands/usage_spec.d.ts +4 -0
  28. package/dist/agent/commands/usage_spec.js +10 -4
  29. package/dist/agent/runtime/policy.d.ts +25 -0
  30. package/dist/agent/runtime/policy.js +154 -26
  31. package/dist/agent/runtime/source_verification.js +6 -2
  32. package/dist/agent/runtime/tool_runtime.js +81 -3
  33. package/dist/agent/tools/apply_patch.js +678 -131
  34. package/dist/agent/tools/bus_message.d.ts +26 -1
  35. package/dist/agent/tools/bus_message.js +126 -10
  36. package/dist/agent/tools/file.d.ts +16 -1
  37. package/dist/agent/tools/file.js +43 -5
  38. package/dist/agent/tools/index.d.ts +1 -1
  39. package/dist/agent/tools/index.js +1 -1
  40. package/dist/agent/tools/pane.js +5 -0
  41. package/dist/agent/tools/search.js +5 -1
  42. package/dist/agent/tools/supervision.js +16 -2
  43. package/dist/agent/tools/types.d.ts +22 -0
  44. package/dist/app/mirror_startup.d.ts +7 -5
  45. package/dist/app/mirror_startup.js +7 -5
  46. package/dist/app/navigator_mirrors.d.ts +20 -0
  47. package/dist/app/navigator_mirrors.js +36 -0
  48. package/dist/app/workspace_layout_controller.d.ts +11 -2
  49. package/dist/app/workspace_layout_controller.js +13 -2
  50. package/dist/batch/worktree.js +9 -1
  51. package/dist/cli_ratatui.d.ts +264 -12
  52. package/dist/cli_ratatui.js +1198 -103
  53. package/dist/config/types.d.ts +29 -0
  54. package/dist/desktop/daily/source_baseline.js +3 -1
  55. package/dist/diagnostics/session_export.d.ts +1 -0
  56. package/dist/diagnostics/session_export.js +229 -26
  57. package/dist/emulation/tool_adapters.js +42 -5
  58. package/dist/headless.js +24 -5
  59. package/dist/instance_registry.d.ts +7 -0
  60. package/dist/mcp/workspace_server.d.ts +12 -1
  61. package/dist/mcp/workspace_server.js +75 -8
  62. package/dist/panes/agent_cli.d.ts +60 -3
  63. package/dist/panes/agent_cli.js +169 -16
  64. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  65. package/dist/panes/agent_pane_sessions.js +111 -0
  66. package/dist/panes/agent_panes.d.ts +77 -3
  67. package/dist/panes/agent_panes.js +199 -10
  68. package/dist/panes/agent_profiles.d.ts +5 -0
  69. package/dist/panes/agent_profiles.js +7 -0
  70. package/dist/panes/agent_resume.d.ts +134 -0
  71. package/dist/panes/agent_resume.js +155 -0
  72. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  73. package/dist/panes/agent_sessions/claude_head.js +122 -0
  74. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  75. package/dist/panes/agent_sessions/claude_store.js +223 -0
  76. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  77. package/dist/panes/agent_sessions/codex_head.js +161 -0
  78. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  79. package/dist/panes/agent_sessions/codex_store.js +187 -0
  80. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  81. package/dist/panes/agent_sessions/controller.js +110 -0
  82. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  83. package/dist/panes/agent_sessions/cut_json.js +109 -0
  84. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  85. package/dist/panes/agent_sessions/limits.js +48 -0
  86. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  87. package/dist/panes/agent_sessions/scan.js +86 -0
  88. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  89. package/dist/panes/agent_sessions/store_fs.js +128 -0
  90. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  91. package/dist/panes/agent_sessions/stores.js +89 -0
  92. package/dist/panes/agent_sessions/title.d.ts +9 -0
  93. package/dist/panes/agent_sessions/title.js +51 -0
  94. package/dist/panes/agent_sessions/types.d.ts +48 -0
  95. package/dist/panes/agent_sessions/types.js +2 -0
  96. package/dist/panes/reply_arbitrator.d.ts +39 -0
  97. package/dist/panes/reply_arbitrator.js +185 -0
  98. package/dist/panes/reply_modes.d.ts +291 -0
  99. package/dist/panes/reply_modes.js +598 -0
  100. package/dist/runtime_info.js +11 -2
  101. package/dist/session.js +4 -2
  102. package/dist/simulation/living/context.d.ts +8 -8
  103. package/dist/simulation/living/types.d.ts +5 -5
  104. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  105. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  106. package/dist/ui/ratatui/ipc_path.js +23 -3
  107. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  108. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  109. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  110. package/dist/ui/ratatui/pane_relay.js +86 -19
  111. package/dist/ui/ratatui/process.js +3 -0
  112. package/dist/ui/ratatui/protocol.d.ts +50 -1
  113. package/dist/ui/ratatui/protocol.js +56 -0
  114. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  115. package/dist/ui/ratatui/relay_policy.js +94 -0
  116. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  117. package/dist/ui/ratatui/screen_privacy.js +24 -0
  118. package/dist/ui/scrollback.js +8 -0
  119. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  120. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  121. package/dist/ui/widgets/log_view.d.ts +5 -1
  122. package/dist/ui/widgets/log_view.js +40 -4
  123. package/dist/utils/atomic_write.js +9 -11
  124. package/dist/utils/canonical_path.d.ts +19 -0
  125. package/dist/utils/canonical_path.js +44 -0
  126. package/dist/utils/compaction.d.ts +2 -1
  127. package/dist/utils/compaction.js +3 -1
  128. package/dist/utils/git_directory_names.d.ts +51 -0
  129. package/dist/utils/git_directory_names.js +429 -0
  130. package/dist/utils/temporary_write_root.d.ts +6 -1
  131. package/dist/utils/temporary_write_root.js +32 -2
  132. package/dist/utils/tool_result_message.d.ts +4 -1
  133. package/dist/utils/tool_result_message.js +6 -2
  134. package/dist/web/bus_hold.d.ts +70 -0
  135. package/dist/web/bus_hold.js +118 -0
  136. package/dist/web/mirror_client.d.ts +7 -3
  137. package/dist/web/mirror_client.js +61 -23
  138. package/dist/web/mirror_route_gate.d.ts +40 -0
  139. package/dist/web/mirror_route_gate.js +71 -0
  140. package/dist/web/mirror_stream.d.ts +147 -22
  141. package/dist/web/mirror_stream.js +350 -83
  142. package/dist/web/pane_credentials.d.ts +32 -1
  143. package/dist/web/pane_credentials.js +62 -2
  144. package/dist/workspace_collision.js +11 -2
  145. package/dist/zlm-embed.mjs +940 -273
  146. package/package.json +34 -12
@@ -10,8 +10,16 @@ import { reconcileOrderedTranscript } from './app/ordered_transcript.js';
10
10
  import { listCommandJobs, shutdownCommandJobs, subscribeCommandJobs } from './agent/runtime/command_jobs.js';
11
11
  import { CommandPaneManager, commandPaneText } from './agent/runtime/command_panes.js';
12
12
  import { isPaneRefusalFor, waitForPaneCreatedOrError } from './agent/tools/pane.js';
13
- import { findAgentCli } from './panes/agent_cli.js';
14
- import { agentCliFromRequestId, formatAgentPaneMessage, openAgentPane, typeLineIntoPane } from './panes/agent_panes.js';
13
+ import { AGENT_CLIS, findAgentCli } from './panes/agent_cli.js';
14
+ import { openResumedAgentPane, openedSessionLine, resumeLaunchPlan, resumeSavedAgentPane, elsewhereCommandLine } from './panes/agent_resume.js';
15
+ import { createAgentSessionsController } from './panes/agent_sessions/controller.js';
16
+ import { orderRows } from './panes/agent_sessions/scan.js';
17
+ import { RECENT_ACTIVITY_MS } from './panes/agent_sessions/limits.js';
18
+ import { openAgentSessionPanes } from './panes/agent_pane_sessions.js';
19
+ import { AgentSessionsPanelWidget } from './ui/widgets/agent_sessions_panel.js';
20
+ import { agentCliFromRequestId, agentPaneAnswerText, agentPaneNoteForModel, formatAgentPaneMessage, openAgentPane, typeLineIntoPane, typingSettled } from './panes/agent_panes.js';
21
+ import { ReplyExchanges, arbitrationNotice, arbitrationStopForPane, arbitrationSummary, arrivalNote, capLoweredNotice, capLoweredStopForPane, capNoteForPane, capStopNotice, heldNotice, heldNoticeForPane, knownSecrets, replyModeRefusal, replyModeSettings, resumedNotice, staleArbitrationNotice, withheldNotice } from './panes/reply_modes.js';
22
+ import { askArbitrator } from './panes/reply_arbitrator.js';
15
23
  import { agentCliFromChoice, newPaneChoices } from './panes/new_pane_choices.js';
16
24
  import { MOTSI_PANE_ENV, remoteViewMotsi, runsMotsi, throughMotsi } from './panes/motsi.js';
17
25
  import { IntakeNotifications } from './intake/notifications.js';
@@ -30,7 +38,7 @@ import { formatTaskHandoffNotice, projectTaskHandoff } from './session_handoff_c
30
38
  import { resolve } from 'path';
31
39
  import { beginSimTurn } from './agent/tools/sim_turn_budget.js';
32
40
  import { randomUUID } from 'crypto';
33
- import { appendFileSync, existsSync, writeFileSync } from 'fs';
41
+ import { appendFileSync, existsSync, promises as fsPromises, writeFileSync } from 'fs';
34
42
  import { tmpdir, homedir } from 'os';
35
43
  import { dirname, join } from 'path';
36
44
  import { execFile, spawnSync } from 'child_process';
@@ -42,11 +50,11 @@ import { normalizeProviderId } from './agent/backends/provider_ids.js';
42
50
  import { collectUsageViews, buildUsageViews, nativeUsageView } from './usage_projection.js';
43
51
  import { createUsageSnapshot, recordUsageReceipt } from './usage_snapshot.js';
44
52
  import { withActiveProfileArg } from './config/profiles.js';
45
- import { DEFAULT_ROUTER_ORIGIN, RouterConfigurationError, routerSignInRefusal } from './router_auth.js';
53
+ import { DEFAULT_ROUTER_ORIGIN, RouterConfigurationError, readRouterCredentialsSync, routerSignInRefusal } from './router_auth.js';
46
54
  import { CODEX_REASONING_EFFORTS } from './config/types.js';
47
55
  import { getSupportedCodexReasoningEfforts, unsupportedEffortMessage, } from './utils/models.js';
48
56
  import { getVersion } from './utils/version.js';
49
- import { isPersistableAssistantMessage } from './utils/assistant_message.js';
57
+ import { isPersistableAssistantMessage, isToolUsePlaceholderMessage } from './utils/assistant_message.js';
50
58
  import { claimObservationWarning, withHostClaimObservation } from './agent/claim_observation.js';
51
59
  import { isMirrorMediaPath } from './utils/mirror_media.js';
52
60
  import { readDurableSessionImageSync, SessionMediaError } from './session_media.js';
@@ -84,9 +92,10 @@ import { showConnectPrompt } from './agent/commands/connect.js';
84
92
  import { onZergAILoginWaitChange, pendingZergAILogin, stopZergAILogin } from './agent/commands/auth.js';
85
93
  import { connectionSnapshot } from './agent/commands/credential_status.js';
86
94
  import { redactCredentialCommand } from './agent/commands/credential_redaction.js';
95
+ import { redactMirroredCommand } from './agent/commands/session_redaction.js';
87
96
  import { goalManager, goalPinTask, hasSustainedGoalIntent, detectGoalCompletion, detectGoalBlocked, goalBlockedReason, goalFinalNote, turnProducedText, turnToolOutcomes, shouldAccountFinalTurn, snapshotGoalForTurn } from './agent/commands/goal.js';
88
97
  import { allocatePlanArtifact, askPlanApproval, findPlanContent, generatePlanPath, commitPlan, PlanFileCreationError, } from './agent/commands/plan.js';
89
- import { setTodoUpdateCallback, clearTodoUpdateCallback, setPaneToolsTuiProcess, clearPaneToolsTuiProcess, setPaneToolsOwnId, setPaneToolsExitCallback, setPaneToolsMirrorCallback, setPaneToolsZdeLiteCallback, setPaneToolsPendingLaunchCallback, clearPaneToolsPendingLaunchCallback, setSupervisionManager, clearSupervisionManager, setBusTransport, clearBusTransport, setEvolutionTuiProcess, clearEvolutionTuiProcess, resetAskUserTurnFlag } from './agent/tools/index.js';
98
+ import { setTodoUpdateCallback, clearTodoUpdateCallback, setPaneToolsTuiProcess, clearPaneToolsTuiProcess, setPaneToolsOwnId, setPaneToolsExitCallback, setPaneToolsMirrorCallback, setPaneToolsZdeLiteCallback, setPaneToolsPendingLaunchCallback, clearPaneToolsPendingLaunchCallback, setSupervisionManager, clearSupervisionManager, setBusTransport, clearBusTransport, overseerBusTransport, setEvolutionTuiProcess, clearEvolutionTuiProcess, resetAskUserTurnFlag } from './agent/tools/index.js';
90
99
  import { shutdownLSPManager } from './lsp/index.js';
91
100
  import { MAX_CORRELATED_TURNS, correlatedInputDigest, projectCorrelatedTurns, restoreCorrelatedTurns, restoreCorrelatedTurnHistory } from './app/correlated_turn.js';
92
101
  import { buildRuntimeChoices, checkRuntimeSelection, desktopTaskSignature, RuntimeChoicesPublication } from './app/runtime_choices.js';
@@ -94,7 +103,7 @@ import { RuntimeChoicesSource } from './app/runtime_choices_source.js';
94
103
  import { PaneModelMemory } from './config/provider_models.js';
95
104
  import { zmuxKeymapPayload } from './config/keybindings.js';
96
105
  import { customPaneOptions } from './config/panes.js';
97
- import { CAPABILITY_DESKTOP_UPDATE_RESTART, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_ROUTER_CHROME, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CHOICES, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_KITTY_GRAPHICS, isDesktopSessionShareAction, CAPABILITY_SCROLLBACK_ANCHOR, CAPABILITY_TERMINAL_INTERACTION, } from './ui/ratatui/protocol.js';
106
+ import { CAPABILITY_DESKTOP_CLOSE_WINDOW, CAPABILITY_DESKTOP_UPDATE_RESTART, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_ROUTER_CHROME, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CHOICES, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_KITTY_GRAPHICS, isDesktopSessionShareAction, CAPABILITY_SCROLLBACK_ANCHOR, CAPABILITY_TERMINAL_INTERACTION, } from './ui/ratatui/protocol.js';
98
107
  import { writeClipboard } from './utils/clipboard.js';
99
108
  import { saveClipboardImagePng } from './utils/clipboard_image.js';
100
109
  import { loadEmulationProfiles, getEmulationProfile } from './emulation/catalog.js';
@@ -127,6 +136,7 @@ import { dumpContextOverflow } from './agent/contextDump.js';
127
136
  import { BROWSER_BUS_MEMBER_ID, OVERSEER_BUS_MEMBER_ID, createMirrorStreamServer, startMirrorStreamServer, stopMirrorStreamServer, } from './web/mirror_stream.js';
128
137
  import { initMirrorClient } from './web/mirror_client.js';
129
138
  import { PaneRelayServer, PaneRelayClient, generateRelaySocketPath } from './ui/ratatui/pane_relay.js';
139
+ import { paneReadRefusal, setPaneReadRefusal } from './ui/ratatui/screen_privacy.js';
130
140
  import { perfBeginKeystroke, perfStage, perfEndKeystroke } from './debug/perf_trace.js';
131
141
  import { resolveMuxPersistenceOptions, sanitizeMuxSessionState, validateWorkspaceState } from './ui/ratatui/mux_persistence.js';
132
142
  import { buildModelsController, buildSkillsController, buildShellController, routeUserInput, getPlanModeCommandDenial } from './app/command_context.js';
@@ -141,6 +151,7 @@ import { isPhantomCompletion } from './app/phantom_completion.js';
141
151
  import { SelectionCompletion } from './app/selection_completion.js';
142
152
  import { routerCatalogScope } from './utils/router_catalog.js';
143
153
  import { mirrorPaneControlNeedsCredential, shouldAttachParentMirrorClient, shouldMarkMirrorServerAsColonyChild } from './app/mirror_startup.js';
154
+ import { linkOnlyLogsNotice, linkOnlyPageNotice, remoteMirrorLogSource } from './app/navigator_mirrors.js';
144
155
  import { keylessRouterModelRefusal } from './agent/commands/router_availability.js';
145
156
  import { keylessZtcPaneRoute } from './panes/worker_route.js';
146
157
  import { buildDesktopUpdateRelaunchContext, buildHotRestartLaunch, prepareDesktopUpdateAuthorization, reduceDesktopUpdateOwnerHandshake, requestColonyCellRestart, } from './app/restart.js';
@@ -172,6 +183,24 @@ import { hasLaunchFlag } from './cli_args.js';
172
183
  import { askHowToConnectAtLaunch } from './onboarding/zergai_login.js';
173
184
  /** A Zerg Router login tip stays in the status line long enough to read. */
174
185
  const ROUTER_TIP_TOAST_MS = 12_000;
186
+ /** How long after the sessions picker closes Main's screen is still read by no one: a frame that held it may linger. */
187
+ const MAIN_SCREEN_PRIVATE_AFTER_MS = 1000;
188
+ /** Folders under macOS's automounters, whose first part names a host that looking at the folder would contact. */
189
+ const AUTOMOUNTED = /^\/(?:net|Network)(?:\/|$)/;
190
+ /** A folder's real path, Unicode-normalized, asked off the event loop with a deadline; the folder as given when it can't be. */
191
+ async function realFolder(path, timeoutMs = 1000) {
192
+ const given = path.normalize('NFC');
193
+ let timer;
194
+ try {
195
+ return await Promise.race([
196
+ fsPromises.realpath(path).then(real => real.normalize('NFC'), () => given),
197
+ new Promise(resolve => { timer = setTimeout(() => resolve(given), timeoutMs); }),
198
+ ]);
199
+ }
200
+ finally {
201
+ clearTimeout(timer);
202
+ }
203
+ }
175
204
  import { selectCurrentTranscriptMessages, selectFallbackLiveMessages, } from './app/transcript_window.js';
176
205
  export { openUrlInBrowser } from './utils/open_url.js';
177
206
  export { LIVE_TRANSCRIPT_LIMIT, isRecapMessage, liveWindowBoundary, selectCurrentTranscriptMessages, selectFallbackLiveMessages, } from './app/transcript_window.js';
@@ -290,6 +319,34 @@ const INTERRUPT_NOTICE = 'Interrupted. Tell me what to do next, or use /rewind t
290
319
  /** A turn Zerg Router cut off on every attempt: the answer so far stays, and a message continues it. */
291
320
  const ROUTER_STREAM_LOST_NOTICE = 'Zerg Router lost the answer partway through. Send a message to continue from there.';
292
321
  const ESCAPE_STOP_NOTICE = 'Esc again to stop';
322
+ /**
323
+ * What the transcript says when the person closes REQUEST's approval without a choice, which denies it: a hook's
324
+ * first-run approval leaves that hook out for the session while the tool goes on; a tool's approval stops the tool.
325
+ * The approval itself is drawn in the live frame only, so this line is all a reader of the transcript has of it.
326
+ */
327
+ function closedApprovalNotice(request) {
328
+ if (request.kind === 'first_run') {
329
+ const hook = request.firstRun;
330
+ return `Closed the Hook First-Run Approval: the ${hook?.event ?? ''} hook \`${hook?.command ?? request.toolName}\` won't run this session, `
331
+ + 'and the tool goes on without it.';
332
+ }
333
+ return `Closed the approval for ${request.toolName}: it was denied, so ${request.toolName} didn't run.`;
334
+ }
335
+ /**
336
+ * A prompt the person wrote themselves: not an agent's message, their answer to a question Main asked (in the terminal
337
+ * or the browser mirror) or its skip, what their decision on a plan adds (planDecision: its approval's "Implement the
338
+ * following plan.", their feedback), nor what ZTC adds to the conversation on its own.
339
+ */
340
+ function isPersonPrompt(message) {
341
+ const metadata = message.metadata;
342
+ return message.role === 'user' && message.content !== '__SKIP__' && !metadata?.busFrom && !metadata?.askUserAnswer
343
+ && !metadata?.planDecision && !metadata?.toolResult && !metadata?.synthetic && !metadata?.hostContext;
344
+ }
345
+ /** What Main wrote on ASKS, one pane's: the earlier turns' text the one with the longest record of them has, then TEXT. */
346
+ function writtenOn(asks, text) {
347
+ const earlier = asks.reduce((longest, ask) => ask.written.length > longest.length ? ask.written : longest, []);
348
+ return [...earlier, text].filter(part => part.length > 0).join('\n\n');
349
+ }
293
350
  /** What the browser mirror shows for a select. */
294
351
  function mirrorSelectOptions(options) {
295
352
  return {
@@ -329,6 +386,8 @@ const DEFAULT_INSTANCE_REGISTRY = {
329
386
  reapStopped: () => reapStoppedInstances(),
330
387
  };
331
388
  const INSTANCE_TITLE_TIMEOUT_MS = 2_000;
389
+ /** How long the owner waits for ZTerm to answer close_window: the person may be reading its close sheet. */
390
+ const WINDOW_CLOSE_TIMEOUT_MS = 120_000;
332
391
  const execFileAsync = promisify(execFile);
333
392
  async function resolveNavigatorInstanceTitle(cwd) {
334
393
  const fallback = cwd.split('/').pop() || 'ZTC';
@@ -631,6 +690,17 @@ export class RatatuiApp {
631
690
  busyScopeChoice = null;
632
691
  busyScopeChoicePending = false;
633
692
  pendingBusTrigger = false; // Bus message arrived while agent was busy — trigger runAgent after current run
693
+ /** A bus message that pendingBusTrigger waits on is in the conversation already, not only among agentPaneAsksWaiting. */
694
+ busMessageInConversation = false;
695
+ /**
696
+ * An agent's messages (ztc_message, but for the parent's control commands) that reached this ZTC on its parent's bus
697
+ * before it could take one, oldest first; null once it can, and in a ZTC that joins no parent's bus. A ZTC pane or a
698
+ * colony cell joins as it starts, and the mirror hands it at once what it held for it; startup then restores the
699
+ * session the pane resumes, which replaces its conversation, and last submits the task the pane was opened with. So
700
+ * they wait until startup is done and that task's turn has ended (admitWaitingAgentMessages): the pane's model gets
701
+ * the restored conversation and its task first, and each message after them, in the order they came.
702
+ */
703
+ waitingAgentMessages = null;
634
704
  // Queue state lives in the controller; this latch guards single-flight flush.
635
705
  flushingQueue = false;
636
706
  // A turn owns admission through startup and post-run persistence/compaction,
@@ -749,6 +819,11 @@ export class RatatuiApp {
749
819
  statusLinePanelWidget;
750
820
  colorPanelWidget;
751
821
  resumePanelWidget;
822
+ /** The Claude Code and Codex sessions picker (/claude resume, /codex sessions): Main's alone. */
823
+ agentSessionsPanelWidget;
824
+ agentSessionsControllerInstance = null;
825
+ /** Main's screen is read by no one until then, a moment after the sessions picker closes (mainScreenReadRefusal). */
826
+ mainScreenPrivateUntil = 0;
752
827
  navigatorPanelWidget;
753
828
  rewindPanelWidget;
754
829
  /**
@@ -864,6 +939,35 @@ export class RatatuiApp {
864
939
  childPaneIds = new Set();
865
940
  /** Panes running the user's own Claude Code or Codex, by pane id. */
866
941
  agentCliPanes = new Map();
942
+ /**
943
+ * The messages a Claude Code or Codex pane sent Main that Main owes an answer (answersAgentPane), by message id. The
944
+ * end of the work on one answers it (answerAgentPanes): the end of the turn that read it, or of the turns that go on
945
+ * with that work.
946
+ */
947
+ agentPaneAsks = new Map();
948
+ /**
949
+ * The messages agent panes sent Main that came while it was busy or waited on the person, in the order they came:
950
+ * they wait out of the conversation for a turn of their own (admitAgentPaneAsksWaiting), since the turn running, or
951
+ * the one that goes on from the person's reply, would read them with its own work and answer them with it.
952
+ */
953
+ agentPaneAsksWaiting = [];
954
+ /**
955
+ * Main's exchanges with the Claude Code and Codex panes it answers by itself (panes/reply_modes.ts): each one's reply
956
+ * mode, which the pane that started it chose or the person's default, and the automatic answers sent in it.
957
+ */
958
+ replyExchanges = new ReplyExchanges(() => replyModeSettings(configStore.get().panes).mode);
959
+ /**
960
+ * The messages agent panes sent Main after their exchange stopped, by pane, in the order they came: they wait out of the
961
+ * conversation for the person, whose next message here gives them a turn of their own (resumeAgentPaneExchanges).
962
+ */
963
+ agentPaneMessagesHeld = new Map();
964
+ /**
965
+ * Per agent pane, what Main still has to say to it once an arbitrator has decided on its answer: whatever Main says to
966
+ * that pane meanwhile goes in after it, in order.
967
+ */
968
+ agentPaneSaying = new Map();
969
+ /** The bus transport Main speaks on while it runs the workspace (overseerBusTransport); its answers go out on it. */
970
+ mainBusTransport = null;
867
971
  colonyPaneIds = new Set();
868
972
  /** Cache of latest pane list from pane_state events (including colony panes, filtered in switcher) */
869
973
  knownPanes = [];
@@ -1264,10 +1368,14 @@ export class RatatuiApp {
1264
1368
  { value: 'Deny', label: 'Deny', description: `Block ${request.toolName} for this request` },
1265
1369
  ],
1266
1370
  allowOther: false,
1371
+ // Closing it denies it; the line below says what that did, instead of the select's "Cancelled.".
1372
+ silentCancel: true,
1267
1373
  callback: (value) => {
1268
1374
  this.activeApprovalWidgetId = null;
1269
1375
  if (!this.pendingHookApprovals.has(headId))
1270
1376
  return;
1377
+ if (value === null)
1378
+ this.addSystemMessage(closedApprovalNotice(request));
1271
1379
  if (value === 'Approve') {
1272
1380
  this.resolveHookApproval(headId, { approved: true });
1273
1381
  return;
@@ -1487,6 +1595,10 @@ export class RatatuiApp {
1487
1595
  this.statusLinePanelWidget = new StatusLinePanelWidget(widgetHost);
1488
1596
  this.colorPanelWidget = new ColorPanelWidget(widgetHost);
1489
1597
  this.resumePanelWidget = new ResumePanelWidget(widgetHost);
1598
+ this.agentSessionsPanelWidget = new AgentSessionsPanelWidget(widgetHost);
1599
+ // The relay, read_terminal_pane and the mirror ask before reading pane 0, Main's screen (screen_privacy.ts).
1600
+ if (!this.paneMode)
1601
+ setPaneReadRefusal(paneId => this.mainScreenReadRefusal(paneId));
1490
1602
  this.navigatorPanelWidget = new NavigatorPanelWidget(widgetHost);
1491
1603
  this.rewindPanelWidget = new RewindPanelWidget(widgetHost);
1492
1604
  this.promptViewer = new PromptViewerWidget(widgetHost);
@@ -1552,8 +1664,8 @@ export class RatatuiApp {
1552
1664
  // incoming connections?" firewall prompt for every background ZTC.
1553
1665
  const autoHost = autoMirror ? '127.0.0.1' : undefined;
1554
1666
  this.mirrorServer = createMirrorStreamServer(this.pendingMirrorPort, this.shouldPersistSession(), this.sessionId, autoHost, this.sessionId);
1555
- // The desktop owner's mirror and a zmux owner's own silent one open panes and take typing only from a caller with
1556
- // a credential while sign-in is off; the link ZTC opens the browser with carries one.
1667
+ // The desktop owner's mirror and a zmux owner's own silent one answer only a caller with a credential while
1668
+ // sign-in is off, reads included; the link ZTC opens the browser with carries one.
1557
1669
  this.mirrorServer.setPaneControlCredentialRequired(mirrorPaneControlNeedsCredential({
1558
1670
  desktopMode: this.desktopMode, muxMode: this.muxMode, autoStarted: this.mirrorAutoStarted
1559
1671
  }));
@@ -1591,8 +1703,8 @@ export class RatatuiApp {
1591
1703
  // Enable multi-pane mode if running zmux
1592
1704
  if (this.muxMode) {
1593
1705
  this.mirrorServer.setMultiPaneMode(true, configStore.getModel(), configStore.getProvider());
1594
- // Register parent (Overseer) as bus member 0
1595
- this.mirrorServer.onBusMessage(0, 'Overseer', (msg) => {
1706
+ // Register parent (Main) as bus member 0
1707
+ this.mirrorServer.onBusMessage(0, this.mainBusMember().name, (msg) => {
1596
1708
  this.handleBusMessage(msg);
1597
1709
  });
1598
1710
  this.registerMirrorPaneFallbacks(this.mirrorServer);
@@ -1620,10 +1732,10 @@ export class RatatuiApp {
1620
1732
  if (paneId !== 0 && this.muxMode) {
1621
1733
  debugLog(`[Mirror] Routing widget answer to child pane ${paneId} via bus`);
1622
1734
  const payload = JSON.stringify({ __ztc_cmd: 'widget_answer', widget_id: widgetId, answer });
1623
- // A child takes control commands only from its parent (handleBusMessage), so this one speaks as the overseer.
1735
+ // A child takes control commands only from its parent (handleBusMessage), so this one speaks as Main.
1624
1736
  this.mirrorServer.deliverBusMessage({
1625
1737
  id: randomUUID(),
1626
- from: { id: OVERSEER_BUS_MEMBER_ID, name: 'Overseer' },
1738
+ from: this.mainBusMember(),
1627
1739
  to: paneId,
1628
1740
  type: 'ztc_message',
1629
1741
  text: payload,
@@ -1660,7 +1772,9 @@ export class RatatuiApp {
1660
1772
  this.mirrorClient = initMirrorClient(this.sessionId);
1661
1773
  if (this.mirrorClient) {
1662
1774
  debugLog(`[Mirror] Client initialized for pane ${process.env.ZTC_PANE_ID || '?'} -> port ${process.env.ZTC_MIRROR_PORT}`);
1663
- // Connect to bus for receiving messages from other ZTCs and browser
1775
+ // Connect to bus for receiving messages from other ZTCs and browser. An agent's message that comes before this ZTC
1776
+ // can take one waits for it (waitingAgentMessages).
1777
+ this.waitingAgentMessages = [];
1664
1778
  this.mirrorClient.connectToBus((msg) => {
1665
1779
  this.handleBusMessage(msg);
1666
1780
  });
@@ -1668,21 +1782,15 @@ export class RatatuiApp {
1668
1782
  setBusTransport(this.mirrorClient);
1669
1783
  }
1670
1784
  }
1671
- // Wire bus transport for send_message tool. The parent sends as the overseer through the mirror it runs at the time:
1672
- // the one it started with, or the one /mirror start started, whose bus its panes' mirror clients rejoin; never one
1673
- // /mirror stop stopped, whose bus is gone. While it runs none, the message is typed into the panes.
1674
- if (this.muxMode && !this.mirrorClient) {
1675
- setBusTransport({
1676
- sendBusMessage: (to, text, type = 'ztc_message') => {
1677
- const message = { id: randomUUID(), from: { id: 0, name: 'Overseer' }, to, type, text };
1678
- if (this.mirrorServer)
1679
- this.mirrorServer.deliverBusMessage(message);
1680
- else
1681
- this.typeOverseerMessage(message);
1682
- },
1683
- getPaneId() { return 0; },
1684
- getPaneName() { return 'Overseer'; },
1685
- });
1785
+ // Main's own bus transport: it sends as Main through the mirror it runs at the time, the one it started with, or the
1786
+ // one /mirror start started, whose bus its panes' mirror clients rejoin; never one /mirror stop stopped, whose bus is
1787
+ // gone. While it runs none, the message is typed into the panes. Its answers to the Claude Code and Codex panes in
1788
+ // its workspace go out on it, a colony cell's included. Its model's send_message speaks on it too, unless this ZTC
1789
+ // has a parent mirror client (a colony cell), whose model speaks on its parent's bus (above).
1790
+ if (this.muxMode) {
1791
+ this.mainBusTransport = overseerBusTransport(() => this.mirrorServer, message => this.typeOverseerMessage(message), () => this.mainBusMember().name);
1792
+ if (!this.mirrorClient)
1793
+ setBusTransport(this.answerFirstTransport(this.mainBusTransport));
1686
1794
  }
1687
1795
  // Set up the todo update callback
1688
1796
  setTodoUpdateCallback((todos) => {
@@ -1784,6 +1892,13 @@ export class RatatuiApp {
1784
1892
  defaultPaneTitle(paneId) {
1785
1893
  return paneId === 0 ? 'Main' : `ZTC ${paneId}`;
1786
1894
  }
1895
+ /**
1896
+ * Who this ZTC is on its bus while it runs the workspace: bus member 0, named as its pane is, "Main" or the name
1897
+ * /rename gave it, which list_panes and the pane's header give it too.
1898
+ */
1899
+ mainBusMember() {
1900
+ return { id: OVERSEER_BUS_MEMBER_ID, name: this.sessionName ?? this.defaultPaneTitle(OVERSEER_BUS_MEMBER_ID) };
1901
+ }
1787
1902
  ownPaneTitle() {
1788
1903
  const paneId = this.ownPaneId();
1789
1904
  if (paneId === null)
@@ -3596,6 +3711,10 @@ export class RatatuiApp {
3596
3711
  void this.openResumePanel(options);
3597
3712
  },
3598
3713
  },
3714
+ // The person's Claude Code and Codex sessions are Main's alone: never a pane's, the headless mirror's, the
3715
+ // agent's (ztc_command) or relayed input's, so none of those can list or look one up.
3716
+ ...(!this.paneMode && !this.headlessMirror && commandOrigin !== 'agent' && commandOrigin !== 'relayed'
3717
+ ? { agentSessions: this.agentSessions() } : {}),
3599
3718
  rewindPanel: {
3600
3719
  open: () => this.openRewindPanelWhenIdle(),
3601
3720
  },
@@ -3641,6 +3760,7 @@ export class RatatuiApp {
3641
3760
  || this.statusLinePanelWidget.isActive()
3642
3761
  || this.colorPanelWidget.isActive()
3643
3762
  || this.resumePanelWidget.isActive()
3763
+ || this.agentSessionsPanelWidget.isActive()
3644
3764
  || this.navigatorPanelWidget.isActive()
3645
3765
  || this.rewindPanelWidget.isActive();
3646
3766
  }
@@ -3751,7 +3871,7 @@ export class RatatuiApp {
3751
3871
  debugLog(`[Mirror] Server started on port ${actualPort}`);
3752
3872
  if (this.muxMode) {
3753
3873
  this.mirrorServer.setMultiPaneMode(true, configStore.getModel(), configStore.getProvider());
3754
- this.mirrorServer.onBusMessage(0, 'Overseer', (msg) => {
3874
+ this.mirrorServer.onBusMessage(0, this.mainBusMember().name, (msg) => {
3755
3875
  this.handleBusMessage(msg);
3756
3876
  });
3757
3877
  this.registerMirrorPaneFallbacks(this.mirrorServer);
@@ -3808,13 +3928,15 @@ export class RatatuiApp {
3808
3928
  return false;
3809
3929
  return typeLineIntoPane(this.tui, paneId, formatAgentPaneMessage(msg));
3810
3930
  });
3931
+ // A pane's message is checked for its reply mode first, and its sender told what became of it.
3932
+ server.onBusMessageCheck(msg => this.checkAgentPaneBusMessage(msg));
3811
3933
  }
3812
3934
  /**
3813
- * The overseer's MESSAGE while this ZTC runs no mirror (it started without one, or /mirror stop stopped it): there is
3814
- * no bus, so it is typed into the panes it is for. One for this ZTC itself reaches its own agent, as a mirror's member
3815
- * 0 hands it over. A Claude Code or Codex pane gets it as a mirror types it in (registerMirrorPaneFallbacks); any other
3816
- * pane, as the prompt "[Message from Overseer]: …". A broadcast reaches the ZTC panes, the members a bus would have,
3817
- * and no shell, which would run it as a command.
3935
+ * Main's MESSAGE while this ZTC runs no mirror (it started without one, or /mirror stop stopped it): there is no bus,
3936
+ * so it is typed into the panes it is for. One for this ZTC itself reaches its own agent, as a mirror's member 0
3937
+ * hands it over. A Claude Code or Codex pane gets it as a mirror types it in (registerMirrorPaneFallbacks); any other
3938
+ * pane, as the prompt "[Message from Main]: …", Main named as its pane is. A broadcast reaches the ZTC panes, the
3939
+ * members a bus would have, and no shell, which would run it as a command.
3818
3940
  */
3819
3941
  typeOverseerMessage(message) {
3820
3942
  if (message.to === OVERSEER_BUS_MEMBER_ID) {
@@ -3828,9 +3950,508 @@ export class RatatuiApp {
3828
3950
  if (this.agentCliPanes.has(paneId))
3829
3951
  typeLineIntoPane(this.tui, paneId, formatAgentPaneMessage(message));
3830
3952
  else
3831
- this.tui.send({ type: 'write_pane', pane_id: paneId, input: `[Message from Overseer]: ${message.text}`, submit: true });
3953
+ this.tui.send({ type: 'write_pane', pane_id: paneId, input: `[Message from ${message.from.name}]: ${message.text}`, submit: true });
3954
+ }
3955
+ }
3956
+ /**
3957
+ * Whether Main owes MSG an answer when the turn that reads it ends: a plain message for Main itself from a Claude Code
3958
+ * or Codex pane, whose agent hears only what is typed into it. One sent to every agent, a request that asks for a
3959
+ * reply with send_message, and a ZTC pane's or the browser's message get none.
3960
+ */
3961
+ answersAgentPane(msg) {
3962
+ return this.muxMode && !this.paneMode && msg.to === OVERSEER_BUS_MEMBER_ID && this.agentCliPanes.has(msg.from.id)
3963
+ && !process.env.ZTC_SIM_FREE_MODE && !msg.text.startsWith('{"__ztc_request":');
3964
+ }
3965
+ /**
3966
+ * The turn OWNER runs reads MESSAGES: each agent pane's message among them that no turn has read yet is its to answer,
3967
+ * as is one a turn before it passed on to it. One still owed after a turn that stopped for the person is the turn's
3968
+ * only when it goes on from their reply: a turn that brings a prompt of the person's own since then isn't, and that
3969
+ * pane hears its turn was interrupted instead.
3970
+ */
3971
+ adoptAgentPaneAsks(messages, owner) {
3972
+ if (this.agentPaneAsks.size === 0)
3973
+ return;
3974
+ const ids = new Set(messages.map(message => message.id));
3975
+ const movedOn = [];
3976
+ for (const [id, ask] of this.agentPaneAsks) {
3977
+ if (ask.turn !== null || !ids.has(id))
3978
+ continue;
3979
+ const waitedFrom = ask.waitedFrom;
3980
+ if (waitedFrom && messages.some(message => !waitedFrom.has(message.id) && isPersonPrompt(message))) {
3981
+ this.agentPaneAsks.delete(id);
3982
+ movedOn.push(ask);
3983
+ continue;
3984
+ }
3985
+ ask.turn = owner;
3986
+ delete ask.waitedFrom;
3987
+ delete ask.toldPaused;
3988
+ }
3989
+ this.tellAgentPanes(movedOn, { outcome: 'interrupted' });
3990
+ }
3991
+ /**
3992
+ * Main's wait on the person ended with nothing going on from it (WHY: they closed its question without answering it,
3993
+ * cancelled its plan or took it to edit): each agent pane whose message waited on them hears that Main stopped, and
3994
+ * why, and the message is no longer owed.
3995
+ */
3996
+ closeWaitingAgentPaneAsks(why) {
3997
+ const closed = [];
3998
+ for (const [id, ask] of this.agentPaneAsks) {
3999
+ if (ask.turn !== null || !ask.waitedFrom)
4000
+ continue;
4001
+ this.agentPaneAsks.delete(id);
4002
+ closed.push(ask);
4003
+ }
4004
+ this.tellAgentPanes(closed, { outcome: 'closed', why });
4005
+ }
4006
+ /**
4007
+ * Main's conversation no longer holds some messages agent panes sent it (/clear, /rewind): each pane whose owed
4008
+ * message no turn is working on any more hears that Main won't answer it.
4009
+ */
4010
+ dropClearedAgentPaneAsks() {
4011
+ const kept = new Set(this.controller.getState().messages.map(message => message.id));
4012
+ const dropped = [];
4013
+ for (const [id, ask] of this.agentPaneAsks) {
4014
+ if (ask.turn !== null || kept.has(id))
4015
+ continue;
4016
+ this.agentPaneAsks.delete(id);
4017
+ dropped.push(ask);
4018
+ }
4019
+ this.tellAgentPanes(dropped, { outcome: 'closed', why: 'cleared' });
4020
+ }
4021
+ /**
4022
+ * A turn couldn't start because this session is paused for a workspace overlap: each agent pane whose message waits
4023
+ * for it hears so, once, and its answer comes when the person continues the session (/sessions continue).
4024
+ */
4025
+ tellAgentPanesPaused() {
4026
+ if (!this.workspacePaused)
4027
+ return;
4028
+ const kept = new Set(this.controller.getState().messages.map(message => message.id));
4029
+ const told = [];
4030
+ for (const [id, ask] of this.agentPaneAsks) {
4031
+ if (ask.turn !== null || ask.toldPaused || !kept.has(id))
4032
+ continue;
4033
+ ask.toldPaused = true;
4034
+ told.push(ask);
4035
+ }
4036
+ this.tellAgentPanes(told, { outcome: 'waiting', on: 'workspace' });
4037
+ }
4038
+ /**
4039
+ * This process is about to hand Main to another session: every agent pane Main owes an answer, for a message it read
4040
+ * or one still waiting for its turn, hears that Main won't answer it, and its line is typed in before the hand-over.
4041
+ */
4042
+ async closeAgentPaneAsksForSwitch() {
4043
+ const waited = [...this.agentPaneAsksWaiting.splice(0), ...[...this.agentPaneMessagesHeld.values()].flat()];
4044
+ this.agentPaneMessagesHeld.clear();
4045
+ const owed = [...this.agentPaneAsks.values(),
4046
+ ...waited.map(msg => ({ messageId: msg.id, from: msg.from, turn: null, written: [], held: [] }))];
4047
+ this.agentPaneAsks.clear();
4048
+ if (owed.length === 0)
4049
+ return;
4050
+ this.tellAgentPanes(owed, { outcome: 'closed', why: 'session_switched' }, true);
4051
+ // What waits on an arbitrator's decision goes in first, for as long as typing gets.
4052
+ await Promise.race([Promise.allSettled([...this.agentPaneSaying.values()]), new Promise(resolve => setTimeout(resolve, 2000))]);
4053
+ await typingSettled(this.tui, 2000);
4054
+ }
4055
+ /**
4056
+ * The turn OWNER ran ended waiting on the person, for their answer to a question or their approval of a plan (ON):
4057
+ * each agent pane whose message it read hears so now. The messages stay owed, for the turn that goes on from the
4058
+ * person's reply (adoptAgentPaneAsks), as of the messages there are now, with what this turn wrote on them (TEXT) for
4059
+ * that turn's answer to carry, and what its model sent their panes, which follows that answer.
4060
+ */
4061
+ deferAgentPaneAsks(owner, on, text) {
4062
+ const waitedFrom = new Set(this.controller.getState().messages.map(message => message.id));
4063
+ const waiting = [];
4064
+ for (const ask of this.agentPaneAsks.values()) {
4065
+ if (ask.turn !== owner)
4066
+ continue;
4067
+ ask.turn = null;
4068
+ ask.waitedFrom = waitedFrom;
4069
+ if (text)
4070
+ ask.written.push(text);
4071
+ waiting.push(ask);
4072
+ }
4073
+ this.tellAgentPanes(waiting, { outcome: 'waiting', on });
4074
+ }
4075
+ /**
4076
+ * The turn OWNER ended with its work going on in a turn ZTC starts by itself: the plan turn its model asked for, the
4077
+ * turn that reads the person's steering, the next step of a /goal. Each of its agent panes' messages that KEEP picks
4078
+ * (every one, unless given) waits for that turn, with what this one wrote on it (TEXT) and what its model sent the
4079
+ * pane, and the pane hears nothing yet. GOAL_ID: the /goal that goes on with the work.
4080
+ */
4081
+ passAgentPaneAsks(owner, text, keep = () => true, goalId) {
4082
+ for (const ask of this.agentPaneAsks.values()) {
4083
+ if (ask.turn !== owner || !keep(ask))
4084
+ continue;
4085
+ ask.turn = null;
4086
+ if (text)
4087
+ ask.written.push(text);
4088
+ if (goalId)
4089
+ ask.goalId = goalId;
4090
+ }
4091
+ }
4092
+ /**
4093
+ * Main's bus transport as its model's tools use it (send_message, ask_ztc_pane), over INNER, Main's own
4094
+ * (mainBusTransport): a message for an agent pane the running turn owes an answer waits, to go out right after that
4095
+ * answer when the work on it ends, and the tool says so (a held send). Every other message goes out on INNER at once.
4096
+ * None passes for one of Main's answers.
4097
+ */
4098
+ answerFirstTransport(inner) {
4099
+ return {
4100
+ sendBusMessage: (to, sent, type) => {
4101
+ // An agent pane reads a message from Main that starts as Main's answers do as one (agentPaneAnswerText): what the
4102
+ // model sends one goes with a space in front, and is typed in as the message it is.
4103
+ const text = typeof to === 'number' && this.agentCliPanes.has(to) && sent.startsWith('{"__ztc_answer":') ? ` ${sent}` : sent;
4104
+ const owner = this.agentTurnOwner;
4105
+ const ask = owner && typeof to === 'number'
4106
+ ? [...this.agentPaneAsks.values()].find(candidate => candidate.turn === owner && candidate.from.id === to) : undefined;
4107
+ if (ask) {
4108
+ ask.held.push({ text, type });
4109
+ return { ok: true, held: true, notice: `Held: ${ask.from.name} (pane ${ask.from.id}) gets this right after your answer to its message.` };
4110
+ }
4111
+ // An answer of Main's to that pane still waits on an arbitrator's decision: this goes in after it.
4112
+ if (typeof to === 'number' && this.agentPaneSaying.has(to)) {
4113
+ this.afterAgentPaneSaying(to, () => { void inner.sendBusMessage(to, text, type); });
4114
+ return { ok: true, held: true, notice: `Held: ${this.agentPaneTitle(to)} (pane ${to}) gets this right after Main's answer to it, `
4115
+ + 'which waits for an arbitrator\'s decision.' };
4116
+ }
4117
+ return inner.sendBusMessage(to, text, type);
4118
+ },
4119
+ getPaneId: () => inner.getPaneId(),
4120
+ getPaneName: () => inner.getPaneName(),
4121
+ replyModes: this.replyModeHost(),
4122
+ };
4123
+ }
4124
+ /** What the messages Main's model sends the agent panes do to their exchanges with Main (BusTransport.replyModes). */
4125
+ replyModeHost() {
4126
+ return {
4127
+ refusal: mode => replyModeRefusal(mode, replyModeSettings(configStore.get().panes).arbitrators),
4128
+ answers: to => this.agentCliPanes.has(to),
4129
+ sent: (to, text, mode) => {
4130
+ const arrival = this.replyExchanges.arrive('main', to, text, mode);
4131
+ // A different mode from Main, which started the exchange, resumes it: what the pane sent meanwhile gets its turn.
4132
+ if (arrival.reset)
4133
+ this.releaseHeldAgentPaneMessages(to);
4134
+ // The model hears of the mode it gave; a message with none joins the exchange, or starts one, saying nothing.
4135
+ return mode === undefined ? '' : arrivalNote(arrival, this.agentPaneTitle(to), this.mainBusMember().name);
4136
+ },
4137
+ };
4138
+ }
4139
+ /** The name pane PANE_ID goes by, as list_panes gives it: its title, else its program's name. */
4140
+ agentPaneTitle(paneId) {
4141
+ const pane = this.knownPanes.find(candidate => candidate.id === paneId);
4142
+ const title = pane?.labels?.manual_title || pane?.title;
4143
+ if (title)
4144
+ return title;
4145
+ const cli = this.agentCliPanes.get(paneId);
4146
+ return cli ? AGENT_CLIS[cli].label : `pane ${paneId}`;
4147
+ }
4148
+ /**
4149
+ * What Main says of a message a pane posts to its mirror, before the mirror delivers it (onBusMessageCheck): a reply
4150
+ * mode that names an arbitrator the person didn't set up is refused; for an agent pane's message Main answers by itself,
4151
+ * the sender's send_message says what the message does to their exchange, or that Main holds it for the person.
4152
+ */
4153
+ checkAgentPaneBusMessage(msg) {
4154
+ if (msg.replyMode !== undefined) {
4155
+ const refused = replyModeRefusal(msg.replyMode, replyModeSettings(configStore.get().panes).arbitrators);
4156
+ if (refused)
4157
+ return { refuse: refused };
4158
+ }
4159
+ const main = this.mainBusMember().name;
4160
+ if (!this.answersAgentPane(msg) || process.env.ZTC_HUMAN_SIM_PANE === '1') {
4161
+ return msg.replyMode === undefined ? {}
4162
+ : { notice: `Its reply_mode wasn't applied: ${main} answers by itself only a Claude Code or Codex pane's message for it (pane 0).` };
4163
+ }
4164
+ const arrival = this.replyExchanges.preview('pane', msg.from.id, msg.replyMode);
4165
+ // A held message is always said, since no turn reads it; otherwise only a mode the message gave is spoken of.
4166
+ if (arrival.held)
4167
+ return { notice: heldNoticeForPane(arrival.view, main) };
4168
+ return msg.replyMode === undefined ? {} : { notice: arrivalNote(arrival, main, main) };
4169
+ }
4170
+ /** MSG, an agent pane's message that came after its exchange stopped, waits for the person, and pane 0 says so. */
4171
+ holdAgentPaneMessage(msg) {
4172
+ this.agentPaneMessagesHeld.set(msg.from.id, [...(this.agentPaneMessagesHeld.get(msg.from.id) ?? []), msg]);
4173
+ this.addSystemMessage(heldNotice(this.mainBusMember().name, msg.from.name, msg.from.id, msg.text));
4174
+ }
4175
+ /**
4176
+ * The exchange with pane PANE_ID stopped: its messages still waiting for a turn of their own wait for the person
4177
+ * instead, and nothing waits to start a turn for them alone.
4178
+ */
4179
+ holdWaitingAgentPaneMessages(paneId) {
4180
+ const waiting = this.agentPaneAsksWaiting.filter(msg => msg.from.id === paneId);
4181
+ if (waiting.length === 0)
4182
+ return;
4183
+ this.agentPaneAsksWaiting = this.agentPaneAsksWaiting.filter(msg => msg.from.id !== paneId);
4184
+ for (const msg of waiting)
4185
+ this.holdAgentPaneMessage(msg);
4186
+ if (this.agentPaneAsksWaiting.length === 0 && !this.busMessageInConversation)
4187
+ this.pendingBusTrigger = false;
4188
+ }
4189
+ /**
4190
+ * Pane PANE_ID closed: its messages still waiting for a turn of their own (agentPaneAsksWaiting) go, and nothing waits
4191
+ * to start a turn for them alone.
4192
+ */
4193
+ dropWaitingAgentPaneMessages(paneId) {
4194
+ const waiting = this.agentPaneAsksWaiting.length;
4195
+ this.agentPaneAsksWaiting = this.agentPaneAsksWaiting.filter(msg => msg.from.id !== paneId);
4196
+ if (this.agentPaneAsksWaiting.length === waiting)
4197
+ return;
4198
+ if (this.agentPaneAsksWaiting.length === 0 && !this.busMessageInConversation)
4199
+ this.pendingBusTrigger = false;
4200
+ }
4201
+ /**
4202
+ * The messages pane PANE_ID sent while its exchange was stopped (agentPaneMessagesHeld) wait for a turn of their own
4203
+ * now, as messages that came while Main was busy do. Returns whether there were any.
4204
+ */
4205
+ releaseHeldAgentPaneMessages(paneId) {
4206
+ const held = this.agentPaneMessagesHeld.get(paneId) ?? [];
4207
+ this.agentPaneMessagesHeld.delete(paneId);
4208
+ if (held.length === 0)
4209
+ return false;
4210
+ this.agentPaneAsksWaiting.push(...held);
4211
+ this.pendingBusTrigger = true;
4212
+ return true;
4213
+ }
4214
+ /**
4215
+ * The person sent Main a message of their own: every exchange with an agent pane starts its count again, and one that
4216
+ * had stopped goes on, saying so, its pane's held messages getting a turn of their own after the person's.
4217
+ */
4218
+ resumeAgentPaneExchanges() {
4219
+ const main = this.mainBusMember().name;
4220
+ for (const paneId of this.replyExchanges.person()) {
4221
+ const held = this.releaseHeldAgentPaneMessages(paneId);
4222
+ this.addSystemMessage(resumedNotice(main, this.agentPaneTitle(paneId), paneId, held));
4223
+ }
4224
+ }
4225
+ /** SAY runs once what Main is saying to pane PANE_ID now has gone in (agentPaneSaying), and what follows waits for it. */
4226
+ afterAgentPaneSaying(paneId, say) {
4227
+ const before = this.agentPaneSaying.get(paneId) ?? Promise.resolve();
4228
+ this.trackAgentPaneSaying(paneId, before.then(say));
4229
+ }
4230
+ /** SAYING is what Main is saying to pane PANE_ID until it settles. */
4231
+ trackAgentPaneSaying(paneId, saying) {
4232
+ const tracked = saying
4233
+ .catch(error => debugLog(`[Bus] answering pane ${paneId} failed: ${error instanceof Error ? error.message : String(error)}`))
4234
+ .finally(() => { if (this.agentPaneSaying.get(paneId) === tracked)
4235
+ this.agentPaneSaying.delete(paneId); });
4236
+ this.agentPaneSaying.set(paneId, tracked);
4237
+ }
4238
+ /** What the current turn wrote after PRE_RUN_IDS: its assistant text, in order, without reasoning or tool rows. */
4239
+ turnAnswerText(preRunIds) {
4240
+ return this.controller.getState().messages
4241
+ .filter(message => !preRunIds.has(message.id) && message.role === 'assistant' && message.metadata?.reasoning !== true
4242
+ && !isToolUsePlaceholderMessage(message) && message.content.trim().length > 0)
4243
+ .map(message => message.content.trim())
4244
+ .join('\n\n');
4245
+ }
4246
+ /**
4247
+ * The work on the agent panes' messages the turn OWNER read has ended with it: each of those panes hears ANSWER, once,
4248
+ * however many it sent, then what the model sent it meanwhile (answerFirstTransport).
4249
+ */
4250
+ answerAgentPanes(owner, answer) {
4251
+ const answered = [];
4252
+ for (const [id, ask] of this.agentPaneAsks) {
4253
+ if (ask.turn !== owner)
4254
+ continue;
4255
+ this.agentPaneAsks.delete(id);
4256
+ answered.push(ask);
4257
+ }
4258
+ this.tellAgentPanes(answered, answer);
4259
+ }
4260
+ /**
4261
+ * The pane of each of ASKS hears ANSWER, once however many of them it sent, once pane 0's transcript has reached the
4262
+ * renderer, so read_pane 0 holds what Main showed. An answer carries what Main wrote on those messages in earlier
4263
+ * turns ahead of its own text. Then the pane hears what Main's model sent it meanwhile (answerFirstTransport), which
4264
+ * keeps waiting, for the answer, while the messages wait on the person. A pane closed since hears nothing. An older
4265
+ * renderer, without the atomic transcript, has a turn's answer printed to scrollback only once the turn has finished
4266
+ * (until then it is in the live frame, a few rows high), so there the pane hears it just after (NOW: at once anyway).
4267
+ */
4268
+ tellAgentPanes(asks, answer, now = false) {
4269
+ if (asks.length === 0)
4270
+ return;
4271
+ if (now || this.isAtomicRebuildActive())
4272
+ this.sayToAgentPanes(asks, answer);
4273
+ else
4274
+ setTimeout(() => this.sayToAgentPanes(asks, answer), 0);
4275
+ }
4276
+ /** What tellAgentPanes says, now, or after what Main is still saying to a pane (agentPaneSaying). */
4277
+ sayToAgentPanes(asks, answer) {
4278
+ this.shipTranscriptNow();
4279
+ const byPane = new Map();
4280
+ for (const ask of asks)
4281
+ byPane.set(ask.from.id, [...(byPane.get(ask.from.id) ?? []), ask]);
4282
+ for (const [paneId, paneAsks] of byPane) {
4283
+ if (!this.agentCliPanes.has(paneId))
4284
+ continue;
4285
+ // Made as it goes in, so a cut answer's read_pane counts the rows pane 0 has then.
4286
+ const said = () => answer.outcome === 'answered' || answer.outcome === 'unfinished'
4287
+ ? { ...answer, text: writtenOn(paneAsks, answer.text), read: this.paneZeroReadFrom(paneAsks[0].messageId) } : answer;
4288
+ // What the model sent the pane meanwhile follows the answer; while the messages wait on the person, it waits too.
4289
+ const held = answer.outcome === 'waiting' ? [] : paneAsks.flatMap(ask => ask.held.splice(0));
4290
+ const from = paneAsks[0].from;
4291
+ if (this.agentPaneSaying.has(paneId)) {
4292
+ this.afterAgentPaneSaying(paneId, () => this.answerAgentPane(paneId, from, said, held));
4293
+ }
4294
+ else {
4295
+ const saying = this.answerAgentPane(paneId, from, said, held);
4296
+ if (saying)
4297
+ this.trackAgentPaneSaying(paneId, saying);
4298
+ }
3832
4299
  }
3833
4300
  }
4301
+ /**
4302
+ * Main's answer to agent pane PANE_ID (FROM), made by SAID, goes in as the reply mode of their exchange has it, then
4303
+ * HELD, what Main's model sent the pane meanwhile. A wait on the person, or an end with no answer to come, goes in as it
4304
+ * is: no automatic answer the person isn't in on. Otherwise it is the exchange's next automatic answer: it goes in,
4305
+ * the last its cap allows saying so, and pane 0 saying the exchange stopped; or, after the first, the arbitrator its
4306
+ * mode names decides first, pane 0 showing the decision, and the pane hears instead that the exchange stopped, and
4307
+ * why, unless it goes on (the promise returned is that decision's); or, once the exchange has stopped, it is not sent.
4308
+ * A cap the person's default was lowered to, below the answers already sent, stops it now: pane 0 says so, and the
4309
+ * pane hears that instead of the answer.
4310
+ */
4311
+ answerAgentPane(paneId, from, said, held) {
4312
+ const main = this.mainBusMember();
4313
+ const send = (answer) => {
4314
+ const text = agentPaneAnswerText(answer);
4315
+ void this.mainBusTransport?.sendBusMessage(paneId, text, 'ztc_message');
4316
+ return formatAgentPaneMessage({ from: main, text });
4317
+ };
4318
+ const sendHeld = () => {
4319
+ for (const message of held)
4320
+ void this.mainBusTransport?.sendBusMessage(paneId, message.text, message.type);
4321
+ };
4322
+ const first = said();
4323
+ if (first.outcome === 'waiting' || first.outcome === 'closed' || first.outcome === 'stopped') {
4324
+ send(first);
4325
+ sendHeld();
4326
+ return;
4327
+ }
4328
+ return this.deliverAgentPaneAnswer(paneId, from, first, said, send, sendHeld);
4329
+ }
4330
+ /**
4331
+ * ANSWER, Main's answer to agent pane PANE_ID (FROM; SAID makes it again as it goes in), as the exchange's gate has it
4332
+ * now (see answerAgentPane): SEND types it in, SEND_HELD what Main's model sent the pane meanwhile. A decision of an
4333
+ * arbitrator's that comes once the exchange's count has started again (the person's message, a new mode) is about a
4334
+ * count that no longer stands: pane 0 says so, and the answer goes as the exchange has it then.
4335
+ */
4336
+ deliverAgentPaneAnswer(paneId, from, answer, said, send, sendHeld) {
4337
+ const main = this.mainBusMember();
4338
+ const gate = this.replyExchanges.gate(paneId);
4339
+ if (gate.kind === 'withhold' && gate.lowered) {
4340
+ // A cap the person lowered below the answers already sent stops the exchange now: pane 0 says so before the pane
4341
+ // hears it instead of the answer, which stays in pane 0.
4342
+ const number = gate.view.answers + 1;
4343
+ this.addSystemMessage(capLoweredNotice(gate.view, main.name, from.name, paneId, number));
4344
+ this.shipTranscriptNow();
4345
+ send({ outcome: 'stopped', note: capLoweredStopForPane(gate.view, main.name, number) });
4346
+ this.holdWaitingAgentPaneMessages(paneId);
4347
+ sendHeld();
4348
+ return;
4349
+ }
4350
+ if (gate.kind === 'withhold') {
4351
+ this.addSystemMessage(withheldNotice(gate.view, main.name, from.name, paneId));
4352
+ this.holdWaitingAgentPaneMessages(paneId);
4353
+ sendHeld();
4354
+ return;
4355
+ }
4356
+ if (gate.kind === 'send') {
4357
+ if (!gate.last) {
4358
+ this.replyExchanges.answered(paneId, send(answer));
4359
+ sendHeld();
4360
+ return;
4361
+ }
4362
+ // The cap's answer: pane 0 says the exchange stopped before the pane hears it, so read_pane 0 shows that too.
4363
+ this.replyExchanges.stop(paneId, { why: 'cap', cap: gate.number });
4364
+ this.addSystemMessage(capStopNotice(gate.view, main.name, from.name, paneId, gate.number));
4365
+ this.shipTranscriptNow();
4366
+ const last = said();
4367
+ this.replyExchanges.answered(paneId, send({ ...last, exchangeNote: capNoteForPane(gate.view, main.name, gate.number) }));
4368
+ this.holdWaitingAgentPaneMessages(paneId);
4369
+ sendHeld();
4370
+ return;
4371
+ }
4372
+ const summary = arbitrationSummary({ main: main.name, pane: from.name }, gate.view.answers, [...this.replyExchanges.recent(paneId), { from: 'main', text: formatAgentPaneMessage({ from: main, text: agentPaneAnswerText(answer) }) }], this.arbitratorSecrets());
4373
+ return askArbitrator(gate.arbitrator, summary, { config: configStore.get(), cwd: this.shellCwd || process.cwd() })
4374
+ .catch((error) => ({ ok: false, why: `asking it failed (${error instanceof Error ? error.message : String(error)})` }))
4375
+ .then(outcome => {
4376
+ if (this.exiting || !this.agentCliPanes.has(paneId))
4377
+ return;
4378
+ if (!this.replyExchanges.isCurrent(paneId, gate.epoch)) {
4379
+ this.addSystemMessage(staleArbitrationNotice(gate.arbitrator, outcome, main.name, from.name, paneId, gate.number));
4380
+ return this.deliverAgentPaneAnswer(paneId, from, said(), said, send, sendHeld);
4381
+ }
4382
+ const goesOn = outcome.ok && outcome.decision.continue;
4383
+ if (!goesOn) {
4384
+ this.replyExchanges.stop(paneId, outcome.ok
4385
+ ? { why: 'arbitrator', arbitrator: gate.arbitrator, reason: outcome.decision.reason }
4386
+ : { why: 'arbitrator_failed', arbitrator: gate.arbitrator, error: outcome.why });
4387
+ }
4388
+ this.addSystemMessage(arbitrationNotice(gate.view, gate.arbitrator, outcome, main.name, from.name, paneId, gate.number));
4389
+ this.shipTranscriptNow();
4390
+ if (goesOn) {
4391
+ this.replyExchanges.answered(paneId, send(said()));
4392
+ }
4393
+ else {
4394
+ send({ outcome: 'stopped', note: arbitrationStopForPane(gate.view, gate.arbitrator, outcome, main.name, gate.number) });
4395
+ this.holdWaitingAgentPaneMessages(paneId);
4396
+ }
4397
+ sendHeld();
4398
+ });
4399
+ }
4400
+ /**
4401
+ * The credentials no arbitrator reads (knownSecrets): those ZTC's settings and environment hold, and the profile's Zerg
4402
+ * Router sign-in as router-auth.json holds it now, whether or not it has expired.
4403
+ */
4404
+ arbitratorSecrets() {
4405
+ let routerToken;
4406
+ try {
4407
+ routerToken = readRouterCredentialsSync()?.token;
4408
+ }
4409
+ catch {
4410
+ // An unreadable sign-in file gives no token to leave out.
4411
+ }
4412
+ return knownSecrets(configStore.get(), process.env, [routerToken]);
4413
+ }
4414
+ /**
4415
+ * How read_pane 0 reads the work on the message MESSAGE_ID whole: with as many lines as pane 0 has rows from that
4416
+ * message to the end, every answer shown in full, and its live frame below (LINES); and, while the person's reading
4417
+ * cap still reveals some of it, about how long the rest takes (REVEAL_SECONDS).
4418
+ */
4419
+ paneZeroReadFrom(messageId) {
4420
+ const state = this.controller.getState();
4421
+ const display = resolveMessageDisplaySettings(configStore.get());
4422
+ const configKey = this.transcriptConfigKey(display);
4423
+ const messages = this.materializeToolOutputMessages(state.messages, state.expandToolOutputs);
4424
+ let lines = this.rows;
4425
+ let unrevealedWords = 0;
4426
+ for (const message of messages.slice(Math.max(0, messages.findIndex(candidate => candidate.id === messageId)))) {
4427
+ if (message.metadata?.steeringPending === true)
4428
+ continue;
4429
+ const rendered = this.transcriptRenderCache.render(message, configKey);
4430
+ if (rendered.lines.length > 0)
4431
+ lines += rendered.lines.length + 1;
4432
+ const tracked = this.streamTypewriters.get(message.id);
4433
+ if (tracked && this.hasPendingProseReveal(message)) {
4434
+ unrevealedWords += message.content.slice(tracked.shown).split(/\s+/).filter(Boolean).length;
4435
+ }
4436
+ }
4437
+ const rate = display.proseReadingRateWordsPerSecond;
4438
+ return rate !== null && unrevealedWords > 0 ? { lines, revealSeconds: Math.ceil(unrevealedWords / rate) } : { lines };
4439
+ }
4440
+ /** Ship pane 0's transcript to the renderer now, outside the rebuild throttle, so read_pane 0 holds what is shown. */
4441
+ shipTranscriptNow() {
4442
+ if (!this.isAtomicRebuildActive()) {
4443
+ this._bypassThrottleOnce = true;
4444
+ this.render();
4445
+ return;
4446
+ }
4447
+ if (this.transcriptRebuildTimer) {
4448
+ clearTimeout(this.transcriptRebuildTimer);
4449
+ this.transcriptRebuildTimer = null;
4450
+ }
4451
+ this.transcriptDirty = false;
4452
+ this.transcriptLastRebuildAt = Date.now();
4453
+ this.rebuildTranscript();
4454
+ }
3834
4455
  resolveOwnQuestion(questionId) {
3835
4456
  if (this.activeQuestionId !== questionId)
3836
4457
  return false;
@@ -3841,8 +4462,8 @@ export class RatatuiApp {
3841
4462
  }
3842
4463
  handleQuestionAnswer(answer, paneId, questionId) {
3843
4464
  if (paneId !== 0 && this.muxMode) {
3844
- // Relayed as the overseer: a child takes control commands only from its parent (handleBusMessage).
3845
- this.mirrorServer?.deliverBusMessage({ id: randomUUID(), from: { id: OVERSEER_BUS_MEMBER_ID, name: 'Overseer' }, to: paneId,
4465
+ // Relayed as Main: a child takes control commands only from its parent (handleBusMessage).
4466
+ this.mirrorServer?.deliverBusMessage({ id: randomUUID(), from: this.mainBusMember(), to: paneId,
3846
4467
  type: 'ztc_message', text: JSON.stringify({ __ztc_cmd: 'ask_user_answer', question_id: questionId, answer }) });
3847
4468
  return;
3848
4469
  }
@@ -3916,8 +4537,8 @@ export class RatatuiApp {
3916
4537
  }
3917
4538
  handleApprovalAnswer(id, decision, reason, paneId = 0) {
3918
4539
  if (paneId !== 0 && this.muxMode) {
3919
- // Relayed as the overseer: a child takes control commands only from its parent (handleBusMessage).
3920
- this.mirrorServer?.deliverBusMessage({ id: randomUUID(), from: { id: OVERSEER_BUS_MEMBER_ID, name: 'Overseer' }, to: paneId,
4540
+ // Relayed as Main: a child takes control commands only from its parent (handleBusMessage).
4541
+ this.mirrorServer?.deliverBusMessage({ id: randomUUID(), from: this.mainBusMember(), to: paneId,
3921
4542
  type: 'ztc_message', text: JSON.stringify({ __ztc_cmd: 'hook_approval', id, decision, reason }) });
3922
4543
  return;
3923
4544
  }
@@ -4347,6 +4968,8 @@ export class RatatuiApp {
4347
4968
  hidden: false,
4348
4969
  cwd: registrationCwd,
4349
4970
  zmuxSocketPath,
4971
+ // Another ZTC's navigator opens neither the logs nor the page of a mirror that answers only this ZTC's link.
4972
+ mirrorNeedsLink: this.mirrorServer?.isPaneControlCredentialRequired() === true,
4350
4973
  });
4351
4974
  if (!zmuxSocketPath && this.muxMode && !this.desktopMode) {
4352
4975
  this.tui.onZmuxMirrorSocketReady((path) => {
@@ -5162,7 +5785,7 @@ export class RatatuiApp {
5162
5785
  }
5163
5786
  // Wire bus for multi-pane mode (register parent as member 0 if not already)
5164
5787
  if (this.muxMode) {
5165
- this.mirrorServer.onBusMessage(0, 'Overseer', (msg) => {
5788
+ this.mirrorServer.onBusMessage(0, this.mainBusMember().name, (msg) => {
5166
5789
  this.handleBusMessage(msg);
5167
5790
  });
5168
5791
  }
@@ -5172,7 +5795,7 @@ export class RatatuiApp {
5172
5795
  // mode so that navigator-originated browser visits can send messages.
5173
5796
  debugLog(`[Mirror] Auto-started silent mirror on port ${this.mirrorServer.getPort()}`);
5174
5797
  if (this.muxMode) {
5175
- this.mirrorServer.onBusMessage(0, 'Overseer', (msg) => {
5798
+ this.mirrorServer.onBusMessage(0, this.mainBusMember().name, (msg) => {
5176
5799
  this.handleBusMessage(msg);
5177
5800
  });
5178
5801
  }
@@ -5491,13 +6114,16 @@ export class RatatuiApp {
5491
6114
  });
5492
6115
  }
5493
6116
  }
6117
+ // The task this ZTC was started with, submitted once startup is done. It goes first: an agent's message that came
6118
+ // meanwhile waits for its turn to end (admitWaitingAgentMessages).
6119
+ let launchTask = null;
5494
6120
  if (this.paneMode && process.env.ZTC_INITIAL_PANE_INPUT) {
5495
6121
  try {
5496
6122
  this.initialPaneInput = await loadPaneInitialInput(process.env.ZTC_INITIAL_PANE_INPUT, this.sessionId);
5497
6123
  this.assertStartupActive();
5498
6124
  if (this.initialPaneInput) {
5499
6125
  const input = this.initialPaneInput.input;
5500
- setTimeout(() => void this.handleSubmit(input, undefined, undefined, true), 0);
6126
+ launchTask = () => this.handleSubmit(input, undefined, undefined, true);
5501
6127
  }
5502
6128
  }
5503
6129
  catch (error) {
@@ -5513,14 +6139,19 @@ export class RatatuiApp {
5513
6139
  }
5514
6140
  else if (this.initialPromptAsMessage) {
5515
6141
  // An agent's task: a message to this pane's agent, word for word, which no one entered here.
5516
- setTimeout(() => void this.handleSubmit(prompt, undefined, undefined, true), 0);
6142
+ launchTask = () => this.handleSubmit(prompt, undefined, undefined, true);
5517
6143
  }
5518
6144
  else {
5519
- setTimeout(() => {
5520
- void this.submitPersonInput(prompt);
5521
- }, 0);
6145
+ launchTask = () => this.submitPersonInput(prompt);
5522
6146
  }
5523
6147
  }
6148
+ if (launchTask) {
6149
+ const submit = launchTask;
6150
+ setTimeout(() => { void submit().finally(() => this.admitWaitingAgentMessages()); }, 0);
6151
+ }
6152
+ else {
6153
+ this.admitWaitingAgentMessages();
6154
+ }
5524
6155
  // `ztc resume` with no target opens the picker instead of silently taking
5525
6156
  // the most recent session. Runs after the first frame so the page paints on
5526
6157
  // top of a live UI; the initial prompt path above is skipped for the picker.
@@ -6100,6 +6731,11 @@ export class RatatuiApp {
6100
6731
  if (spec)
6101
6732
  this.registerPaneSpec(pane.id, spec.paneType, spec.title, spec.launchSpec);
6102
6733
  }
6734
+ }, (paneId, session) => {
6735
+ // A saved Claude Code or Codex pane runs again on its session, as the person's /claude resume opens it.
6736
+ const sessions = this.agentSessions();
6737
+ return resumeSavedAgentPane(this.tui, paneId, session, sessions, { cwdNow: this.shellCwd || process.cwd(),
6738
+ deps: { findBinary: id => this.installedAgentClis()[id] ?? null, motsi: this.paneMotsi() } });
6103
6739
  });
6104
6740
  }
6105
6741
  formatTime(date) {
@@ -6120,6 +6756,54 @@ export class RatatuiApp {
6120
6756
  });
6121
6757
  });
6122
6758
  }
6759
+ /**
6760
+ * Ask ZTerm to close tab WINDOW_ID and the panes in it, as the person's ×, middle-click, Close Tab and close-tab key do
6761
+ * (workspace spec §5.2). With CONFIRMED the owner has already asked the person, so ZTerm shows no close sheet. Resolves
6762
+ * with ZTerm's window_closed for this request: closed; partly_closed, with the panes it kept (pinned panes, and Main's);
6763
+ * cancelled, when the person cancelled its sheet; or refused (Main's tab, the only tab, a tab it doesn't have), in its
6764
+ * words. Sends nothing to a renderer without desktop_close_window_v1. Rejects on an error ZTerm names for the request,
6765
+ * and when it hasn't answered within WINDOW_CLOSE_TIMEOUT_MS.
6766
+ *
6767
+ * A timeout is not a cancel. ZTerm's sheet has no deadline: the person can still close the tab after this rejects, and
6768
+ * its late window_closed reaches no caller (the saved workspace still drops the tab, as on every window_closed). While
6769
+ * that sheet is up, ZTerm refuses any other unconfirmed close that would ask ("Another tab's close is waiting for an
6770
+ * answer"). So a caller must not report the tab as kept when this times out; say it may yet close.
6771
+ */
6772
+ closeWindow(windowId, options = {}) {
6773
+ if (!Number.isInteger(windowId) || windowId < 0 || windowId > 0xffff_ffff) {
6774
+ return Promise.reject(new Error(`There's no tab ${String(windowId)}.`));
6775
+ }
6776
+ if (!this.tui.hasCapability(CAPABILITY_DESKTOP_CLOSE_WINDOW)) {
6777
+ return Promise.reject(new Error(this.desktopMode
6778
+ ? 'Closing a tab needs a newer ZTerm: update the desktop app.'
6779
+ : 'Closing a tab needs the desktop app.'));
6780
+ }
6781
+ const requestId = `close-window-${randomUUID()}`;
6782
+ return new Promise((resolve, reject) => {
6783
+ const timer = setTimeout(() => {
6784
+ unsubscribe();
6785
+ reject(new Error(`ZTerm didn't say within ${WINDOW_CLOSE_TIMEOUT_MS / 60_000} minutes whether it closed tab ${windowId}.`));
6786
+ }, WINDOW_CLOSE_TIMEOUT_MS);
6787
+ timer.unref?.();
6788
+ const unsubscribe = this.tui.on(event => {
6789
+ if (event.type === 'window_closed' && event.request_id === requestId) {
6790
+ clearTimeout(timer);
6791
+ unsubscribe();
6792
+ resolve(event);
6793
+ }
6794
+ else if (event.type === 'error' && event.request_id === requestId) {
6795
+ clearTimeout(timer);
6796
+ unsubscribe();
6797
+ reject(new Error(`ZTerm didn't close tab ${windowId}: ${event.message}`));
6798
+ }
6799
+ });
6800
+ if (!this.tui.send({ type: 'close_window', window_id: windowId, request_id: requestId, confirmed: options.confirmed === true })) {
6801
+ clearTimeout(timer);
6802
+ unsubscribe();
6803
+ reject(new Error(`ZTerm couldn't be reached to close tab ${windowId}.`));
6804
+ }
6805
+ });
6806
+ }
6123
6807
  /**
6124
6808
  * Emergency mux snapshot captured synchronously during SIGTERM/SIGINT,
6125
6809
  * before child process 'close' events delete panes from the manager.
@@ -6512,7 +7196,7 @@ export class RatatuiApp {
6512
7196
  if (this.mirrorServer) {
6513
7197
  this.mirrorServer.deliverBusMessage({
6514
7198
  id: randomUUID(),
6515
- from: { id: 0, name: 'Overseer' },
7199
+ from: this.mainBusMember(),
6516
7200
  to: command.pane_id,
6517
7201
  type: 'ztc_message',
6518
7202
  text: hotSwapPayload,
@@ -6572,7 +7256,7 @@ export class RatatuiApp {
6572
7256
  if (this.mirrorServer) {
6573
7257
  this.mirrorServer.deliverBusMessage({
6574
7258
  id: randomUUID(),
6575
- from: { id: 0, name: 'Overseer' },
7259
+ from: this.mainBusMember(),
6576
7260
  to: command.pane_id,
6577
7261
  type: 'ztc_message',
6578
7262
  text: JSON.stringify({ __ztc_cmd: 'set_effort', model: command.model, provider: command.provider, effort }),
@@ -6773,6 +7457,9 @@ export class RatatuiApp {
6773
7457
  if (!this.muxMode || this.paneMode) {
6774
7458
  return { ok: false, error: 'pane viewport unavailable' };
6775
7459
  }
7460
+ const refused = paneReadRefusal(paneId);
7461
+ if (refused !== null)
7462
+ return { ok: false, error: refused };
6776
7463
  const eventPromise = this.waitForTuiEvent((event) => event.type === 'pane_read' && event.pane_id === paneId && event.viewport === true, 4000);
6777
7464
  const sent = this.tui.send({ type: 'read_pane', pane_id: paneId, viewport: true, ansi });
6778
7465
  if (!sent) {
@@ -7099,6 +7786,7 @@ export class RatatuiApp {
7099
7786
  this.workspacePausedQueueId = null;
7100
7787
  this.workspaceDeferredRun = false;
7101
7788
  this.controller.clearMessages();
7789
+ this.dropClearedAgentPaneAsks();
7102
7790
  this.printedMessageIds.clear();
7103
7791
  this.pendingScrollbackLines = [];
7104
7792
  this.pendingScrollbackIds.clear();
@@ -7297,6 +7985,13 @@ export class RatatuiApp {
7297
7985
  this.transcriptDirty = true;
7298
7986
  this.transcriptLastRebuildAt = 0;
7299
7987
  }
7988
+ /**
7989
+ * Everything a rendered message depends on besides the message itself, as the transcript's render cache keys it. A
7990
+ * change here (resize, thinking visibility) invalidates every entry.
7991
+ */
7992
+ transcriptConfigKey(display) {
7993
+ return `${this.cols}|${display.showThinking ? 1 : 0}|${display.showTurnMetadata ? 1 : 0}|${this.showsLaunchWordmark() ? 1 : 0}`;
7994
+ }
7300
7995
  /**
7301
7996
  * Atomic transcript rebuild: render every message via
7302
7997
  * `messageToScrollbackLines` and ship the entire transcript in one
@@ -7312,9 +8007,7 @@ export class RatatuiApp {
7312
8007
  rebuildTranscript() {
7313
8008
  const state = this.controller.getState();
7314
8009
  const display = resolveMessageDisplaySettings(configStore.get());
7315
- // Everything a rendered message depends on besides the message itself.
7316
- // A change here (resize, thinking visibility) invalidates every entry.
7317
- const configKey = `${this.cols}|${display.showThinking ? 1 : 0}|${display.showTurnMetadata ? 1 : 0}|${this.showsLaunchWordmark() ? 1 : 0}`;
8010
+ const configKey = this.transcriptConfigKey(display);
7318
8011
  const allLines = [];
7319
8012
  const fingerprint = [];
7320
8013
  for (const msg of this.materializeToolOutputMessages(state.messages, state.expandToolOutputs)) {
@@ -7445,7 +8138,8 @@ export class RatatuiApp {
7445
8138
  const msgs = this.controller.getState().messages.slice(0, initialMessageCount);
7446
8139
  let lastUser = null;
7447
8140
  for (let i = msgs.length - 1; i >= 0; i--) {
7448
- if (msgs[i].role === 'user') {
8141
+ // The note after an agent pane's message is the host's, not the request (its "the text you write" reads as one).
8142
+ if (msgs[i].role === 'user' && msgs[i].metadata?.agentPaneNote !== true) {
7449
8143
  lastUser = msgs[i].content;
7450
8144
  break;
7451
8145
  }
@@ -7820,6 +8514,11 @@ export class RatatuiApp {
7820
8514
  case 'window_switched':
7821
8515
  this.currentMuxWindow = event.window_id;
7822
8516
  break;
8517
+ case 'window_closed':
8518
+ // ZTerm closed a tab, or didn't: the person's own close, or its answer to closeWindow. Each pane it closed came
8519
+ // first as pane_closed; the layout is saved at once, as for a closed pane, so a closed tab stays closed.
8520
+ this.scheduleMuxPersistenceSave(0);
8521
+ break;
7823
8522
  case 'show_pane_picker':
7824
8523
  // Fire-and-forget: the picker itself awaits session-preview reads
7825
8524
  // in parallel with a hard per-file timeout, so the user sees the
@@ -7903,6 +8602,11 @@ export class RatatuiApp {
7903
8602
  this.childPaneSessionIds.delete(event.pane_id);
7904
8603
  this.colonyPaneIds.delete(event.pane_id);
7905
8604
  this.agentCliPanes.delete(event.pane_id);
8605
+ // Its exchange with Main ends, and what Main held of it, or kept for a turn of its own, goes with it: no turn
8606
+ // runs for a pane that is gone. A pane that takes its number starts its own exchange.
8607
+ this.replyExchanges.closed(event.pane_id);
8608
+ this.agentPaneMessagesHeld.delete(event.pane_id);
8609
+ this.dropWaitingAgentPaneMessages(event.pane_id);
7906
8610
  this.paneRegistry.remove(event.pane_id);
7907
8611
  if (this.mirrorServer) {
7908
8612
  this.mirrorServer.unregisterPane(event.pane_id);
@@ -7961,7 +8665,7 @@ export class RatatuiApp {
7961
8665
  this.processInputBuffer();
7962
8666
  }
7963
8667
  clipboardInputTarget() {
7964
- const widgets = [this.promptViewer, this.logViewWidget, this.resumePanelWidget,
8668
+ const widgets = [this.promptViewer, this.logViewWidget, this.resumePanelWidget, this.agentSessionsPanelWidget,
7965
8669
  this.navigatorPanelWidget, this.rewindPanelWidget, this.statusLinePanelWidget,
7966
8670
  this.colorPanelWidget, this.settingsPanelWidget, this.questionnaireWidget,
7967
8671
  this.formWidget, this.selectWidget, this.textInputWidget];
@@ -8085,6 +8789,11 @@ export class RatatuiApp {
8085
8789
  this.resumePanelWidget.handleInput(input, key);
8086
8790
  return;
8087
8791
  }
8792
+ // Handle the Claude Code and Codex sessions picker (full-page; owns Enter/Esc)
8793
+ if (this.agentSessionsPanelWidget.isActive()) {
8794
+ this.agentSessionsPanelWidget.handleInput(input, key);
8795
+ return;
8796
+ }
8088
8797
  // Handle navigator panel input (full-page attach picker; owns Enter/Esc)
8089
8798
  if (this.navigatorPanelWidget.isActive()) {
8090
8799
  this.navigatorPanelWidget.handleInput(input, key);
@@ -8834,11 +9543,15 @@ export class RatatuiApp {
8834
9543
  return existsSync(path) ? { previewPath: path } : {};
8835
9544
  };
8836
9545
  // Seed from all remoteInstances (including local colony children) keyed by paneId.
9546
+ // A mirror an instance says answers only its own link opens no logs from here (see openNavigatorPanel).
9547
+ const linkOnlyPorts = new Set();
8837
9548
  for (const inst of remoteInstances) {
8838
9549
  if (inst.mirrorPort) {
8839
9550
  if (inst.paneId !== undefined)
8840
9551
  logPortMap.set(`ztc:${inst.paneId}`, inst.mirrorPort);
8841
9552
  logPortMap.set(`mirror:${inst.pid}`, inst.mirrorPort);
9553
+ if (inst.mirrorNeedsLink === true)
9554
+ linkOnlyPorts.add(inst.mirrorPort);
8842
9555
  }
8843
9556
  }
8844
9557
  const options = [];
@@ -9124,6 +9837,7 @@ export class RatatuiApp {
9124
9837
  colonyState,
9125
9838
  mirrorTargets,
9126
9839
  logPortMap,
9840
+ linkOnlyPorts,
9127
9841
  restoreValue,
9128
9842
  });
9129
9843
  }
@@ -9135,7 +9849,7 @@ export class RatatuiApp {
9135
9849
  * ZTC list uses (fuzzy filter, windowing, footer key legend).
9136
9850
  */
9137
9851
  openNavigatorPanel(context) {
9138
- const { options, logPortMap, restoreValue } = context;
9852
+ const { options, logPortMap, linkOnlyPorts, restoreValue } = context;
9139
9853
  this.retireClipboardPaste();
9140
9854
  this.clipboardTargetRevision += 1;
9141
9855
  this.navigatorPanelWidget.show({
@@ -9172,16 +9886,12 @@ export class RatatuiApp {
9172
9886
  return;
9173
9887
  }
9174
9888
  const label = value.startsWith('mirror:') ? (options.find(o => o.value === value)?.label?.trim() ?? value) : value;
9175
- this.logViewWidget.show({
9176
- title: label,
9177
- fetch: async (since) => {
9178
- const resp = await fetch(`http://localhost:${port}/debug/logs?since=${since}`);
9179
- if (!resp.ok)
9180
- return { lines: [], total: since };
9181
- const data = await resp.json();
9182
- return { lines: data.lines, total: data.total };
9183
- },
9184
- }, backToNavigator);
9889
+ // Its mirror answers only the link its own ZTC gives: say where its logs open, rather than show none.
9890
+ if (linkOnlyPorts.has(port)) {
9891
+ this.addSystemMessage(linkOnlyLogsNotice(context.mirrorTargets.get(value)?.title ?? label), { ephemeral: true });
9892
+ return;
9893
+ }
9894
+ this.logViewWidget.show(remoteMirrorLogSource(label, port), backToNavigator);
9185
9895
  this.render();
9186
9896
  },
9187
9897
  },
@@ -9350,7 +10060,11 @@ export class RatatuiApp {
9350
10060
  type: 'attach_mirror',
9351
10061
  socket_path: inst.zmuxSocketPath,
9352
10062
  });
9353
- if (!sent) {
10063
+ if (!sent && inst.mirrorNeedsLink === true) {
10064
+ debugLog(`[Navigator] attach_mirror dispatch failed; ${inst.title}'s mirror answers only its own link`);
10065
+ this.addSystemMessage(`Could not attach. ${linkOnlyPageNotice(inst.title)}`, { ephemeral: true });
10066
+ }
10067
+ else if (!sent) {
9354
10068
  debugLog(`[Navigator] attach_mirror dispatch failed; falling back to browser`);
9355
10069
  this.addSystemMessage(`Could not attach. Opening ${inst.title} in browser instead.`, { ephemeral: true });
9356
10070
  const port = inst.mirrorPort;
@@ -9366,6 +10080,11 @@ export class RatatuiApp {
9366
10080
  this.addSystemMessage(`Attaching to ${inst.title}… (Ctrl+\\ to detach)`, { ephemeral: true });
9367
10081
  }
9368
10082
  }
10083
+ else if (inst.mirrorPort && inst.mirrorNeedsLink === true) {
10084
+ // No zmux socket (the desktop app), and a mirror that answers only its own ZTC's link: its bare address loads
10085
+ // nothing, so say where it opens.
10086
+ this.addSystemMessage(linkOnlyPageNotice(inst.title), { ephemeral: true });
10087
+ }
9369
10088
  else if (inst.mirrorPort) {
9370
10089
  // Legacy / headless fallback: no zmux socket, open browser.
9371
10090
  const port = inst.mirrorPort;
@@ -9430,6 +10149,12 @@ export class RatatuiApp {
9430
10149
  this.handleSubmit({ text: msg.text, attachments: msg.attachments || [] }, undefined, undefined, false, false, fromBrowser, msg.via === 'broadcast' ? 'broadcast' : fromBrowser ? 'browser' : 'terminal');
9431
10150
  }
9432
10151
  else if (msg.type === 'ztc_message') {
10152
+ // An agent's message waits until this ZTC can take one (admitWaitingAgentMessages); its parent's control commands
10153
+ // never do.
10154
+ if (this.waitingAgentMessages && !(fromParent && msg.text.startsWith('{"__ztc_cmd":'))) {
10155
+ this.waitingAgentMessages.push(msg);
10156
+ return;
10157
+ }
9433
10158
  // Intercept structured control commands from parent (model hot-swap, widget answers).
9434
10159
  if (msg.text.startsWith('{"__ztc_cmd":')) {
9435
10160
  if (!fromParent) {
@@ -9504,14 +10229,31 @@ export class RatatuiApp {
9504
10229
  if (process.env.ZTC_SIM_FREE_MODE && msg.from.id === 0) {
9505
10230
  beginSimTurn(messageText);
9506
10231
  }
10232
+ // A Claude Code or Codex pane hears only what is typed into it: Main answers its message when the turn that reads
10233
+ // it ends, and its model is told so (addAgentMessage).
10234
+ const asker = !humanSimPane && this.answersAgentPane(msg) ? msg.from : null;
10235
+ if (asker) {
10236
+ // The message joins its pane's exchange with Main, with the reply mode it carries (panes/reply_modes.ts). One that
10237
+ // comes after the exchange stopped waits for the person; a different mode from the pane that started it starts
10238
+ // it over, and what the pane sent while it was stopped goes first.
10239
+ const arrival = this.replyExchanges.arrive('pane', asker.id, msg.text, msg.replyMode);
10240
+ if (arrival.held) {
10241
+ this.holdAgentPaneMessage(msg);
10242
+ return;
10243
+ }
10244
+ if (arrival.reset && this.releaseHeldAgentPaneMessages(asker.id)) {
10245
+ this.agentPaneAsksWaiting.push(msg);
10246
+ this.runAgentPaneAsksWaiting();
10247
+ return;
10248
+ }
10249
+ }
10250
+ if (asker && (this.isAgentBusy() || this.pendingAskUser || this.pendingPlanApproval)) {
10251
+ this.agentPaneAsksWaiting.push(msg);
10252
+ this.pendingBusTrigger = true;
10253
+ return;
10254
+ }
9507
10255
  // From another ZTC — add with attribution metadata, trigger agent turn
9508
- const metadata = { busFrom: msg.from };
9509
- this.controller.addMessage({
9510
- role: 'user',
9511
- content: messageText,
9512
- metadata,
9513
- });
9514
- this.mirror?.publishMessage('user', displayText, metadata);
10256
+ this.addAgentMessage(msg, messageText, displayText, asker);
9515
10257
  if (humanSimPane) {
9516
10258
  return;
9517
10259
  }
@@ -9521,6 +10263,8 @@ export class RatatuiApp {
9521
10263
  if (busy) {
9522
10264
  debugLog(`[Bus] Agent busy (${state.agentState.status}), deferring runAgent for bus message from ${msg.from.name}`);
9523
10265
  this.pendingBusTrigger = true;
10266
+ // In the conversation already: its turn is due whatever becomes of the agent panes' waiting messages.
10267
+ this.busMessageInConversation = true;
9524
10268
  return;
9525
10269
  }
9526
10270
  const preRunLength = this.controller.getState().messages.length;
@@ -9563,6 +10307,60 @@ export class RatatuiApp {
9563
10307
  }
9564
10308
  }
9565
10309
  }
10310
+ /**
10311
+ * Add MSG, an agent's message for this ZTC, to the conversation as MESSAGE_TEXT, which pane 0 and the mirror show as
10312
+ * DISPLAY_TEXT. One from an agent pane Main answers (ASKER) is owed an answer, and Main's model reads right after it
10313
+ * who sent it and how its answer goes back: the note is the host's, and the transcript leaves it out
10314
+ * (isHostPromptMessage).
10315
+ */
10316
+ addAgentMessage(msg, messageText, displayText, asker) {
10317
+ const metadata = { busFrom: msg.from };
10318
+ this.controller.addMessage({ role: 'user', content: messageText, metadata });
10319
+ const added = asker
10320
+ ? [...this.controller.getState().messages].reverse().find(message => message.metadata === metadata) : undefined;
10321
+ if (asker && added) {
10322
+ this.agentPaneAsks.set(added.id, { messageId: added.id, from: asker, turn: null, written: [], held: [] });
10323
+ // A colony cell's model speaks on its parent's bus: what it sends reaches the colony, not this pane.
10324
+ this.controller.addMessage({ role: 'user', content: agentPaneNoteForModel(asker, !this.mirrorClient),
10325
+ metadata: { synthetic: true, hostContext: true, agentPaneNote: true } });
10326
+ }
10327
+ this.mirror?.publishMessage('user', displayText, metadata);
10328
+ }
10329
+ /**
10330
+ * The agent panes' messages that waited for Main (agentPaneAsksWaiting) go into the conversation, in order, now.
10331
+ * Returns whether there were any.
10332
+ */
10333
+ admitAgentPaneAsksWaiting() {
10334
+ const waiting = this.agentPaneAsksWaiting.splice(0);
10335
+ for (const msg of waiting)
10336
+ this.addAgentMessage(msg, msg.text, msg.text, msg.from);
10337
+ return waiting.length > 0;
10338
+ }
10339
+ /**
10340
+ * The agent panes' messages that waited for Main get their turn now, if Main is free and nothing else is about to
10341
+ * start one: a wait the person closed with nothing after it leaves the queue paused, and its dispatch with it.
10342
+ */
10343
+ runAgentPaneAsksWaiting() {
10344
+ if (this.agentPaneAsksWaiting.length === 0 || this.exiting || this.isAgentBusy() || this.pendingAgentTurn
10345
+ || this.pendingAskUser || this.pendingPlanApproval)
10346
+ return;
10347
+ this.pendingBusTrigger = false;
10348
+ this.busMessageInConversation = false;
10349
+ this.admitAgentPaneAsksWaiting();
10350
+ void this.runAgent();
10351
+ }
10352
+ /**
10353
+ * From now on this ZTC takes an agent's message as it comes; take those that waited (waitingAgentMessages), in the
10354
+ * order they came, after the conversation startup restored and the turn of the task it was started with.
10355
+ */
10356
+ admitWaitingAgentMessages() {
10357
+ const waiting = this.waitingAgentMessages ?? [];
10358
+ this.waitingAgentMessages = null;
10359
+ if (this.exiting)
10360
+ return;
10361
+ for (const msg of waiting)
10362
+ void this.handleBusMessage(msg);
10363
+ }
9566
10364
  /**
9567
10365
  * Collapse the input to a single text segment with the cursor at `offset`.
9568
10366
  * Used by completion (slash / path / @-mention) which operates on plain text.
@@ -9827,10 +10625,15 @@ export class RatatuiApp {
9827
10625
  return;
9828
10626
  }
9829
10627
  if (route.type === 'command') {
9830
- this.mirror?.publishMessage('user', redactCredentialCommand(text));
10628
+ // The mirror records it without a key or a session of the person's (redactMirroredCommand); it runs as typed.
10629
+ this.mirror?.publishMessage('user', redactMirroredCommand(text));
9831
10630
  await this.handleCommand(route.cmd, route.args, false, origin);
9832
10631
  return;
9833
10632
  }
10633
+ // A message of the person's own starts the count of every exchange with an agent pane again, and one that had
10634
+ // stopped goes on (panes/reply_modes.ts).
10635
+ if (origin === undefined)
10636
+ this.resumeAgentPaneExchanges();
9834
10637
  // Regular message - send to agent once the route it would use can reach a model.
9835
10638
  const sendRoute = this.resolveSendRoute();
9836
10639
  if (sendRoute.awaitingChoice !== undefined) {
@@ -10559,8 +11362,14 @@ export class RatatuiApp {
10559
11362
  this.busyScopeChoicePending = false;
10560
11363
  } while (choice === 'defer');
10561
11364
  if (this.exiting || epoch !== this.busyInputEpoch || choice === null) {
10562
- if (!this.exiting)
10563
- this.restoreBusyDraft(input);
11365
+ const kept = this.exiting ? null : this.restoreBusyDraft(input);
11366
+ // The person closed the chooser, which only the live frame drew: the transcript names it, and says where their
11367
+ // message went (the select's own "Cancelled." is left out).
11368
+ if (kept && choice === null && epoch === this.busyInputEpoch) {
11369
+ this.addSystemMessage(kept === 'composer'
11370
+ ? 'Closed the Separate task chooser: your message wasn\'t sent, and it\'s back in the composer.'
11371
+ : 'Closed the Separate task chooser: your message wasn\'t sent; it\'s kept above as unsent input.');
11372
+ }
10564
11373
  return;
10565
11374
  }
10566
11375
  if (choice !== 'steer') {
@@ -10656,7 +11465,7 @@ export class RatatuiApp {
10656
11465
  this.busyScopeChoice = choice;
10657
11466
  const ctx = this.buildCommandContext(message => this.controller.addMessage(message));
10658
11467
  ctx.select.showSelect({ title: 'Separate task', question: 'This looks like a separate task. Where should it run?',
10659
- type: 'select', allowOther: false,
11468
+ type: 'select', allowOther: false, silentCancel: true,
10660
11469
  options: [
10661
11470
  { value: 'pane', label: 'New pane', description: 'Start the task in a separate agent pane' },
10662
11471
  { value: 'session', label: 'New session', description: 'Start a fresh session in a separate window' },
@@ -10677,20 +11486,24 @@ export class RatatuiApp {
10677
11486
  this.busyScopeChoice?.finish(null);
10678
11487
  return pending;
10679
11488
  }
10680
- /** Restore only an empty composer; retain a competing draft in the transcript. */
11489
+ /** Restore only an empty composer; retain a competing draft in the transcript. Says where it went, if anywhere. */
10681
11490
  restoreBusyDraft(input, retainOnly = false) {
10682
11491
  if (this.exiting)
10683
- return;
11492
+ return null;
10684
11493
  const empty = this.inputState.segments.length === 0 || this.inputState.segments.every(segment => segment.type === 'text' && segment.text.length === 0);
11494
+ let kept;
10685
11495
  if (!retainOnly && empty && !this.routingInteractionOccupied() && input.attachments.every(attachment => attachment.localPath)) {
10686
11496
  this.restoreComposerAfterRewind(input.text, input.attachments);
11497
+ kept = 'composer';
10687
11498
  }
10688
11499
  else {
10689
11500
  this.controller.addMessage({ role: 'system', content: `Unsent input retained:\n${input.text}`,
10690
11501
  attachments: input.attachments, metadata: { unsentDraft: true } });
10691
11502
  this.mirror?.publishMessage('system', `Unsent input retained:\n${input.text}`, input.attachments.length ? { attachments: input.attachments } : undefined);
11503
+ kept = 'transcript';
10692
11504
  }
10693
11505
  this.render();
11506
+ return kept;
10694
11507
  }
10695
11508
  /**
10696
11509
  * `routerAttempt`: the steering takes the person's one real attempt past a Zerg Router refusal (see
@@ -10826,6 +11639,7 @@ export class RatatuiApp {
10826
11639
  // Direct plan/bus/queued continuations share this final admission gate.
10827
11640
  if (!await this.guardWorkspaceAdmission()) {
10828
11641
  this.workspaceDeferredRun = true;
11642
+ this.tellAgentPanesPaused();
10829
11643
  return;
10830
11644
  }
10831
11645
  if (!this.isHostedRuntime())
@@ -10882,6 +11696,7 @@ export class RatatuiApp {
10882
11696
  if (this.waitingInteraction?.owner === owner) {
10883
11697
  this.waitingInteraction = null;
10884
11698
  this.dispatchPendingAgentWork();
11699
+ this.runAgentPaneAsksWaiting();
10885
11700
  }
10886
11701
  }
10887
11702
  };
@@ -10889,15 +11704,19 @@ export class RatatuiApp {
10889
11704
  completeBrowserAskUserAnswer(answer) {
10890
11705
  if (this.waitingInteraction?.kind !== 'ask-user')
10891
11706
  return;
10892
- this.controller.addMessage({ role: 'user', content: answer });
11707
+ // An answer is one, as the terminal's is; a skip is its own marker.
11708
+ this.controller.addMessage({ role: 'user', content: answer, ...(answer === '__SKIP__' ? {} : { metadata: { askUserAnswer: true } }) });
10893
11709
  this.mirror?.publishMessage('user', answer, { isAskUserAnswer: true });
10894
11710
  this.waitingInteraction = null;
10895
11711
  if (answer === '__SKIP__') {
10896
11712
  this.queuePaused = true;
11713
+ // Nothing goes on from a skip here: an agent pane whose message waited on the question hears so.
11714
+ this.closeWaitingAgentPaneAsks('question_skipped');
10897
11715
  }
10898
11716
  else {
10899
11717
  this.requestAgentTurn();
10900
11718
  }
11719
+ this.runAgentPaneAsksWaiting();
10901
11720
  }
10902
11721
  /** Parent-routed answers are distinct from ordinary input on the pane bus. */
10903
11722
  acceptChildAskUserAnswer(answer) {
@@ -10953,6 +11772,8 @@ export class RatatuiApp {
10953
11772
  }
10954
11773
  if (this.pendingBusTrigger) {
10955
11774
  this.pendingBusTrigger = false;
11775
+ this.busMessageInConversation = false;
11776
+ this.admitAgentPaneAsksWaiting();
10956
11777
  void this.runAgent();
10957
11778
  return;
10958
11779
  }
@@ -11041,8 +11862,13 @@ export class RatatuiApp {
11041
11862
  const detail = error instanceof Error ? error.message : String(error);
11042
11863
  debugLog(`[runAgent] startup failed: ${detail}`);
11043
11864
  this.addErrorMessage(`Unable to start agent turn: ${detail}`);
11865
+ // The turn would have read every message there is now; an agent pane that sent one hears why it didn't run.
11866
+ this.adoptAgentPaneAsks(this.controller.getState().messages, owner);
11867
+ this.answerAgentPanes(owner, { outcome: 'failed', error: `Unable to start agent turn: ${detail}` });
11044
11868
  return;
11045
11869
  }
11870
+ // This turn reads what it admitted: an agent pane's message among them gets its answer when the turn ends.
11871
+ this.adoptAgentPaneAsks(admittedMessages, owner);
11046
11872
  const human = [...this.controller.getState().messages].reverse().find(message => message.role === 'user' && !message.metadata?.toolResult && !message.metadata?.synthetic);
11047
11873
  if (!this.activePromptTurn || (!isRetry && !this.nextTurnAutomaticGoal && human && human.id !== this.activePromptTurn.snapshot().id)) {
11048
11874
  this.beginPromptTurn(human?.id ?? generateId());
@@ -11075,6 +11901,8 @@ export class RatatuiApp {
11075
11901
  }
11076
11902
  // Snapshot message count before the run so we can roll back on cancel
11077
11903
  const preRunMessageCount = this.controller.getState().messages.length;
11904
+ // What was here before the run: the rest is what this turn shows, its answer to an agent pane (turnAnswerText).
11905
+ const preRunIds = new Set(this.controller.getState().messages.map(message => message.id));
11078
11906
  const checkpointTurn = ++this.toolCheckpointTurn;
11079
11907
  let historyCheckpoint = [];
11080
11908
  // The answer an attempt showed before the agent withdrew it (stream_reset). It stays shown until the agent says what
@@ -11434,8 +12262,10 @@ export class RatatuiApp {
11434
12262
  }
11435
12263
  }
11436
12264
  catch (err) {
11437
- if (this.agentTurnOwner !== owner || this.activeToolCheckpointHandler !== checkpointHandler)
12265
+ if (this.agentTurnOwner !== owner || this.activeToolCheckpointHandler !== checkpointHandler) {
12266
+ this.answerAgentPanes(owner, { outcome: 'interrupted' });
11438
12267
  return;
12268
+ }
11439
12269
  // Zerg Router lost the stream on every attempt: the answer the last one showed stays, finished, where it streamed,
11440
12270
  // and the next message continues from it. Any other error withdraws it, as a retry would have.
11441
12271
  const lostStream = err instanceof StreamLostError;
@@ -11495,6 +12325,7 @@ export class RatatuiApp {
11495
12325
  this.stopSpinner();
11496
12326
  this.mirror?.publishStreamEnd();
11497
12327
  this.mirror?.publishStatus('error');
12328
+ this.answerAgentPanes(owner, { outcome: 'failed', error: errorMsg });
11498
12329
  setTimeout(() => {
11499
12330
  if (this.toolCheckpointTurn !== checkpointTurn || this.agentTurnOwner || this.waitingInteraction)
11500
12331
  return;
@@ -11520,8 +12351,10 @@ export class RatatuiApp {
11520
12351
  }
11521
12352
  // Cancellation can expose a new prompt before a held tool finishes. Its
11522
12353
  // terminal source was saved by its bound handler; newer UI work owns cleanup.
11523
- if (this.agentTurnOwner !== owner || this.toolCheckpointTurn !== checkpointTurn)
12354
+ if (this.agentTurnOwner !== owner || this.toolCheckpointTurn !== checkpointTurn) {
12355
+ this.answerAgentPanes(owner, { outcome: 'interrupted' });
11524
12356
  return;
12357
+ }
11525
12358
  // Close tool groups, including any interrupted calls.
11526
12359
  this.flushLocalStreamDelta();
11527
12360
  this.finishLocalStreamingMessages();
@@ -11564,8 +12397,12 @@ export class RatatuiApp {
11564
12397
  }
11565
12398
  if (observedTurnTokens > 0)
11566
12399
  this.accountGoalFinalTurn(null, observedTurnTokens);
12400
+ this.answerAgentPanes(owner, { outcome: 'interrupted' });
11567
12401
  return;
11568
12402
  }
12403
+ // Why this turn's answer, if it wrote one, isn't finished: it stopped at the iteration limit, or ZTC flagged it as a
12404
+ // claim its tools don't show. An agent pane whose message it read hears that with it.
12405
+ let unfinished = null;
11569
12406
  if (result) {
11570
12407
  // The agent's ordered tool-use/result/steering messages are the source of
11571
12408
  // truth for a steered turn. The normal display path collapses all tool
@@ -11661,6 +12498,7 @@ export class RatatuiApp {
11661
12498
  // when the agent streamed commentary before its final tool call.
11662
12499
  if (result.stopReason === 'max_iterations') {
11663
12500
  this.addSystemMessage('Agent reached the configured iteration limit. The task is unfinished. Send a message to continue.');
12501
+ unfinished = 'iteration_limit';
11664
12502
  }
11665
12503
  const newMessages = this.controller.getState().messages.slice(initialMessageCount);
11666
12504
  // Reasoning is not an answer: with thinking hidden, a turn of reasoning alone shows the person nothing.
@@ -11682,6 +12520,7 @@ export class RatatuiApp {
11682
12520
  : message));
11683
12521
  }
11684
12522
  this.addSystemMessage(claimObservationWarning(basis));
12523
+ unfinished ??= basis === 'no_tool_calls' ? 'claimed_without_tools' : 'claimed_despite_errors';
11685
12524
  if (sourceIndex >= 0)
11686
12525
  await this.saveCurrentSession(true);
11687
12526
  }
@@ -11735,6 +12574,16 @@ export class RatatuiApp {
11735
12574
  this.controller.setToast(loginTip, ROUTER_TIP_TOAST_MS);
11736
12575
  // Write last assistant response for evolution conductor to read
11737
12576
  this.maybeWritePaneResponse();
12577
+ // What this turn wrote on the agent panes' messages it read, taken before compaction can rewrite the transcript, and
12578
+ // its answer to them, once nothing goes on with this work.
12579
+ const turnText = this.turnAnswerText(preRunIds);
12580
+ const turnAnswer = unfinished ? { outcome: 'unfinished', reason: unfinished, text: turnText }
12581
+ : { outcome: 'answered', text: turnText };
12582
+ // An agent pane whose message this turn read hears now that the turn waits on the person (a question or a plan to
12583
+ // approve), and the turn that goes on from their reply answers it. Otherwise it hears its answer once nothing goes
12584
+ // on with this work (below): the work may go on in a turn ZTC starts by itself.
12585
+ if (this.pendingAskUser || this.pendingPlanApproval)
12586
+ this.deferAgentPaneAsks(owner, this.pendingAskUser ? 'question' : 'plan', turnText);
11738
12587
  // Check if auto-compaction is needed after agent completes
11739
12588
  await this.maybeAutoCompact();
11740
12589
  // Process any pending background agent events
@@ -11757,15 +12606,21 @@ export class RatatuiApp {
11757
12606
  catch (error) {
11758
12607
  const detail = error instanceof Error ? error.message : String(error);
11759
12608
  debugLog(`[runAgent] plan transition rebuild failed: ${detail}`);
11760
- this.addErrorMessage(`Plan mode activated, but the artifact-safe plan agent could not be created: ${detail}`);
12609
+ const failure = `Plan mode activated, but the artifact-safe plan agent could not be created: ${detail}`;
12610
+ this.addErrorMessage(failure);
12611
+ this.answerAgentPanes(owner, { outcome: 'failed', error: failure });
11761
12612
  return;
11762
12613
  }
11763
12614
  if (!this.agent
11764
12615
  || this.agentBuiltForMode !== 'plan'
11765
12616
  || this.agentBuiltForPlanFile !== this.controller.getPlanFile()) {
11766
- this.addErrorMessage('Plan mode activated, but the artifact-safe plan agent could not be created.');
12617
+ const failure = 'Plan mode activated, but the artifact-safe plan agent could not be created.';
12618
+ this.addErrorMessage(failure);
12619
+ this.answerAgentPanes(owner, { outcome: 'failed', error: failure });
11767
12620
  return;
11768
12621
  }
12622
+ // The plan turn goes on with this work: it answers the agent panes' messages this turn read.
12623
+ this.passAgentPaneAsks(owner, turnText);
11769
12624
  this.requestAgentTurn();
11770
12625
  return;
11771
12626
  }
@@ -11779,14 +12634,23 @@ export class RatatuiApp {
11779
12634
  // Process pending bus trigger — bus message was already added to controller,
11780
12635
  // just need to trigger runAgent() now that the agent is idle
11781
12636
  if (this.pendingBusTrigger) {
12637
+ const inConversation = this.busMessageInConversation;
11782
12638
  this.pendingBusTrigger = false;
12639
+ this.busMessageInConversation = false;
11783
12640
  debugLog(`[Bus] Draining pending bus trigger — starting deferred runAgent()`);
11784
- this.requestAgentTurn();
11785
- return;
12641
+ this.answerAgentPanes(owner, turnAnswer);
12642
+ // That answer may have stopped an exchange, and the messages its pane sent meanwhile wait for the person now: a turn
12643
+ // starts only for what is left, and with nothing left this turn ends as any other does.
12644
+ if (this.admitAgentPaneAsksWaiting() || inConversation) {
12645
+ this.requestAgentTurn();
12646
+ return;
12647
+ }
11786
12648
  }
11787
12649
  // A prompt sent during inference had no later tool boundary. Its user
11788
- // message is already in the transcript; start a fresh turn with it now.
12650
+ // message is already in the transcript; start a fresh turn with it now. It
12651
+ // steers this work, so that turn answers the agent panes' messages this one read.
11789
12652
  if (needsSteeringTurn) {
12653
+ this.passAgentPaneAsks(owner, turnText);
11790
12654
  this.requestAgentTurn();
11791
12655
  return;
11792
12656
  }
@@ -11799,17 +12663,28 @@ export class RatatuiApp {
11799
12663
  // Flushing is also subscribed to idle transitions in start().
11800
12664
  const processedQueue = this.controller.getQueue().length > 0 || this.maybeFlushQueue();
11801
12665
  if (strandedSubturn) {
12666
+ // Entered during this turn to reach it soon, it goes on with this work, as steering does.
12667
+ this.passAgentPaneAsks(owner, turnText);
11802
12668
  void this.handleSubmit({ text: strandedSubturn.text, attachments: strandedSubturn.attachments || [] }, undefined, undefined, false, false, strandedSubturn.person === true, strandedSubturn.via ?? 'terminal');
11803
12669
  return;
11804
12670
  }
11805
12671
  // If nothing the user queued is taking the next turn, let an active /goal
11806
12672
  // drive the next step. Queued user input always wins, so the goal only
11807
12673
  // continues when the queue is empty.
11808
- if (!processedQueue) {
11809
- this.maybeContinueGoal(result, scopedGoalDecision);
12674
+ const goal = !processedQueue && this.maybeContinueGoal(result, scopedGoalDecision) ? goalManager.get() : null;
12675
+ // The goal's next turn goes on with an agent pane's message when the goal was set while Main worked on it: in this
12676
+ // turn, or in one before that passed it on. A goal that was already driving when this turn began is the person's,
12677
+ // and the pane hears this turn's answer now.
12678
+ if (goal) {
12679
+ const setMeanwhile = this.turnStartGoal.goalId !== goal.goalId || this.turnStartGoal.status !== 'active';
12680
+ this.passAgentPaneAsks(owner, turnText, ask => setMeanwhile || ask.goalId === goal.goalId, goal.goalId);
11810
12681
  }
12682
+ this.answerAgentPanes(owner, turnAnswer);
11811
12683
  }
11812
12684
  finally {
12685
+ // A turn that ended some other way, by an error in what follows its run, tells the agent panes whose messages it
12686
+ // still owes an answer that it was interrupted, instead of leaving them waiting.
12687
+ this.answerAgentPanes(owner, { outcome: 'interrupted' });
11813
12688
  this.syncPromptTurn(this.streamingPromptTurn ?? promptTurn, initialMessageCount);
11814
12689
  for (const turn of promptTurns) {
11815
12690
  if (turn.snapshot().state === 'running')
@@ -11884,12 +12759,6 @@ export class RatatuiApp {
11884
12759
  if (accounted)
11885
12760
  this.postGoalNote(goalFinalNote(accounted));
11886
12761
  }
11887
- /**
11888
- * Account the just-finished turn against the active /goal and, if it should
11889
- * keep going, re-submit a continuation prompt (which re-enters runAgent and
11890
- * eventually lands back here — the loop). All stop conditions live in
11891
- * goalManager.onTurnComplete; this method only reacts to the decision.
11892
- */
11893
12762
  /**
11894
12763
  * Point the R7 task pin at the goal that is now driving.
11895
12764
  *
@@ -11904,10 +12773,17 @@ export class RatatuiApp {
11904
12773
  if (task)
11905
12774
  this.agent?.setPinnedTask(task);
11906
12775
  }
12776
+ /**
12777
+ * Account the just-finished turn against the active /goal and, if it should
12778
+ * keep going, re-submit a continuation prompt (which re-enters runAgent and
12779
+ * eventually lands back here — the loop). All stop conditions live in
12780
+ * goalManager.onTurnComplete; this method only reacts to the decision. It
12781
+ * says whether it started the goal's next turn.
12782
+ */
11907
12783
  maybeContinueGoal(result, scopedGoalDecision) {
11908
12784
  const goal = goalManager.get();
11909
12785
  if (!goal)
11910
- return;
12786
+ return false;
11911
12787
  const turnText = result?.content ?? '';
11912
12788
  // A turn counts as real work if it called a tool OR said anything (text or
11913
12789
  // reasoning) — Codex's `has_activity`. Without the text half, a turn that
@@ -11922,7 +12798,7 @@ export class RatatuiApp {
11922
12798
  // accountGoalFinalTurn, which runs in the turn-end hook above every early
11923
12799
  // return; here we only handle the active case.
11924
12800
  if (goal.status !== 'active')
11925
- return;
12801
+ return false;
11926
12802
  // Re-pin the task when a different goal starts driving. The kick path pins on
11927
12803
  // set/resume; this covers an agent-set goal whose kick was dropped, and guards
11928
12804
  // against a stale pin carried over from a previous goal.
@@ -11935,7 +12811,7 @@ export class RatatuiApp {
11935
12811
  const done = goalManager.complete({ turnTokens });
11936
12812
  if (done)
11937
12813
  this.postGoalNote(goalFinalNote(done));
11938
- return;
12814
+ return false;
11939
12815
  }
11940
12816
  // Provider-agnostic blocker: the agent ended the turn saying it is stuck.
11941
12817
  // Pausing here is the difference between the user deciding what to do next and
@@ -11944,7 +12820,7 @@ export class RatatuiApp {
11944
12820
  const blocked = goalManager.block(goalBlockedReason(turnText), { turnTokens });
11945
12821
  if (blocked)
11946
12822
  this.postGoalNote(goalFinalNote(blocked));
11947
- return;
12823
+ return false;
11948
12824
  }
11949
12825
  const decision = scopedGoalDecision ?? goalManager.onTurnComplete({
11950
12826
  ...(detectGoalBlocked(turnText) ? { blockedReason: goalBlockedReason(turnText) } : {}),
@@ -11959,7 +12835,7 @@ export class RatatuiApp {
11959
12835
  evidence: this.agent?.getEvidenceSnapshot(),
11960
12836
  });
11961
12837
  if (decision.kind === 'idle')
11962
- return;
12838
+ return false;
11963
12839
  if (decision.kind === 'continue') {
11964
12840
  this.postGoalNote(decision.note);
11965
12841
  // Defer through handleSubmit so the continuation gets normal queue/busy
@@ -11967,10 +12843,11 @@ export class RatatuiApp {
11967
12843
  // Goal-launched: this continuation is the loop driving itself.
11968
12844
  this.nextTurnAutomaticGoal = true;
11969
12845
  setTimeout(() => void this.handleSubmit(decision.prompt), 0);
11970
- return;
12846
+ return true;
11971
12847
  }
11972
12848
  // decision.kind === 'stop'
11973
12849
  this.postGoalNote(decision.note);
12850
+ return false;
11974
12851
  }
11975
12852
  /** Post a /goal status line to both the terminal transcript and the mirror. */
11976
12853
  publishCurrentGoal() {
@@ -12622,7 +13499,7 @@ export class RatatuiApp {
12622
13499
  }
12623
13500
  const cmdText = `/${cmd}${cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''}`;
12624
13501
  if (publishUserMessage) {
12625
- this.mirror?.publishMessage('user', redactCredentialCommand(cmdText));
13502
+ this.mirror?.publishMessage('user', redactMirroredCommand(cmdText));
12626
13503
  }
12627
13504
  await this.ensureOptionalControllersForCommand(cmd);
12628
13505
  const denial = getPlanModeCommandDenial(this.controller.getMode(), cmd, cmdArgs);
@@ -13458,6 +14335,7 @@ export class RatatuiApp {
13458
14335
  askPlanApproval(ctx, decision => {
13459
14336
  if (decision.kind === 'cancel') {
13460
14337
  this.controller.addMessage({ role: 'system', content: 'Plan execution cancelled. Still in plan mode.' });
14338
+ this.closeWaitingAgentPaneAsks('plan_cancelled');
13461
14339
  return;
13462
14340
  }
13463
14341
  if (decision.kind === 'approve') {
@@ -13467,10 +14345,12 @@ export class RatatuiApp {
13467
14345
  }
13468
14346
  else if (decision.kind === 'edit') {
13469
14347
  this.controller.addMessage({ role: 'system', content: 'Returning to plan mode. Continue editing your plan, then run /execute when ready.' });
14348
+ this.closeWaitingAgentPaneAsks('plan_edit');
13470
14349
  }
13471
14350
  else {
13472
14351
  this.controller.addMessage({ role: 'system', content: `Feedback noted. Still in plan mode.\n\nFeedback: ${decision.text}` });
13473
- this.controller.addMessage({ role: 'user', content: `Please update the plan based on this feedback: ${decision.text}` });
14352
+ this.controller.addMessage({ role: 'user', content: `Please update the plan based on this feedback: ${decision.text}`,
14353
+ metadata: { planDecision: true } });
13474
14354
  this.requestAgentTurn();
13475
14355
  }
13476
14356
  });
@@ -14025,6 +14905,11 @@ export class RatatuiApp {
14025
14905
  widgetContent = surface.content;
14026
14906
  widgetView = surface.view;
14027
14907
  }
14908
+ else if (this.agentSessionsPanelWidget.isActive()) {
14909
+ const surface = this.agentSessionsPanelWidget.buildSurface(this.cols, widgetLayout.widgetHeight || widgetLayout.contentAreaHeight);
14910
+ widgetContent = surface.content;
14911
+ widgetView = surface.view;
14912
+ }
14028
14913
  else if (this.navigatorPanelWidget.isActive()) {
14029
14914
  const surface = this.navigatorPanelWidget.buildSurface(this.cols, widgetLayout.widgetHeight || widgetLayout.contentAreaHeight);
14030
14915
  widgetContent = surface.content;
@@ -14297,6 +15182,7 @@ export class RatatuiApp {
14297
15182
  this.rewindPanelWidget,
14298
15183
  this.navigatorPanelWidget,
14299
15184
  this.resumePanelWidget,
15185
+ this.agentSessionsPanelWidget,
14300
15186
  this.settingsPanelWidget,
14301
15187
  this.statusLinePanelWidget,
14302
15188
  this.colorPanelWidget,
@@ -15333,6 +16219,8 @@ export class RatatuiApp {
15333
16219
  try {
15334
16220
  debugLog(`[${options.label}] Saving session before relaunch...`);
15335
16221
  await this.saveCurrentSession();
16222
+ // Over this mirror's bus, before it stops: the agent panes Main owes an answer hear it won't come.
16223
+ await this.closeAgentPaneAsksForSwitch();
15336
16224
  if (this.mirrorServer) {
15337
16225
  this.mirrorServer.publishSessionEnd({ reloadOnReconnect: true });
15338
16226
  await stopMirrorStreamServer();
@@ -15519,6 +16407,212 @@ export class RatatuiApp {
15519
16407
  this.controller.setToast('Session scan failed');
15520
16408
  }
15521
16409
  }
16410
+ /**
16411
+ * Why Main's screen (pane 0) can't be read now: while it shows the person's sessions picker, whose titles are their
16412
+ * opening prompts, and for a moment after it closes, so a read the renderer answered from a frame that still held it
16413
+ * is refused too. No other pane, agent or mirror viewer reads it then (workspace spec §14).
16414
+ */
16415
+ mainScreenReadRefusal(paneId) {
16416
+ if (paneId !== 0)
16417
+ return null;
16418
+ if (!this.agentSessionsPanelWidget.isActive() && Date.now() >= this.mainScreenPrivateUntil)
16419
+ return null;
16420
+ return 'Pane 0 (Main) is showing the person\'s Claude Code and Codex sessions picker, which only they may see: read it again once it closes.';
16421
+ }
16422
+ /**
16423
+ * The person's Claude Code and Codex sessions, Main's alone (see CommandContext.agentSessions): read only when they
16424
+ * open the picker or resume, and never sent anywhere.
16425
+ */
16426
+ agentSessions() {
16427
+ if (!this.agentSessionsControllerInstance) {
16428
+ this.agentSessionsControllerInstance = createAgentSessionsController({
16429
+ // As given, so a resumed pane's profile folder is spelled as every other pane's on that profile.
16430
+ home: homedir(),
16431
+ registered: cli => configStore.get().panes?.agentProfileDirs?.[cli] ?? {},
16432
+ openPicker: (cli, request) => { void this.openAgentSessionsPicker(cli, request); },
16433
+ });
16434
+ }
16435
+ return this.agentSessionsControllerInstance;
16436
+ }
16437
+ /**
16438
+ * Open the Claude Code or Codex sessions picker in Main (/claude resume, /codex sessions…). It paints at once and
16439
+ * fills as each session file's head is read; nothing is read before the person asks. In the desktop app Main takes
16440
+ * the keyboard while it is open, and gives it back to the pane that had it when it closes without opening one.
16441
+ */
16442
+ async openAgentSessionsPicker(cli, request) {
16443
+ if (this.agentSessionsPanelWidget.isActive())
16444
+ return;
16445
+ if (this.routingInteractionOccupied()) {
16446
+ this.addSystemMessage('Finish the open prompt, then open the sessions picker again.');
16447
+ return;
16448
+ }
16449
+ const origin = this.desktopMode ? await this.rendererFocusedPane() : null;
16450
+ if (this.desktopMode)
16451
+ this.tui.send({ type: 'focus_pane', pane_id: 0 });
16452
+ const sessions = this.agentSessions();
16453
+ const cwdNow = this.shellCwd || process.cwd();
16454
+ // This folder, resolved once and off the event loop; a session's folder is compared as its file names it, never
16455
+ // resolved, as the CLIs write it resolved already.
16456
+ const typed = cwdNow.normalize('NFC');
16457
+ let here = typed;
16458
+ const hereResolved = realFolder(cwdNow).then(real => { here = real; });
16459
+ const under = (folder, root) => folder === root ? '' : folder.startsWith(`${root}/`) ? folder.slice(root.length + 1) : null;
16460
+ // The sessions open in panes (resume only: forking one makes a new session), read again on each refresh.
16461
+ let openPanes = new Map();
16462
+ const panesHolding = async () => (request.mode === 'resume' && this.muxMode && !this.paneMode ? openAgentSessionPanes(this.tui) : new Map());
16463
+ // Whether each folder is there, asked once per reading, off the event loop and with a deadline, however many rows
16464
+ // name it; until it answers the row isn't marked gone. A folder under an automounter's /net or /Network names a host
16465
+ // that looking would contact, so it is looked at only when its session is chosen.
16466
+ let folders = new Map();
16467
+ let republish = () => { };
16468
+ const folderGone = (cwd) => {
16469
+ const known = folders.get(cwd);
16470
+ if (known === undefined && !AUTOMOUNTED.test(cwd)) {
16471
+ const asked = folders;
16472
+ asked.set(cwd, 'asking');
16473
+ void sessions.folderExists(cwd).then(exists => {
16474
+ if (folders !== asked)
16475
+ return;
16476
+ asked.set(cwd, exists);
16477
+ if (!exists)
16478
+ republish();
16479
+ });
16480
+ }
16481
+ return known === false;
16482
+ };
16483
+ const toRow = (session) => {
16484
+ const at = session.cwd?.normalize('NFC') ?? null;
16485
+ const inHere = at === null ? null : under(at, here) ?? under(at, typed);
16486
+ const folderMissing = session.cwd === null || !session.folderVerified || folderGone(session.cwd);
16487
+ return { session, inHere, folderMissing, openInPane: openPanes.get(`${cli}:${session.id}`) ?? null };
16488
+ };
16489
+ const scoped = (rows) => (request.profile === undefined ? [...rows] : rows.filter(row => row.profile === request.profile));
16490
+ const local = { ephemeral: true, localOnly: true };
16491
+ let chosen = false;
16492
+ let generation = 0;
16493
+ const load = async () => {
16494
+ const mine = ++generation;
16495
+ let found = [];
16496
+ let status = { loading: true };
16497
+ folders = new Map();
16498
+ // The rows as they stand, again: as each head is read, and when a folder answers that it is gone.
16499
+ republish = () => {
16500
+ if (mine === generation)
16501
+ this.agentSessionsPanelWidget.updateRows(scoped(orderRows(found)).map(toRow), status);
16502
+ };
16503
+ try {
16504
+ openPanes = await panesHolding();
16505
+ await hereResolved;
16506
+ if (mine !== generation)
16507
+ return;
16508
+ const listing = await sessions.list(cli, {
16509
+ cwd: here,
16510
+ onRow: row => {
16511
+ if (mine !== generation)
16512
+ return;
16513
+ found.push(row);
16514
+ republish();
16515
+ },
16516
+ });
16517
+ if (mine !== generation)
16518
+ return;
16519
+ found = listing.rows;
16520
+ status = {
16521
+ loading: false, unreadable: listing.unreadable, partial: listing.partial,
16522
+ read: listing.read, skipped: listing.skipped, older: listing.older, links: listing.links,
16523
+ };
16524
+ republish();
16525
+ }
16526
+ catch {
16527
+ if (mine === generation)
16528
+ this.agentSessionsPanelWidget.updateRows([], { loading: false });
16529
+ }
16530
+ };
16531
+ /**
16532
+ * A row the person chose, checked again as native resume does (its file still in the same store, its folder still
16533
+ * there), then opened in its folder on its sign-in like any pane the person opens; a folder that is gone or unknown
16534
+ * waits for a second ↵, which opens it here.
16535
+ */
16536
+ const choose = async (entry, confirmed, recentConfirmed) => {
16537
+ const pane = (await panesHolding()).get(`${cli}:${entry.session.id}`);
16538
+ if (pane !== undefined) {
16539
+ chosen = true;
16540
+ this.agentSessionsPanelWidget.cancel();
16541
+ this.tui.send({ type: 'focus_pane', pane_id: pane });
16542
+ this.controller.setToast(`Already open in pane ${pane}`);
16543
+ this.render();
16544
+ return 'closed';
16545
+ }
16546
+ const fresh = (await sessions.find(cli, entry.session.id, { cwd: here })).find(match => match.profile === entry.session.profile);
16547
+ if (!fresh) {
16548
+ this.controller.setToast('That session is no longer in its store');
16549
+ return 'stay';
16550
+ }
16551
+ // Written moments ago and held by no pane ZTC can read: it may be open in a Codex or --continue pane, or another
16552
+ // terminal, and two CLIs writing one session lose messages, so the person confirms first. A fork is a new session.
16553
+ if (request.mode === 'resume' && !recentConfirmed && Date.now() - fresh.mtimeMs < RECENT_ACTIVITY_MS)
16554
+ return 'confirm-recent';
16555
+ const inThisFolder = confirmed || request.here;
16556
+ // Asked now even under /net: the person chose this session. A folder that doesn't answer counts as gone.
16557
+ const exists = !inThisFolder && fresh.cwd !== null && fresh.folderVerified ? await sessions.folderExists(fresh.cwd) : false;
16558
+ const planned = resumeLaunchPlan(fresh, {
16559
+ mode: request.mode, here: inThisFolder, cwdNow,
16560
+ ...(request.prompt ? { prompt: request.prompt } : {}), folderExists: () => exists,
16561
+ });
16562
+ if ('error' in planned)
16563
+ return 'confirm-here';
16564
+ const plan = planned.plan;
16565
+ chosen = true;
16566
+ this.agentSessionsPanelWidget.cancel();
16567
+ if (!this.muxMode || this.paneMode) {
16568
+ const signIn = sessions.signInFor(cli, plan.profile ?? null);
16569
+ this.controller.addMessage({ role: 'system', content: elsewhereCommandLine(plan, signIn.dir, { profile: signIn.profile }),
16570
+ metadata: { ...local } });
16571
+ this.render();
16572
+ return 'closed';
16573
+ }
16574
+ const opened = await openResumedAgentPane(this.tui, plan, {
16575
+ findBinary: id => this.installedAgentClis()[id] ?? null,
16576
+ motsi: this.paneMotsi(),
16577
+ profilesHome: sessions.home,
16578
+ });
16579
+ if (opened.error) {
16580
+ this.controller.addMessage({ role: 'system', content: opened.error, metadata: { ...local } });
16581
+ }
16582
+ else {
16583
+ // Other panes and their agents may read Main's screen, so the line names neither the session nor its folder.
16584
+ this.controller.addMessage({ role: 'system', metadata: { ...local }, content: openedSessionLine(opened, request.mode) });
16585
+ if (opened.notice)
16586
+ this.controller.addMessage({ role: 'system', content: opened.notice, metadata: { ...local } });
16587
+ }
16588
+ this.render();
16589
+ return 'closed';
16590
+ };
16591
+ this.retireClipboardPaste();
16592
+ this.clipboardTargetRevision += 1;
16593
+ this.agentSessionsPanelWidget.show({
16594
+ cli,
16595
+ mode: request.mode,
16596
+ ...(request.profile ? { profile: request.profile } : {}),
16597
+ hasProfiles: sessions.describeStores(cli).profiles.length > 0,
16598
+ cwd: here,
16599
+ home: sessions.displayHome,
16600
+ rows: [],
16601
+ loading: true,
16602
+ ...(request.all ? { initialView: 'all' } : {}),
16603
+ onChoose: choose,
16604
+ onRefresh: () => { void load(); },
16605
+ onClose: () => {
16606
+ generation += 1;
16607
+ this.mainScreenPrivateUntil = Date.now() + MAIN_SCREEN_PRIVATE_AFTER_MS;
16608
+ if (origin !== null && !chosen)
16609
+ this.tui.send({ type: 'focus_pane', pane_id: origin });
16610
+ this.render();
16611
+ },
16612
+ });
16613
+ this.render();
16614
+ await load();
16615
+ }
15522
16616
  /** /rewind and two idle Escapes open the picker only between turns. */
15523
16617
  openRewindPanelWhenIdle() {
15524
16618
  if (this.isAgentBusy()) {
@@ -15564,6 +16658,7 @@ export class RatatuiApp {
15564
16658
  this.rewindPanelWidget.cancel();
15565
16659
  this.retireBusyInputRouting();
15566
16660
  this.controller.setMessages(plan.messages);
16661
+ this.dropClearedAgentPaneAsks();
15567
16662
  // The pinned task header is captured from the first user prompt, so a
15568
16663
  // rewind has to let the next turn recapture it from the new history.
15569
16664
  this.agent?.clearPinnedTask();