u-foo 3.1.7 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +238 -21
  3. package/README.zh-CN.md +165 -20
  4. package/SKILLS/ufoo/SKILL.md +40 -4
  5. package/SKILLS/ufoo-bus/SKILL.md +46 -3
  6. package/bin/uclaude.js +4 -0
  7. package/bin/ucodex.js +4 -0
  8. package/bin/ufoo.js +6 -4
  9. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  10. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  11. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  12. package/dist/tui/linux-x64/ufoo-tui +0 -0
  13. package/package.json +14 -7
  14. package/scripts/postinstall-skills.js +53 -0
  15. package/scripts/postinstall.js +11 -16
  16. package/scripts/smoke-native-messages.js +214 -0
  17. package/src/agents/activity/activityDetector.js +1 -1
  18. package/src/agents/activity/activityStateWriter.js +37 -38
  19. package/src/agents/capabilities/agentManagement/index.js +4 -0
  20. package/src/agents/capabilities/agentManagement/service.js +140 -0
  21. package/src/agents/capabilities/agentRouting/index.js +4 -0
  22. package/src/agents/capabilities/coding/index.js +32 -0
  23. package/src/agents/capabilities/coordination/index.js +37 -0
  24. package/src/agents/capabilities/globalRouting/index.js +5 -0
  25. package/src/agents/capabilities/groups/index.js +3 -0
  26. package/src/agents/capabilities/index.js +25 -0
  27. package/src/agents/capabilities/planning/index.js +123 -0
  28. package/src/agents/capabilities/planning/main.js +28 -0
  29. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  30. package/src/agents/capabilities/scheduling/index.js +3 -0
  31. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  32. package/src/agents/capabilities/skills/index.js +12 -0
  33. package/src/agents/capabilities/taskExecution/index.js +3 -0
  34. package/src/agents/capabilities/taskReports/index.js +6 -0
  35. package/src/agents/controller/controllerToolExecutor.js +40 -22
  36. package/src/agents/controller/index.js +1 -6
  37. package/src/agents/internal/internalRunner.js +181 -76
  38. package/src/agents/launch/index.js +0 -1
  39. package/src/agents/launch/launcher.js +96 -14
  40. package/src/agents/launch/nativeCapabilities.js +40 -0
  41. package/src/agents/launch/nativeMessages.js +362 -0
  42. package/src/agents/launch/notifier.js +15 -20
  43. package/src/agents/launch/readyDetector.js +28 -14
  44. package/src/agents/profiles/coding.js +6 -0
  45. package/src/agents/profiles/globalRouter.js +2 -0
  46. package/src/agents/profiles/main.js +5 -0
  47. package/src/agents/prompts/cooperation.js +14 -0
  48. package/src/agents/prompts/defaultBootstrap.js +1 -1
  49. package/src/agents/prompts/groupBootstrap.js +32 -6
  50. package/src/agents/prompts/mainAgent.js +48 -0
  51. package/src/agents/prompts/native/system.js +4 -1
  52. package/src/agents/prompts/native/tasks.js +2 -2
  53. package/src/agents/prompts/native/ufoo.js +14 -3
  54. package/src/agents/prompts/promptProfiles.js +2 -0
  55. package/src/agents/prompts/reporting.js +16 -0
  56. package/src/agents/providers/claudeEventTranslator.js +9 -1
  57. package/src/agents/providers/claudeThreadProvider.js +47 -4
  58. package/src/agents/providers/clientIdentity.js +75 -0
  59. package/src/agents/providers/codexEventTranslator.js +68 -7
  60. package/src/agents/providers/codexThreadProvider.js +18 -8
  61. package/src/agents/providers/credentials/claude.js +10 -3
  62. package/src/agents/providers/credentials/index.js +2 -0
  63. package/src/agents/providers/directAuthStatus.js +1 -1
  64. package/src/agents/providers/index.js +1 -1
  65. package/src/agents/providers/modelSettings.js +34 -0
  66. package/src/agents/providers/modelsCatalog.js +379 -0
  67. package/src/agents/providers/nativeTransport.js +1146 -0
  68. package/src/agents/providers/runtimeConfig.js +188 -0
  69. package/src/agents/providers/thinkingLevels.js +106 -0
  70. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  71. package/src/agents/providers/transports/index.js +10 -0
  72. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  73. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  74. package/src/agents/providers/transports/responsesProtocol.js +504 -0
  75. package/src/agents/providers/transports/systemBlocks.js +16 -0
  76. package/src/agents/providers/transports/transportContract.js +50 -0
  77. package/src/agents/providers/transports/visionBlocks.js +151 -0
  78. package/src/agents/providers/upstreamRuntime.js +135 -0
  79. package/src/agents/runtime/composeCapabilities.js +89 -0
  80. package/src/agents/runtime/context/checkpointStore.js +38 -0
  81. package/src/agents/runtime/context/commandStore.js +43 -0
  82. package/src/agents/runtime/context/compaction.js +151 -0
  83. package/src/agents/runtime/context/contextBudget.js +93 -0
  84. package/src/agents/runtime/context/contextWindow.js +119 -0
  85. package/src/agents/runtime/context/fileLock.js +36 -0
  86. package/src/agents/runtime/context/replayHistory.js +28 -0
  87. package/src/agents/runtime/context/runtimeStore.js +127 -0
  88. package/src/agents/runtime/context/sessionJournal.js +360 -0
  89. package/src/agents/runtime/context/sessionStore.js +57 -0
  90. package/src/agents/runtime/core/agentLoop.js +351 -0
  91. package/src/agents/runtime/core/executionBudget.js +36 -0
  92. package/src/agents/runtime/core/stableJson.js +29 -0
  93. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  94. package/src/agents/runtime/createAgentRuntime.js +259 -0
  95. package/src/agents/runtime/index.js +14 -0
  96. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  97. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  98. package/src/agents/runtime/protocol/materialize.js +107 -0
  99. package/src/agents/runtime/protocol/runObservation.js +24 -0
  100. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  101. package/src/agents/runtime/protocol/traceContext.js +9 -0
  102. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  103. package/src/agents/runtime/tasks/scheduler.js +73 -0
  104. package/src/agents/runtime/tools/registry.js +57 -0
  105. package/src/app/chat/ChatController.js +29 -45
  106. package/src/app/chat/agentDirectory.js +9 -18
  107. package/src/app/chat/bootstrap.js +1 -2
  108. package/src/app/chat/commandExecutor.js +111 -313
  109. package/src/app/chat/commands.js +39 -45
  110. package/src/app/chat/daemonConnection.js +58 -5
  111. package/src/app/chat/daemonMessageRouter.js +61 -48
  112. package/src/app/chat/historyStore.js +12 -48
  113. package/src/app/chat/inputSubmitHandler.js +21 -35
  114. package/src/app/chat/internalAgentLogHistory.js +19 -60
  115. package/src/app/chat/launchRequestContext.js +42 -0
  116. package/src/app/chat/multiWindow/paneManager.js +91 -164
  117. package/src/app/chat/streamState.js +3 -7
  118. package/src/app/chat/transport.js +1 -1
  119. package/src/app/cli/busCoreCommands.js +9 -0
  120. package/src/app/cli/features/doctor.js +33 -0
  121. package/src/app/cli/features/init.js +5 -5
  122. package/src/app/cli/features/skills.js +16 -4
  123. package/src/app/cli/metricsCommands.js +68 -0
  124. package/src/app/cli/reportCoreCommands.js +37 -0
  125. package/src/app/cli/run.js +82 -42
  126. package/src/app/cli/traceCommands.js +36 -0
  127. package/src/code/agent.js +34 -17
  128. package/src/code/busConsumer.js +1 -3
  129. package/src/code/commands.js +1 -1
  130. package/src/code/context/artifacts.js +12 -11
  131. package/src/code/context/assembler.js +9 -9
  132. package/src/code/context/promptLayers.js +1 -13
  133. package/src/code/context/stableJson.js +2 -27
  134. package/src/code/context/stateCommit.js +2 -1
  135. package/src/code/contextWindow.js +2 -117
  136. package/src/code/conversation/sessionJournal.js +3 -349
  137. package/src/code/internalThread.js +107 -0
  138. package/src/code/launcher/ucode.js +1 -1
  139. package/src/code/launcher/ucodeBootstrap.js +1 -1
  140. package/src/code/modelCommand.js +11 -35
  141. package/src/code/nativeRunner.js +104 -2697
  142. package/src/code/protocol/faultHarness.js +2 -88
  143. package/src/code/protocol/materialize.js +2 -105
  144. package/src/code/protocol/toolCallLedger.js +5 -215
  145. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  146. package/src/code/providers/modelsCatalog.js +1 -317
  147. package/src/code/providers/openaiChatTransport.js +2 -114
  148. package/src/code/providers/openaiResponsesTransport.js +2 -117
  149. package/src/code/providers/responsesProtocol.js +2 -497
  150. package/src/code/providers/transportContract.js +2 -48
  151. package/src/code/providers/visionBlocks.js +2 -149
  152. package/src/code/repl.js +2 -11
  153. package/src/code/sessionStore.js +27 -99
  154. package/src/code/taskDecomposer.js +18 -0
  155. package/src/code/thinkingLevels.js +1 -130
  156. package/src/code/toolBudget.js +1 -17
  157. package/src/code/toolLoopGuard.js +3 -49
  158. package/src/code/tools/artifactRead.js +1 -1
  159. package/src/code/tools/executor.js +373 -0
  160. package/src/code/tools/specs.js +312 -0
  161. package/src/config.js +95 -131
  162. package/src/coordination/bus/deliveryQueue.js +16 -2
  163. package/src/coordination/bus/index.js +14 -9
  164. package/src/coordination/bus/inject.js +15 -7
  165. package/src/coordination/bus/message.js +15 -1
  166. package/src/coordination/bus/nativeReceipts.js +100 -0
  167. package/src/coordination/bus/nickname.js +1 -1
  168. package/src/coordination/bus/queue.js +1 -3
  169. package/src/coordination/bus/subscriber.js +3 -2
  170. package/src/coordination/bus/utils.js +8 -4
  171. package/src/coordination/history/agentPerformance.js +279 -0
  172. package/src/coordination/history/agentSurface.js +142 -0
  173. package/src/coordination/history/agentTrace.js +249 -0
  174. package/src/coordination/memory/index.js +5 -21
  175. package/src/coordination/report/store.js +103 -83
  176. package/src/coordination/state/agentsStore.js +57 -3
  177. package/src/coordination/state/fileLock.js +2 -0
  178. package/src/coordination/state/workspaceAccess.js +36 -0
  179. package/src/orchestration/controller/index.js +1 -8
  180. package/src/orchestration/controller/launchRouting.js +1 -1
  181. package/src/orchestration/solo/commands.js +3 -1
  182. package/src/runtime/contracts/agentMode.js +26 -0
  183. package/src/runtime/contracts/eventContract.js +3 -0
  184. package/src/runtime/contracts/uiProtocol.js +20 -17
  185. package/src/runtime/daemon/agentHost.js +407 -0
  186. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  187. package/src/runtime/daemon/busBridge.js +396 -0
  188. package/src/runtime/daemon/claudeChannel.js +159 -0
  189. package/src/runtime/daemon/controlPlaneService.js +28 -18
  190. package/src/runtime/daemon/cronOps.js +25 -17
  191. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  192. package/src/runtime/daemon/globalDaemon.js +28 -1
  193. package/src/runtime/daemon/groupOrchestrator.js +21 -5
  194. package/src/runtime/daemon/groupStatus.js +20 -0
  195. package/src/runtime/daemon/index.js +120 -375
  196. package/src/runtime/daemon/ipcServer.js +32 -10
  197. package/src/runtime/daemon/mcpConfigure.js +113 -20
  198. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  199. package/src/runtime/daemon/mcpServer.js +8 -5
  200. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  201. package/src/runtime/daemon/nicknameScope.js +1 -1
  202. package/src/runtime/daemon/ops.js +68 -40
  203. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  204. package/src/runtime/daemon/promptRequest.js +92 -570
  205. package/src/runtime/daemon/providerSessions.js +67 -33
  206. package/src/runtime/daemon/reportControlBus.js +59 -25
  207. package/src/runtime/daemon/status.js +9 -6
  208. package/src/runtime/privacy/redactor.js +2 -2
  209. package/src/runtime/projects/identity.js +2 -1
  210. package/src/runtime/projects/registry.js +98 -38
  211. package/src/tools/controllerSchemas.js +28 -0
  212. package/src/tools/handlers/dispatchMessage.js +5 -2
  213. package/src/tools/handlers/listAgents.js +3 -1
  214. package/src/tools/handlers/readBusSummary.js +3 -1
  215. package/src/tools/handlers/readProjectRegistry.js +29 -2
  216. package/src/tools/handlers/routeAgent.js +35 -0
  217. package/src/tools/handlers/tier2.js +4 -2
  218. package/src/tools/index.js +1 -0
  219. package/src/tools/registry.js +6 -0
  220. package/src/tools/schemaFixtures.js +42 -5
  221. package/src/tools/tier0/readAgentMetrics.js +14 -0
  222. package/src/tools/tier0/readAgentTrace.js +12 -0
  223. package/src/tools/tier1/routeAgent.js +2 -2
  224. package/src/tools/tier2/runtimeCoordination.js +38 -0
  225. package/src/tools/types.js +2 -0
  226. package/src/ui/agentPresentation.js +109 -0
  227. package/src/ui/agentSettingsController.js +107 -0
  228. package/src/ui/agentSurface.js +270 -0
  229. package/src/ui/dashboardBridge.js +1 -1
  230. package/src/ui/format/banner.js +9 -15
  231. package/src/ui/format/index.js +14 -10
  232. package/src/ui/format/loopSummary.js +50 -0
  233. package/src/ui/format/markdownRenderer.js +3 -4
  234. package/src/ui/format/startupBanner.js +50 -0
  235. package/src/ui/multiPaneBusMirror.js +29 -3
  236. package/src/ui/rustChatHost.js +316 -599
  237. package/src/ui/rustMultiSession.js +288 -73
  238. package/src/ui/rustUcodeHost.js +21 -88
  239. package/src/ui/settingsBridge.js +34 -14
  240. package/src/ui/toolMergeBridge.js +0 -4
  241. package/src/ui/uiHostServer.js +5 -8
  242. package/src/agents/controller/loopObservability.js +0 -200
  243. package/src/agents/controller/loopRuntime.js +0 -472
  244. package/src/agents/controller/ufooAgent.js +0 -829
  245. package/src/agents/launch/ptyRunner.js +0 -1135
  246. package/src/agents/providers/upstreamTransport.js +0 -689
  247. package/src/app/chat/agentBar.js +0 -135
  248. package/src/app/chat/agentEnter.js +0 -70
  249. package/src/app/chat/agentSockets.js +0 -225
  250. package/src/app/chat/dashboardView.js +0 -405
  251. package/src/app/chat/multiWindow/index.js +0 -310
  252. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  253. package/src/app/chat/multiWindow/renderer.js +0 -420
  254. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  255. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  256. package/src/app/chat/rawKeyMap.js +0 -42
  257. package/src/app/chat/settingsController.js +0 -111
  258. package/src/orchestration/controller/flags.js +0 -167
  259. package/src/orchestration/controller/gateRouter.js +0 -211
  260. package/src/orchestration/controller/routerFastPath.js +0 -22
  261. package/src/orchestration/controller/routerFinalize.js +0 -222
  262. package/src/orchestration/controller/shadowGuard.js +0 -280
  263. package/src/runtime/daemon/promptLoop.js +0 -136
  264. package/src/runtime/privacy/shadowDiff.js +0 -174
  265. package/src/ui/multiWindowHandoff.js +0 -232
  266. package/src/ui/ptyHandoff.js +0 -23
