@zergai/ztc 0.19.0-beta.1 → 0.20.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.
- package/README.md +222 -6
- package/bin/zmux-darwin-arm64 +0 -0
- package/bin/ztc-audio-darwin-arm64 +0 -0
- package/bin/ztc-capture-darwin-arm64 +0 -0
- package/bin/ztc-tui-darwin-arm64 +0 -0
- package/bin/zterm-darwin-arm64 +2 -2
- package/dist/agent/agent.d.ts +17 -0
- package/dist/agent/agent.js +77 -4
- package/dist/agent/backends/index.js +5 -3
- package/dist/agent/backends/zrouter_stream.js +8 -4
- package/dist/agent/commands/goal.d.ts +2 -0
- package/dist/agent/commands/goal.js +7 -2
- package/dist/agent/factory.d.ts +2 -0
- package/dist/agent/factory.js +1 -0
- package/dist/agent/request_encoder.d.ts +2 -1
- package/dist/agent/request_encoder.js +4 -3
- package/dist/agent/runtime/policy.d.ts +1 -0
- package/dist/agent/runtime/policy.js +23 -3
- package/dist/agent/runtime/tool_runtime.js +13 -12
- package/dist/agent/subagent.js +2 -1
- package/dist/agent/tools/ask_user.d.ts +1 -1
- package/dist/agent/tools/ask_user.js +15 -8
- package/dist/agent/tools/pane.d.ts +6 -0
- package/dist/agent/tools/pane.js +18 -4
- package/dist/agent/tools/search.js +1 -1
- package/dist/agent/tools/sim_domain_tools.d.ts +4 -0
- package/dist/agent/tools/sim_domain_tools.js +28 -2
- package/dist/agent/tools/types.d.ts +3 -0
- package/dist/app/correlated_turn.d.ts +14 -0
- package/dist/app/correlated_turn.js +78 -0
- package/dist/app/prompt_turn.d.ts +2 -1
- package/dist/app/prompt_turn.js +15 -2
- package/dist/app/session_manager.d.ts +17 -11
- package/dist/app/session_manager.js +74 -30
- package/dist/app/tool_callbacks.d.ts +1 -1
- package/dist/app/workspace_layout_controller.d.ts +21 -2
- package/dist/app/workspace_layout_controller.js +61 -10
- package/dist/app/workspace_monitor.js +67 -7
- package/dist/app/workspace_presets.d.ts +1 -0
- package/dist/app/workspace_presets.js +2 -2
- package/dist/cli.js +6 -2
- package/dist/cli_args.js +1 -0
- package/dist/cli_main.js +48 -2
- package/dist/cli_ratatui.d.ts +56 -8
- package/dist/cli_ratatui.js +689 -109
- package/dist/config/permissions.js +1 -1
- package/dist/config/router_required.d.ts +11 -0
- package/dist/config/router_required.js +23 -0
- package/dist/config/types.d.ts +5 -0
- package/dist/config.d.ts +3 -1
- package/dist/config.js +66 -49
- package/dist/desktop/daily/broker.d.ts +26 -0
- package/dist/desktop/daily/broker.js +140 -0
- package/dist/desktop/daily/codex_config.d.ts +2 -0
- package/dist/desktop/daily/codex_config.js +119 -0
- package/dist/desktop/daily/codex_exec_adapter.d.ts +42 -0
- package/dist/desktop/daily/codex_exec_adapter.js +251 -0
- package/dist/desktop/daily/control_client.d.ts +4 -0
- package/dist/desktop/daily/control_client.js +214 -0
- package/dist/desktop/daily/control_credentials.d.ts +15 -0
- package/dist/desktop/daily/control_credentials.js +85 -0
- package/dist/desktop/daily/control_hello.d.ts +10 -0
- package/dist/desktop/daily/control_hello.js +6 -0
- package/dist/desktop/daily/control_protocol.d.ts +39 -0
- package/dist/desktop/daily/control_protocol.js +4 -0
- package/dist/desktop/daily/control_schema.d.ts +9 -0
- package/dist/desktop/daily/control_schema.js +25 -0
- package/dist/desktop/daily/control_server.d.ts +44 -0
- package/dist/desktop/daily/control_server.js +286 -0
- package/dist/desktop/daily/daily_store.d.ts +71 -0
- package/dist/desktop/daily/daily_store.js +290 -0
- package/dist/desktop/daily/delegated_ztc_contract.d.ts +37 -0
- package/dist/desktop/daily/delegated_ztc_contract.js +90 -0
- package/dist/desktop/daily/desktop_wiring.d.ts +112 -0
- package/dist/desktop/daily/desktop_wiring.js +1048 -0
- package/dist/desktop/daily/enrollment.d.ts +74 -0
- package/dist/desktop/daily/enrollment.js +77 -0
- package/dist/desktop/daily/file_facts.d.ts +2 -0
- package/dist/desktop/daily/file_facts.js +41 -0
- package/dist/desktop/daily/lease.d.ts +57 -0
- package/dist/desktop/daily/lease.js +332 -0
- package/dist/desktop/daily/legacy_codex_homes.d.ts +1 -0
- package/dist/desktop/daily/legacy_codex_homes.js +26 -0
- package/dist/desktop/daily/native_pane_launcher.d.ts +31 -0
- package/dist/desktop/daily/native_pane_launcher.js +226 -0
- package/dist/desktop/daily/native_records.d.ts +13 -0
- package/dist/desktop/daily/native_records.js +81 -0
- package/dist/desktop/daily/native_status.d.ts +4 -0
- package/dist/desktop/daily/native_status.js +28 -0
- package/dist/desktop/daily/native_tool.d.ts +134 -0
- package/dist/desktop/daily/native_tool.js +91 -0
- package/dist/desktop/daily/owner_files.d.ts +3 -0
- package/dist/desktop/daily/owner_files.js +88 -0
- package/dist/desktop/daily/owner_seals.d.ts +9 -0
- package/dist/desktop/daily/owner_seals.js +56 -0
- package/dist/desktop/daily/process_identity.d.ts +13 -0
- package/dist/desktop/daily/process_identity.js +137 -0
- package/dist/desktop/daily/profile_bootstrap.d.ts +60 -0
- package/dist/desktop/daily/profile_bootstrap.js +194 -0
- package/dist/desktop/daily/raw_receipts.d.ts +1 -0
- package/dist/desktop/daily/raw_receipts.js +18 -0
- package/dist/desktop/daily/recipes.d.ts +36 -0
- package/dist/desktop/daily/recipes.js +177 -0
- package/dist/desktop/daily/router_state.d.ts +33 -0
- package/dist/desktop/daily/router_state.js +39 -0
- package/dist/desktop/daily/schema_registry.d.ts +19 -0
- package/dist/desktop/daily/schema_registry.js +71 -0
- package/dist/desktop/daily/source_baseline.d.ts +13 -0
- package/dist/desktop/daily/source_baseline.js +44 -0
- package/dist/desktop/daily/status_restore.d.ts +9 -0
- package/dist/desktop/daily/status_restore.js +114 -0
- package/dist/desktop/daily/summary.d.ts +59 -0
- package/dist/desktop/daily/summary.js +75 -0
- package/dist/desktop/daily/worker_provenance.d.ts +2 -0
- package/dist/desktop/daily/worker_provenance.js +18 -0
- package/dist/desktop/daily/worker_stop.d.ts +2 -0
- package/dist/desktop/daily/worker_stop.js +26 -0
- package/dist/desktop/daily/ztc_headless_adapter.d.ts +40 -0
- package/dist/desktop/daily/ztc_headless_adapter.js +194 -0
- package/dist/domain.d.ts +1 -1
- package/dist/domain.js +1 -1
- package/dist/events.d.ts +23 -1
- package/dist/headless.d.ts +9 -0
- package/dist/headless.js +161 -26
- package/dist/headless_approval.d.ts +29 -0
- package/dist/headless_approval.js +69 -0
- package/dist/headless_cli.js +2 -0
- package/dist/headless_cli_args.d.ts +4 -0
- package/dist/headless_cli_args.js +5 -0
- package/dist/library.d.ts +20 -0
- package/dist/library.js +66 -12
- package/dist/mcp/client.d.ts +16 -1
- package/dist/mcp/client.js +11 -5
- package/dist/mcp/registry.d.ts +3 -1
- package/dist/mcp/registry.js +10 -1
- package/dist/panes/pane_registry.js +14 -3
- package/dist/panes/types.d.ts +7 -1
- package/dist/panes/ztc_launch.d.ts +5 -0
- package/dist/panes/ztc_launch.js +30 -14
- package/dist/session.d.ts +6 -3
- package/dist/session.js +21 -2
- package/dist/simulation/domain_types.d.ts +2 -0
- package/dist/simulation/domains/loader.d.ts +7 -1
- package/dist/simulation/domains/loader.js +33 -1
- package/dist/simulation/living/context.d.ts +19 -19
- package/dist/simulation/living/definition.d.ts +2 -2
- package/dist/simulation/living/frame.d.ts +1 -1
- package/dist/simulation/living/open-world.d.ts +3 -3
- package/dist/simulation/living/types.d.ts +24 -24
- package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
- package/dist/skills/bundled/init-context/SKILL.md +16 -0
- package/dist/skills/registry.js +7 -3
- package/dist/tools.d.ts +6 -0
- package/dist/tools.js +14 -0
- package/dist/types.d.ts +30 -0
- package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
- package/dist/ui/ratatui/mux_persistence.js +9 -2
- package/dist/ui/ratatui/pane_credential_broker.d.ts +8 -4
- package/dist/ui/ratatui/pane_credential_broker.js +26 -11
- package/dist/ui/ratatui/pane_relay.d.ts +2 -0
- package/dist/ui/ratatui/process.d.ts +6 -0
- package/dist/ui/ratatui/process.js +104 -6
- package/dist/ui/ratatui/protocol.d.ts +13 -0
- package/dist/ui/ratatui/protocol.js +1 -0
- package/dist/utils/compaction.js +6 -4
- package/dist/utils/subprocess_env.js +2 -0
- package/dist/web/browser_events.d.ts +10 -0
- package/dist/web/browser_events.js +9 -0
- package/dist/web/mirror_stream.d.ts +17 -5
- package/dist/web/mirror_stream.js +105 -13
- package/dist/web/pane_credentials.d.ts +6 -3
- package/dist/web/pane_credentials.js +20 -12
- package/dist/web/pane_registry.js +1 -0
- package/dist/workspace_agent.d.ts +2 -1
- package/dist/workspace_agent.js +7 -1
- package/dist/workspace_collision.d.ts +3 -0
- package/dist/workspace_collision.js +1 -1
- package/dist/workspace_layout.d.ts +3 -2
- package/dist/workspace_layout.js +8 -2
- package/dist/workspace_runtime.d.ts +7 -1
- package/dist/workspace_runtime.js +3 -3
- package/dist/zerg/manifest_builder_tools.js +35 -4
- package/dist/zerg/manifest_validator.js +55 -0
- package/dist/zlm-embed.mjs +261 -116
- package/node_modules/@zerg/model-contracts/README.md +19 -0
- package/node_modules/@zerg/model-contracts/index.js +19 -1
- package/node_modules/@ztc/sim-graph/dist/index.d.ts +1 -0
- package/node_modules/@ztc/sim-graph/dist/index.js +1 -0
- package/node_modules/@ztc/sim-graph/dist/sim_graph.d.ts +351 -0
- package/node_modules/@ztc/sim-graph/dist/sim_graph.js +795 -0
- package/node_modules/@ztc/sim-graph/package.json +37 -0
- package/node_modules/@ztc/sim-graph/src/index.ts +1 -0
- package/node_modules/@ztc/sim-graph/src/sim_graph.ts +1305 -0
- package/package.json +25 -24
- package/packages/model-contracts/README.md +19 -0
- package/packages/model-contracts/index.js +19 -1
package/dist/cli_ratatui.js
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
+
import { statusPlacement, statusRestoreState, remapWorkspacePaneIds } from './desktop/daily/status_restore.js';
|
|
2
|
+
import { routerChromeState } from './desktop/daily/native_status.js';
|
|
3
|
+
import { buildWorkspaceMonitorLaunch, loadWorkspacePreset } from './app/workspace_presets.js';
|
|
4
|
+
import { DesktopDaily, nativeChoices, canResumeNative, safeDailyMessage } from './desktop/daily/desktop_wiring.js';
|
|
5
|
+
import { parseNativeRecords } from './desktop/daily/native_records.js';
|
|
1
6
|
import { environmentOperationInProgress } from './agent/commands/environment.js';
|
|
2
7
|
import { getEnvironment, openEnvironment, releaseEnvironment, describeEnvironmentForAgent, isEnvironmentWorkspacePath } from './environment/store.js';
|
|
3
8
|
import { readPaneLabels, sessionNamePaneTitle } from './panes/labels.js';
|
|
4
9
|
import { reconcileOrderedTranscript } from './app/ordered_transcript.js';
|
|
5
10
|
import { listCommandJobs, shutdownCommandJobs, subscribeCommandJobs } from './agent/runtime/command_jobs.js';
|
|
6
11
|
import { CommandPaneManager, commandPaneText } from './agent/runtime/command_panes.js';
|
|
7
|
-
import { waitForPaneCreatedOrError } from './agent/tools/pane.js';
|
|
12
|
+
import { isPaneRefusalFor, waitForPaneCreatedOrError } from './agent/tools/pane.js';
|
|
8
13
|
import { findAgentCli } from './panes/agent_cli.js';
|
|
9
14
|
import { agentCliFromRequestId, formatAgentPaneMessage, openAgentPane, typeLineIntoPane } from './panes/agent_panes.js';
|
|
10
15
|
import { agentCliFromChoice, newPaneChoices } from './panes/new_pane_choices.js';
|
|
@@ -29,7 +34,7 @@ import { appendFileSync, existsSync, writeFileSync } from 'fs';
|
|
|
29
34
|
import { tmpdir, homedir } from 'os';
|
|
30
35
|
import { join } from 'path';
|
|
31
36
|
import { execFile, spawnSync } from 'child_process';
|
|
32
|
-
import { promisify } from 'util';
|
|
37
|
+
import { promisify, isDeepStrictEqual } from 'util';
|
|
33
38
|
import { configStore, resolveTerminalInteractionSettings } from './config.js';
|
|
34
39
|
import { applyAccountOp, getAccountsPayloadWithCodexStatus } from './web/accounts_mirror.js';
|
|
35
40
|
import { canonicalAccountProvider } from './agent/backends/account_pool.js';
|
|
@@ -76,13 +81,14 @@ import { showConnectPrompt } from './agent/commands/connect.js';
|
|
|
76
81
|
import { onZergAILoginWaitChange, pendingZergAILogin, stopZergAILogin } from './agent/commands/auth.js';
|
|
77
82
|
import { connectionSnapshot } from './agent/commands/credential_status.js';
|
|
78
83
|
import { redactCredentialCommand } from './agent/commands/credential_redaction.js';
|
|
79
|
-
import { goalManager, goalPinTask, detectGoalCompletion, detectGoalBlocked, goalBlockedReason, goalFinalNote, turnProducedText, turnToolOutcomes, shouldAccountFinalTurn, snapshotGoalForTurn } from './agent/commands/goal.js';
|
|
84
|
+
import { goalManager, goalPinTask, hasSustainedGoalIntent, detectGoalCompletion, detectGoalBlocked, goalBlockedReason, goalFinalNote, turnProducedText, turnToolOutcomes, shouldAccountFinalTurn, snapshotGoalForTurn } from './agent/commands/goal.js';
|
|
80
85
|
import { allocatePlanArtifact, askPlanApproval, findPlanContent, generatePlanPath, commitPlan, PlanFileCreationError, } from './agent/commands/plan.js';
|
|
81
86
|
import { setTodoUpdateCallback, clearTodoUpdateCallback, setPaneToolsTuiProcess, clearPaneToolsTuiProcess, setPaneToolsOwnId, setPaneToolsExitCallback, setPaneToolsMirrorCallback, setPaneToolsZdeLiteCallback, setPaneToolsPendingLaunchCallback, clearPaneToolsPendingLaunchCallback, setSupervisionManager, clearSupervisionManager, setBusTransport, clearBusTransport, setEvolutionTuiProcess, clearEvolutionTuiProcess, resetAskUserTurnFlag } from './agent/tools/index.js';
|
|
82
87
|
import { shutdownLSPManager } from './lsp/index.js';
|
|
88
|
+
import { MAX_CORRELATED_TURNS, correlatedInputDigest, projectCorrelatedTurns, restoreCorrelatedTurns, restoreCorrelatedTurnHistory } from './app/correlated_turn.js';
|
|
83
89
|
import { zmuxKeymapPayload } from './config/keybindings.js';
|
|
84
90
|
import { customPaneOptions } from './config/panes.js';
|
|
85
|
-
import { CAPABILITY_DESKTOP_UPDATE_RESTART, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_KITTY_GRAPHICS, isDesktopSessionShareAction, CAPABILITY_SCROLLBACK_ANCHOR, CAPABILITY_TERMINAL_INTERACTION, } from './ui/ratatui/protocol.js';
|
|
91
|
+
import { CAPABILITY_DESKTOP_UPDATE_RESTART, CAPABILITY_DESKTOP_TASK_CONTROLS, CAPABILITY_DESKTOP_ROUTER_CHROME, CAPABILITY_DESKTOP_RUNTIME_CONTROLS, CAPABILITY_DESKTOP_SESSION_SHARE, CAPABILITY_KITTY_GRAPHICS, isDesktopSessionShareAction, CAPABILITY_SCROLLBACK_ANCHOR, CAPABILITY_TERMINAL_INTERACTION, } from './ui/ratatui/protocol.js';
|
|
86
92
|
import { writeClipboard } from './utils/clipboard.js';
|
|
87
93
|
import { saveClipboardImagePng } from './utils/clipboard_image.js';
|
|
88
94
|
import { loadEmulationProfiles, getEmulationProfile } from './emulation/catalog.js';
|
|
@@ -116,7 +122,7 @@ import { BROWSER_BUS_MEMBER_ID, OVERSEER_BUS_MEMBER_ID, createMirrorStreamServer
|
|
|
116
122
|
import { initMirrorClient } from './web/mirror_client.js';
|
|
117
123
|
import { PaneRelayServer, PaneRelayClient, generateRelaySocketPath } from './ui/ratatui/pane_relay.js';
|
|
118
124
|
import { perfBeginKeystroke, perfStage, perfEndKeystroke } from './debug/perf_trace.js';
|
|
119
|
-
import { resolveMuxPersistenceOptions, sanitizeMuxSessionState } from './ui/ratatui/mux_persistence.js';
|
|
125
|
+
import { resolveMuxPersistenceOptions, sanitizeMuxSessionState, validateWorkspaceState } from './ui/ratatui/mux_persistence.js';
|
|
120
126
|
import { buildModelsController, buildSkillsController, buildShellController, routeUserInput, getPlanModeCommandDenial } from './app/command_context.js';
|
|
121
127
|
import { advanceEscapeStop, isEscapeStopArmed, ESCAPE_STOP_WINDOW_MS } from './app/escape_stop.js';
|
|
122
128
|
import { createAgentWithConfig, AgentRunLifecycle } from './app/agent_runner.js';
|
|
@@ -130,7 +136,7 @@ import { SelectionCompletion } from './app/selection_completion.js';
|
|
|
130
136
|
import { routerCatalogScope } from './utils/router_catalog.js';
|
|
131
137
|
import { shouldAttachParentMirrorClient, shouldMarkMirrorServerAsColonyChild } from './app/mirror_startup.js';
|
|
132
138
|
import { buildDesktopUpdateRelaunchContext, buildHotRestartLaunch, prepareDesktopUpdateAuthorization, reduceDesktopUpdateOwnerHandshake, requestColonyCellRestart, } from './app/restart.js';
|
|
133
|
-
import { paneCredentialRelaunchArgs, withoutMirrorCredentials } from './web/pane_credentials.js';
|
|
139
|
+
import { PANE_CREDENTIAL_ENV, WORKSPACE_MONITOR_CREDENTIAL_REQUEST, paneCredentialRelaunchArgs, withoutMirrorCredentials } from './web/pane_credentials.js';
|
|
134
140
|
export { buildDesktopUpdateRelaunchContext, buildHotRestartArgs, requestColonyCellRestart, } from './app/restart.js';
|
|
135
141
|
import { formatWorkflowEventDisplay } from './app/workflow_event_display.js';
|
|
136
142
|
import { getBackgroundRegistry, clearBackgroundRegistry } from './agent/tools/index.js';
|
|
@@ -827,6 +833,9 @@ export class RatatuiApp {
|
|
|
827
833
|
colonyPaneIds = new Set();
|
|
828
834
|
/** Cache of latest pane list from pane_state events (including colony panes, filtered in switcher) */
|
|
829
835
|
knownPanes = [];
|
|
836
|
+
awaitingRestoredPaneState = false;
|
|
837
|
+
nativeRestore = Promise.resolve();
|
|
838
|
+
nativeRestorePending = false;
|
|
830
839
|
/** Currently active zmux window (0 = normal, 1 = colony) */
|
|
831
840
|
currentMuxWindow = 0;
|
|
832
841
|
/** Pane currently zoomed full-screen, or null if in normal (unzoomed) view */
|
|
@@ -880,6 +889,12 @@ export class RatatuiApp {
|
|
|
880
889
|
paneRelay = null;
|
|
881
890
|
paneRelayClient = null;
|
|
882
891
|
supervisionManager = null;
|
|
892
|
+
dailyDesktop = null;
|
|
893
|
+
dailyStatusPane = null;
|
|
894
|
+
retainedStartupLayout = null;
|
|
895
|
+
retainedStartupTopology = null;
|
|
896
|
+
dailyStatusCancel = null;
|
|
897
|
+
dailyDialogs = Promise.resolve();
|
|
883
898
|
// Per-turn snapshots feed the post-turn recap trigger. They live on `this`
|
|
884
899
|
// because the idle-transition hook runs outside runAgent's scope. Tool calls
|
|
885
900
|
// are counted here (not read from Message.toolCalls) because streaming only
|
|
@@ -887,6 +902,10 @@ export class RatatuiApp {
|
|
|
887
902
|
recapController = createRecapController();
|
|
888
903
|
turnStartTime = 0;
|
|
889
904
|
activePromptTurn = null;
|
|
905
|
+
correlatedAdmission = Promise.resolve();
|
|
906
|
+
/** Read-only projection of the canonical committed session, never an input ledger. */
|
|
907
|
+
committedTurnMessages = [];
|
|
908
|
+
committedPromptTurns = [];
|
|
890
909
|
streamingPromptTurn = null;
|
|
891
910
|
promptRunTurns = new Set();
|
|
892
911
|
promptMetadataTimer = null;
|
|
@@ -1313,6 +1332,8 @@ export class RatatuiApp {
|
|
|
1313
1332
|
if (options?.resumeSession) {
|
|
1314
1333
|
this.sessionId = options.resumeSession.metadata.id;
|
|
1315
1334
|
this.resumedSession = options.resumeSession;
|
|
1335
|
+
this.resumedSession.prompt_turns = restoreCorrelatedTurnHistory(this.resumedSession.prompt_turns ?? []);
|
|
1336
|
+
this.committedPromptTurns = this.resumedSession.prompt_turns;
|
|
1316
1337
|
if (options.resumeSession.task_handoff) {
|
|
1317
1338
|
this.taskHandoff = projectTaskHandoff(options.resumeSession.task_handoff);
|
|
1318
1339
|
this.restoredHandoffCorrections = options.resumeSession.task_handoff.corrections.map(correction => ({
|
|
@@ -1322,6 +1343,9 @@ export class RatatuiApp {
|
|
|
1322
1343
|
if (!options.resumeSession.hosted_settings)
|
|
1323
1344
|
configStore.restoreSessionSelection(options.resumeSession.metadata);
|
|
1324
1345
|
this.resumedPaneSpecs = mergeSessionPaneSpecs(options.resumeSession.mux_state, options.resumeSession.pane_specs);
|
|
1346
|
+
if (this.desktopMode && this.muxMode && !this.paneMode && options.resumeSession.mux_state) {
|
|
1347
|
+
this.retainedStartupLayout = structuredClone({ muxState: options.resumeSession.mux_state, paneSpecs: this.resumedPaneSpecs });
|
|
1348
|
+
}
|
|
1325
1349
|
this.sessionName = options.resumeSession.metadata.name;
|
|
1326
1350
|
this.sessionLabels = { ...options.resumeSession.metadata.labels, manual_title: this.sessionName };
|
|
1327
1351
|
this.hostedSessionSettings = options.resumeSession.hosted_settings
|
|
@@ -1466,7 +1490,7 @@ export class RatatuiApp {
|
|
|
1466
1490
|
// avoids triggering the "accept incoming connections?" firewall
|
|
1467
1491
|
// prompt for every background ZTC.
|
|
1468
1492
|
const autoHost = autoMirror ? '127.0.0.1' : undefined;
|
|
1469
|
-
this.mirrorServer = createMirrorStreamServer(this.pendingMirrorPort, this.shouldPersistSession(), this.sessionId, autoHost);
|
|
1493
|
+
this.mirrorServer = createMirrorStreamServer(this.pendingMirrorPort, this.shouldPersistSession(), this.sessionId, autoHost, this.sessionId);
|
|
1470
1494
|
const hostedRuntime = this.isHostedRuntime();
|
|
1471
1495
|
this.mirrorServer.setHostedMode(hostedRuntime);
|
|
1472
1496
|
if (hostedRuntime) {
|
|
@@ -1478,6 +1502,8 @@ export class RatatuiApp {
|
|
|
1478
1502
|
this.mirrorServer.setAccountReloadHook(() => this.reloadAgentInPlace());
|
|
1479
1503
|
this.mirrorServer.setAccountOperationHook(body => this.applyAccountOperation(body));
|
|
1480
1504
|
this.mirrorServer.setRuntimeStatsProvider(() => this.getRuntimeStats());
|
|
1505
|
+
this.mirrorServer.setPromptTurnsProvider(() => projectCorrelatedTurns(this.committedTurnMessages, this.sessionId, this.committedPromptTurns));
|
|
1506
|
+
this.mirrorServer.onCorrelatedInput(async (input) => (await this.handleMirrorInput(input)) ?? { ok: false, reason: 'input_unavailable' }, () => goalManager.get()?.status !== 'active');
|
|
1481
1507
|
for (const viewPlugin of runtimePluginRegistry.getViewPlugins()) {
|
|
1482
1508
|
this.mirrorServer.registerViewPlugin(viewPlugin);
|
|
1483
1509
|
}
|
|
@@ -1506,10 +1532,10 @@ export class RatatuiApp {
|
|
|
1506
1532
|
this.registerMirrorPaneFallbacks(this.mirrorServer);
|
|
1507
1533
|
}
|
|
1508
1534
|
// Handle input from browser mirror (single-pane mode fallback), what a ZTC process or pane relays, and what
|
|
1509
|
-
// /broadcast delivers (see
|
|
1535
|
+
// /broadcast delivers (see handleMirrorInput)
|
|
1510
1536
|
this.mirrorServer.onInput((input, via) => {
|
|
1511
1537
|
debugLog(`[Mirror] Received input from ${via}: length=${input.text.length}`);
|
|
1512
|
-
|
|
1538
|
+
return this.handleMirrorInput(input, via);
|
|
1513
1539
|
});
|
|
1514
1540
|
this.mirrorServer.onCancel((paneId) => {
|
|
1515
1541
|
debugLog(`[Mirror] Cancel requested from browser: pane=${paneId}`);
|
|
@@ -2086,6 +2112,7 @@ export class RatatuiApp {
|
|
|
2086
2112
|
can_stop: runOwner !== null && this.runLifecycle.isRunning(),
|
|
2087
2113
|
...(this.paneActivityTransport().hasCapability(CAPABILITY_DESKTOP_RUNTIME_CONTROLS)
|
|
2088
2114
|
? { runtime: this.desktopRuntimeProjection() } : {}),
|
|
2115
|
+
...(this.dailyDesktop && this.paneActivityTransport().hasCapability(CAPABILITY_DESKTOP_ROUTER_CHROME) ? { router: routerChromeState(this.dailyDesktop.snapshot()) } : {}),
|
|
2089
2116
|
...(share ? { share } : {}),
|
|
2090
2117
|
...(this.paneActivityTransport().hasCapability(CAPABILITY_DESKTOP_SESSION_SHARE) ? { share_available: true } : {}),
|
|
2091
2118
|
entries: this.controller.getQueue().slice(0, MAX_QUEUE).map(entry => {
|
|
@@ -3373,8 +3400,10 @@ export class RatatuiApp {
|
|
|
3373
3400
|
if (!process.env.ZTC_API_URL) {
|
|
3374
3401
|
process.env.ZTC_API_URL = configStore.getApiBaseUrl();
|
|
3375
3402
|
}
|
|
3376
|
-
this.mirrorServer = await startMirrorStreamServer(requestedPort, this.sessionId);
|
|
3403
|
+
this.mirrorServer = await startMirrorStreamServer(requestedPort, this.sessionId, this.sessionId);
|
|
3377
3404
|
this.mirrorServer.setRuntimeStatsProvider(() => this.getRuntimeStats());
|
|
3405
|
+
this.mirrorServer.setPromptTurnsProvider(() => projectCorrelatedTurns(this.committedTurnMessages, this.sessionId, this.committedPromptTurns));
|
|
3406
|
+
this.mirrorServer.onCorrelatedInput(async (input) => (await this.handleMirrorInput(input)) ?? { ok: false, reason: 'input_unavailable' }, () => goalManager.get()?.status !== 'active');
|
|
3378
3407
|
for (const viewPlugin of runtimePluginRegistry.getViewPlugins()) {
|
|
3379
3408
|
this.mirrorServer.registerViewPlugin(viewPlugin);
|
|
3380
3409
|
}
|
|
@@ -3411,7 +3440,7 @@ export class RatatuiApp {
|
|
|
3411
3440
|
}
|
|
3412
3441
|
this.mirrorServer.onInput((input, via) => {
|
|
3413
3442
|
debugLog(`[Mirror] Received input from ${via}: length=${input.text.length}`);
|
|
3414
|
-
|
|
3443
|
+
return this.handleMirrorInput(input, via);
|
|
3415
3444
|
});
|
|
3416
3445
|
this.mirrorServer.onCancel((paneId) => {
|
|
3417
3446
|
debugLog(`[Mirror] Cancel requested from browser: pane=${paneId}`);
|
|
@@ -4191,6 +4220,7 @@ export class RatatuiApp {
|
|
|
4191
4220
|
// Subscribe to pane events from HeadlessPaneManager for mirror forwarding + pane tracking
|
|
4192
4221
|
if (this.tui instanceof HeadlessPaneManager) {
|
|
4193
4222
|
this.tui.on((event) => {
|
|
4223
|
+
this.observeRestoredPaneState(event);
|
|
4194
4224
|
if (event.type === 'pane_created') {
|
|
4195
4225
|
this.childPaneIds.add(event.pane_id);
|
|
4196
4226
|
// Track which child requested this pane (for replace flow / origin paneRegistry).
|
|
@@ -4236,7 +4266,9 @@ export class RatatuiApp {
|
|
|
4236
4266
|
this.mirrorServer.updatePaneState({ ...event, panes: filteredPanes });
|
|
4237
4267
|
}
|
|
4238
4268
|
if (event.type === 'pane_closed') {
|
|
4269
|
+
this.dailyDesktop?.paneClosed(event.pane_id);
|
|
4239
4270
|
if (!this.shouldIgnorePaneClosed(event.pane_id)) {
|
|
4271
|
+
this.observeDailyStatusClosed(event.pane_id);
|
|
4240
4272
|
this.childPaneIds.delete(event.pane_id);
|
|
4241
4273
|
this.colonyPaneIds.delete(event.pane_id);
|
|
4242
4274
|
if (this.mirrorServer) {
|
|
@@ -4248,7 +4280,7 @@ export class RatatuiApp {
|
|
|
4248
4280
|
}
|
|
4249
4281
|
}
|
|
4250
4282
|
// Stream pane output to mirror (process, doc, feed)
|
|
4251
|
-
if (event.type === 'pane_output' && this.mirrorServer && !this.colonyPaneIds.has(event.pane_id)) {
|
|
4283
|
+
if (event.type === 'pane_output' && this.mirrorServer && !this.colonyPaneIds.has(event.pane_id) && !this.dailyDesktop?.hasPane(event.pane_id)) {
|
|
4252
4284
|
this.mirrorServer.publish({
|
|
4253
4285
|
type: 'pane_output',
|
|
4254
4286
|
data: { pane_id: event.pane_id, content: event.content },
|
|
@@ -4466,6 +4498,8 @@ export class RatatuiApp {
|
|
|
4466
4498
|
// Initialize Colony Agent Bridge now that the transport is ready.
|
|
4467
4499
|
// Must happen AFTER tui.start() so create_pane commands can be sent.
|
|
4468
4500
|
this._initColonyBridge();
|
|
4501
|
+
if (this.desktopMode && !this.paneMode && this.mirrorServer)
|
|
4502
|
+
await this.startDailyDesktop();
|
|
4469
4503
|
// Push the live pane identity to the native mux surface. This keeps
|
|
4470
4504
|
// desktop status/footer labels aligned with bus names even before /rename.
|
|
4471
4505
|
const labelPaneId = this.ownPaneId();
|
|
@@ -4486,7 +4520,8 @@ export class RatatuiApp {
|
|
|
4486
4520
|
// allocates a fresh identity and deduplicates prose, so restore through
|
|
4487
4521
|
// the canonical replacement action instead. JSON timestamps are revived
|
|
4488
4522
|
// without changing the authored instant or the remaining source fields.
|
|
4489
|
-
this.
|
|
4523
|
+
this.committedTurnMessages = restoreCorrelatedTurns(this.resumedSession.messages);
|
|
4524
|
+
this.controller.setMessages(this.committedTurnMessages.map(message => ({
|
|
4490
4525
|
...message,
|
|
4491
4526
|
timestamp: new Date(message.timestamp),
|
|
4492
4527
|
})));
|
|
@@ -4835,37 +4870,13 @@ export class RatatuiApp {
|
|
|
4835
4870
|
this.intakePollTimer.unref();
|
|
4836
4871
|
this.ensureSessionManager().runStartupCleanup();
|
|
4837
4872
|
// Signal-safe shutdown: preserve colony state + save session before exit
|
|
4838
|
-
const
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
|
|
4842
|
-
|
|
4843
|
-
|
|
4844
|
-
|
|
4845
|
-
// Preserve colony cell state so cells resume on next startup.
|
|
4846
|
-
// prepareForShutdown() is synchronous — marks cells as 'starting' and
|
|
4847
|
-
// writes colony.json before the process exits.
|
|
4848
|
-
try {
|
|
4849
|
-
getColonyService()?.getAgentBridge?.()?.prepareForShutdown();
|
|
4850
|
-
debugLog('[signal] Colony state preserved');
|
|
4851
|
-
}
|
|
4852
|
-
catch { /* colony module optional */ }
|
|
4853
|
-
// Snapshot mux state SYNCHRONOUSLY before child processes die.
|
|
4854
|
-
// When SIGTERM arrives, sub-pane processes in our process group also
|
|
4855
|
-
// receive the signal. Their 'close' events fire and delete them from
|
|
4856
|
-
// HeadlessPaneManager.panes, so by the time an async getMuxState()
|
|
4857
|
-
// runs the pane map is empty. Capture the snapshot now while panes
|
|
4858
|
-
// are still registered.
|
|
4859
|
-
this._captureEmergencyMuxSnapshot();
|
|
4860
|
-
void this.saveCurrentSession()
|
|
4861
|
-
.finally(() => this.workspaceCoordinator?.close())
|
|
4862
|
-
.then(() => { debugLog('[signal] Save complete'); process.exit(0); })
|
|
4863
|
-
.catch(() => { process.exit(1); });
|
|
4864
|
-
// Hard deadline: if save hangs, exit after 3 seconds
|
|
4865
|
-
setTimeout(() => process.exit(1), 3000).unref();
|
|
4866
|
-
};
|
|
4867
|
-
process.on('SIGINT', emergencySave);
|
|
4868
|
-
process.on('SIGTERM', emergencySave);
|
|
4873
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {
|
|
4874
|
+
process.on(signal, () => {
|
|
4875
|
+
if (signal === 'SIGINT' && this.exiting)
|
|
4876
|
+
process.exit(130);
|
|
4877
|
+
void this.emergencyExit();
|
|
4878
|
+
});
|
|
4879
|
+
}
|
|
4869
4880
|
process.on('SIGUSR1', () => {
|
|
4870
4881
|
debugLog('[SIGUSR1] Hot-restart requested by child pane');
|
|
4871
4882
|
void this.hotRestart();
|
|
@@ -5332,6 +5343,7 @@ export class RatatuiApp {
|
|
|
5332
5343
|
this.childPaneSessionIds.delete(paneId);
|
|
5333
5344
|
}
|
|
5334
5345
|
trackPendingPaneReplacement(paneId, requestId) {
|
|
5346
|
+
this.dailyDesktop?.paneClosed(paneId);
|
|
5335
5347
|
this.pendingPaneReplacements.set(paneId, { requestId, sawClose: false, ignoreNextClose: false, createdAt: Date.now() });
|
|
5336
5348
|
}
|
|
5337
5349
|
isReplacementStale(pending) {
|
|
@@ -5384,13 +5396,289 @@ export class RatatuiApp {
|
|
|
5384
5396
|
trackPendingPaneLaunch(requestId, launchSpec) {
|
|
5385
5397
|
this.paneRegistry.trackPendingCreate(requestId, launchSpec);
|
|
5386
5398
|
}
|
|
5387
|
-
|
|
5399
|
+
async dailySelect(title, options) {
|
|
5400
|
+
let finish;
|
|
5401
|
+
const previous = this.dailyDialogs;
|
|
5402
|
+
this.dailyDialogs = new Promise(resolve => { finish = resolve; });
|
|
5403
|
+
await previous;
|
|
5404
|
+
try {
|
|
5405
|
+
while ((this.selectWidget.isActive() || this.textInputWidget.isActive()) && !this.exiting)
|
|
5406
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
5407
|
+
if (this.exiting || !options.length)
|
|
5408
|
+
return null;
|
|
5409
|
+
this.tui.send({ type: 'focus_pane', pane_id: 0 });
|
|
5410
|
+
return await new Promise(resolve => this.selectWidget.show({ title, question: title, type: 'select', options, allowOther: false, callback: value => resolve(typeof value === 'string' ? value : null) }));
|
|
5411
|
+
}
|
|
5412
|
+
finally {
|
|
5413
|
+
finish();
|
|
5414
|
+
}
|
|
5415
|
+
}
|
|
5416
|
+
observeRestoredPaneState(event) {
|
|
5417
|
+
if (event.type === 'session_restored') {
|
|
5418
|
+
this.awaitingRestoredPaneState = true;
|
|
5419
|
+
return;
|
|
5420
|
+
}
|
|
5421
|
+
if (event.type !== 'pane_state' || !this.awaitingRestoredPaneState)
|
|
5422
|
+
return;
|
|
5423
|
+
this.awaitingRestoredPaneState = false;
|
|
5424
|
+
const ids = new Set([0, ...event.panes.map(pane => pane.id)]);
|
|
5425
|
+
const previous = new Set([...this.childPaneIds, ...this.paneRegistry.all().map(pane => pane.paneId), ...this.childPaneModels.keys(), ...this.childPaneSessionIds.keys()]);
|
|
5426
|
+
for (const id of previous) {
|
|
5427
|
+
if (ids.has(id))
|
|
5428
|
+
continue;
|
|
5429
|
+
this.childPaneIds.delete(id);
|
|
5430
|
+
this.childPaneModels.delete(id);
|
|
5431
|
+
this.childPaneSessionIds.delete(id);
|
|
5432
|
+
this.childPaneStreamed.delete(id);
|
|
5433
|
+
this.colonyPaneIds.delete(id);
|
|
5434
|
+
this.pendingPaneReplacements.delete(id);
|
|
5435
|
+
this.paneRegistry.remove(id);
|
|
5436
|
+
this.mirrorServer?.unregisterPane(id);
|
|
5437
|
+
}
|
|
5438
|
+
this.resumedPaneSpecs = this.resumedPaneSpecs.filter(pane => ids.has(pane.paneId));
|
|
5439
|
+
}
|
|
5440
|
+
observeDailyStatusClosed(paneId) {
|
|
5441
|
+
this.knownPanes = this.knownPanes.filter(pane => pane.id !== paneId);
|
|
5442
|
+
if (this.dailyStatusPane !== paneId)
|
|
5443
|
+
return;
|
|
5444
|
+
this.dailyStatusPane = null;
|
|
5445
|
+
this.dailyDesktop?.store.setStatusPane('unavailable');
|
|
5446
|
+
}
|
|
5447
|
+
async readDailyPanes() {
|
|
5448
|
+
const observe = this.tui.on(event => { if (event.type === 'pane_list' || event.type === 'pane_state')
|
|
5449
|
+
this.knownPanes = event.panes; });
|
|
5450
|
+
try {
|
|
5451
|
+
// list_panes names no request: a refusal the renderer names for another request (a pane mutation queued
|
|
5452
|
+
// meanwhile) is not its answer.
|
|
5453
|
+
const listed = this.waitForTuiEvent(event => event.type === 'pane_list' || (event.type === 'error' && event.request_id === undefined), 4000);
|
|
5454
|
+
if (!this.tui.send({ type: 'list_panes' })) {
|
|
5455
|
+
void listed.catch(() => { });
|
|
5456
|
+
throw new Error('Cannot inspect the desktop Status pane');
|
|
5457
|
+
}
|
|
5458
|
+
const event = await listed;
|
|
5459
|
+
if (event.type === 'error')
|
|
5460
|
+
throw new Error(event.message);
|
|
5461
|
+
if (event.type !== 'pane_list')
|
|
5462
|
+
throw new Error('Cannot inspect the desktop Status pane');
|
|
5463
|
+
return this.knownPanes;
|
|
5464
|
+
}
|
|
5465
|
+
finally {
|
|
5466
|
+
observe();
|
|
5467
|
+
}
|
|
5468
|
+
}
|
|
5469
|
+
dailyStatusLaunch() {
|
|
5470
|
+
const daily = this.dailyDesktop;
|
|
5471
|
+
return buildWorkspaceMonitorLaunch('status', { cwd: this.shellCwd || process.cwd(), env: this.childZtcPaneEnv(), mirrorPort: this.mirrorServer.getPort(), workspaceOwnerId: daily.ownerId, trackLaunch: () => { } }, { ...loadWorkspacePreset(this.shellCwd || process.cwd(), 'orchestrator'), refresh_ms: 1000 });
|
|
5472
|
+
}
|
|
5473
|
+
async recoverDailyStatus(plan) {
|
|
5474
|
+
const daily = this.dailyDesktop;
|
|
5475
|
+
const panes = await this.readDailyPanes();
|
|
5476
|
+
const current = panes.find(pane => pane.id === plan.paneId);
|
|
5477
|
+
if (current?.is_alive && this.dailyStatusPane === plan.paneId) {
|
|
5478
|
+
daily.store.setStatusPane('ready');
|
|
5479
|
+
return;
|
|
5480
|
+
}
|
|
5481
|
+
if (current?.is_alive)
|
|
5482
|
+
throw new Error('Desktop Status slot is occupied by another running process');
|
|
5483
|
+
if (this.dailyStatusPane !== null)
|
|
5484
|
+
this.observeDailyStatusClosed(this.dailyStatusPane);
|
|
5485
|
+
if (current && await this.startDailyStatus(current.id, plan.state.focused_pane_id) && this.dailyStatusPane === current.id)
|
|
5486
|
+
return;
|
|
5487
|
+
const state = await this.readMuxSessionState();
|
|
5488
|
+
if (!state)
|
|
5489
|
+
throw new Error('Desktop Status recovery snapshot is unavailable');
|
|
5490
|
+
const present = await this.readDailyPanes();
|
|
5491
|
+
if (present.some(pane => pane.id === plan.paneId))
|
|
5492
|
+
throw new Error('Desktop Status replacement failed');
|
|
5493
|
+
const template = plan.state.panes.find(pane => pane.id === plan.paneId);
|
|
5494
|
+
const id = Math.max(0, ...state.panes.map(pane => pane.id), ...present.map(pane => pane.id)) + 1;
|
|
5495
|
+
statusRestoreState(state, { ...template, id }, new Set(present.map(pane => pane.id)));
|
|
5496
|
+
if (!await this.startDailyStatus(null, plan.state.focused_pane_id) || this.dailyStatusPane === null)
|
|
5497
|
+
throw new Error('Desktop Status is unavailable after workspace restore');
|
|
5498
|
+
}
|
|
5499
|
+
dailyLayoutOwner(remapped = () => { }) {
|
|
5500
|
+
const daily = this.dailyDesktop;
|
|
5501
|
+
let plan;
|
|
5502
|
+
return daily ? { records: () => daily.exportRecords(), isRestoring: () => this.nativeRestorePending, beginRestore: () => {
|
|
5503
|
+
if (this.nativeRestorePending)
|
|
5504
|
+
throw new Error('A workspace restore is in progress; try again when it finishes.');
|
|
5505
|
+
this.nativeRestorePending = true;
|
|
5506
|
+
let finish;
|
|
5507
|
+
this.nativeRestore = new Promise(resolve => { finish = resolve; });
|
|
5508
|
+
return () => { this.nativeRestorePending = false; finish(); };
|
|
5509
|
+
}, snapshot: () => this.completeSessionLayout(), restore: async (records, state, prepared) => {
|
|
5510
|
+
daily.store.setStatusPane('pending');
|
|
5511
|
+
try {
|
|
5512
|
+
if (prepared)
|
|
5513
|
+
await prepared();
|
|
5514
|
+
else
|
|
5515
|
+
await daily.restoreRecords(records);
|
|
5516
|
+
}
|
|
5517
|
+
finally {
|
|
5518
|
+
try {
|
|
5519
|
+
await this.recoverDailyStatus(plan);
|
|
5520
|
+
}
|
|
5521
|
+
catch (error) {
|
|
5522
|
+
daily.store.setStatusPane('unavailable');
|
|
5523
|
+
throw error;
|
|
5524
|
+
}
|
|
5525
|
+
}
|
|
5526
|
+
this.retainedStartupLayout = null;
|
|
5527
|
+
}, beforeRestore: () => daily.beforeRestore(), prepareRecords: (records) => daily.prepareRestoreRecords(records),
|
|
5528
|
+
prepareRestore: async (state) => {
|
|
5529
|
+
let liveIds = [];
|
|
5530
|
+
if (this.dailyStatusPane !== null) {
|
|
5531
|
+
const panes = await this.readDailyPanes();
|
|
5532
|
+
liveIds = panes.map(pane => pane.id);
|
|
5533
|
+
const status = this.dailyStatusPane;
|
|
5534
|
+
if (status !== null && !panes.some(pane => pane.id === status && pane.is_alive))
|
|
5535
|
+
this.observeDailyStatusClosed(status);
|
|
5536
|
+
}
|
|
5537
|
+
const status = this.dailyStatusPane;
|
|
5538
|
+
const saved = status === null ? this.savedDailyStatus(state) : this.savedDailyStatus(state, status);
|
|
5539
|
+
const paneIds = new Map();
|
|
5540
|
+
if (status !== null && !saved && state.panes.some(pane => pane.id === status)) {
|
|
5541
|
+
const replacement = Math.max(0, ...state.panes.map(pane => pane.id), ...liveIds) + 1;
|
|
5542
|
+
if (replacement > 0xffffffff)
|
|
5543
|
+
throw new Error('No free workspace pane ID is available');
|
|
5544
|
+
paneIds.set(status, replacement);
|
|
5545
|
+
state = remapWorkspacePaneIds(state, paneIds);
|
|
5546
|
+
}
|
|
5547
|
+
remapped(paneIds);
|
|
5548
|
+
const paneId = status ?? saved?.id ?? Math.max(0, ...state.panes.map(pane => pane.id)) + 1;
|
|
5549
|
+
const spec = this.dailyStatusLaunch();
|
|
5550
|
+
const pane = { id: paneId, title: 'Status', pane_type: 'process', desktop_status: true, command: spec.command, args: spec.args, cwd: spec.cwd };
|
|
5551
|
+
plan = { state: statusRestoreState(state, pane), paneId, preservePaneIds: status === null ? [0] : [0, status] };
|
|
5552
|
+
return plan;
|
|
5553
|
+
} } : undefined;
|
|
5554
|
+
}
|
|
5555
|
+
async startDailyDesktop() {
|
|
5556
|
+
let daily = null;
|
|
5557
|
+
try {
|
|
5558
|
+
const mirror = this.mirrorServer;
|
|
5559
|
+
daily = new DesktopDaily(mirror.getWorkspaceRuntimeSnapshot().owner_id, {
|
|
5560
|
+
transport: this.tui, cwd: () => this.shellCwd || process.cwd(), isRestoring: () => this.nativeRestorePending,
|
|
5561
|
+
delegatedSkillRoots: () => configStore.get().desktopDelegatedSkillRoots ?? [],
|
|
5562
|
+
select: (title, options) => this.dailySelect(title, options),
|
|
5563
|
+
input: (title, defaultValue) => new Promise(resolve => this.textInputWidget.show({ title, question: title, defaultValue, callback: resolve })),
|
|
5564
|
+
track: record => { const clean = parseNativeRecords({ [record.paneId]: record })[String(record.paneId)]; this.registerPaneSpec(clean.paneId, clean.launch.mode === 'interactive' ? 'process' : 'feed', `${clean.launch.tool} ${clean.launch.mode}`, { kind: 'native_tool', title: clean.launch.tool, record: clean }); },
|
|
5565
|
+
changed: () => { this.scheduleMuxPersistenceSave(100); this.syncOwnPaneTaskControls(); }, notify: message => this.controller.addMessage({ role: 'system', content: message }),
|
|
5566
|
+
});
|
|
5567
|
+
await daily.start();
|
|
5568
|
+
this.dailyDesktop = daily;
|
|
5569
|
+
this.syncOwnPaneTaskControls();
|
|
5570
|
+
const active = daily;
|
|
5571
|
+
mirror.setDailyDesktop(() => active.snapshot(), () => active.refreshRouter(), (action, paneId) => {
|
|
5572
|
+
const sent = this.tui.send(action === 'zoom' ? { type: 'zoom_pane', pane_id: paneId, return_focus_pane_id: this.dailyStatusPane ?? 0 } : { type: 'toggle_zoom', pane_id: paneId });
|
|
5573
|
+
if (action === 'collapse')
|
|
5574
|
+
this.tui.send({ type: 'focus_pane', pane_id: this.dailyStatusPane ?? 0 });
|
|
5575
|
+
return sent;
|
|
5576
|
+
});
|
|
5577
|
+
}
|
|
5578
|
+
catch (error) {
|
|
5579
|
+
this.dailyDesktop = null;
|
|
5580
|
+
this.mirrorServer?.setDailyDesktop(null, null, null);
|
|
5581
|
+
await daily?.close().catch(() => { });
|
|
5582
|
+
const value = error;
|
|
5583
|
+
const type = typeof value?.class === 'string' && /^(?:unauthorized|stale|forbidden_interactive|unknown_schema|lease_refused|launch_refused|not_found|invalid)$/.test(value.class) ? value.class
|
|
5584
|
+
: typeof value?.code === 'string' && /^(?:EACCES|EPERM|EADDRINUSE|ENAMETOOLONG|ENOTDIR|ENOENT|EEXIST|EROFS)$/.test(value.code) ? value.code : 'unavailable';
|
|
5585
|
+
this.controller.addMessage({ role: 'system', content: `Native tool panes unavailable: ${type}` });
|
|
5586
|
+
}
|
|
5587
|
+
void this.startDailyStatus();
|
|
5588
|
+
}
|
|
5589
|
+
savedDailyStatus(state, paneId) {
|
|
5590
|
+
return state?.panes.find(pane => {
|
|
5591
|
+
if (paneId !== undefined && pane.id !== paneId)
|
|
5592
|
+
return false;
|
|
5593
|
+
if (pane.pane_type !== 'process' || pane.agent_session || state.native_tools?.[pane.id])
|
|
5594
|
+
return false;
|
|
5595
|
+
if (pane.desktop_status !== undefined)
|
|
5596
|
+
return pane.desktop_status;
|
|
5597
|
+
const args = pane.args ?? [];
|
|
5598
|
+
const entry = args[0] === '--import' ? 2 : 0;
|
|
5599
|
+
return /(?:^|\/)node$/.test(pane.command ?? '') && /\/(?:src|dist)\/app\/workspace_monitor\.[tj]s$/.test(args[entry] ?? '')
|
|
5600
|
+
&& args[entry + 1] === 'status';
|
|
5601
|
+
});
|
|
5602
|
+
}
|
|
5603
|
+
startDailyStatus(replacement = null, focusedPaneId = 0) {
|
|
5604
|
+
const daily = this.dailyDesktop;
|
|
5605
|
+
if (!daily || this.exiting)
|
|
5606
|
+
return Promise.resolve(false);
|
|
5607
|
+
this.dailyStatusCancel?.();
|
|
5608
|
+
daily.store.setStatusPane('pending');
|
|
5609
|
+
return new Promise(resolve => {
|
|
5610
|
+
let timer;
|
|
5611
|
+
let unsubscribe = () => { };
|
|
5612
|
+
const cancel = () => {
|
|
5613
|
+
clearTimeout(timer);
|
|
5614
|
+
unsubscribe();
|
|
5615
|
+
if (this.dailyStatusCancel === cancel)
|
|
5616
|
+
this.dailyStatusCancel = null;
|
|
5617
|
+
resolve(false);
|
|
5618
|
+
};
|
|
5619
|
+
const unavailable = (reason) => {
|
|
5620
|
+
if (!this.exiting && this.dailyDesktop === daily) {
|
|
5621
|
+
daily.store.setStatusPane('unavailable');
|
|
5622
|
+
debugLog(`[daily-status] unavailable: ${reason}`);
|
|
5623
|
+
}
|
|
5624
|
+
if (reason === 'timeout')
|
|
5625
|
+
resolve(false);
|
|
5626
|
+
else
|
|
5627
|
+
cancel();
|
|
5628
|
+
};
|
|
5629
|
+
this.dailyStatusCancel = cancel;
|
|
5630
|
+
try {
|
|
5631
|
+
const spec = this.dailyStatusLaunch();
|
|
5632
|
+
const requestId = `daily-status-${generateSessionId()}`;
|
|
5633
|
+
this.trackPendingPaneLaunch(requestId, spec);
|
|
5634
|
+
unsubscribe = this.tui.on(event => {
|
|
5635
|
+
if (event.type !== 'pane_created' || event.request_id !== requestId)
|
|
5636
|
+
return;
|
|
5637
|
+
if (!this.exiting && this.dailyDesktop === daily) {
|
|
5638
|
+
this.dailyStatusPane = event.pane_id;
|
|
5639
|
+
daily.store.setStatusPane('ready');
|
|
5640
|
+
resolve(true);
|
|
5641
|
+
}
|
|
5642
|
+
cancel();
|
|
5643
|
+
});
|
|
5644
|
+
timer = setTimeout(() => unavailable('timeout'), 5000);
|
|
5645
|
+
timer.unref();
|
|
5646
|
+
if (replacement !== null && this.headlessMirror)
|
|
5647
|
+
this.trackPendingPaneReplacement(replacement, requestId);
|
|
5648
|
+
const sent = this.tui.send(replacement !== null ? { type: 'replace_pane', pane_id: replacement, command: spec.command, args: spec.args, cwd: spec.cwd, title: 'Status', pane_type: 'process', desktop_status: true, request_id: requestId }
|
|
5649
|
+
: { type: 'create_pane', command: spec.command, args: spec.args, cwd: spec.cwd, title: 'Status', pane_type: 'process', desktop_status: true,
|
|
5650
|
+
// Status is a workspace monitor: it asks for a monitor's credential of its own, from the mirror its command line
|
|
5651
|
+
// names, handed in a one-time file, as /layout orchestrator's monitors do (workspace_presets.ts). Started again in
|
|
5652
|
+
// place (replace_pane), it gets a fresh one from the pane transport (PaneCredentialBroker.prepareReplace).
|
|
5653
|
+
env: { ...this.childZtcPaneEnv(), ZTC_MIRROR_PORT: String(this.mirrorServer.getPort()), [PANE_CREDENTIAL_ENV]: WORKSPACE_MONITOR_CREDENTIAL_REQUEST },
|
|
5654
|
+
request_id: requestId, ...statusPlacement });
|
|
5655
|
+
if (!sent)
|
|
5656
|
+
unavailable('transport');
|
|
5657
|
+
else
|
|
5658
|
+
this.tui.send({ type: 'focus_pane', pane_id: focusedPaneId });
|
|
5659
|
+
}
|
|
5660
|
+
catch {
|
|
5661
|
+
unavailable('launch');
|
|
5662
|
+
}
|
|
5663
|
+
});
|
|
5664
|
+
}
|
|
5665
|
+
createWorkspaceLayoutOwner(restoredSpecs = []) {
|
|
5666
|
+
let restoredIds = new Map();
|
|
5388
5667
|
return createWorkspaceLayoutController(this.tui, () => this.paneRegistry.toSessionSpecs(), paneId => this.resumeWorkspacePane(paneId), this.mirrorServer ? {
|
|
5389
5668
|
cwd: this.shellCwd || process.cwd(), env: this.childZtcPaneEnv(),
|
|
5390
5669
|
mirrorPort: this.mirrorServer.getPort(), workspaceOwnerId: this.mirrorServer.getWorkspaceRuntimeSnapshot().owner_id,
|
|
5391
5670
|
trackLaunch: (requestId, spec) => this.trackPendingPaneLaunch(requestId, spec),
|
|
5392
5671
|
isActive: () => !this.exiting,
|
|
5393
|
-
} : undefined)
|
|
5672
|
+
} : undefined, this.dailyLayoutOwner(ids => { restoredIds = ids; }), state => {
|
|
5673
|
+
for (const pane of state.panes) {
|
|
5674
|
+
if (pane.id === 0 || pane.id === this.dailyStatusPane)
|
|
5675
|
+
continue;
|
|
5676
|
+
this.paneRegistry.remove(pane.id);
|
|
5677
|
+
const spec = restoredSpecs.find(saved => (restoredIds.get(saved.paneId) ?? saved.paneId) === pane.id);
|
|
5678
|
+
if (spec)
|
|
5679
|
+
this.registerPaneSpec(pane.id, spec.paneType, spec.title, spec.launchSpec);
|
|
5680
|
+
}
|
|
5681
|
+
});
|
|
5394
5682
|
}
|
|
5395
5683
|
formatTime(date) {
|
|
5396
5684
|
return formatTranscriptTime(date);
|
|
@@ -5415,14 +5703,14 @@ export class RatatuiApp {
|
|
|
5415
5703
|
* before child process 'close' events delete panes from the manager.
|
|
5416
5704
|
* getMuxSessionState() returns this cached snapshot if available.
|
|
5417
5705
|
*/
|
|
5418
|
-
|
|
5706
|
+
_emergencyLayoutSnapshot = undefined;
|
|
5419
5707
|
/**
|
|
5420
5708
|
* Synchronously capture the mux state before signal handlers cause
|
|
5421
5709
|
* child processes to die and be cleaned up from HeadlessPaneManager.
|
|
5422
5710
|
* Must be called at the very start of the emergency save handler.
|
|
5423
5711
|
*/
|
|
5424
5712
|
_captureEmergencyMuxSnapshot() {
|
|
5425
|
-
if (!this.muxMode || this.paneMode)
|
|
5713
|
+
if (!this.muxMode || this.paneMode || this.nativeRestorePending)
|
|
5426
5714
|
return;
|
|
5427
5715
|
try {
|
|
5428
5716
|
// For HeadlessPaneManager, send() + emit() are synchronous.
|
|
@@ -5437,8 +5725,9 @@ export class RatatuiApp {
|
|
|
5437
5725
|
this.tui.send({ type: 'get_session_state' });
|
|
5438
5726
|
unsub();
|
|
5439
5727
|
if (captured && captured.panes && captured.panes.length > 0) {
|
|
5440
|
-
const
|
|
5441
|
-
|
|
5728
|
+
const paneSpecs = this.paneRegistry.toSessionSpecs();
|
|
5729
|
+
const sanitized = sanitizeMuxSessionState(linkWorkspaceAgentSessions(captured, paneSpecs), resolveMuxPersistenceOptions());
|
|
5730
|
+
this._emergencyLayoutSnapshot = structuredClone({ muxState: sanitized, paneSpecs });
|
|
5442
5731
|
debugLog(`[signal] Captured mux snapshot: ${sanitized.panes.length} panes`);
|
|
5443
5732
|
}
|
|
5444
5733
|
}
|
|
@@ -5451,11 +5740,11 @@ export class RatatuiApp {
|
|
|
5451
5740
|
* Fire-and-forget — errors are silently logged.
|
|
5452
5741
|
*/
|
|
5453
5742
|
readAndPublishDocContent(paneId) {
|
|
5454
|
-
if (!this.mirrorServer)
|
|
5743
|
+
if (!this.mirrorServer || this.dailyDesktop?.hasPane(paneId))
|
|
5455
5744
|
return;
|
|
5456
5745
|
const mirror = this.mirrorServer;
|
|
5457
5746
|
this.waitForTuiEvent((event) => event.type === 'pane_read' && event.pane_id === paneId, 3000).then((event) => {
|
|
5458
|
-
if (event.type === 'pane_read' && event.content) {
|
|
5747
|
+
if (event.type === 'pane_read' && event.content && !this.dailyDesktop?.hasPane(paneId)) {
|
|
5459
5748
|
mirror.publish({
|
|
5460
5749
|
type: 'pane_output',
|
|
5461
5750
|
data: { pane_id: paneId, content: event.content },
|
|
@@ -5467,13 +5756,13 @@ export class RatatuiApp {
|
|
|
5467
5756
|
this.tui.send({ type: 'read_pane', pane_id: paneId });
|
|
5468
5757
|
}
|
|
5469
5758
|
async getMuxSessionState(timeoutMs = 4000) {
|
|
5759
|
+
// Return emergency snapshot if captured during signal handler
|
|
5760
|
+
return (await this.completeSessionLayout(timeoutMs))?.muxState;
|
|
5761
|
+
}
|
|
5762
|
+
async readMuxSessionState(timeoutMs = 4000) {
|
|
5470
5763
|
if (!this.muxMode || this.paneMode) {
|
|
5471
5764
|
return undefined;
|
|
5472
5765
|
}
|
|
5473
|
-
// Return emergency snapshot if captured during signal handler
|
|
5474
|
-
if (this._emergencyMuxSnapshot) {
|
|
5475
|
-
return this._emergencyMuxSnapshot;
|
|
5476
|
-
}
|
|
5477
5766
|
const eventPromise = this.waitForTuiEvent((event) => event.type === 'session_state', timeoutMs);
|
|
5478
5767
|
const sent = this.tui.send({ type: 'get_session_state' });
|
|
5479
5768
|
if (!sent) {
|
|
@@ -5482,9 +5771,12 @@ export class RatatuiApp {
|
|
|
5482
5771
|
}
|
|
5483
5772
|
try {
|
|
5484
5773
|
const event = await eventPromise;
|
|
5485
|
-
|
|
5486
|
-
|
|
5487
|
-
|
|
5774
|
+
if (event.type !== 'session_state')
|
|
5775
|
+
return undefined;
|
|
5776
|
+
validateWorkspaceState(event.state);
|
|
5777
|
+
if (this.retainedStartupLayout && this.retainedStartupTopology === null)
|
|
5778
|
+
this.retainedStartupTopology = this.workspacePaneTopology(event.state);
|
|
5779
|
+
return event.state;
|
|
5488
5780
|
}
|
|
5489
5781
|
catch (err) {
|
|
5490
5782
|
debugLog(`[mux-session] Failed to snapshot mux state: ${err.message}`);
|
|
@@ -6062,27 +6354,36 @@ export class RatatuiApp {
|
|
|
6062
6354
|
const state = this.resumedSession?.mux_state;
|
|
6063
6355
|
if (!state || !this.muxMode || this.paneMode)
|
|
6064
6356
|
return null;
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
const owner = createWorkspaceLayoutController(this.tui, () => this.resumedPaneSpecs, id => this.resumeWorkspacePane(id));
|
|
6357
|
+
const retained = structuredClone({ muxState: state, paneSpecs: this.resumedPaneSpecs });
|
|
6358
|
+
const owner = this.createWorkspaceLayoutOwner(this.resumedPaneSpecs);
|
|
6068
6359
|
try {
|
|
6069
|
-
const result = await owner.restoreSnapshot(state);
|
|
6360
|
+
const result = await owner.restoreSnapshot(linkWorkspaceAgentSessions(state, this.resumedPaneSpecs));
|
|
6361
|
+
this.retainedStartupLayout = null;
|
|
6070
6362
|
return { restoredPanes: result.restored_panes, skippedPanes: result.skipped_panes };
|
|
6071
6363
|
}
|
|
6072
6364
|
catch (error) {
|
|
6365
|
+
this.retainedStartupLayout = retained;
|
|
6366
|
+
this.retainedStartupTopology = null;
|
|
6367
|
+
await this.readMuxSessionState();
|
|
6073
6368
|
const diagnostic = error.message;
|
|
6074
6369
|
debugLog(`[mux-session] Retained saved workspace after refused restore: ${diagnostic}`);
|
|
6075
6370
|
return { restoredPanes: 0, skippedPanes: state.panes?.length ?? 0, diagnostic };
|
|
6076
6371
|
}
|
|
6077
6372
|
}
|
|
6078
6373
|
async resumeWorkspacePane(paneId) {
|
|
6374
|
+
if (this.dailyDesktop?.exportRecords()[String(paneId)]) {
|
|
6375
|
+
await this.dailyDesktop.resume(paneId);
|
|
6376
|
+
return;
|
|
6377
|
+
}
|
|
6079
6378
|
if (this.isHostedRuntime())
|
|
6080
6379
|
throw new Error('Hosted workbenches allow one agent pane per thread.');
|
|
6081
6380
|
const state = await this.getMuxSessionState();
|
|
6082
6381
|
const pane = state?.panes.find(saved => saved.id === paneId);
|
|
6083
6382
|
if (!pane?.agent_session || paneId === 0)
|
|
6084
6383
|
throw new Error('This pane has no canonical saved agent session link.');
|
|
6085
|
-
|
|
6384
|
+
// list_panes names no request: a refusal the renderer names for another request (a pane mutation queued
|
|
6385
|
+
// meanwhile) is not its answer.
|
|
6386
|
+
const listed = this.waitForTuiEvent(event => event.type === 'pane_list' || (event.type === 'error' && event.request_id === undefined), 4000);
|
|
6086
6387
|
if (!this.tui.send({ type: 'list_panes' })) {
|
|
6087
6388
|
listed.catch(() => { });
|
|
6088
6389
|
throw new Error('Cannot inspect the saved pane before resuming.');
|
|
@@ -6096,7 +6397,7 @@ export class RatatuiApp {
|
|
|
6096
6397
|
const spec = this.createZtcPaneSpec({ sessionId: session.metadata.id, sessionMode: 'resume', cwd: pane.agent_session.project_path, title: pane.title });
|
|
6097
6398
|
const child = this.buildZtcCommand(spec);
|
|
6098
6399
|
const requestId = `resume-workspace-${generateSessionId()}`;
|
|
6099
|
-
const created = this.waitForTuiEvent(event => event
|
|
6400
|
+
const created = this.waitForTuiEvent(event => isPaneRefusalFor(event, requestId) || (event.type === 'pane_created' && event.request_id === requestId), 15000);
|
|
6100
6401
|
this.trackPendingPaneLaunch(requestId, spec);
|
|
6101
6402
|
this.trackPendingPaneReplacement(paneId, requestId);
|
|
6102
6403
|
// The pane transport gives the resumed ZTC a mirror credential of its own, as for a new pane (PaneCredentialBroker).
|
|
@@ -7025,6 +7326,10 @@ export class RatatuiApp {
|
|
|
7025
7326
|
break;
|
|
7026
7327
|
// Pane lifecycle events — forward to mirror server for multi-pane browser UI
|
|
7027
7328
|
case 'pane_created': {
|
|
7329
|
+
if (!this.nativeRestorePending)
|
|
7330
|
+
this.retainedStartupLayout = null;
|
|
7331
|
+
if (this.dailyDesktop?.hasPane(event.pane_id))
|
|
7332
|
+
this.dailyDesktop.paneClosed(event.pane_id);
|
|
7028
7333
|
this.childPaneIds.add(event.pane_id);
|
|
7029
7334
|
this.notePaneCreated(event.pane_id, event.request_id);
|
|
7030
7335
|
const agentCli = agentCliFromRequestId(event.request_id);
|
|
@@ -7086,7 +7391,7 @@ export class RatatuiApp {
|
|
|
7086
7391
|
// Ctrl+B c: zmux consumed the key, and the owner picks the pane because
|
|
7087
7392
|
// the options live in ZTC's config and a ZTC pane needs this process's
|
|
7088
7393
|
// entrypoint and environment.
|
|
7089
|
-
this.showNewPanePicker(event.cwd);
|
|
7394
|
+
void this.showNewPanePicker(event.cwd);
|
|
7090
7395
|
break;
|
|
7091
7396
|
case 'show_keybindings':
|
|
7092
7397
|
// zmux's shortcut page handed off to the editor; the Shortcuts panel
|
|
@@ -7097,6 +7402,11 @@ export class RatatuiApp {
|
|
|
7097
7402
|
this.handleWidgetWheel(event.direction, event.col, event.row);
|
|
7098
7403
|
break;
|
|
7099
7404
|
case 'pane_state':
|
|
7405
|
+
this.observeRestoredPaneState(event);
|
|
7406
|
+
if (!this.nativeRestorePending && this.knownPanes.length
|
|
7407
|
+
&& JSON.stringify(this.knownPanes.map(pane => [pane.id, pane.window_id ?? 0]).sort((a, b) => a[0] - b[0]))
|
|
7408
|
+
!== JSON.stringify(event.panes.map(pane => [pane.id, pane.window_id ?? 0]).sort((a, b) => a[0] - b[0])))
|
|
7409
|
+
this.retainedStartupLayout = null;
|
|
7100
7410
|
if (JSON.stringify(this.knownPanes.map(pane => [pane.id, pane.labels])) !== JSON.stringify(event.panes.map(pane => [pane.id, pane.labels]))) {
|
|
7101
7411
|
this.scheduleMuxPersistenceSave();
|
|
7102
7412
|
}
|
|
@@ -7129,20 +7439,26 @@ export class RatatuiApp {
|
|
|
7129
7439
|
}
|
|
7130
7440
|
break;
|
|
7131
7441
|
case 'session_state':
|
|
7442
|
+
break;
|
|
7132
7443
|
case 'session_restored':
|
|
7444
|
+
this.observeRestoredPaneState(event);
|
|
7133
7445
|
break;
|
|
7134
7446
|
case 'workspace_pane_action': {
|
|
7135
|
-
const owner =
|
|
7447
|
+
const owner = this.createWorkspaceLayoutOwner();
|
|
7136
7448
|
void owner.execute([event.action, String(event.pane_id)])
|
|
7137
7449
|
.then(message => this.addSystemMessage(message))
|
|
7138
7450
|
.catch(error => this.addSystemMessage(`Workspace: ${error.message}`));
|
|
7139
7451
|
break;
|
|
7140
7452
|
}
|
|
7141
7453
|
case 'pane_closed':
|
|
7454
|
+
if (!this.nativeRestorePending)
|
|
7455
|
+
this.retainedStartupLayout = null;
|
|
7456
|
+
this.dailyDesktop?.paneClosed(event.pane_id);
|
|
7142
7457
|
if (this.shouldIgnorePaneClosed(event.pane_id)) {
|
|
7143
7458
|
debugLog(`[Mirror] Ignoring pane_closed during replace for pane ${event.pane_id}`);
|
|
7144
7459
|
break;
|
|
7145
7460
|
}
|
|
7461
|
+
this.observeDailyStatusClosed(event.pane_id);
|
|
7146
7462
|
this.childPaneIds.delete(event.pane_id);
|
|
7147
7463
|
this.childPaneModels.delete(event.pane_id);
|
|
7148
7464
|
this.childPaneSessionIds.delete(event.pane_id);
|
|
@@ -7159,7 +7475,7 @@ export class RatatuiApp {
|
|
|
7159
7475
|
this.scheduleMuxPersistenceSave(0);
|
|
7160
7476
|
break;
|
|
7161
7477
|
case 'pane_output':
|
|
7162
|
-
if (this.mirrorServer && !this.colonyPaneIds.has(event.pane_id)) {
|
|
7478
|
+
if (this.mirrorServer && !this.colonyPaneIds.has(event.pane_id) && !this.dailyDesktop?.hasPane(event.pane_id)) {
|
|
7163
7479
|
// zmux streams terminal panes as whole-viewport ANSI snapshots with
|
|
7164
7480
|
// reset=true; pass it through so the browser clears the terminal and
|
|
7165
7481
|
// repaints the frame instead of appending duplicated screens.
|
|
@@ -8871,6 +9187,75 @@ export class RatatuiApp {
|
|
|
8871
9187
|
takesRouterAttempt(person, via) {
|
|
8872
9188
|
return person && (via === 'broadcast' || !this.relayedHere(via));
|
|
8873
9189
|
}
|
|
9190
|
+
/**
|
|
9191
|
+
* Input from the browser mirror, a ZTC process or pane, or /broadcast (`via`), or a correlated turn from /pane-input.
|
|
9192
|
+
* Uncorrelated input runs as submitMirrorInput describes. A correlated turn is posted with the mirror's token by an
|
|
9193
|
+
* automated supervisor (Zerg's clone delivery), never typed by the person, so it runs as relayed input whichever
|
|
9194
|
+
* credential carried it: it never takes the person's attempt past a Zerg Router refusal, and it is refused rather than
|
|
9195
|
+
* queued or made a steering input.
|
|
9196
|
+
*/
|
|
9197
|
+
async handleMirrorInput(input, via = 'browser') {
|
|
9198
|
+
if (input.correlation_id === undefined) {
|
|
9199
|
+
void this.submitMirrorInput(input, via);
|
|
9200
|
+
return;
|
|
9201
|
+
}
|
|
9202
|
+
// Serialize admission only, never the model run. A repeated caller key is
|
|
9203
|
+
// reconciled from canonical source even while the first turn is active.
|
|
9204
|
+
const prior = this.correlatedAdmission;
|
|
9205
|
+
let unlock;
|
|
9206
|
+
this.correlatedAdmission = new Promise(resolve => { unlock = resolve; });
|
|
9207
|
+
await prior;
|
|
9208
|
+
try {
|
|
9209
|
+
await this.awaitStartupReady();
|
|
9210
|
+
const digest = correlatedInputDigest(input);
|
|
9211
|
+
const history = this.ensureSessionManager().getPromptTurns();
|
|
9212
|
+
const existing = history.find(turn => turn.correlationId === input.correlation_id);
|
|
9213
|
+
if (existing) {
|
|
9214
|
+
if (existing.inputSha256 !== digest)
|
|
9215
|
+
return { ok: false, reason: 'input_conflict' };
|
|
9216
|
+
await this.saveCurrentSession(true);
|
|
9217
|
+
const turn = projectCorrelatedTurns(this.committedTurnMessages, this.sessionId, this.committedPromptTurns)
|
|
9218
|
+
.find(receipt => receipt.turn_id === existing.id);
|
|
9219
|
+
return turn ? { ok: true, turn } : { ok: false, reason: 'input_unavailable' };
|
|
9220
|
+
}
|
|
9221
|
+
if (goalManager.get()?.status === 'active' || hasSustainedGoalIntent(input.text)) {
|
|
9222
|
+
return { ok: false, reason: 'input_not_admitted', refusal: { schema_version: 1,
|
|
9223
|
+
session_id: this.sessionId, pane_id: 0, correlation_id: input.correlation_id, code: 'persistent_goal_unsupported' } };
|
|
9224
|
+
}
|
|
9225
|
+
if (history.length >= MAX_CORRELATED_TURNS || this.exiting || this.isAgentBusy() || this.agentTurnOwner || this.runtimeMutationInFlight
|
|
9226
|
+
|| this.waitingInteraction || this.pendingAgentTurn || this.pendingPlanApproval || this.pendingAskUser
|
|
9227
|
+
|| this.controller.getState().messages.some(message => message.turn?.correlationId
|
|
9228
|
+
&& (message.turn.state === 'admitted' || message.turn.state === 'running'))
|
|
9229
|
+
|| routeUserInput(input.text).type !== 'message' || !this.resolveSendRoute().ready) {
|
|
9230
|
+
return { ok: false, reason: 'input_not_admitted' };
|
|
9231
|
+
}
|
|
9232
|
+
let acknowledge;
|
|
9233
|
+
const acknowledged = new Promise(resolve => { acknowledge = resolve; });
|
|
9234
|
+
const submitted = this.handleSubmit(input, undefined, undefined, true, false, false, via, async () => {
|
|
9235
|
+
const message = this.controller.getState().messages.at(-1);
|
|
9236
|
+
const metadata = { id: message.id, startedAt: Date.now(), tokens: 0,
|
|
9237
|
+
estimated: false, correlationId: input.correlation_id, inputSha256: digest, state: 'admitted', revision: 1 };
|
|
9238
|
+
this.controller.setMessages(this.controller.getState().messages.map(source => source.id === message.id
|
|
9239
|
+
? { ...source, turn: metadata } : source));
|
|
9240
|
+
this.beginPromptTurn(message.id, metadata);
|
|
9241
|
+
await this.saveCurrentSession(true);
|
|
9242
|
+
const turn = projectCorrelatedTurns(this.committedTurnMessages, this.sessionId, this.committedPromptTurns)
|
|
9243
|
+
.find(receipt => receipt.turn_id === message.id);
|
|
9244
|
+
acknowledge(turn ? { ok: true, turn } : { ok: false, reason: 'input_unavailable' });
|
|
9245
|
+
}).then(() => ({ ok: false, reason: 'input_not_admitted' }), error => {
|
|
9246
|
+
debugLog(`[mirror] Correlated input unavailable: ${String(error)}`);
|
|
9247
|
+
return { ok: false, reason: 'input_unavailable' };
|
|
9248
|
+
});
|
|
9249
|
+
return await Promise.race([acknowledged, submitted]);
|
|
9250
|
+
}
|
|
9251
|
+
catch (error) {
|
|
9252
|
+
debugLog(`[mirror] Correlated admission unavailable: ${String(error)}`);
|
|
9253
|
+
return { ok: false, reason: 'input_unavailable' };
|
|
9254
|
+
}
|
|
9255
|
+
finally {
|
|
9256
|
+
unlock();
|
|
9257
|
+
}
|
|
9258
|
+
}
|
|
8874
9259
|
/**
|
|
8875
9260
|
* `person`: the person entered this input themselves (see submitPersonInput). A /loop tick, a goal continuation,
|
|
8876
9261
|
* another pane's or the coordinator's message and a pane's initial task never are, so none of them passes a Zerg
|
|
@@ -8881,9 +9266,11 @@ export class RatatuiApp {
|
|
|
8881
9266
|
* a pane, which is never the person's (submitMirrorInput). In a ZTC another ZTC launched into one of its panes, what
|
|
8882
9267
|
* the terminal gives it isn't only the person's, and what /broadcast gives any ZTC never is (see relayedHere). What
|
|
8883
9268
|
* is relayed here makes none of the person's choices and, unless /broadcast delivered it, passes no refusal either
|
|
8884
|
-
* (see takesRouterAttempt).
|
|
9269
|
+
* (see takesRouterAttempt). A correlated turn from /pane-input is not the person's either (see handleMirrorInput).
|
|
9270
|
+
* `admitted`: that turn's acknowledgement, run once its message is admitted and before the model run; such input is
|
|
9271
|
+
* refused instead of being queued or steering a busy turn.
|
|
8885
9272
|
*/
|
|
8886
|
-
async handleSubmit(rawInput, queuedEntryId, queuedAdmission, literalInput = false, credentialPrompted = false, person = false, via = 'terminal') {
|
|
9273
|
+
async handleSubmit(rawInput, queuedEntryId, queuedAdmission, literalInput = false, credentialPrompted = false, person = false, via = 'terminal', admitted) {
|
|
8887
9274
|
if (this.exiting)
|
|
8888
9275
|
return;
|
|
8889
9276
|
const input = parseStructuredSubmitInput(rawInput);
|
|
@@ -8911,6 +9298,8 @@ export class RatatuiApp {
|
|
|
8911
9298
|
this.idleCompaction.cancel();
|
|
8912
9299
|
this.lastInputAt = Date.now();
|
|
8913
9300
|
if (this.runtimeMutationInFlight) {
|
|
9301
|
+
if (admitted)
|
|
9302
|
+
return;
|
|
8914
9303
|
// A key command is never kept in the queue (it is stored word for word).
|
|
8915
9304
|
if (redactCredentialCommand(text) !== text) {
|
|
8916
9305
|
this.addSystemMessage('Account or model change in progress; run the key command again when it finishes.');
|
|
@@ -9033,6 +9422,10 @@ export class RatatuiApp {
|
|
|
9033
9422
|
const busy = this.isAgentBusy() && !(this.agentTurnOwner !== null && this.agentTurnOwner === this.cancelledTurnOwner);
|
|
9034
9423
|
const inputMode = state.inputMode;
|
|
9035
9424
|
if (busy) {
|
|
9425
|
+
// A correlated request may not become an unacknowledged steering input
|
|
9426
|
+
// if another transport won admission while workspace checks yielded.
|
|
9427
|
+
if (admitted)
|
|
9428
|
+
return;
|
|
9036
9429
|
if (inputMode === 'steer') {
|
|
9037
9430
|
await this.routeBusyInput(input, routerAttempt);
|
|
9038
9431
|
return;
|
|
@@ -9088,6 +9481,8 @@ export class RatatuiApp {
|
|
|
9088
9481
|
this.addErrorMessage('Failed to initialize agent. Please check your configuration.');
|
|
9089
9482
|
return;
|
|
9090
9483
|
}
|
|
9484
|
+
if (admitted)
|
|
9485
|
+
await admitted();
|
|
9091
9486
|
// Publish user message to observer (with attachments so thumbnails survive a refresh).
|
|
9092
9487
|
this.mirror?.publishMessage('user', text, attachments.length > 0 ? { attachments } : undefined);
|
|
9093
9488
|
queuedAdmission?.onQueuedAdmission();
|
|
@@ -10600,6 +10995,7 @@ export class RatatuiApp {
|
|
|
10600
10995
|
return this.runAgentTurn(true, owner);
|
|
10601
10996
|
}
|
|
10602
10997
|
}
|
|
10998
|
+
promptTurn.setOutcome('failed');
|
|
10603
10999
|
this.addErrorMessage(`Error: ${errorMsg}`);
|
|
10604
11000
|
let routedTurn = false;
|
|
10605
11001
|
try {
|
|
@@ -10652,6 +11048,7 @@ export class RatatuiApp {
|
|
|
10652
11048
|
this.finishLocalStreamingMessages();
|
|
10653
11049
|
this.finishToolGroups(cancelled ? 'Cancelled' : 'No result received');
|
|
10654
11050
|
if (cancelled) {
|
|
11051
|
+
promptTurn.setOutcome('interrupted');
|
|
10655
11052
|
this.pendingPlanApproval = false;
|
|
10656
11053
|
this.pendingAskUser = false;
|
|
10657
11054
|
this.askUserData = null;
|
|
@@ -10935,15 +11332,20 @@ export class RatatuiApp {
|
|
|
10935
11332
|
}
|
|
10936
11333
|
finally {
|
|
10937
11334
|
this.syncPromptTurn(this.streamingPromptTurn ?? promptTurn, initialMessageCount);
|
|
10938
|
-
for (const
|
|
10939
|
-
|
|
11335
|
+
for (const turn of promptTurns) {
|
|
11336
|
+
if (turn.snapshot().state === 'running')
|
|
11337
|
+
turn.setOutcome('completed');
|
|
11338
|
+
turn.finish();
|
|
11339
|
+
}
|
|
11340
|
+
if (promptTurn.snapshot().correlationId)
|
|
11341
|
+
await this.saveCurrentSession(true);
|
|
10940
11342
|
this.lastCacheActivityAt = Date.now();
|
|
10941
11343
|
if (!this.exiting)
|
|
10942
11344
|
this.idleCompaction.arm();
|
|
10943
11345
|
}
|
|
10944
11346
|
}
|
|
10945
|
-
beginPromptTurn(id) {
|
|
10946
|
-
const turn = new PromptTurn(id, () => this.syncPromptTurn(turn));
|
|
11347
|
+
beginPromptTurn(id, initial) {
|
|
11348
|
+
const turn = new PromptTurn(id, () => this.syncPromptTurn(turn), initial?.startedAt, initial);
|
|
10947
11349
|
this.activePromptTurn = turn;
|
|
10948
11350
|
if (this.runLifecycle.isRunning()) {
|
|
10949
11351
|
this.promptRunTurns.add(turn);
|
|
@@ -10966,10 +11368,13 @@ export class RatatuiApp {
|
|
|
10966
11368
|
if (this.exiting)
|
|
10967
11369
|
return;
|
|
10968
11370
|
const snapshot = turn.snapshot();
|
|
11371
|
+
if (snapshot.correlationId)
|
|
11372
|
+
this.ensureSessionManager().restorePromptTurns([snapshot]);
|
|
10969
11373
|
const messages = this.controller.getState().messages;
|
|
10970
11374
|
let changed = false;
|
|
10971
11375
|
const next = messages.map((message, index) => {
|
|
10972
|
-
|
|
11376
|
+
const authored = message.role === 'user' && message.id === snapshot.id && message.turn?.correlationId;
|
|
11377
|
+
if (!authored && (message.role !== 'assistant' || (message.turn?.id !== snapshot.id && !(attachFromIndex !== undefined && index >= attachFromIndex && !message.turn))))
|
|
10973
11378
|
return message;
|
|
10974
11379
|
changed = true;
|
|
10975
11380
|
return { ...message, turn: snapshot };
|
|
@@ -11708,6 +12113,25 @@ export class RatatuiApp {
|
|
|
11708
12113
|
* its panes reads from its terminal (see handleSubmit).
|
|
11709
12114
|
*/
|
|
11710
12115
|
async handleCommand(cmd, cmdArgs, publishUserMessage = true, origin) {
|
|
12116
|
+
if (cmd === 'pane' && cmdArgs[0] === 'stop' && this.dailyDesktop) {
|
|
12117
|
+
if (origin === 'relayed') {
|
|
12118
|
+
this.addSystemMessage('Native Stop requires a direct human command');
|
|
12119
|
+
return;
|
|
12120
|
+
}
|
|
12121
|
+
const paneId = Number(cmdArgs[1]);
|
|
12122
|
+
if (cmdArgs.length !== 2 || !Number.isSafeInteger(paneId) || !this.dailyDesktop.hasPane(paneId)) {
|
|
12123
|
+
this.addSystemMessage('Usage: /pane stop <native pane id>');
|
|
12124
|
+
return;
|
|
12125
|
+
}
|
|
12126
|
+
try {
|
|
12127
|
+
const outcome = await this.dailyDesktop.stop(paneId);
|
|
12128
|
+
this.addSystemMessage(`Pane ${paneId}: ${outcome.stopState}; observed survivors ${outcome.survivors.join(', ') || 'none'}`);
|
|
12129
|
+
}
|
|
12130
|
+
catch {
|
|
12131
|
+
this.addSystemMessage('Native Stop refused');
|
|
12132
|
+
}
|
|
12133
|
+
return;
|
|
12134
|
+
}
|
|
11711
12135
|
const cmdText = `/${cmd}${cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''}`;
|
|
11712
12136
|
if (publishUserMessage) {
|
|
11713
12137
|
this.mirror?.publishMessage('user', redactCredentialCommand(cmdText));
|
|
@@ -12305,7 +12729,7 @@ export class RatatuiApp {
|
|
|
12305
12729
|
return;
|
|
12306
12730
|
if (!this.shouldPersistSession())
|
|
12307
12731
|
return;
|
|
12308
|
-
this.ensureSessionManager().startAutoSave(this.AUTO_SAVE_INTERVAL);
|
|
12732
|
+
this.ensureSessionManager().startAutoSave(this.AUTO_SAVE_INTERVAL, () => this.saveBackgroundSession());
|
|
12309
12733
|
}
|
|
12310
12734
|
idleCompactionInput() {
|
|
12311
12735
|
const provider = configStore.getProvider();
|
|
@@ -12332,6 +12756,50 @@ export class RatatuiApp {
|
|
|
12332
12756
|
return;
|
|
12333
12757
|
await this.ensureSessionManager().save({ persistEmpty: force, required: force, signal, ...(this.exiting ? { captureLayout: true } : {}) });
|
|
12334
12758
|
}
|
|
12759
|
+
workspacePaneTopology(state) {
|
|
12760
|
+
const layout = (node) => node.type === 'leaf' ? node.pane_id : [node.direction, layout(node.first), layout(node.second)];
|
|
12761
|
+
return JSON.stringify({ windows: state.windows
|
|
12762
|
+
? state.windows.map(window => [window.id, layout(window.layout)]).sort((a, b) => Number(a[0]) - Number(b[0]))
|
|
12763
|
+
: [[0, layout(state.layout)]], panes: state.panes.map(pane => [pane.id, pane.window_id ?? 0]).sort((a, b) => a[0] - b[0]) });
|
|
12764
|
+
}
|
|
12765
|
+
async completeSessionLayout(timeoutMs = 4000, checkpoint = false) {
|
|
12766
|
+
if (this.nativeRestorePending)
|
|
12767
|
+
return undefined;
|
|
12768
|
+
if (this._emergencyLayoutSnapshot)
|
|
12769
|
+
return structuredClone(checkpoint && this.retainedStartupLayout || this._emergencyLayoutSnapshot);
|
|
12770
|
+
const restoring = this.nativeRestore;
|
|
12771
|
+
const state = await this.readMuxSessionState(timeoutMs);
|
|
12772
|
+
if (this.nativeRestorePending || restoring !== this.nativeRestore)
|
|
12773
|
+
return undefined;
|
|
12774
|
+
if (checkpoint && this.retainedStartupLayout && state && this.retainedStartupTopology !== this.workspacePaneTopology(state))
|
|
12775
|
+
this.retainedStartupLayout = null;
|
|
12776
|
+
if (checkpoint && this.retainedStartupLayout)
|
|
12777
|
+
return structuredClone(this.retainedStartupLayout);
|
|
12778
|
+
const paneSpecs = this.paneRegistry.toSessionSpecs();
|
|
12779
|
+
const muxState = state ? sanitizeMuxSessionState(linkWorkspaceAgentSessions(state, paneSpecs), resolveMuxPersistenceOptions()) : undefined;
|
|
12780
|
+
const status = muxState?.panes.find(pane => pane.id === this.dailyStatusPane);
|
|
12781
|
+
if (status)
|
|
12782
|
+
status.desktop_status = true;
|
|
12783
|
+
return structuredClone({ muxState, paneSpecs });
|
|
12784
|
+
}
|
|
12785
|
+
async backgroundSessionLayout() {
|
|
12786
|
+
const restoring = this.nativeRestore;
|
|
12787
|
+
await restoring;
|
|
12788
|
+
const layout = await this.completeSessionLayout(4000, true);
|
|
12789
|
+
if (restoring !== this.nativeRestore)
|
|
12790
|
+
return this.backgroundSessionLayout();
|
|
12791
|
+
if (!layout?.muxState)
|
|
12792
|
+
throw new Error('Background workspace snapshot is unavailable');
|
|
12793
|
+
return layout;
|
|
12794
|
+
}
|
|
12795
|
+
async saveBackgroundSession(muxOnly = false) {
|
|
12796
|
+
const manager = this.ensureSessionManager();
|
|
12797
|
+
if (this.dailyDesktop)
|
|
12798
|
+
return manager.saveBackground(() => this.backgroundSessionLayout(), muxOnly);
|
|
12799
|
+
if (muxOnly && await manager.saveMuxOnly())
|
|
12800
|
+
return;
|
|
12801
|
+
await manager.save();
|
|
12802
|
+
}
|
|
12335
12803
|
scheduleMuxPersistenceSave(delayMs = 250) {
|
|
12336
12804
|
if (!this.shouldPersistSession())
|
|
12337
12805
|
return;
|
|
@@ -12342,12 +12810,8 @@ export class RatatuiApp {
|
|
|
12342
12810
|
this.pendingMuxPersistenceSave = null;
|
|
12343
12811
|
// Try lightweight mux-only save first; fall back to full session save
|
|
12344
12812
|
// when no dedicated mux dir exists (non-colony global storage).
|
|
12345
|
-
const mgr = this.ensureSessionManager();
|
|
12346
12813
|
// ZTC exits on an unhandled rejection; a failed background save once closed it mid-turn (2026-10-27).
|
|
12347
|
-
void
|
|
12348
|
-
if (!wrote)
|
|
12349
|
-
return mgr.save();
|
|
12350
|
-
}).catch(error => debugLog(`[session] Layout save failed: ${String(error)}`));
|
|
12814
|
+
void this.saveBackgroundSession(true).catch(error => debugLog(`[session] Layout save failed: ${String(error)}`));
|
|
12351
12815
|
};
|
|
12352
12816
|
if (delayMs <= 0) {
|
|
12353
12817
|
doSave();
|
|
@@ -12694,8 +13158,7 @@ export class RatatuiApp {
|
|
|
12694
13158
|
// modelContextWindow) when available, else the static guess. Keeps /context
|
|
12695
13159
|
// + auto-compact on the SAME denominator the bar shows.
|
|
12696
13160
|
getContextWindow: () => this.controller.getState().contextStatus?.total,
|
|
12697
|
-
|
|
12698
|
-
getPaneSpecs: () => this.paneRegistry.toSessionSpecs(),
|
|
13161
|
+
getLayoutSnapshot: () => this.completeSessionLayout(4000, true),
|
|
12699
13162
|
getRuntimeState: () => ({
|
|
12700
13163
|
environment: this.environmentRecord ? { id: this.environmentRecord.id, name: this.environmentRecord.name } : null,
|
|
12701
13164
|
evidence: this.currentSessionEvidenceSnapshot(),
|
|
@@ -12716,14 +13179,19 @@ export class RatatuiApp {
|
|
|
12716
13179
|
getUsageObserver: () => this.activePromptTurn?.observe,
|
|
12717
13180
|
getHandoffSummarizer: (signal, messages) => this.buildHandoffSummarizer(signal, messages),
|
|
12718
13181
|
onCheckpoint: session => {
|
|
13182
|
+
this.committedTurnMessages = session.messages;
|
|
13183
|
+
this.committedPromptTurns = session.prompt_turns ?? [];
|
|
12719
13184
|
this.taskHandoff = session.task_handoff ? projectTaskHandoff(session.task_handoff) : null;
|
|
12720
13185
|
this.agent?.setTaskHandoff(this.taskHandoff);
|
|
12721
13186
|
this.publishTaskHandoff(this.taskHandoff);
|
|
12722
13187
|
},
|
|
12723
13188
|
debugLog,
|
|
12724
13189
|
});
|
|
13190
|
+
this.sessionManager.restorePromptTurns(this.resumedSession?.prompt_turns);
|
|
12725
13191
|
this.sessionManager.restoreDiagnostics(this.resumedSession?.diagnostics);
|
|
12726
13192
|
this.sessionManager.restoreUsageSnapshot(this.resumedSession?.usage);
|
|
13193
|
+
if (this.resumedSession)
|
|
13194
|
+
this.sessionManager.restoreLayout({ muxState: this.resumedSession.mux_state, paneSpecs: mergeSessionPaneSpecs(this.resumedSession.mux_state, this.resumedSession.pane_specs) });
|
|
12727
13195
|
}
|
|
12728
13196
|
return this.sessionManager;
|
|
12729
13197
|
}
|
|
@@ -13540,7 +14008,6 @@ export class RatatuiApp {
|
|
|
13540
14008
|
*/
|
|
13541
14009
|
handleCreatePaneRequest(event) {
|
|
13542
14010
|
const placement = { direction: event.direction, ratio: event.ratio, target: event.target, newWindow: event.new_window };
|
|
13543
|
-
// The desktop app's new-pane menu names what it wants; no kind is a ZTC pane.
|
|
13544
14011
|
if (event.kind === 'shell') {
|
|
13545
14012
|
void this.openRequestedShellPane({ cwd: event.cwd, ...placement })
|
|
13546
14013
|
.then((error) => { if (error)
|
|
@@ -13553,7 +14020,9 @@ export class RatatuiApp {
|
|
|
13553
14020
|
this.addSystemMessage(message); });
|
|
13554
14021
|
return;
|
|
13555
14022
|
}
|
|
13556
|
-
//
|
|
14023
|
+
// No kind is a ZTC pane (+, Cmd+T, the new-pane menu's ZTC tab), native panes up or not: the New pane chooser
|
|
14024
|
+
// opens only when it is asked for by name (show_new_pane_picker). The desktop app shows nothing of a pane that never
|
|
14025
|
+
// opened, so the reason is said here, as for the kinds above.
|
|
13557
14026
|
void this.spawnZtcPane({ cwd: event.cwd, ...placement }).then((result) => {
|
|
13558
14027
|
if (result.error) {
|
|
13559
14028
|
debugLog(`[handleCreatePaneRequest] ${result.error}`);
|
|
@@ -13637,10 +14106,11 @@ export class RatatuiApp {
|
|
|
13637
14106
|
}
|
|
13638
14107
|
this.trackPendingPaneLaunch(requestId, launchSpec);
|
|
13639
14108
|
const created = this.waitForTuiEvent(
|
|
13640
|
-
//
|
|
13641
|
-
//
|
|
13642
|
-
// leaving the user waiting out the
|
|
13643
|
-
|
|
14109
|
+
// A refusal named for another request is another pane's; one that names
|
|
14110
|
+
// none (an older renderer's) is accepted uncorrelated — the same bargain
|
|
14111
|
+
// the pane tools make, and it beats leaving the user waiting out the
|
|
14112
|
+
// timeout on a failed launch.
|
|
14113
|
+
(event) => isPaneRefusalFor(event, requestId)
|
|
13644
14114
|
|| (event.type === 'pane_created' && event.request_id === requestId), 15000);
|
|
13645
14115
|
const motsi = this.paneMotsi();
|
|
13646
14116
|
const launched = motsi ? throughMotsi(motsi, title, child) : child;
|
|
@@ -13693,56 +14163,135 @@ export class RatatuiApp {
|
|
|
13693
14163
|
return { paneId, cwd: child.cwd || cwd };
|
|
13694
14164
|
}
|
|
13695
14165
|
/**
|
|
13696
|
-
* The Ctrl+B c
|
|
13697
|
-
* in `/settings
|
|
14166
|
+
* The New pane chooser, zmux's Ctrl+B c and the desktop app's More… in its new-pane menu: bash, a ZTC pane, the
|
|
14167
|
+
* agent CLIs, any custom option the user added in `/settings`, and, while native panes are up, the native and
|
|
14168
|
+
* delegated panes and their Stop, Resume, Adopt and delegated Router login actions.
|
|
13698
14169
|
*
|
|
13699
|
-
*
|
|
13700
|
-
*
|
|
13701
|
-
*
|
|
14170
|
+
* The renderer raises this rather than acting itself because the answers are this process's business — a ZTC pane
|
|
14171
|
+
* needs its entrypoint, session id, and environment, and the custom options live in ZTC's config. The chooser shows
|
|
14172
|
+
* in Main, so in the desktop app Main takes the keyboard for it, whichever pane asked; the pane chosen splits the pane
|
|
14173
|
+
* that asked, and a cancelled chooser gives that pane the keyboard back.
|
|
13702
14174
|
*/
|
|
13703
|
-
showNewPanePicker(cwd) {
|
|
14175
|
+
async showNewPanePicker(cwd) {
|
|
13704
14176
|
if (!this.muxMode || this.paneMode) {
|
|
13705
14177
|
debugLog('[showNewPanePicker] Ignoring request because mux control is unavailable');
|
|
13706
14178
|
return;
|
|
13707
14179
|
}
|
|
14180
|
+
const origin = this.desktopMode ? await this.rendererFocusedPane() : null;
|
|
14181
|
+
if (this.desktopMode)
|
|
14182
|
+
this.tui.send({ type: 'focus_pane', pane_id: 0 });
|
|
14183
|
+
// An open prompt in Main, a native pane's dialog among them, waits for its answer: the chooser would replace it
|
|
14184
|
+
// unanswered, and its caller, with every native dialog queued after it, would wait for good.
|
|
14185
|
+
if (this.routingInteractionOccupied()) {
|
|
14186
|
+
this.addSystemMessage('Finish the open prompt, then open the New pane chooser again.');
|
|
14187
|
+
return;
|
|
14188
|
+
}
|
|
13708
14189
|
const ctx = this.buildCommandContext((msg) => this.controller.addMessage(msg));
|
|
13709
14190
|
const choices = newPaneChoices(customPaneOptions(configStore.get()), this.installedAgentClis());
|
|
13710
14191
|
ctx.select.showSelect({
|
|
13711
14192
|
title: 'New pane',
|
|
13712
14193
|
question: 'What should the new pane be?',
|
|
13713
14194
|
type: 'select',
|
|
13714
|
-
options:
|
|
14195
|
+
options: [
|
|
14196
|
+
...choices,
|
|
14197
|
+
...(this.dailyDesktop ? [...nativeChoices, { value: 'native:stop', label: 'Stop native pane' }, { value: 'native:resume', label: 'Resume native pane by exact id' }, { value: 'native:adopt', label: 'Adopt orphaned native pane' }, { value: 'native:router-refresh', label: 'Refresh delegated Router login' }, { value: 'native:router-signout', label: 'Sign out delegated Router login (local only)' }] : []),
|
|
14198
|
+
],
|
|
13715
14199
|
}, async (value) => {
|
|
13716
|
-
if (value === null || value === undefined)
|
|
14200
|
+
if (value === null || value === undefined) {
|
|
14201
|
+
if (origin !== null)
|
|
14202
|
+
this.tui.send({ type: 'focus_pane', pane_id: origin });
|
|
13717
14203
|
return;
|
|
13718
|
-
|
|
14204
|
+
}
|
|
14205
|
+
const error = await this.createPickedPane(String(value), cwd, origin ?? undefined);
|
|
13719
14206
|
if (error)
|
|
13720
14207
|
ctx.addMessage({ role: 'system', content: error });
|
|
13721
14208
|
});
|
|
13722
14209
|
}
|
|
14210
|
+
/**
|
|
14211
|
+
* The pane the renderer has focused, as its session state says: where the person was when they asked for something
|
|
14212
|
+
* Main shows. Null when the renderer doesn't say in time.
|
|
14213
|
+
*/
|
|
14214
|
+
async rendererFocusedPane(timeoutMs = 1000) {
|
|
14215
|
+
const answered = this.waitForTuiEvent(event => event.type === 'session_state', timeoutMs);
|
|
14216
|
+
if (!this.tui.send({ type: 'get_session_state' })) {
|
|
14217
|
+
answered.catch(() => { });
|
|
14218
|
+
return null;
|
|
14219
|
+
}
|
|
14220
|
+
try {
|
|
14221
|
+
const event = await answered;
|
|
14222
|
+
return event.type === 'session_state' && Number.isSafeInteger(event.state.focused_pane_id) ? event.state.focused_pane_id : null;
|
|
14223
|
+
}
|
|
14224
|
+
catch {
|
|
14225
|
+
return null;
|
|
14226
|
+
}
|
|
14227
|
+
}
|
|
13723
14228
|
/**
|
|
13724
14229
|
* Create the pane the chooser was given. Returns an error to report, or null
|
|
13725
14230
|
* when the pane is on its way.
|
|
13726
14231
|
*
|
|
13727
14232
|
* The custom list is re-read here rather than captured with the options, so a
|
|
13728
14233
|
* config edit between opening the chooser and answering it cannot create a
|
|
13729
|
-
* pane for an option that no longer exists.
|
|
14234
|
+
* pane for an option that no longer exists. `target` is the pane the new one
|
|
14235
|
+
* splits: the pane the chooser was asked from.
|
|
13730
14236
|
*/
|
|
13731
|
-
async createPickedPane(choice, cwd) {
|
|
14237
|
+
async createPickedPane(choice, cwd, target) {
|
|
14238
|
+
if (choice.startsWith('native:') && this.dailyDesktop) {
|
|
14239
|
+
try {
|
|
14240
|
+
if (choice === 'native:adopt') {
|
|
14241
|
+
const records = Object.values(this.dailyDesktop.exportRecords()).filter(record => this.dailyDesktop.store.snapshotForOwner(record.paneId).orphaned && !this.dailyDesktop.store.parentPaneIdsForOwner().includes(record.paneId));
|
|
14242
|
+
const selected = await this.dailySelect('Adopt orphaned native pane', records.map(record => ({ value: String(record.paneId), label: `Pane ${record.paneId} ${record.launch.tool}` })));
|
|
14243
|
+
if (selected !== null) {
|
|
14244
|
+
const parent = await this.dailySelect('New parent', this.dailyDesktop.store.parentPaneIdsForOwner().map(id => ({ value: String(id), label: id === 0 ? 'Desktop' : `Pane ${id}` })));
|
|
14245
|
+
if (parent !== null)
|
|
14246
|
+
await this.dailyDesktop.adopt(Number(selected), Number(parent));
|
|
14247
|
+
}
|
|
14248
|
+
}
|
|
14249
|
+
else if (choice === 'native:stop' || choice === 'native:resume') {
|
|
14250
|
+
const records = Object.values(this.dailyDesktop.exportRecords()).filter(record => choice === 'native:stop' || canResumeNative(record, this.dailyDesktop.store.leaseFor(record.paneId)));
|
|
14251
|
+
if (records.length === 0 && choice === 'native:resume')
|
|
14252
|
+
throw new Error('Cannot resume this exact session; start a fresh pane or isolate a quarantined worktree');
|
|
14253
|
+
const paneIdentity = (paneId) => {
|
|
14254
|
+
const store = this.dailyDesktop.store;
|
|
14255
|
+
const record = store.getRecord(paneId);
|
|
14256
|
+
return { ownerId: store.ownerId, sessionId: record.identity.canonicalId,
|
|
14257
|
+
leaderPid: record.process?.leaderPid ?? null, leaderStartMs: record.process?.leaderStartMs ?? null,
|
|
14258
|
+
stopState: record.outcome.stopState, leaseAcquiredAt: store.leaseFor(paneId)?.lease.acquiredAt ?? null };
|
|
14259
|
+
};
|
|
14260
|
+
const identities = new Map(records.map(record => [record.paneId, paneIdentity(record.paneId)]));
|
|
14261
|
+
const selected = await this.dailySelect(choice === 'native:stop' ? 'Stop native pane' : 'Resume exact native session', records.map(record => ({ value: String(record.paneId), label: `Pane ${record.paneId} ${record.launch.tool} ${record.identity.state} ${record.outcome.stopState}` })));
|
|
14262
|
+
if (selected !== null) {
|
|
14263
|
+
const expected = identities.get(Number(selected));
|
|
14264
|
+
const current = paneIdentity(Number(selected));
|
|
14265
|
+
if (!isDeepStrictEqual(expected, current))
|
|
14266
|
+
throw new Error('Native pane changed; choose it again');
|
|
14267
|
+
if (choice === 'native:stop')
|
|
14268
|
+
await this.dailyDesktop.stop(Number(selected));
|
|
14269
|
+
else
|
|
14270
|
+
await this.dailyDesktop.resume(Number(selected));
|
|
14271
|
+
}
|
|
14272
|
+
}
|
|
14273
|
+
else
|
|
14274
|
+
await this.dailyDesktop.pick(choice, cwd, target);
|
|
14275
|
+
return null;
|
|
14276
|
+
}
|
|
14277
|
+
catch (error) {
|
|
14278
|
+
return `Native pane: ${safeDailyMessage(error)}`;
|
|
14279
|
+
}
|
|
14280
|
+
}
|
|
13732
14281
|
if (choice === 'bash')
|
|
13733
|
-
return this.spawnShellPane({ cwd });
|
|
14282
|
+
return this.spawnShellPane({ cwd, target });
|
|
13734
14283
|
if (choice === 'ztc') {
|
|
13735
|
-
const result = await this.spawnZtcPane({ cwd });
|
|
14284
|
+
const result = await this.spawnZtcPane({ cwd, target });
|
|
13736
14285
|
return result.error ?? null;
|
|
13737
14286
|
}
|
|
13738
14287
|
const agentCli = agentCliFromChoice(choice);
|
|
13739
14288
|
if (agentCli)
|
|
13740
|
-
return this.spawnAgentCliPane(agentCli, { cwd });
|
|
14289
|
+
return this.spawnAgentCliPane(agentCli, { cwd, target });
|
|
13741
14290
|
if (choice.startsWith('custom:')) {
|
|
13742
14291
|
const option = customPaneOptions(configStore.get())[Number(choice.slice('custom:'.length))];
|
|
13743
14292
|
if (!option)
|
|
13744
14293
|
return 'That custom pane option is no longer in your settings.';
|
|
13745
|
-
return this.spawnCommandPane(option.command, { cwd, title: option.label });
|
|
14294
|
+
return this.spawnCommandPane(option.command, { cwd, title: option.label, target });
|
|
13746
14295
|
}
|
|
13747
14296
|
return null;
|
|
13748
14297
|
}
|
|
@@ -13753,8 +14302,8 @@ export class RatatuiApp {
|
|
|
13753
14302
|
*/
|
|
13754
14303
|
async openRequestedShellPane(options) {
|
|
13755
14304
|
const requestId = `create-shell-${generateSessionId()}`;
|
|
13756
|
-
//
|
|
13757
|
-
const answered = this.waitForTuiEvent((event) => event
|
|
14305
|
+
// A refusal is this pane's when it names this request, or names none (an older renderer's), as spawnZtcPane takes one.
|
|
14306
|
+
const answered = this.waitForTuiEvent((event) => isPaneRefusalFor(event, requestId) || (event.type === 'pane_created' && event.request_id === requestId), 15000);
|
|
13758
14307
|
const error = this.spawnShellPane({ ...options, requestId });
|
|
13759
14308
|
if (error) {
|
|
13760
14309
|
answered.catch(() => { });
|
|
@@ -13840,6 +14389,7 @@ export class RatatuiApp {
|
|
|
13840
14389
|
title,
|
|
13841
14390
|
pane_type: 'command',
|
|
13842
14391
|
...(motsi ? { env: { ...MOTSI_PANE_ENV } } : {}),
|
|
14392
|
+
...(options?.target !== undefined ? { target: options.target } : {}),
|
|
13843
14393
|
})
|
|
13844
14394
|
? null
|
|
13845
14395
|
: 'failed to create command pane';
|
|
@@ -13929,6 +14479,34 @@ export class RatatuiApp {
|
|
|
13929
14479
|
return;
|
|
13930
14480
|
}
|
|
13931
14481
|
}
|
|
14482
|
+
emergencyExitPromise = null;
|
|
14483
|
+
emergencyExit() {
|
|
14484
|
+
if (this.emergencyExitPromise)
|
|
14485
|
+
return this.emergencyExitPromise;
|
|
14486
|
+
const deadline = setTimeout(() => process.exit(1), 3000);
|
|
14487
|
+
deadline.unref();
|
|
14488
|
+
this.emergencyExitPromise = (async () => {
|
|
14489
|
+
debugLog('[signal] Emergency save triggered');
|
|
14490
|
+
this.exiting = true;
|
|
14491
|
+
try {
|
|
14492
|
+
getColonyService()?.getAgentBridge?.()?.prepareForShutdown();
|
|
14493
|
+
}
|
|
14494
|
+
catch { }
|
|
14495
|
+
this._captureEmergencyMuxSnapshot();
|
|
14496
|
+
const saved = this.saveCurrentSession();
|
|
14497
|
+
const stopped = this.tui.stop();
|
|
14498
|
+
let desktopTimer;
|
|
14499
|
+
const desktop = Promise.race([
|
|
14500
|
+
Promise.resolve().then(() => this.dailyDesktop?.close()).catch(() => { }),
|
|
14501
|
+
new Promise(resolve => { desktopTimer = setTimeout(resolve, 500); }),
|
|
14502
|
+
]).finally(() => clearTimeout(desktopTimer));
|
|
14503
|
+
const results = await Promise.allSettled([saved, stopped, desktop]);
|
|
14504
|
+
await this.workspaceCoordinator?.close();
|
|
14505
|
+
clearTimeout(deadline);
|
|
14506
|
+
process.exit(results.some(result => result.status === 'rejected') ? 1 : 0);
|
|
14507
|
+
})().catch(() => { clearTimeout(deadline); process.exit(1); });
|
|
14508
|
+
return this.emergencyExitPromise;
|
|
14509
|
+
}
|
|
13932
14510
|
async exit(forceSessionPersistence = false, options = {}) {
|
|
13933
14511
|
if (this.exiting)
|
|
13934
14512
|
return this.exitComplete;
|
|
@@ -14002,10 +14580,10 @@ export class RatatuiApp {
|
|
|
14002
14580
|
// short bound so an unresponsive renderer can't stall the restore. Plain
|
|
14003
14581
|
// non-mux sessions (the common case) skip this entirely.
|
|
14004
14582
|
this._captureEmergencyMuxSnapshot();
|
|
14005
|
-
if (this.muxMode && !this.paneMode && !this.
|
|
14006
|
-
const snap = await this.
|
|
14583
|
+
if (this.muxMode && !this.paneMode && !this._emergencyLayoutSnapshot) {
|
|
14584
|
+
const snap = await this.completeSessionLayout(300);
|
|
14007
14585
|
if (snap)
|
|
14008
|
-
this.
|
|
14586
|
+
this._emergencyLayoutSnapshot = snap;
|
|
14009
14587
|
}
|
|
14010
14588
|
// Preserve colony cell state BEFORE the transport kills child panes. Without
|
|
14011
14589
|
// this, pane_closed events mark cells as 'done' and they won't auto-resume.
|
|
@@ -14123,6 +14701,8 @@ export class RatatuiApp {
|
|
|
14123
14701
|
clearEvolutionTuiProcess();
|
|
14124
14702
|
clearBackgroundRegistry();
|
|
14125
14703
|
clearBusTransport();
|
|
14704
|
+
this.dailyStatusCancel?.();
|
|
14705
|
+
await this.dailyDesktop?.close();
|
|
14126
14706
|
this.supervisionManager = null;
|
|
14127
14707
|
this.hookLifecycle.stop();
|
|
14128
14708
|
// Stop pane relay server/client
|