@@ -16,22 +16,22 @@ const { createToolMergePublisher } = require("./toolMergeBridge");
16
16
  const { createRustMultiSession } = require("./rustMultiSession");
17
17
  const { writeMultiPaneBusEvent } = require("./multiPaneBusMirror");
18
18
  const { buildSettingsSnapshot, applySettingsPatch } = require("./settingsBridge");
19
+ const { createAgentSettingsController } = require("./agentSettingsController");
19
20
  const fmt = require("./format");
21
+ const { buildUfooStartupEntries } = require("./format/startupBanner");
20
22
  const {
21
23
  loadGlobalProjectRows,
22
24
  buildDashboardPublishPayload,
23
25
  } = require("./dashboardBridge");
24
26
  const { createChatController } = require("../app/chat/ChatController");
25
- const {
26
- resolveAgentEnterRequest,
27
- resolveDashboardAgentEnterAction,
28
- } = require("../app/chat/agentEnter");
27
+ const { isInternalAgentMeta, isInternalDashboardEvent } = require("../runtime/contracts/agentMode");
29
28
  const { loadConfig } = require("../config");
30
29
  const { bootstrapEnvironment, ensureSubscriberId } = require("../app/chat/bootstrap");
31
30
  const {
32
31
  createEnvelope,
33
32
  encodeMessage,
34
33
  MULTI_FRAMES_CAPABILITY,
34
+ WINDOW_MODES_CAPABILITY,
35
35
  } = require("../runtime/contracts/uiProtocol");
36
36
  const { IPC_REQUEST_TYPES, IPC_RESPONSE_TYPES } = require("../runtime/contracts/eventContract");
37
37
  const { createDaemonMessageRouter } = require("../app/chat/daemonMessageRouter");
@@ -41,61 +41,81 @@ const {
41
41
  } = require("../runtime/daemon/endpoint");
42
42
  const PACKAGE_VERSION = require("../../package.json").version;
43
43
 
44
+ async function loadResumeCompletionSources(root, request = require("../app/chat/transport").requestDaemon) {
45
+ const result = await request(root, { type: IPC_REQUEST_TYPES.LIST_RECOVERABLE_AGENTS, internal_only: true }, {
46
+ retries: 1, timeoutMs: 5000,
47
+ });
48
+ const recovery = result.recoverable || {};
49
+ const agents = (recovery.recoverable || []).filter((item) => !item.group_id);
50
+ agents.sort((a, b) => String(b.lastSeen || "").localeCompare(String(a.lastSeen || "")) || a.id.localeCompare(b.id));
51
+ return [
52
+ ...agents.map((item) => ({ id: item.id, label: item.display_nickname || item.nickname || item.id,
53
+ desc: `${item.agent} · session ${item.sessionId}` })),
54
+ ...(recovery.groups || []).map((group) => ({ id: `group:${group.group_id}`,
55
+ desc: `Group · ${group.template_alias || group.group_id} · ${group.members.length} recoverable agents` })),
56
+ ];
57
+ }
58
+
59
+ function parseWindowModeArgs(args = []) {
60
+ const text = args.map((value) => String(value).trim()).join(" ").toLowerCase();
61
+ return ["main", "side", "multi"].includes(text) ? text : "";
62
+ }
63
+
64
+ function resolveSubmittedInputTarget(payload, currentTarget, isInternalAgent) {
65
+ const target = String(payload.target_agent || payload.targetAgent || "").trim();
66
+ if ((payload.has_target && !target) || (target && !isInternalAgent(target))) {
67
+ return { ok: false, error: "Unknown internal target" };
68
+ }
69
+ return { ok: true, target: target || (payload.input_target === "main" ? null : currentTarget) };
70
+ }
71
+
44
72
  function stripTags(value) {
45
73
  return String(value || "").replace(/\{[^}]+\}/g, "");
46
74
  }
47
75
 
48
76
  function historyToEntries(rows) {
49
77
  const list = Array.isArray(rows) ? rows : [];
50
- const markdownState = { inCodeBlock: false };
51
78
  const MARKDOWN_KINDS = new Set(["assistant", "agent", "report", "error"]);
52
- const out = [];
53
- list.forEach((row, index) => {
54
- if (typeof row === "string") {
55
- out.push({
56
- id: `hist-${index}`,
57
- kind: "system",
58
- text: stripTags(row),
59
- speaker: "",
60
- });
61
- return;
62
- }
63
- const sourceType = String(row && (row.sourceType || row.type || row.kind) || "system");
64
- const kind = sourceType === "user" || sourceType === "assistant" || sourceType === "error"
65
- || sourceType === "agent" || sourceType === "report"
66
- ? sourceType
67
- : "system";
68
- const raw = String(row && (row.text || row.content || ""));
69
- const speaker = String(row && row.speaker || "");
70
- if (MARKDOWN_KINDS.has(kind)) {
71
- let lines;
79
+ const KINDS = new Set(["system", "user", "assistant", "error", "agent", "report",
80
+ "thinking", "tool", "spacer", "meta", "bus", "success", "banner"]);
81
+ const cleanText = (text) => String(text || "")
82
+ // Strip presentation tags without eating code such as { value: 1 }.
83
+ .replace(/\{\/?(?:[a-z]+(?:-[a-z]+)*-(?:fg|bg)|#[\da-f]{3,8}-(?:fg|bg)|bold|italic|underline|blink|inverse|invisible|normal|reset|escape)\}/gi, "")
84
+ .replace(/\{open\}/g, "{").replace(/\{close\}/g, "}");
85
+ return list.map((row, index) => {
86
+ const source = row && typeof row === "object" ? row : { text: row };
87
+ const meta = source.meta && typeof source.meta === "object" ? source.meta : {};
88
+ const sourceType = String(source.sourceType || source.type || source.kind || "system");
89
+ const streamed = sourceType === "bus" && meta.stream_done === true;
90
+ const kind = streamed || sourceType === "reply" ? "assistant"
91
+ : KINDS.has(sourceType) ? sourceType : "system";
92
+ let text = cleanText(source.text || source.content || "");
93
+ let speaker = String(source.speaker || meta.speaker || "");
94
+ if (streamed) {
95
+ // Stream persistence prefixes the display name, whereas the live TUI
96
+ // receives it separately. Restore that same identity and raw body.
97
+ const match = text.match(/^([^\n]+?): ([\s\S]*)$/);
98
+ if (match) { speaker = speaker || match[1]; text = match[2]; }
99
+ } else if (MARKDOWN_KINDS.has(kind)) {
72
100
  try {
73
- lines = fmt.renderLogLinesWithMarkdownAnsi(raw, markdownState);
74
- if (!Array.isArray(lines) || lines.length === 0) lines = raw.split(/\r?\n/);
101
+ const lines = fmt.renderLogLinesWithMarkdownAnsi(text, { inCodeBlock: false });
102
+ if (Array.isArray(lines) && lines.length > 0) text = lines.map((line) => String(line || "")).join("\n");
75
103
  } catch {
76
- lines = raw.split(/\r?\n/);
104
+ // Keep the original complete block if markdown rendering fails.
77
105
  }
78
- lines.forEach((line, lineIdx) => {
79
- out.push({
80
- id: `hist-${index}-${lineIdx}`,
81
- kind,
82
- text: String(line || ""),
83
- speaker: lineIdx === 0 ? speaker : "",
84
- });
85
- });
86
- return;
87
106
  }
88
- out.push({
89
- id: `hist-${index}`,
107
+ return {
108
+ id: String(source.id || `hist-${index}`),
90
109
  kind,
91
- text: stripTags(raw),
110
+ text,
92
111
  speaker,
93
- });
112
+ detail: cleanText(source.detail || source.expanded_text || meta.detail || meta.expanded_text || ""),
113
+ expanded: false,
114
+ };
94
115
  });
95
- return out;
96
116
  }
97
117
 
98
- /** Ink parity: `/group run` / `/solo run` dynamic argument lists. */
118
+ /** Completion sources: `/group run` / `/solo run` dynamic argument lists. */
99
119
  function loadDynamicCompletionSources(root) {
100
120
  const sources = { groupTemplates: [], soloProfiles: [] };
101
121
  try {
@@ -146,7 +166,7 @@ async function runChatRust(projectRoot, options = {}) {
146
166
  await init.init({
147
167
  targets: "context,bus",
148
168
  project: projectRoot,
149
- controllerMode: env.globalMode,
169
+ globalController: env.globalMode,
150
170
  });
151
171
  }
152
172
  await ensureSubscriberId(projectRoot);
@@ -174,16 +194,19 @@ async function runChatRust(projectRoot, options = {}) {
174
194
 
175
195
  let entrySeq = 0;
176
196
  const streamIds = new Map();
197
+ const streamLabels = new Map();
198
+ let mainSubmissionRev = 0;
177
199
  let hostRef = null;
178
200
  let daemonSend = () => {};
179
201
  let daemonCoordinator = null;
180
202
  let routedMessageHandler = () => {};
181
203
  let activeProjectRoot = projectRoot;
182
204
  let globalScope = "controller";
183
- let agentViewId = "";
184
205
  let multiSession = null;
206
+ const internalSubmissions = new Map();
185
207
  /** Internal pane agents currently BUS_WATCH'd for multi/side inbound. */
186
208
  const watchedInternalAgents = new Set();
209
+ const welcomedProjects = new Set();
187
210
  const settings = (() => {
188
211
  try {
189
212
  return loadConfig(projectRoot) || {};
@@ -192,6 +215,44 @@ async function runChatRust(projectRoot, options = {}) {
192
215
  }
193
216
  })();
194
217
 
218
+ async function applyAgentSettings(patch) {
219
+ const model = patch.agent_model ?? patch.agentModel;
220
+ if (model) {
221
+ const current = loadConfig(activeProjectRoot);
222
+ const provider = patch.agent_provider ?? patch.agentProvider ?? current.agentProvider;
223
+ const confirmation = await require("../agents/providers/modelSettings").confirmAgentModel(activeProjectRoot, model,
224
+ { config: { ...current, agentProvider: provider } });
225
+ if (!confirmation.allowed) return { ok: false, error: confirmation.error };
226
+ }
227
+ const applied = applySettingsPatch(activeProjectRoot, patch);
228
+ if (!applied.ok) return applied;
229
+ Object.assign(settings, loadConfig(activeProjectRoot));
230
+ publish("settings.snapshot", applied.settings);
231
+ if (applied.providerChanged) appendLocal("system", `Provider: ${applied.settings.agent_provider} · new conversation`);
232
+ if (patch.agent_model != null || patch.agentModel != null) appendLocal("system", `Model: ${applied.settings.agent_model}`);
233
+ if (patch.agent_thinking != null || patch.agentThinking != null) appendLocal("system", `Thinking: ${applied.settings.agent_thinking}`);
234
+ const restart = applied.providerChanged || patch.agent_base_url != null || patch.agent_api_key != null
235
+ || patch.agentBaseUrl != null || patch.agentApiKey != null;
236
+ if (restart && daemonCoordinator?.restart) {
237
+ publish("status.set", { text: "settings saved · restarting daemon…" });
238
+ await daemonCoordinator.restart();
239
+ }
240
+ publish("status.set", { text: "settings saved", busy: false });
241
+ publish("prompt.restore", {});
242
+ return applied;
243
+ }
244
+ const agentSettings = createAgentSettingsController({ getProjectRoot: () => activeProjectRoot,
245
+ applyPatch: applyAgentSettings, publish: (...args) => publish(...args), logMessage: (...args) => appendLocal(...args),
246
+ focusMain() {
247
+ if (multiSession?.isActive()) {
248
+ multiSession.handleFocus({ target: "chat" });
249
+ publish("window.set", multiSession.getSnapshot());
250
+ }
251
+ controller.session.targetAgent = null;
252
+ publish("prompt.set_prefix", { prefix: "› " });
253
+ },
254
+ });
255
+
195
256
  function historyOptions() {
196
257
  const { chatHistoryOptionsForScope } = require("../app/chat/historyStore");
197
258
  return chatHistoryOptionsForScope({
@@ -216,7 +277,7 @@ async function runChatRust(projectRoot, options = {}) {
216
277
 
217
278
  function reconcileMultiInternalWatches() {
218
279
  const next = new Set();
219
- if (multiSession && multiSession.isActive()
280
+ if (multiSession
220
281
  && typeof multiSession.listInternalAgentIds === "function") {
221
282
  for (const id of multiSession.listInternalAgentIds()) {
222
283
  next.add(id);
@@ -233,7 +294,7 @@ async function runChatRust(projectRoot, options = {}) {
233
294
  }
234
295
 
235
296
  function mirrorBusToMultiPanes(data = {}) {
236
- if (!multiSession || !multiSession.isActive()) return false;
297
+ if (!multiSession) return false;
237
298
  if (typeof multiSession.writeToPane !== "function") return false;
238
299
  const ids = typeof multiSession.listInternalAgentIds === "function"
239
300
  ? multiSession.listInternalAgentIds()
@@ -245,6 +306,8 @@ async function runChatRust(projectRoot, options = {}) {
245
306
  try { return controller.session.metaMap.get(agentId) || {}; } catch { return {}; }
246
307
  },
247
308
  writeToPane: (agentId, text) => multiSession.writeToPane(agentId, text),
309
+ acceptEvent: (agentId, event, seq) => multiSession.acceptEvent(agentId, event, seq),
310
+ hasStructuredEvents: (agentId) => multiSession.hasStructuredEvents(agentId),
248
311
  });
249
312
  }
250
313
 
@@ -254,7 +317,7 @@ async function runChatRust(projectRoot, options = {}) {
254
317
  agents: payload.agents,
255
318
  footer: payload.footer,
256
319
  });
257
- if (multiSession && multiSession.isActive()) {
320
+ if (multiSession) {
258
321
  try { multiSession.syncAgents(); } catch {}
259
322
  try { reconcileMultiInternalWatches(); } catch {}
260
323
  }
@@ -299,6 +362,11 @@ async function runChatRust(projectRoot, options = {}) {
299
362
  }));
300
363
  }
301
364
 
365
+ function isInternalChild(agentId) {
366
+ const id = String(agentId || "");
367
+ return id !== "ufoo-agent" && !id.endsWith(":ufoo-agent") && hostApi.isInternalAgent(id);
368
+ }
369
+
302
370
  function publishLossy(name, payload) {
303
371
  if (!hostRef) return;
304
372
  hostRef.broadcast(hostRef.createLossyEvent(name, payload, {
@@ -341,9 +409,7 @@ async function runChatRust(projectRoot, options = {}) {
341
409
  const pathMod = require("path");
342
410
  const label = pathMod.basename(root) || root;
343
411
 
344
- if (multiSession && multiSession.isActive()) {
345
- multiSession.stop();
346
- }
412
+ if (multiSession) multiSession.stop({ clearDrafts: true });
347
413
 
348
414
  const targetEndpoint = resolveDaemonEndpoint(root);
349
415
  const targetDaemonRoot = targetEndpoint.scope === "global"
@@ -366,19 +432,6 @@ async function runChatRust(projectRoot, options = {}) {
366
432
  return { ok: false, error: `project is not running: ${label}`, stopped: true };
367
433
  }
368
434
 
369
- if (agentViewId) {
370
- try {
371
- daemonSend({
372
- type: IPC_REQUEST_TYPES.BUS_WATCH,
373
- agent_id: agentViewId,
374
- enabled: false,
375
- });
376
- } catch {
377
- // ignore
378
- }
379
- agentViewId = "";
380
- publish("agent.view.close", {});
381
- }
382
435
 
383
436
  if (daemonCoordinator && typeof daemonCoordinator.switchProject === "function") {
384
437
  const res = await daemonCoordinator.switchProject({
@@ -412,9 +465,7 @@ async function runChatRust(projectRoot, options = {}) {
412
465
  return { ok: true, project_root: root, root };
413
466
  },
414
467
  async switchToControllerRoot() {
415
- if (multiSession && multiSession.isActive()) {
416
- multiSession.stop();
417
- }
468
+ if (multiSession) multiSession.stop({ clearDrafts: true });
418
469
  if (!env.globalMode) {
419
470
  return { ok: true, project_root: projectRoot, root: projectRoot };
420
471
  }
@@ -433,19 +484,6 @@ async function runChatRust(projectRoot, options = {}) {
433
484
  return res || { ok: false, error: "switch to global failed" };
434
485
  }
435
486
  }
436
- if (agentViewId) {
437
- try {
438
- daemonSend({
439
- type: IPC_REQUEST_TYPES.BUS_WATCH,
440
- agent_id: agentViewId,
441
- enabled: false,
442
- });
443
- } catch {
444
- // ignore
445
- }
446
- agentViewId = "";
447
- publish("agent.view.close", {});
448
- }
449
487
  activeProjectRoot = projectRoot;
450
488
  globalScope = "controller";
451
489
  controller.session.targetAgent = null;
@@ -463,108 +501,25 @@ async function runChatRust(projectRoot, options = {}) {
463
501
  }
464
502
  return { ok: true, project_root: projectRoot, root: projectRoot };
465
503
  },
466
- openBusAgentView(agentId, label = "") {
467
- const id = String(agentId || "").trim();
468
- if (!id) return { ok: false, error: "missing agent_id" };
469
- const viewLabel = String(label || id);
470
- if (agentViewId && agentViewId !== id) {
471
- try {
472
- daemonSend({
473
- type: IPC_REQUEST_TYPES.BUS_WATCH,
474
- agent_id: agentViewId,
475
- enabled: false,
476
- });
477
- } catch {
478
- // ignore
479
- }
480
- }
481
- agentViewId = id;
482
- controller.session.targetAgent = null;
483
- publish("prompt.set_prefix", { prefix: "› " });
484
- try {
485
- const { loadInternalAgentLogHistory } = require("../app/chat/internalAgentLogHistory");
486
- const history = loadInternalAgentLogHistory(activeProjectRoot, id, {
487
- width: 80,
488
- }) || [];
489
- const entries = historyToEntries(
490
- Array.isArray(history) ? history.map((line) => String(line || "")) : []
491
- );
492
- publish("agent.view.open", {
493
- agent_id: id,
494
- label: viewLabel,
495
- status: "ready",
496
- entries,
497
- });
498
- } catch {
499
- publish("agent.view.open", {
500
- agent_id: id,
501
- label: viewLabel,
502
- status: "ready",
503
- entries: [],
504
- });
505
- }
506
- try {
507
- daemonSend({
508
- type: IPC_REQUEST_TYPES.BUS_WATCH,
509
- agent_id: id,
510
- enabled: true,
511
- });
512
- } catch {
513
- // ignore
514
- }
515
- return { ok: true, mode: "agent_view", agent_id: id };
516
- },
517
504
  isInternalAgent(agentId) {
518
- const id = String(agentId || "").trim();
519
- if (!id) return false;
520
- const enter = resolveAgentEnterRequest({
521
- agentId: id,
522
- projectRoot: activeProjectRoot,
523
- activeAgentMeta: controller.session.metaMap,
524
- settings,
525
- });
526
- if (enter && enter.useBus) return true;
527
- // UI launch mode internal + agent without activate/socket → treat as bus.
528
- const mode = String(settings.launchMode || settings.launch_mode || "").trim();
529
- if (mode === "internal" && enter && !enter.supportsActivate && !enter.supportsSocket) {
530
- return true;
531
- }
532
- return false;
505
+ return isInternalAgentMeta(controller.session.metaMap.get(String(agentId || "").trim()));
533
506
  },
534
- /** Internal activate: split like multi-with-1-agent (kind=side). Not /multi. */
507
+ /** Activate an internal child in the one-child window mode. */
535
508
  startSide(agentId) {
536
509
  const id = String(agentId || "").trim();
537
- if (!id) return { ok: false, error: "missing agent_id" };
510
+ if (!hostApi.isInternalAgent(id)) return { ok: false, error: "Dashboard supports internal agents only" };
538
511
  if (!multiSession) return { ok: false, error: "split session not initialised" };
539
512
  // Prefer capability check, but do not hard-fail — connected Rust child
540
- // may be mid-handshake; multi.set is still the right wire.
513
+ // may be mid-handshake; window.set is still the right wire.
541
514
  const caps = hostRef && typeof hostRef.getClientCapabilities === "function"
542
515
  ? hostRef.getClientCapabilities()
543
516
  : [];
544
- if (caps.length > 0 && !caps.includes(MULTI_FRAMES_CAPABILITY)) {
517
+ if (caps.length > 0 && !caps.includes(WINDOW_MODES_CAPABILITY)) {
545
518
  return {
546
519
  ok: false,
547
- error: `Rust TUI lacks ${MULTI_FRAMES_CAPABILITY}; rebuild ufoo-tui`,
520
+ error: `Rust TUI lacks ${WINDOW_MODES_CAPABILITY}; rebuild ufoo-tui`,
548
521
  };
549
522
  }
550
- // Close fullscreen AgentView if it was open.
551
- if (agentViewId) {
552
- try {
553
- daemonSend({
554
- type: IPC_REQUEST_TYPES.BUS_WATCH,
555
- agent_id: agentViewId,
556
- enabled: false,
557
- });
558
- } catch {
559
- // ignore
560
- }
561
- agentViewId = "";
562
- publish("agent.view.close", {});
563
- }
564
- // /multi stays /multi — stop it before entering side.
565
- if (multiSession.isMultiKind && multiSession.isMultiKind()) {
566
- multiSession.stop();
567
- }
568
523
  const result = multiSession.start({
569
524
  kind: "side",
570
525
  agentIds: [id],
@@ -573,131 +528,28 @@ async function runChatRust(projectRoot, options = {}) {
573
528
  if (result && result.ok) {
574
529
  controller.session.targetAgent = null;
575
530
  publish("prompt.set_prefix", { prefix: "› " });
576
- publish("status.set", { text: "ready" });
577
531
  try { reconcileMultiInternalWatches(); } catch { /* ignore */ }
578
532
  return result;
579
533
  }
580
534
  return result || { ok: false, error: "side start failed" };
581
535
  },
582
- enterAgentView(agentId, options = {}) {
536
+ activateInternalAgent(agentId) {
583
537
  const id = String(agentId || "").trim();
584
- if (!id) return;
585
- const enter = resolveAgentEnterRequest({
586
- agentId: id,
587
- projectRoot: activeProjectRoot,
588
- activeAgentMeta: controller.session.metaMap,
589
- settings,
590
- });
591
- const label = (() => {
592
- const meta = controller.session.metaMap.get(id) || {};
593
- return meta.display_nickname || meta.nickname || id;
594
- })();
595
- const action = options.useBus
596
- ? "internal"
597
- : resolveDashboardAgentEnterAction(enter);
598
- const isInternal = action === "internal"
599
- || (enter && enter.useBus)
600
- || options.useBus;
601
-
602
- // /multi (including internal panes): focus the in-window pane.
603
- if (multiSession && multiSession.isMultiKind && multiSession.isMultiKind()) {
604
- try { multiSession.syncAgents(); } catch {}
605
- const focused = multiSession.focusAgent(id);
606
- if (focused && focused.ok) {
607
- appendLocal("system", `Multi focus → ${id}`);
608
- return { ok: true, mode: "multi_focus", agent_id: id };
609
- }
610
- }
611
-
612
- // Non-multi internal activate → side (same chrome as multi×1).
613
- if (isInternal) {
614
- const side = hostApi.startSide(id);
615
- if (side && side.ok) {
616
- return { ok: true, mode: "side", agent_id: id };
617
- }
618
- appendLocal("error", (side && side.error) || "side start failed");
619
- return side || { ok: false, error: "side start failed" };
620
- }
621
-
622
- // Already in side for this agent: re-focus.
623
- if (multiSession && multiSession.isSideKind && multiSession.isSideKind()) {
624
- const focused = multiSession.focusAgent(id);
625
- if (focused && focused.ok) {
626
- return { ok: true, mode: "side", agent_id: id };
627
- }
628
- // Different agent — switch side target.
629
- const side = hostApi.startSide(id);
630
- if (side && side.ok) return { ok: true, mode: "side", agent_id: id };
631
- }
632
-
633
- // Ink parity: activate = focus the agent's external terminal window/tab.
634
- if (action === "activate") {
635
- try {
636
- const AgentActivator = require("../coordination/bus/activate");
637
- const activator = new AgentActivator(activeProjectRoot || projectRoot);
638
- void activator.activate(id).catch((err) => {
639
- appendLocal(
640
- "error",
641
- `Failed to activate ${id}: ${err && err.message ? err.message : err}`
642
- );
643
- });
644
- appendLocal("system", `Activated ${label}`);
645
- return { ok: true, mode: "activate", agent_id: id };
646
- } catch (err) {
647
- appendLocal(
648
- "error",
649
- `Failed to activate ${id}: ${err && err.message ? err.message : err}`
650
- );
651
- return { ok: false, mode: "activate", agent_id: id, error: String(err && err.message || err) };
652
- }
653
- }
654
-
655
- // No PTY fullscreen handoff — host/socket agents need activate capability.
656
- appendLocal(
657
- "error",
658
- `Cannot enter ${label}: no activate support (host should expose activate; use /mode terminal|tmux|internal otherwise)`
659
- );
660
- return { ok: false, mode: "none", agent_id: id, error: "no activate support" };
661
- },
662
- getAgentAdapter(agentId) {
663
- try {
664
- const { createTerminalAdapterRouter } = require("../runtime/terminal/adapterRouter");
665
- const meta = controller.session.metaMap.get(agentId) || {};
666
- const launchMode = String(
667
- meta.launch_mode || meta.launchMode || settings.launchMode || ""
668
- ).trim();
669
- return createTerminalAdapterRouter().getAdapter({ launchMode, agentId, meta });
670
- } catch {
671
- return null;
538
+ if (!hostApi.isInternalAgent(id)) return { ok: false, error: "Dashboard supports internal agents only" };
539
+ if (multiSession && multiSession.isMultiKind()) {
540
+ multiSession.syncAgents();
541
+ const result = multiSession.focusAgent(id);
542
+ if (result && result.ok) return { ...result, mode: "multi_focus", agent_id: id };
672
543
  }
544
+ const result = hostApi.startSide(id);
545
+ return result && result.ok ? { ...result, mode: "side", agent_id: id } : result;
673
546
  },
674
547
  };
675
548
 
676
549
  function appendLocal(kind, text, speaker = "") {
677
- const MARKDOWN_KINDS = new Set(["assistant", "agent", "report", "error"]);
678
550
  const raw = String(text == null ? "" : text);
679
- let lines = [raw];
680
- if (MARKDOWN_KINDS.has(kind)) {
681
- try {
682
- if (!appendLocal._mdState) appendLocal._mdState = { inCodeBlock: false };
683
- lines = fmt.renderLogLinesWithMarkdownAnsi(raw, appendLocal._mdState);
684
- if (!Array.isArray(lines) || lines.length === 0) lines = raw.split(/\r?\n/);
685
- } catch {
686
- lines = raw.split(/\r?\n/);
687
- }
688
- }
689
- let last = null;
690
- for (let i = 0; i < lines.length; i += 1) {
691
- entrySeq += 1;
692
- const line = String(lines[i] || "");
693
- last = {
694
- id: `live-${entrySeq}`,
695
- kind,
696
- text: /\x1b\[/.test(line) ? line : stripTags(line),
697
- speaker: i === 0 ? speaker : "",
698
- };
699
- publish("transcript.append", last);
700
- }
551
+ const last = { ...historyToEntries([{ kind, text: raw, speaker }])[0], id: `live-${++entrySeq}` };
552
+ publish("transcript.append", last);
701
553
  try {
702
554
  const { appendChatHistory } = require("../app/chat/historyStore");
703
555
  appendChatHistory(
@@ -713,6 +565,33 @@ async function runChatRust(projectRoot, options = {}) {
713
565
  return last;
714
566
  }
715
567
 
568
+ function changeWindowLayout(mode) {
569
+ if (!multiSession) return { ok: false, error: "Window session not initialised" };
570
+ if (!["main", "side", "multi", "cycle"].includes(mode)) {
571
+ const error = "Usage: /window main | /window side | /window multi";
572
+ appendLocal("error", error);
573
+ return { ok: false, error };
574
+ }
575
+ if (mode !== "main") {
576
+ const caps = hostRef && typeof hostRef.getClientCapabilities === "function"
577
+ ? hostRef.getClientCapabilities() : [];
578
+ if (!caps.includes(WINDOW_MODES_CAPABILITY)) {
579
+ const error = `Rust TUI lacks ${WINDOW_MODES_CAPABILITY}; upgrade ufoo-tui`;
580
+ appendLocal("error", error);
581
+ return { ok: false, error };
582
+ }
583
+ }
584
+ const result = multiSession.setLayout(mode);
585
+ if (!result.ok) {
586
+ appendLocal("error", result.error || "Layout switch failed");
587
+ return result;
588
+ }
589
+ reconcileMultiInternalWatches();
590
+ controller.session.targetAgent = null;
591
+ publish("prompt.set_prefix", { prefix: "› " });
592
+ return result;
593
+ }
594
+
716
595
  const controller = createChatController({
717
596
  projectRoot,
718
597
  globalMode: env.globalMode,
@@ -759,46 +638,24 @@ async function runChatRust(projectRoot, options = {}) {
759
638
  const { isRunning } = require("../runtime/daemon");
760
639
  return isRunning(root || activeProjectRoot || projectRoot);
761
640
  },
762
- enterAgentView: (...args) => hostApi.enterAgentView(...args),
763
- getAgentAdapter: (...args) => hostApi.getAgentAdapter(...args),
641
+ activateInternalAgent: (...args) => hostApi.activateInternalAgent(...args),
764
642
  focusMultiPane: async (agentId) => {
765
- // /multi: focus pane (terminal or internal — multi unchanged).
643
+ // Focus a visible internal pane.
766
644
  if (multiSession && multiSession.isMultiKind && multiSession.isMultiKind()) {
767
645
  try { multiSession.syncAgents(); } catch { /* ignore */ }
768
646
  const focused = multiSession.focusAgent(agentId);
769
647
  if (focused && focused.ok) {
770
- appendLocal("system", `Multi focus → ${agentId}`);
771
648
  return true;
772
649
  }
773
650
  return false;
774
651
  }
775
- // Non-multi internal → side split (not user-facing /multi).
652
+ // Activate the child in a one-child layout.
776
653
  if (hostApi.isInternalAgent(agentId)) {
777
654
  const side = hostApi.startSide(agentId);
778
655
  return Boolean(side && side.ok);
779
656
  }
780
657
  return false;
781
658
  },
782
- activateAgent: async (agentId) => {
783
- if (multiSession && multiSession.isMultiKind && multiSession.isMultiKind()) {
784
- try { multiSession.syncAgents(); } catch { /* ignore */ }
785
- const focused = multiSession.focusAgent(agentId);
786
- if (focused && focused.ok) {
787
- appendLocal("system", `Multi focus → ${agentId}`);
788
- return;
789
- }
790
- }
791
- if (hostApi.isInternalAgent(agentId)) {
792
- const side = hostApi.startSide(agentId);
793
- if (!side || !side.ok) {
794
- appendLocal("error", (side && side.error) || "side start failed");
795
- }
796
- return;
797
- }
798
- const AgentActivator = require("../coordination/bus/activate");
799
- const activator = new AgentActivator(activeProjectRoot || projectRoot);
800
- await activator.activate(agentId);
801
- },
802
659
  listProjects: () => listProjectsForCommands(),
803
660
  getCurrentProject: () => ({ project_root: activeProjectRoot }),
804
661
  getActiveProjectRoot: () => activeProjectRoot,
@@ -809,12 +666,16 @@ async function runChatRust(projectRoot, options = {}) {
809
666
  },
810
667
  dispatch: (action) => {
811
668
  if (!action || typeof action !== "object") return;
669
+ // Child streams are presented in their own pane, including their busy
670
+ // state. They must not start or complete the main agent's status.
671
+ if (action.publisher && isInternalChild(action.publisher)) return;
812
672
  if (action.type === "stream/begin") {
813
673
  tools.beginScope();
814
674
  const speaker = String(action.publisher || "");
815
675
  const id = `stream-${speaker || "agent"}-${Date.now()}`;
816
676
  streamIds.set(speaker, id);
817
- publish("stream.start", { id, speaker });
677
+ streamLabels.set(speaker, action.displayName || speaker);
678
+ publish("stream.start", { id, speaker: action.displayName || speaker });
818
679
  return;
819
680
  }
820
681
  if (action.type === "stream/delta") {
@@ -825,14 +686,16 @@ async function runChatRust(projectRoot, options = {}) {
825
686
  streamIds.set(key, id);
826
687
  publish("stream.start", { id, speaker: key });
827
688
  }
828
- publish("stream.delta", { id, text: String(action.delta || ""), speaker: key });
689
+ publish("stream.delta", { id, text: String(action.delta || ""), speaker: streamLabels.get(key) || key });
829
690
  return;
830
691
  }
831
692
  if (action.type === "stream/end") {
832
693
  tools.flush();
833
694
  for (const [key, id] of [...streamIds.entries()]) {
695
+ if (action.publisher && key !== action.publisher) continue;
834
696
  publish("stream.done", { id });
835
697
  streamIds.delete(key);
698
+ streamLabels.delete(key);
836
699
  }
837
700
  publish("status.set", { text: "ready", busy: false });
838
701
  return;
@@ -841,44 +704,18 @@ async function runChatRust(projectRoot, options = {}) {
841
704
  publish("transcript.reset", {});
842
705
  }
843
706
  },
844
- toggleMultiWindow: () => {
845
- if (!multiSession) {
846
- appendLocal("error", "Multi-window session not initialised");
847
- return false;
848
- }
849
- // Exit /multi when already in multi. If currently in side (internal
850
- // activate split), fall through and open real /multi instead.
851
- if (multiSession.isActive() && !(multiSession.isSideKind && multiSession.isSideKind())) {
852
- multiSession.stop();
853
- try { reconcileMultiInternalWatches(); } catch { /* ignore */ }
854
- appendLocal("system", "Exited multi-window.");
855
- return true;
856
- }
857
- if (multiSession.isActive()) {
858
- multiSession.stop();
859
- try { reconcileMultiInternalWatches(); } catch { /* ignore */ }
860
- }
861
- const caps = hostRef && typeof hostRef.getClientCapabilities === "function"
862
- ? hostRef.getClientCapabilities()
863
- : [];
864
- if (!caps.includes(MULTI_FRAMES_CAPABILITY)) {
865
- appendLocal(
866
- "error",
867
- `Rust TUI lacks ${MULTI_FRAMES_CAPABILITY}; upgrade ufoo-tui`
868
- );
869
- return false;
870
- }
871
- const result = multiSession.start({ kind: "multi" });
872
- if (!result.ok) {
873
- appendLocal("error", result.error || "multi-window start failed");
874
- return false;
707
+ setWindowLayout: (args) => changeWindowLayout(parseWindowModeArgs(args)).ok,
708
+ openAgentSettings: (section) => agentSettings.open(section),
709
+ applyAgentModel: (...args) => agentSettings.applyModel(...args),
710
+ applyAgentSettings,
711
+ openResumeMenu: () => {
712
+ if (multiSession?.isActive()) {
713
+ multiSession.handleFocus({ target: "chat" });
714
+ publish("window.set", multiSession.getSnapshot());
875
715
  }
876
- try { reconcileMultiInternalWatches(); } catch { /* ignore */ }
877
- appendLocal("system", "Entered multi-window (Ctrl+W focus · Ctrl+Q exit).");
878
- return true;
716
+ publish("prompt.set_text", { text: "/resume ", if_empty: true });
879
717
  },
880
718
  applyChatSettings: (patch = {}) => {
881
- if (patch.launchMode != null) settings.launchMode = patch.launchMode;
882
719
  if (patch.agentProvider != null) settings.agentProvider = patch.agentProvider;
883
720
  publish("settings.snapshot", buildSettingsSnapshot(settings));
884
721
  },
@@ -916,52 +753,48 @@ async function runChatRust(projectRoot, options = {}) {
916
753
  }
917
754
 
918
755
  function resolveMultiPaneOptions(agentId) {
919
- const enter = resolveAgentEnterRequest({
920
- agentId,
921
- projectRoot: activeProjectRoot,
922
- activeAgentMeta: controller.session.metaMap,
923
- settings,
924
- });
925
- if (!enter || !enter.useBus) return { mode: "socket" };
926
- let initialLines = [];
756
+ let initialEntries = [];
927
757
  try {
928
- const { loadInternalAgentLogHistory } = require("../app/chat/internalAgentLogHistory");
929
- initialLines = loadInternalAgentLogHistory(activeProjectRoot, agentId, {
758
+ const { loadInternalAgentTranscript } = require("../app/chat/internalAgentLogHistory");
759
+ initialEntries = loadInternalAgentTranscript(activeProjectRoot, agentId, {
930
760
  maxEvents: 200,
931
- maxLines: 200,
761
+ maxEntries: 200,
932
762
  }) || [];
933
763
  } catch {
934
- initialLines = [];
764
+ initialEntries = [];
935
765
  }
936
766
  return {
937
767
  mode: "internal",
938
- initialLines: [
939
- `ufoo internal agent · ${getAgentLabel(agentId)}`,
940
- `agent: ${agentId}`,
941
- "",
942
- ...initialLines,
943
- ],
768
+ initialEntries,
944
769
  };
945
770
  }
946
771
 
947
772
  multiSession = createRustMultiSession({
773
+ getProjectRoot: () => activeProjectRoot,
948
774
  projectRoot,
949
775
  getActiveAgents: getActiveAgentIds,
950
776
  getAgentMeta: getAgentMetaForMulti,
951
- getInjectSockPath: (id) =>
952
- require("../app/chat/agentEnter").resolveInjectSockPathForAgent(activeProjectRoot, id),
953
777
  resolvePaneOptions: resolveMultiPaneOptions,
954
778
  onInternalSubmit: (agentId, message) => {
779
+ // Layout commands belong to the workspace even when a child has focus.
780
+ if (/^\/window(?:\s|$)/.test(String(message || "").trim())) {
781
+ changeWindowLayout(parseWindowModeArgs(String(message).trim().split(/\s+/).slice(1)));
782
+ return;
783
+ }
784
+ const requestId = `pane-send-${require("crypto").randomUUID()}`;
785
+ internalSubmissions.set(requestId, { agentId, message, projectRoot: activeProjectRoot });
955
786
  try {
956
- daemonSend({
787
+ return daemonSend({
957
788
  type: IPC_REQUEST_TYPES.BUS_SEND,
789
+ request_id: requestId,
958
790
  target: agentId,
959
791
  message: String(message || ""),
960
792
  injection_mode: "immediate",
961
793
  source: "rust-multi-window",
962
794
  });
963
- } catch {
964
- // ignore
795
+ } catch (error) {
796
+ internalSubmissions.delete(requestId);
797
+ throw error;
965
798
  }
966
799
  },
967
800
  publish,
@@ -969,12 +802,15 @@ async function runChatRust(projectRoot, options = {}) {
969
802
  getLabel: getAgentLabel,
970
803
  });
971
804
 
972
- function buildSnapshot() {
805
+ function buildSnapshot({ startup = true } = {}) {
973
806
  const { loadChatHistory, loadInputHistory } = require("../app/chat/historyStore");
974
807
  const historyRoot = activeProjectRoot || projectRoot;
975
808
  const historyOpts = historyOptions();
976
809
  const history = loadChatHistory(historyRoot, 200, historyOpts);
977
810
  const inputHistory = loadInputHistory(historyRoot, 200, historyOpts);
811
+ const showWelcome = startup && history.length === 0 && inputHistory.length === 0
812
+ && !welcomedProjects.has(historyRoot);
813
+ if (showWelcome) welcomedProjects.add(historyRoot);
978
814
  const agents = controller.getAgentsSnapshot();
979
815
  const settingsSnap = buildSettingsSnapshot(settings);
980
816
  const projects = env.globalMode ? loadGlobalProjectRows(activeProjectRoot) : [];
@@ -982,13 +818,19 @@ async function runChatRust(projectRoot, options = {}) {
982
818
  status: "ready",
983
819
  package_version: PACKAGE_VERSION,
984
820
  footer: agents.footer || "",
985
- entries: historyToEntries(history),
821
+ entries: [
822
+ ...historyToEntries(history),
823
+ ...(showWelcome ? buildUfooStartupEntries({
824
+ version: PACKAGE_VERSION,
825
+ workspaceRoot: historyRoot,
826
+ globalMode: Boolean(env.globalMode),
827
+ width: Math.max(1, (process.stdout.columns || 80) - 6),
828
+ }) : []),
829
+ ],
986
830
  input_history: Array.isArray(inputHistory) ? inputHistory.filter(Boolean) : [],
987
831
  agents: agents.agents,
988
832
  settings: settingsSnap,
989
- launch_mode: settingsSnap.launch_mode,
990
833
  agent_provider: settingsSnap.agent_provider,
991
- mode_options: settingsSnap.mode_options,
992
834
  provider_options: settingsSnap.provider_options,
993
835
  global_mode: Boolean(env.globalMode),
994
836
  controller_root: projectRoot,
@@ -998,7 +840,7 @@ async function runChatRust(projectRoot, options = {}) {
998
840
  cron: agents.cron && agents.cron.tasks ? agents.cron.tasks : [],
999
841
  loop: agents.loop || null,
1000
842
  loop_summary: require("./dashboardBridge").formatLoopSummary(agents.loop || null),
1001
- multi: multiSession ? multiSession.getSnapshot() : { active: false },
843
+ window: multiSession ? multiSession.getSnapshot() : { active: false, mode: "main" },
1002
844
  };
1003
845
  }
1004
846
 
@@ -1011,16 +853,17 @@ async function runChatRust(projectRoot, options = {}) {
1011
853
  const host = createUiHostServer({
1012
854
  socketPath: uiSocketPath,
1013
855
  authToken: uiAuthToken,
1014
- capabilities: ["chat", "scrollback", "prompt", MULTI_FRAMES_CAPABILITY],
856
+ capabilities: ["chat", "scrollback", "prompt", MULTI_FRAMES_CAPABILITY, WINDOW_MODES_CAPABILITY],
1015
857
  onClientReady(socket) {
1016
858
  const snap = createEnvelope({
1017
859
  kind: "snapshot",
1018
860
  name: "app.snapshot",
1019
861
  seq: host.nextSeq(),
1020
862
  scope: { surface: "chat", project_id: projectRoot },
1021
- payload: buildSnapshot(),
863
+ payload: buildSnapshot({ startup: true }),
1022
864
  });
1023
865
  socket.write(encodeMessage(snap));
866
+ multiSession?.publishFrames();
1024
867
  if (env.globalMode) publishProjects();
1025
868
  },
1026
869
  async onCommand(cmd) {
@@ -1031,28 +874,45 @@ async function runChatRust(projectRoot, options = {}) {
1031
874
  }
1032
875
  if (name === "ui.resync.request") {
1033
876
  publish("app.snapshot", buildSnapshot());
877
+ multiSession?.publishFrames();
1034
878
  return { ok: true };
1035
879
  }
1036
880
  if (name === "completion.request") {
1037
881
  const fmt = require("./format");
1038
- const { COMMAND_TREE, COMMAND_REGISTRY } = require("../app/chat/commands");
882
+ const { getChatCommandCatalog } = require("../app/chat/commands");
1039
883
  const agents = controller.session.agents.slice();
1040
884
  const agentLabels = agents.map((id) => {
1041
885
  const meta = controller.session.metaMap.get(id) || {};
1042
886
  return meta.display_nickname || meta.nickname || id;
1043
887
  });
1044
888
  const dynamic = loadDynamicCompletionSources(activeProjectRoot);
889
+ const completionRoot = activeProjectRoot;
890
+ const resumeQuery = /^\/resume(?:\s|$)/.test(String(payload.text || "").trimStart());
891
+ let resumeTargets = [];
892
+ if (resumeQuery) {
893
+ try { resumeTargets = await loadResumeCompletionSources(completionRoot); }
894
+ catch (error) {
895
+ appendLocal("error", `Could not load recoverable sessions: ${error.message}`);
896
+ }
897
+ if (completionRoot !== activeProjectRoot) return { ok: true, stale: true };
898
+ }
899
+ const settingsLists = /^\/settings\s+agent\s+(?:model|thinking)(?:\s|$)/.test(String(payload.text || "").trimStart())
900
+ ? await agentSettings.completions(String(payload.text || "")) : {};
901
+ if (completionRoot !== activeProjectRoot) return { ok: true, stale: true };
1045
902
  const items = fmt.buildCompletions({
1046
903
  text: String(payload.text || ""),
1047
904
  agents,
1048
905
  agentLabels,
1049
- commands: COMMAND_REGISTRY,
1050
- commandTree: COMMAND_TREE,
906
+ ...getChatCommandCatalog({ globalMode: env.globalMode }),
1051
907
  groupTemplates: dynamic.groupTemplates,
1052
908
  soloProfiles: dynamic.soloProfiles,
1053
- limit: 20,
909
+ argumentLists: { ...settingsLists, ...(resumeQuery ? { "/resume": resumeTargets } : {}) },
910
+ limit: Math.max(20, resumeTargets.length, ...Object.values(settingsLists).map((list) => list.length)),
1054
911
  });
1055
- publish("completions.set", { items });
912
+ publish("completions.set", { items, text: String(payload.text || "") });
913
+ if (resumeQuery && resumeTargets.length === 0 && String(payload.text || "").trim() === "/resume") {
914
+ appendLocal("system", "No recoverable internal agent sessions or groups.");
915
+ }
1056
916
  return { ok: true, count: items.length };
1057
917
  }
1058
918
  if (name === "task.cancel") {
@@ -1062,12 +922,10 @@ async function runChatRust(projectRoot, options = {}) {
1062
922
  }
1063
923
  if (name === "agent.select") {
1064
924
  const agentId = String(payload.agent_id || payload.agentId || "").trim();
925
+ if (agentId && !hostApi.isInternalAgent(agentId)) return { ok: false, error: "Unknown internal agent" };
1065
926
  if (agentId) {
1066
927
  controller.session.targetAgent = agentId;
1067
928
  const label = payload.label || agentId;
1068
- publish("status.set", {
1069
- text: `target @${label}`,
1070
- });
1071
929
  publish("prompt.set_prefix", { prefix: `›@${label} ` });
1072
930
  } else {
1073
931
  controller.session.targetAgent = null;
@@ -1075,21 +933,15 @@ async function runChatRust(projectRoot, options = {}) {
1075
933
  }
1076
934
  return { ok: true, agent_id: agentId };
1077
935
  }
1078
- if (name === "agent.open" || name === "ui.suspend.request") {
936
+ if (name === "agent.open") {
1079
937
  const agentId = String(payload.agent_id || payload.agentId || "").trim();
1080
- if (name === "agent.open") {
1081
- return hostApi.enterAgentView(agentId, payload) || { ok: true, agent_id: agentId };
1082
- }
1083
- // Suspend handoff removed (no PTY mirror). Ignore explicit suspend.
1084
- appendLocal("system", "ui.suspend ignored (PTY handoff removed)");
1085
- return { ok: true, suspend: false, agent_id: agentId };
938
+ return hostApi.activateInternalAgent(agentId) || { ok: true, agent_id: agentId };
1086
939
  }
1087
- if (name === "multi.exit") {
1088
- if (multiSession && multiSession.isActive()) {
1089
- multiSession.stop();
1090
- try { reconcileMultiInternalWatches(); } catch { /* ignore */ }
940
+ if (name === "window.set" || name === "window.cycle") {
941
+ if (name === "window.set" && payload.session_id && (!multiSession || payload.session_id !== multiSession.getSessionId())) {
942
+ return { ok: false, error: "stale session_id" };
1091
943
  }
1092
- return { ok: true };
944
+ return changeWindowLayout(name === "window.cycle" ? "cycle" : payload.mode);
1093
945
  }
1094
946
  if (name === "multi.focus") {
1095
947
  return multiSession
@@ -1106,52 +958,15 @@ async function runChatRust(projectRoot, options = {}) {
1106
958
  ? multiSession.handleRaw(payload)
1107
959
  : { ok: false, error: "multi not active" };
1108
960
  }
1109
- if (name === "agent.view.exit") {
1110
- if (agentViewId) {
1111
- try {
1112
- daemonSend({
1113
- type: IPC_REQUEST_TYPES.BUS_WATCH,
1114
- agent_id: agentViewId,
1115
- enabled: false,
1116
- });
1117
- } catch {
1118
- // ignore
1119
- }
1120
- }
1121
- for (const [key, id] of [...streamIds.entries()]) {
1122
- if (String(id).startsWith("av-stream-") || key === agentViewId) {
1123
- publish("stream.done", { id });
1124
- streamIds.delete(key);
1125
- }
1126
- }
1127
- agentViewId = "";
1128
- publish("agent.view.close", {});
1129
- publish("app.snapshot", buildSnapshot());
1130
- return { ok: true };
1131
- }
1132
- if (name === "agent.view.submit") {
1133
- const agentId = String(payload.agent_id || agentViewId || "").trim();
1134
- const text = String(payload.text || "").trim();
1135
- if (!agentId || !text) return { ok: false, error: "missing agent or text" };
1136
- publish("agent.view.append", {
1137
- id: `av-user-${Date.now()}`,
1138
- kind: "user",
1139
- text: `> ${text}`,
1140
- speaker: "",
1141
- });
1142
- daemonSend({
1143
- type: IPC_REQUEST_TYPES.BUS_SEND,
1144
- target: agentId,
1145
- message: text,
1146
- injection_mode: "immediate",
1147
- source: "chat-internal-agent-view",
1148
- });
1149
- publish("agent.view.status", { text: "working" });
1150
- return { ok: true };
961
+ if (name === "multi.scroll") {
962
+ return multiSession
963
+ ? multiSession.handleScroll(payload)
964
+ : { ok: false, error: "multi not active" };
1151
965
  }
966
+ if (name === "multi.expand") return multiSession?.handleExpand(payload) || { ok: false };
1152
967
  if (name === "agent.close") {
1153
968
  const agentId = String(payload.agent_id || payload.agentId || "").trim();
1154
- if (!agentId) return { ok: false, error: "missing agent_id" };
969
+ if (!hostApi.isInternalAgent(agentId)) return { ok: false, error: "Unknown internal agent" };
1155
970
  daemonSend({ type: IPC_REQUEST_TYPES.CLOSE_AGENT, agent_id: agentId });
1156
971
  publish("status.set", { text: `closing ${agentId}` });
1157
972
  return { ok: true };
@@ -1226,57 +1041,17 @@ async function runChatRust(projectRoot, options = {}) {
1226
1041
  return { ok: false, error: err && err.message ? err.message : String(err) };
1227
1042
  }
1228
1043
  }
1044
+ if (name === "settings.open") return agentSettings.open(payload.section || "model");
1229
1045
  if (name === "settings.set") {
1230
- try {
1231
- const applied = applySettingsPatch(projectRoot, payload);
1232
- if (!applied.ok) return applied;
1233
- Object.assign(settings, {
1234
- launchMode: applied.settings.launch_mode,
1235
- agentProvider: applied.settings.agent_provider,
1236
- });
1237
- publish("settings.snapshot", applied.settings);
1238
- if (payload.launch_mode || payload.launchMode) {
1239
- appendLocal("system", `Launch mode: ${applied.settings.launch_mode}`);
1240
- }
1241
- if (payload.agent_provider || payload.agentProvider) {
1242
- const label = applied.settings.provider_options.find(
1243
- (opt) => opt.value === applied.settings.agent_provider
1244
- );
1245
- appendLocal(
1246
- "system",
1247
- `ufoo-agent: ${(label && label.label) || applied.settings.agent_provider}`
1248
- );
1249
- try {
1250
- const { getUfooPaths } = require("../coordination/state/paths");
1251
- const fs = require("fs");
1252
- const pathMod = require("path");
1253
- const agentDir = getUfooPaths(projectRoot).agentDir;
1254
- fs.rmSync(pathMod.join(agentDir, "ufoo-agent.json"), { force: true });
1255
- fs.rmSync(pathMod.join(agentDir, "ufoo-agent.history.jsonl"), { force: true });
1256
- } catch {
1257
- // ignore
1258
- }
1259
- }
1260
- publish("status.set", { text: "settings saved · restarting daemon…" });
1261
- try {
1262
- if (daemonCoordinator && typeof daemonCoordinator.restart === "function") {
1263
- await daemonCoordinator.restart();
1264
- }
1265
- } catch (err) {
1266
- appendLocal("error", `Daemon restart failed: ${err && err.message ? err.message : err}`);
1267
- }
1268
- try {
1269
- daemonSend({ type: IPC_REQUEST_TYPES.STATUS });
1270
- } catch {
1271
- // ignore
1272
- }
1273
- publish("status.set", { text: "settings saved" });
1274
- return { ok: true, settings: applied.settings };
1275
- } catch (err) {
1276
- return { ok: false, error: err && err.message ? err.message : String(err) };
1046
+ try { return await applyAgentSettings(payload); }
1047
+ catch (error) {
1048
+ appendLocal("error", `Settings failed: ${error.message}`);
1049
+ return { ok: false, error: error.message };
1277
1050
  }
1278
1051
  }
1279
1052
  if (name === "interaction.respond") {
1053
+ const settingsReply = await agentSettings.respond(payload);
1054
+ if (settingsReply) return settingsReply;
1280
1055
  appendLocal("system", payload.cancelled
1281
1056
  ? "interaction cancelled"
1282
1057
  : `interaction answer: ${String(payload.text || "").slice(0, 200)}`);
@@ -1285,28 +1060,31 @@ async function runChatRust(projectRoot, options = {}) {
1285
1060
  }
1286
1061
  if (name === "input.submit") {
1287
1062
  const text = String(payload.text || "");
1288
- const payloadTarget = String(payload.target_agent || payload.targetAgent || "").trim();
1289
- if (payloadTarget && !controller.session.targetAgent) {
1290
- controller.session.targetAgent = payloadTarget;
1291
- }
1063
+ // The submitted identity wins over mutable footer/focus state. Never
1064
+ // send an unresolved explicit child target to the main agent.
1065
+ const routing = resolveSubmittedInputTarget(payload, controller.session.targetAgent, hostApi.isInternalAgent);
1066
+ if (!routing.ok) return routing;
1067
+ controller.session.targetAgent = routing.target;
1068
+ const childOrLayout = Boolean(routing.target)
1069
+ || text.trimStart().startsWith("@") || /^\/window(?:\s|$)/.test(text.trim());
1292
1070
  // Empty ›@ Enter for internal: open side split directly (do not
1293
1071
  // depend solely on tryActivate → focusMultiPane chain).
1294
1072
  if (!text.trim()) {
1295
- const target = controller.session.targetAgent || payloadTarget;
1073
+ const target = routing.target;
1296
1074
  if (target && hostApi.isInternalAgent(target)
1297
1075
  && !(multiSession && multiSession.isMultiKind && multiSession.isMultiKind())) {
1298
1076
  const side = hostApi.startSide(target);
1299
1077
  if (!side || !side.ok) {
1300
1078
  appendLocal("error", `side failed: ${(side && side.error) || "unknown"}`);
1301
- // Fall through to submitInput for bus AgentView fallback.
1079
+ // Preserve the target and let the input handler report the failed focus.
1302
1080
  } else {
1303
- publish("status.set", { text: "ready", busy: false });
1304
1081
  return { ok: true, routed: "side", agent_id: target };
1305
1082
  }
1306
1083
  }
1307
1084
  }
1085
+ const beforeSubmit = mainSubmissionRev;
1308
1086
  await controller.submitInput(text);
1309
- publish("status.set", { text: "ready", busy: false });
1087
+ if (!childOrLayout && beforeSubmit === mainSubmissionRev) publish("status.set", { text: "ready", busy: false });
1310
1088
  return { ok: true, routed: text.trim() ? "submit" : "empty" };
1311
1089
  }
1312
1090
  return { ok: false, error: `unsupported command ${name}` };
@@ -1317,21 +1095,13 @@ async function runChatRust(projectRoot, options = {}) {
1317
1095
 
1318
1096
  const router = createDaemonMessageRouter({
1319
1097
  escapeBlessed: (value) => String(value || ""),
1098
+ resolveAgentDisplayName: getAgentLabel,
1320
1099
  stripBlessedTags: stripTags,
1321
1100
  logMessage: (kind, text) => {
1322
1101
  const normalized = kind === "error" ? "error"
1323
1102
  : kind === "user" ? "user"
1324
1103
  : kind === "assistant" ? "assistant"
1325
1104
  : "system";
1326
- if (agentViewId) {
1327
- publish("agent.view.append", {
1328
- id: `av-log-${Date.now()}`,
1329
- kind: normalized,
1330
- text: stripTags(text),
1331
- speaker: "",
1332
- });
1333
- return;
1334
- }
1335
1105
  appendLocal(normalized, text);
1336
1106
  },
1337
1107
  renderScreen: () => {},
@@ -1345,79 +1115,17 @@ async function runChatRust(projectRoot, options = {}) {
1345
1115
  setPending: (value) => {
1346
1116
  controller.session.pending = value || null;
1347
1117
  },
1348
- resolveStatusLine: (text) => {
1349
- if (agentViewId) {
1350
- publish("agent.view.status", { text: stripTags(text || "ready") });
1351
- return;
1352
- }
1353
- publish("status.set", { text: stripTags(text || "ready") });
1354
- },
1355
- enqueueBusStatus: (text) => {
1356
- if (agentViewId) {
1357
- publish("agent.view.status", { text: stripTags(text) });
1358
- return;
1359
- }
1360
- publish("status.set", { text: stripTags(text) });
1361
- },
1362
- resolveBusStatus: () => {
1363
- if (agentViewId) {
1364
- publish("agent.view.status", { text: "ready" });
1365
- return;
1366
- }
1367
- publish("status.set", { text: "ready" });
1118
+ resolveStatusLine: (text, data) => {
1119
+ if (data?.key && isInternalChild(data.key)) return;
1120
+ publish("status.set", { text: stripTags(text || "ready"), busy: false });
1368
1121
  },
1369
- getCurrentView: () => (agentViewId ? "agent" : "main"),
1370
- isAgentViewUsesBus: () => Boolean(agentViewId),
1371
- getViewingAgent: () => agentViewId || "",
1372
- isAgentEventForViewingAgent: (data, viewingAgent, publisher) => {
1373
- if (!viewingAgent) return false;
1374
- const candidates = [
1375
- viewingAgent,
1376
- publisher,
1377
- data && data.publisher,
1378
- data && data.target,
1379
- data && data.subscriber,
1380
- ].filter(Boolean).map(String);
1381
- return candidates.some((id) => (
1382
- id === viewingAgent
1383
- || id.endsWith(`:${viewingAgent}`)
1384
- || viewingAgent.endsWith(`:${id}`)
1385
- || viewingAgent === id
1386
- ));
1122
+ enqueueBusStatus: (item) => {
1123
+ if (item?.key && isInternalChild(item.key)) return;
1124
+ publish("status.set", { text: stripTags(typeof item === "object" ? item.text : item), busy: true });
1387
1125
  },
1388
- writeToAgentTerm: (text, meta = {}) => {
1389
- if (!agentViewId) return;
1390
- const streamPayload = meta && meta.streamPayload && typeof meta.streamPayload === "object"
1391
- ? meta.streamPayload
1392
- : null;
1393
- const publisher = String((meta && meta.publisher) || agentViewId);
1394
- const raw = stripTags(text);
1395
- if (streamPayload) {
1396
- let id = streamIds.get(publisher);
1397
- if (!id) {
1398
- id = `av-stream-${publisher || "agent"}-${Date.now()}`;
1399
- streamIds.set(publisher, id);
1400
- publish("stream.start", { id, speaker: publisher });
1401
- }
1402
- if (raw) {
1403
- publish("stream.delta", { id, text: raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n"), speaker: publisher });
1404
- }
1405
- if (streamPayload.done || meta.done) {
1406
- publish("stream.done", { id });
1407
- streamIds.delete(publisher);
1408
- publish("agent.view.status", { text: "ready" });
1409
- } else {
1410
- publish("agent.view.status", { text: "working" });
1411
- }
1412
- return;
1413
- }
1414
- if (!raw) return;
1415
- publish("agent.view.append", {
1416
- id: `av-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1417
- kind: meta && meta.kind ? meta.kind : "assistant",
1418
- text: raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n"),
1419
- speaker: publisher,
1420
- });
1126
+ resolveBusStatus: (item) => {
1127
+ if (item?.key && isInternalChild(item.key)) return;
1128
+ publish("status.set", { text: "ready", busy: false });
1421
1129
  },
1422
1130
  beginStream: (...args) => controller.getStreamState().beginStream(...args),
1423
1131
  appendStreamDelta: (...args) => controller.getStreamState().appendStreamDelta(...args),
@@ -1430,18 +1138,12 @@ async function runChatRust(projectRoot, options = {}) {
1430
1138
  activity_state: value,
1431
1139
  activity_detail: options.detail || "",
1432
1140
  });
1433
- if (agentViewId && agentId === agentViewId) {
1434
- publish("agent.view.status", { text: value || "ready" });
1435
- }
1436
1141
  },
1437
1142
  clearTransientAgentState: (agentId) => {
1438
1143
  controller.patchAgentActivity(agentId, {
1439
1144
  activity_state: "",
1440
1145
  activity_detail: "",
1441
1146
  });
1442
- if (agentViewId && agentId === agentViewId) {
1443
- publish("agent.view.status", { text: "ready" });
1444
- }
1445
1147
  },
1446
1148
  });
1447
1149
 
@@ -1453,22 +1155,37 @@ async function runChatRust(projectRoot, options = {}) {
1453
1155
  return;
1454
1156
  }
1455
1157
  if (!msg || typeof msg !== "object") return;
1158
+ if ([IPC_RESPONSE_TYPES.BUS_SEND_OK, IPC_RESPONSE_TYPES.ERROR].includes(msg.type)) {
1159
+ // Older daemons return uncorrelated bus_send_ok; retain compatibility.
1160
+ const id = msg.request_id || (msg.type === IPC_RESPONSE_TYPES.BUS_SEND_OK
1161
+ ? internalSubmissions.keys().next().value : "");
1162
+ const submission = internalSubmissions.get(id);
1163
+ if (submission) {
1164
+ internalSubmissions.delete(id);
1165
+ if (submission.projectRoot === activeProjectRoot && msg.type === IPC_RESPONSE_TYPES.ERROR) {
1166
+ multiSession.acceptEvent(submission.agentId, { type: "submission_failed", message: submission.message,
1167
+ error: `Message delivery failed: ${msg.error || "unknown error"}` });
1168
+ }
1169
+ controller.requestDaemonStatus();
1170
+ return;
1171
+ }
1172
+ }
1173
+ if (msg.type === IPC_RESPONSE_TYPES.STATUS) {
1174
+ const root = msg.data && (msg.data.projectRoot || msg.data.project_root);
1175
+ if (root) {
1176
+ const { canonicalProjectRoot } = require("../runtime/projects");
1177
+ if (canonicalProjectRoot(root) !== canonicalProjectRoot(activeProjectRoot)) return;
1178
+ }
1179
+ const key = msg.data && msg.data.key;
1180
+ if (key && String(key).includes(":") && !hostApi.isInternalAgent(key)) return;
1181
+ }
1456
1182
  if (msg.type === IPC_RESPONSE_TYPES.BUS) {
1183
+ if (!isInternalDashboardEvent(msg.data || {}, (id) => controller.session.metaMap.get(id))) return;
1457
1184
  try { mirrorBusToMultiPanes(msg.data || {}); } catch { /* ignore */ }
1185
+ if (msg.data?.event === "agent_surface") return;
1458
1186
  }
1459
1187
  if (msg.type === IPC_RESPONSE_TYPES.BUS_SEND_OK) {
1460
- if (agentViewId) {
1461
- publish("agent.view.append", {
1462
- id: `av-ok-${Date.now()}`,
1463
- kind: "system",
1464
- text: "✓ Message delivered",
1465
- speaker: "",
1466
- });
1467
- publish("agent.view.status", { text: "ready" });
1468
- } else {
1469
- appendLocal("system", "✓ Message delivered");
1470
- publish("status.set", { text: "ready" });
1471
- }
1188
+ appendLocal("system", "✓ Message delivered");
1472
1189
  controller.requestDaemonStatus();
1473
1190
  return;
1474
1191
  }
@@ -1501,7 +1218,10 @@ async function runChatRust(projectRoot, options = {}) {
1501
1218
  });
1502
1219
 
1503
1220
  await daemonConnection.connect();
1504
- daemonSend = (req) => daemonConnection.send(req);
1221
+ daemonSend = (req) => {
1222
+ if (req.type === IPC_REQUEST_TYPES.PROMPT) mainSubmissionRev += 1;
1223
+ return daemonConnection.send(req);
1224
+ };
1505
1225
  controller.setSend(daemonSend);
1506
1226
 
1507
1227
  controller.start({
@@ -1534,19 +1254,13 @@ async function runChatRust(projectRoot, options = {}) {
1534
1254
  });
1535
1255
  }
1536
1256
 
1537
- // PTY suspend handoff removed. If an old ufoo-tui still exits 75, respawn once.
1538
- const EXIT_SUSPEND = 75;
1539
- let exitCode = await spawnTuiOnce();
1540
- if (exitCode === EXIT_SUSPEND) {
1541
- appendLocal("system", "Suspend exit ignored (PTY handoff removed); resuming chat.");
1542
- publish("ui.resume", { ok: true });
1543
- exitCode = await spawnTuiOnce();
1544
- }
1257
+ const exitCode = await spawnTuiOnce();
1545
1258
 
1546
1259
  if (multiSession && multiSession.isActive()) {
1547
1260
  try { multiSession.stop(); } catch {}
1548
1261
  }
1549
1262
  controller.stop();
1263
+ internalSubmissions.clear();
1550
1264
  daemonConnection.markExit();
1551
1265
  daemonConnection.close();
1552
1266
  await host.close();
@@ -1557,4 +1271,7 @@ module.exports = {
1557
1271
  runChatRust,
1558
1272
  historyToEntries,
1559
1273
  loadDynamicCompletionSources,
1274
+ loadResumeCompletionSources,
1275
+ parseWindowModeArgs,
1276
+ resolveSubmittedInputTarget,
1560
1277
  };