u-foo 4.0.10 → 4.1.2
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/OPTIONAL_SKILLS/ufoo-bus-poll/SKILL.md +27 -0
- package/README.md +279 -789
- package/README.zh-CN.md +290 -439
- package/SKILLS/ufoo/SKILL.md +7 -0
- package/bin/ufoo.js +36 -3
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/docs/OBSERVABILITY.md +4 -2
- package/docs/README.md +1 -0
- package/package.json +6 -2
- package/scripts/pack-desktop.js +174 -0
- package/src/agents/capabilities/coding/index.js +26 -3
- package/src/agents/capabilities/index.js +2 -1
- package/src/agents/capabilities/mac/index.js +145 -0
- package/src/agents/capabilities/planning/index.js +1 -1
- package/src/agents/capabilities/turnRecall/index.js +5 -16
- package/src/agents/profiles/coding.js +1 -1
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/providers/nativeTransport.js +105 -116
- package/src/agents/providers/runtimeConfig.js +15 -4
- package/src/agents/providers/transports/anthropicCache.js +78 -0
- package/src/agents/providers/transports/antigravityTransport.js +3 -2
- package/src/agents/providers/transports/openaiResponsesTransport.js +7 -12
- package/src/agents/providers/transports/requestCacheObservation.js +61 -0
- package/src/agents/providers/transports/responsesProtocol.js +54 -46
- package/src/agents/providers/upstreamRuntime.js +2 -2
- package/src/agents/runtime/context/contextWindow.js +10 -0
- package/src/agents/runtime/context/slidingWindowManager.js +97 -41
- package/src/agents/runtime/context/topicSelector.js +4 -2
- package/src/agents/runtime/context/turnAnalyzer.js +17 -29
- package/src/agents/runtime/core/agentLoop.js +23 -7
- package/src/agents/runtime/createAgentRuntime.js +1 -1
- package/src/agents/runtime/protocol/auxiliaryModelRequest.js +28 -0
- package/src/app/chat/ChatController.js +1 -0
- package/src/app/chat/commandExecutor.js +25 -0
- package/src/app/chat/commands.js +2 -0
- package/src/app/chat/daemonMessageRouter.js +30 -3
- package/src/app/cli/appCommands.js +107 -0
- package/src/app/cli/features/skills.js +2 -0
- package/src/app/cli/macCommands.js +321 -0
- package/src/app/cli/metricsCommands.js +6 -1
- package/src/app/cli/run.js +26 -0
- package/src/app/cli/setupCommands.js +1 -0
- package/src/code/agent.js +1 -0
- package/src/code/context/assembler.js +8 -6
- package/src/code/context/promptLayers.js +3 -1
- package/src/code/context/stateCommit.js +2 -2
- package/src/code/context/transcript.js +11 -5
- package/src/code/nativeRunner.js +25 -5
- package/src/code/skills/loader.js +10 -2
- package/src/code/skills/render.js +8 -1
- package/src/config.js +42 -0
- package/src/coordination/bus/activate.js +44 -19
- package/src/coordination/history/agentPerformance.js +88 -11
- package/src/coordination/history/agentTrace.js +2 -0
- package/src/coordination/history/modelInputCost.js +52 -0
- package/src/runtime/contracts/uiProtocol.js +26 -0
- package/src/runtime/daemon/agentHost.js +35 -12
- package/src/runtime/daemon/mcpStdioProxy.js +3 -2
- package/src/runtime/mac/helperClient.js +279 -0
- package/src/runtime/mac/helperCompiler.js +235 -0
- package/src/runtime/mac/macSession.js +866 -0
- package/src/runtime/mac/native/ufoo_mac_helper.swift +2493 -0
- package/src/runtime/mac/paths.js +63 -0
- package/src/ui/agentSettingsController.js +12 -5
- package/src/ui/cliHandoff.js +484 -0
- package/src/ui/desktopArchive.js +41 -0
- package/src/ui/desktopUiHost.js +1601 -0
- package/src/ui/desktopUiHostCli.js +66 -0
- package/src/ui/format/index.js +17 -0
- package/src/ui/rustChatHost.js +45 -6
- package/src/ui/workspaceInspector.js +621 -0
|
@@ -0,0 +1,1601 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Shared Node UI Host for Ufoo macOS Desktop App (`ufoo-ui/1` + `desktop-host-v1`).
|
|
5
|
+
*
|
|
6
|
+
* Connects to the single user-scoped `GlobalDaemon` (`~/.ufoo/run/ufoo.sock`),
|
|
7
|
+
* reuses `ChatController`, `rustMultiSession`, `agentSurface`, and `settingsBridge`,
|
|
8
|
+
* emits raw Markdown + structured metadata (`markdown-raw-v1`), aggregates the
|
|
9
|
+
* multi-project + 2nd-level Worker Agent tree, and serves Right Inspector queries.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const fs = require("fs");
|
|
13
|
+
const os = require("os");
|
|
14
|
+
const path = require("path");
|
|
15
|
+
const crypto = require("crypto");
|
|
16
|
+
const { createUiHostServer, createAuthToken } = require("./uiHostServer");
|
|
17
|
+
const { createDesktopArchive } = require("./desktopArchive");
|
|
18
|
+
const { createToolMergePublisher } = require("./toolMergeBridge");
|
|
19
|
+
const { createRustMultiSession } = require("./rustMultiSession");
|
|
20
|
+
const { createAgentSurface } = require("./agentSurface");
|
|
21
|
+
const { writeMultiPaneBusEvent } = require("./multiPaneBusMirror");
|
|
22
|
+
const { buildSettingsSnapshot, applySettingsPatch } = require("./settingsBridge");
|
|
23
|
+
const { createAgentSettingsController } = require("./agentSettingsController");
|
|
24
|
+
const { listAgentModels, confirmAgentModel } = require("../agents/providers/modelSettings");
|
|
25
|
+
const { loadGlobalProjectRows, buildDashboardPublishPayload, formatLoopSummary } = require("./dashboardBridge");
|
|
26
|
+
const {
|
|
27
|
+
loadWorkspaceChanges,
|
|
28
|
+
loadWorkspaceDocs,
|
|
29
|
+
handleWorkspaceContext,
|
|
30
|
+
detectGitBranch,
|
|
31
|
+
} = require("./workspaceInspector");
|
|
32
|
+
const {
|
|
33
|
+
createDesktopHandoffServer,
|
|
34
|
+
parseHandoffUrl,
|
|
35
|
+
launchCliHandoff,
|
|
36
|
+
focusExternalAgentHost,
|
|
37
|
+
installCliShims,
|
|
38
|
+
} = require("./cliHandoff");
|
|
39
|
+
const { createChatController } = require("../app/chat/ChatController");
|
|
40
|
+
const { createDaemonMessageRouter } = require("../app/chat/daemonMessageRouter");
|
|
41
|
+
const { bootstrapEnvironment, ensureSubscriberId } = require("../app/chat/bootstrap");
|
|
42
|
+
const { loadInternalAgentTranscript } = require("../app/chat/internalAgentLogHistory");
|
|
43
|
+
const { readAgentSurfaceEvents, createAgentSurfaceReader } = require("../coordination/history/agentSurface");
|
|
44
|
+
const { listReports } = require("../coordination/report/store");
|
|
45
|
+
const { getUfooPaths } = require("../coordination/state/paths");
|
|
46
|
+
const { loadAgentsData } = require("../coordination/state/agentsStore");
|
|
47
|
+
const { isAgentPidAlive } = require("../coordination/bus/utils");
|
|
48
|
+
const { isInternalAgentMeta, isInternalDashboardEvent } = require("../runtime/contracts/agentMode");
|
|
49
|
+
const {
|
|
50
|
+
createEnvelope,
|
|
51
|
+
encodeMessage,
|
|
52
|
+
MULTI_FRAMES_CAPABILITY,
|
|
53
|
+
WINDOW_MODES_CAPABILITY,
|
|
54
|
+
RAW_MARKDOWN_CAPABILITY,
|
|
55
|
+
DESKTOP_HOST_CAPABILITY,
|
|
56
|
+
} = require("../runtime/contracts/uiProtocol");
|
|
57
|
+
const { IPC_REQUEST_TYPES, IPC_RESPONSE_TYPES } = require("../runtime/contracts/eventContract");
|
|
58
|
+
const { resolveDaemonEndpoint, routeDaemonRequest } = require("../runtime/daemon/endpoint");
|
|
59
|
+
const {
|
|
60
|
+
canonicalProjectRoot,
|
|
61
|
+
buildProjectId,
|
|
62
|
+
upsertProjectRuntime,
|
|
63
|
+
resolveGlobalControllerProjectRoot,
|
|
64
|
+
} = require("../runtime/projects");
|
|
65
|
+
const { loadConfig, normalizeAgentProvider, defaultAgentModelForProvider } = require("../config");
|
|
66
|
+
const {
|
|
67
|
+
loadDynamicCompletionSources,
|
|
68
|
+
loadResumeCompletionSources,
|
|
69
|
+
parseWindowModeArgs,
|
|
70
|
+
resolveSubmittedInputTarget,
|
|
71
|
+
} = require("./rustChatHost");
|
|
72
|
+
|
|
73
|
+
const PACKAGE_VERSION = require("../../package.json").version;
|
|
74
|
+
|
|
75
|
+
function stripTags(value) {
|
|
76
|
+
return String(value || "")
|
|
77
|
+
.replace(/\{\/?(?:[a-z]+(?:-[a-z]+)*-(?:fg|bg)|#[\da-f]{3,8}-(?:fg|bg)|bold|italic|underline|blink|inverse|invisible|normal|reset|escape)\}/gi, "")
|
|
78
|
+
.replace(/\{open\}/g, "{")
|
|
79
|
+
.replace(/\{close\}/g, "}");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function rawHistoryToEntries(rows) {
|
|
83
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
84
|
+
const KINDS = new Set([
|
|
85
|
+
"system", "user", "assistant", "error", "agent", "report",
|
|
86
|
+
"thinking", "tool", "spacer", "meta", "bus", "success", "banner",
|
|
87
|
+
]);
|
|
88
|
+
return list.map((row, index) => {
|
|
89
|
+
const source = row && typeof row === "object" ? row : { text: row };
|
|
90
|
+
const meta = source.meta && typeof source.meta === "object" ? source.meta : {};
|
|
91
|
+
const sourceType = String(source.sourceType || source.type || source.kind || "system");
|
|
92
|
+
const streamed = sourceType === "bus" && meta.stream_done === true;
|
|
93
|
+
const kind = streamed || sourceType === "reply"
|
|
94
|
+
? "assistant"
|
|
95
|
+
: KINDS.has(sourceType) ? sourceType : "system";
|
|
96
|
+
let text = stripTags(source.text || source.content || "");
|
|
97
|
+
let speaker = String(source.speaker || meta.speaker || "");
|
|
98
|
+
if (streamed) {
|
|
99
|
+
const match = text.match(/^([^\n]+?): ([\s\S]*)$/);
|
|
100
|
+
if (match) {
|
|
101
|
+
speaker = speaker || match[1];
|
|
102
|
+
text = match[2];
|
|
103
|
+
}
|
|
104
|
+
} else if (kind === "assistant" && /^ufoo\s*·\s*/.test(text)) {
|
|
105
|
+
speaker = speaker || "ufoo";
|
|
106
|
+
text = text.replace(/^ufoo\s*·\s*/, "");
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
id: String(source.id || `hist-${index}`),
|
|
110
|
+
kind,
|
|
111
|
+
text,
|
|
112
|
+
speaker,
|
|
113
|
+
detail: stripTags(source.detail || source.expanded_text || meta.detail || meta.expanded_text || ""),
|
|
114
|
+
expanded: false,
|
|
115
|
+
ts: source.ts || "",
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function inspectDormantProjectSummary(projectRoot) {
|
|
121
|
+
const out = {
|
|
122
|
+
mainBusy: false,
|
|
123
|
+
waitingUser: false,
|
|
124
|
+
conversationId: "main-default",
|
|
125
|
+
workers: [],
|
|
126
|
+
};
|
|
127
|
+
try {
|
|
128
|
+
const cfg = loadConfig(projectRoot) || {};
|
|
129
|
+
const convId = cfg.agentConversationId || "main-default";
|
|
130
|
+
out.conversationId = convId;
|
|
131
|
+
const snapFile = path.join(projectRoot, ".ufoo", "agent", "main", "runtimes", convId, "snapshot.json");
|
|
132
|
+
if (fs.existsSync(snapFile)) {
|
|
133
|
+
const snap = JSON.parse(fs.readFileSync(snapFile, "utf8"));
|
|
134
|
+
const tasks = Object.values((snap && snap.tasks) || {});
|
|
135
|
+
out.mainBusy = tasks.some((t) => t && ["queued", "running"].includes(t.status));
|
|
136
|
+
out.waitingUser = tasks.some((t) => t && t.status === "waiting_user");
|
|
137
|
+
}
|
|
138
|
+
} catch {
|
|
139
|
+
// ignore snapshot read errors
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
const paths = getUfooPaths(projectRoot);
|
|
144
|
+
if (fs.existsSync(paths.agentsFile)) {
|
|
145
|
+
const data = loadAgentsData(paths.agentsFile) || {};
|
|
146
|
+
for (const [id, meta] of Object.entries(data.agents || {})) {
|
|
147
|
+
if (!meta || meta.status !== "active") continue;
|
|
148
|
+
if (id === "ufoo-agent" || meta.agent_type === "ufoo-agent") continue;
|
|
149
|
+
const pid = Number.parseInt(meta.pid, 10);
|
|
150
|
+
const alive = meta.mcp_bridge === true || !pid || isAgentPidAlive(pid);
|
|
151
|
+
if (!alive) continue;
|
|
152
|
+
const internal = isInternalAgentMeta(meta);
|
|
153
|
+
out.workers.push({
|
|
154
|
+
id,
|
|
155
|
+
label: String(meta.display_nickname || meta.nickname || id),
|
|
156
|
+
type: String(meta.agent_type || meta.type || id.split(":")[0] || "worker"),
|
|
157
|
+
internal,
|
|
158
|
+
external: !internal,
|
|
159
|
+
activity_state: String(meta.activity_state || "idle"),
|
|
160
|
+
activity_detail: String(meta.activity_detail || ""),
|
|
161
|
+
group_id: String(meta.group_id || ""),
|
|
162
|
+
group_member_id: String(meta.group_member_id || ""),
|
|
163
|
+
group_template_alias: String(meta.group_template_alias || ""),
|
|
164
|
+
host_name: String(meta.host_name || ""),
|
|
165
|
+
launch_mode: String(meta.launch_mode || ""),
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
} catch {
|
|
170
|
+
// ignore agent registry read errors
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function startDesktopUiHost(options = {}) {
|
|
176
|
+
const controllerRoot = canonicalProjectRoot(
|
|
177
|
+
options.controllerRoot || resolveGlobalControllerProjectRoot()
|
|
178
|
+
);
|
|
179
|
+
const initialProjectRoot = options.initialProjectRoot
|
|
180
|
+
? canonicalProjectRoot(options.initialProjectRoot)
|
|
181
|
+
: controllerRoot;
|
|
182
|
+
const desktopArchive = createDesktopArchive(controllerRoot);
|
|
183
|
+
|
|
184
|
+
const shortTmp = process.platform === "darwin" && fs.existsSync("/tmp") ? "/tmp" : os.tmpdir();
|
|
185
|
+
const uiSocketPath = options.socketPath || path.join(
|
|
186
|
+
shortTmp,
|
|
187
|
+
`ufoo-ui-d-${process.pid}-${Date.now().toString(36)}.sock`
|
|
188
|
+
);
|
|
189
|
+
const uiAuthToken = options.authToken || createAuthToken();
|
|
190
|
+
|
|
191
|
+
const env = bootstrapEnvironment(controllerRoot, {
|
|
192
|
+
...options,
|
|
193
|
+
globalMode: true,
|
|
194
|
+
});
|
|
195
|
+
if (env.needsBootstrap || !fs.existsSync(env.runtimePaths.ufooDir)) {
|
|
196
|
+
const repoRoot = path.join(__dirname, "..", "..");
|
|
197
|
+
const init = new env.UfooInit(repoRoot);
|
|
198
|
+
await init.init({
|
|
199
|
+
targets: "context,bus",
|
|
200
|
+
project: controllerRoot,
|
|
201
|
+
globalController: true,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
await ensureSubscriberId(controllerRoot);
|
|
205
|
+
|
|
206
|
+
const isDaemonRunning = typeof options.isRunning === "function" ? options.isRunning : env.isRunning;
|
|
207
|
+
const startDaemonFn = typeof options.startDaemon === "function" ? options.startDaemon : env.startDaemon;
|
|
208
|
+
|
|
209
|
+
const initialEndpoint = resolveDaemonEndpoint(controllerRoot, { controllerRoot });
|
|
210
|
+
const daemonRoot = initialEndpoint.scope === "global"
|
|
211
|
+
? initialEndpoint.controllerRoot
|
|
212
|
+
: initialEndpoint.projectRoot;
|
|
213
|
+
if (!isDaemonRunning(daemonRoot)) {
|
|
214
|
+
startDaemonFn(controllerRoot);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const { connectWithRetry, requestDaemon, startDaemon, stopDaemon } = require("../app/chat/transport");
|
|
218
|
+
const { createDaemonTransport } = require("../app/chat/daemonTransport");
|
|
219
|
+
const { createDaemonConnection } = require("../app/chat/daemonConnection");
|
|
220
|
+
const { createDaemonCoordinator } = require("../app/chat/daemonCoordinator");
|
|
221
|
+
const { isRunning } = require("../runtime/daemon");
|
|
222
|
+
|
|
223
|
+
const daemonTransport = createDaemonTransport({
|
|
224
|
+
projectRoot: controllerRoot,
|
|
225
|
+
sockPath: initialEndpoint.socketPath,
|
|
226
|
+
daemonRoot,
|
|
227
|
+
isRunning: isDaemonRunning,
|
|
228
|
+
startDaemon: startDaemonFn,
|
|
229
|
+
connectWithRetry,
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
let entrySeq = 0;
|
|
233
|
+
let mainSubmissionRev = 0;
|
|
234
|
+
let hostRef = null;
|
|
235
|
+
let daemonSend = () => {};
|
|
236
|
+
let daemonCoordinator = null;
|
|
237
|
+
let activeProjectRoot = controllerRoot;
|
|
238
|
+
let globalScope = "controller";
|
|
239
|
+
let multiSession = null;
|
|
240
|
+
let stageTarget = { kind: "project_main", agentId: "" };
|
|
241
|
+
let activePendingInteraction = null;
|
|
242
|
+
const streamIds = new Map();
|
|
243
|
+
const streamLabels = new Map();
|
|
244
|
+
const ownRequestIds = new Set();
|
|
245
|
+
const internalSubmissions = new Map();
|
|
246
|
+
const watchedInternalAgents = new Set();
|
|
247
|
+
const standaloneSurfaces = new Map();
|
|
248
|
+
const standaloneDrafts = new Map();
|
|
249
|
+
let standaloneReader = null;
|
|
250
|
+
let standaloneReaderRoot = "";
|
|
251
|
+
let standalonePollTimer = null;
|
|
252
|
+
let treePollTimer = null;
|
|
253
|
+
const recoverableCache = new Map();
|
|
254
|
+
|
|
255
|
+
const settings = (() => {
|
|
256
|
+
try {
|
|
257
|
+
return loadConfig(activeProjectRoot) || {};
|
|
258
|
+
} catch {
|
|
259
|
+
return {};
|
|
260
|
+
}
|
|
261
|
+
})();
|
|
262
|
+
|
|
263
|
+
function publish(name, payload) {
|
|
264
|
+
if (!hostRef) return;
|
|
265
|
+
hostRef.broadcast(hostRef.createEvent(name, payload, {
|
|
266
|
+
surface: "desktop",
|
|
267
|
+
project_id: activeProjectRoot,
|
|
268
|
+
view_id: stageTarget.kind === "worker_single" ? stageTarget.agentId : "main",
|
|
269
|
+
}));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function publishLossy(name, payload) {
|
|
273
|
+
if (!hostRef) return;
|
|
274
|
+
hostRef.broadcast(hostRef.createLossyEvent(name, payload, {
|
|
275
|
+
surface: "desktop",
|
|
276
|
+
project_id: activeProjectRoot,
|
|
277
|
+
view_id: stageTarget.kind === "worker_single" ? stageTarget.agentId : "main",
|
|
278
|
+
}));
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function historyOptions() {
|
|
282
|
+
const { chatHistoryOptionsForScope } = require("../app/chat/historyStore");
|
|
283
|
+
return chatHistoryOptionsForScope({
|
|
284
|
+
globalMode: true,
|
|
285
|
+
globalScope,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function appendLocal(kind, text, speaker = "") {
|
|
290
|
+
const raw = String(text == null ? "" : text);
|
|
291
|
+
const entry = {
|
|
292
|
+
...rawHistoryToEntries([{ kind, text: raw, speaker, ts: new Date().toISOString() }])[0],
|
|
293
|
+
id: `live-${++entrySeq}`,
|
|
294
|
+
};
|
|
295
|
+
publish("transcript.append", entry);
|
|
296
|
+
try {
|
|
297
|
+
const { appendChatHistory } = require("../app/chat/historyStore");
|
|
298
|
+
appendChatHistory(activeProjectRoot, kind, raw, { speaker }, historyOptions());
|
|
299
|
+
} catch {
|
|
300
|
+
// best-effort persistence
|
|
301
|
+
}
|
|
302
|
+
return entry;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function isInternalChild(agentId) {
|
|
306
|
+
const id = String(agentId || "");
|
|
307
|
+
return id !== "ufoo-agent" && !id.endsWith(":ufoo-agent") && isInternalAgentMeta(controller.session.metaMap.get(id));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function getAgentLabel(agentId) {
|
|
311
|
+
const meta = controller.session.metaMap.get(agentId) || {};
|
|
312
|
+
return String(meta.display_nickname || meta.nickname || agentId);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function getHandoffAgentMeta(agentId) {
|
|
316
|
+
const { agentsFile } = getUfooPaths(activeProjectRoot);
|
|
317
|
+
const agents = loadAgentsData(agentsFile)?.agents;
|
|
318
|
+
return agents?.[agentId] || controller.session.metaMap.get(agentId);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function refreshRecoverableForActiveProject() {
|
|
322
|
+
if (globalScope === "controller") return [];
|
|
323
|
+
try {
|
|
324
|
+
const items = await loadResumeCompletionSources(
|
|
325
|
+
activeProjectRoot,
|
|
326
|
+
(root, payload, opts = {}) => requestDaemon(root, payload, { ...opts, controllerRoot })
|
|
327
|
+
);
|
|
328
|
+
recoverableCache.set(activeProjectRoot, items);
|
|
329
|
+
return items;
|
|
330
|
+
} catch {
|
|
331
|
+
return recoverableCache.get(activeProjectRoot) || [];
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function buildActiveProjectWorkerRows() {
|
|
336
|
+
const list = [];
|
|
337
|
+
for (const id of controller.session.agents) {
|
|
338
|
+
if (id === "ufoo-agent" || id.endsWith(":ufoo-agent")) continue;
|
|
339
|
+
const meta = controller.session.metaMap.get(id) || {};
|
|
340
|
+
const internal = isInternalAgentMeta(meta);
|
|
341
|
+
list.push({
|
|
342
|
+
id,
|
|
343
|
+
label: getAgentLabel(id),
|
|
344
|
+
type: String(meta.agent_type || meta.type || id.split(":")[0] || "worker"),
|
|
345
|
+
internal,
|
|
346
|
+
external: !internal,
|
|
347
|
+
activity_state: String(meta.activity_state || "idle"),
|
|
348
|
+
activity_detail: String(meta.activity_detail || ""),
|
|
349
|
+
group_id: String(meta.group_id || ""),
|
|
350
|
+
group_member_id: String(meta.group_member_id || ""),
|
|
351
|
+
group_template_alias: String(meta.group_template_alias || ""),
|
|
352
|
+
host_name: String(meta.host_name || ""),
|
|
353
|
+
launch_mode: String(meta.launch_mode || ""),
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
return list;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function listUnarchivedProjects(archive = desktopArchive.read()) {
|
|
360
|
+
const archivedRoots = new Set(archive.projects.map(({ root }) => root));
|
|
361
|
+
return loadGlobalProjectRows(activeProjectRoot).filter(({ root }) => !archivedRoots.has(root));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function buildProjectsTreePayload() {
|
|
365
|
+
const archive = desktopArchive.read();
|
|
366
|
+
const rawProjects = listUnarchivedProjects(archive);
|
|
367
|
+
const seen = new Set(rawProjects.map((r) => r.root));
|
|
368
|
+
if (activeProjectRoot && activeProjectRoot !== controllerRoot
|
|
369
|
+
&& !archive.projects.some(({ root }) => root === activeProjectRoot) && !seen.has(activeProjectRoot)) {
|
|
370
|
+
rawProjects.unshift({
|
|
371
|
+
id: buildProjectId(activeProjectRoot),
|
|
372
|
+
label: path.basename(activeProjectRoot) || activeProjectRoot,
|
|
373
|
+
root: activeProjectRoot,
|
|
374
|
+
status: "running",
|
|
375
|
+
active: true,
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const projects = rawProjects.map((row) => {
|
|
380
|
+
const isCurrent = row.root === activeProjectRoot && globalScope === "project";
|
|
381
|
+
const dormant = inspectDormantProjectSummary(row.root);
|
|
382
|
+
const workers = isCurrent ? buildActiveProjectWorkerRows() : dormant.workers;
|
|
383
|
+
const archivedIds = new Set(archive.sessions.filter(({ root }) => root === row.root).map(({ id }) => id));
|
|
384
|
+
return {
|
|
385
|
+
id: row.id || buildProjectId(row.root),
|
|
386
|
+
label: row.label || path.basename(row.root),
|
|
387
|
+
root: row.root,
|
|
388
|
+
branch: detectGitBranch(row.root),
|
|
389
|
+
status: row.status || "running",
|
|
390
|
+
active: isCurrent,
|
|
391
|
+
selectedAsMain: isCurrent && stageTarget.kind === "project_main",
|
|
392
|
+
selectedWorkerId: isCurrent && stageTarget.kind === "worker_single" ? stageTarget.agentId : "",
|
|
393
|
+
mainBusy: isCurrent ? Boolean(controller.session.pending) || dormant.mainBusy : dormant.mainBusy,
|
|
394
|
+
waitingUser: isCurrent ? Boolean(activePendingInteraction) || dormant.waitingUser : dormant.waitingUser,
|
|
395
|
+
conversationId: dormant.conversationId,
|
|
396
|
+
workers: workers.filter(({ id }) => !archivedIds.has(id)),
|
|
397
|
+
recoverable: (recoverableCache.get(row.root) || []).filter(({ id }) => !archivedIds.has(id)),
|
|
398
|
+
};
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
return {
|
|
402
|
+
controller_root: controllerRoot,
|
|
403
|
+
active_root: activeProjectRoot,
|
|
404
|
+
scope: globalScope,
|
|
405
|
+
stage_target: { ...stageTarget },
|
|
406
|
+
projects,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function publishProjectsTree() {
|
|
411
|
+
const tree = buildProjectsTreePayload();
|
|
412
|
+
publish("projects.tree", tree);
|
|
413
|
+
publish("projects.snapshot", {
|
|
414
|
+
global_mode: true,
|
|
415
|
+
controller_root: controllerRoot,
|
|
416
|
+
active_root: activeProjectRoot,
|
|
417
|
+
scope: globalScope,
|
|
418
|
+
projects: tree.projects,
|
|
419
|
+
});
|
|
420
|
+
return tree;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function ensureStandaloneSurface(agentId) {
|
|
424
|
+
if (!standaloneSurfaces.has(agentId)) {
|
|
425
|
+
const surface = createAgentSurface();
|
|
426
|
+
const initial = loadInternalAgentTranscript(activeProjectRoot, agentId, {
|
|
427
|
+
maxEvents: 300,
|
|
428
|
+
maxEntries: 300,
|
|
429
|
+
});
|
|
430
|
+
if (initial.length) {
|
|
431
|
+
surface.apply("transcript.reset", { entries: initial });
|
|
432
|
+
}
|
|
433
|
+
const events = readAgentSurfaceEvents(activeProjectRoot, [agentId]);
|
|
434
|
+
let maxSeq = 0;
|
|
435
|
+
if (events.length) {
|
|
436
|
+
surface.apply("transcript.reset", { entries: [] });
|
|
437
|
+
for (const evt of events) {
|
|
438
|
+
surface.accept(evt.data.surface);
|
|
439
|
+
maxSeq = Math.max(maxSeq, evt.seq || 0);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
standaloneSurfaces.set(agentId, { surface, seq: maxSeq });
|
|
443
|
+
}
|
|
444
|
+
return standaloneSurfaces.get(agentId);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function pollStandaloneWorkerSurface() {
|
|
448
|
+
if (stageTarget.kind !== "worker_single" || !stageTarget.agentId) return;
|
|
449
|
+
const agentId = stageTarget.agentId;
|
|
450
|
+
const meta = controller.session.metaMap.get(agentId) || {};
|
|
451
|
+
if (!isInternalAgentMeta(meta)) return;
|
|
452
|
+
|
|
453
|
+
if (standaloneReaderRoot !== activeProjectRoot || !standaloneReader) {
|
|
454
|
+
standaloneReaderRoot = activeProjectRoot;
|
|
455
|
+
standaloneReader = createAgentSurfaceReader(activeProjectRoot);
|
|
456
|
+
}
|
|
457
|
+
const holder = ensureStandaloneSurface(agentId);
|
|
458
|
+
let dirty = false;
|
|
459
|
+
for (const evt of standaloneReader.read([agentId])) {
|
|
460
|
+
if ((evt.seq || 0) > holder.seq) {
|
|
461
|
+
holder.seq = evt.seq || holder.seq;
|
|
462
|
+
if (holder.surface.accept(evt.data.surface)) dirty = true;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (dirty) publishStandaloneWorkerFrame(agentId);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function buildStandaloneWorkerFrame(agentId) {
|
|
469
|
+
const id = String(agentId || "").trim();
|
|
470
|
+
const meta = controller.session.metaMap.get(id) || {};
|
|
471
|
+
const internal = isInternalAgentMeta(meta);
|
|
472
|
+
const draft = standaloneDrafts.get(id) || { text: "", revision: 0 };
|
|
473
|
+
|
|
474
|
+
if (internal) {
|
|
475
|
+
const holder = ensureStandaloneSurface(id);
|
|
476
|
+
const snap = holder.surface.snapshot();
|
|
477
|
+
return {
|
|
478
|
+
project_root: activeProjectRoot,
|
|
479
|
+
agent_id: id,
|
|
480
|
+
label: getAgentLabel(id),
|
|
481
|
+
type: String(meta.agent_type || meta.type || id.split(":")[0] || "worker"),
|
|
482
|
+
internal: true,
|
|
483
|
+
external: false,
|
|
484
|
+
entries: snap.entries.map((e) => ({
|
|
485
|
+
...e,
|
|
486
|
+
text: stripTags(e.text || ""),
|
|
487
|
+
detail: stripTags(e.detail || ""),
|
|
488
|
+
})),
|
|
489
|
+
status: snap.status || String(meta.activity_state || "ready"),
|
|
490
|
+
busy: Boolean(snap.busy || meta.activity_state === "working"),
|
|
491
|
+
usage: snap.usage || "",
|
|
492
|
+
plan: snap.plan || [],
|
|
493
|
+
activity_detail: String(meta.activity_detail || ""),
|
|
494
|
+
group_id: String(meta.group_id || ""),
|
|
495
|
+
group_template_alias: String(meta.group_template_alias || ""),
|
|
496
|
+
worktree_root: String(meta.worktree_root || meta.cwd || activeProjectRoot),
|
|
497
|
+
input: draft.text,
|
|
498
|
+
input_revision: draft.revision,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const entries = loadInternalAgentTranscript(activeProjectRoot, id, {
|
|
503
|
+
maxEvents: 400,
|
|
504
|
+
maxEntries: 300,
|
|
505
|
+
});
|
|
506
|
+
const reports = listReports(activeProjectRoot, { agent: id, num: 25 });
|
|
507
|
+
return {
|
|
508
|
+
project_root: activeProjectRoot,
|
|
509
|
+
agent_id: id,
|
|
510
|
+
label: getAgentLabel(id),
|
|
511
|
+
type: String(meta.agent_type || meta.type || id.split(":")[0] || "external"),
|
|
512
|
+
internal: false,
|
|
513
|
+
external: true,
|
|
514
|
+
entries,
|
|
515
|
+
reports,
|
|
516
|
+
status: String(meta.activity_state || "online"),
|
|
517
|
+
busy: meta.activity_state === "working",
|
|
518
|
+
usage: "",
|
|
519
|
+
plan: [],
|
|
520
|
+
activity_detail: String(meta.activity_detail || ""),
|
|
521
|
+
host_name: String(meta.host_name || meta.launch_mode || "terminal"),
|
|
522
|
+
launch_mode: String(meta.launch_mode || "external"),
|
|
523
|
+
worktree_root: String(meta.cwd || activeProjectRoot),
|
|
524
|
+
input: draft.text,
|
|
525
|
+
input_revision: draft.revision,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function publishStandaloneWorkerFrame(agentId = stageTarget.agentId) {
|
|
530
|
+
if (!agentId) return null;
|
|
531
|
+
const frame = buildStandaloneWorkerFrame(agentId);
|
|
532
|
+
publishLossy("worker.view.frame", frame);
|
|
533
|
+
return frame;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function applyAgentSettings(patch) {
|
|
537
|
+
const root = activeProjectRoot;
|
|
538
|
+
const model = patch.agent_model ?? patch.agentModel;
|
|
539
|
+
if (model) {
|
|
540
|
+
const current = loadConfig(root);
|
|
541
|
+
const agentProvider = normalizeAgentProvider(patch.agent_provider ?? patch.agentProvider ?? current.agentProvider);
|
|
542
|
+
const agentBaseUrl = patch.agent_base_url ?? patch.agentBaseUrl ?? current.agentBaseUrl;
|
|
543
|
+
const confirmation = await confirmAgentModel(root, model, { config: { ...current, agentProvider, agentBaseUrl } });
|
|
544
|
+
if (!confirmation.allowed) return { ok: false, error: confirmation.error };
|
|
545
|
+
}
|
|
546
|
+
if (root !== activeProjectRoot) return { ok: false, error: "The active workspace changed. Reopen settings and try again." };
|
|
547
|
+
const applied = applySettingsPatch(root, patch);
|
|
548
|
+
if (!applied.ok) return applied;
|
|
549
|
+
Object.assign(settings, loadConfig(root));
|
|
550
|
+
publish("settings.snapshot", applied.settings);
|
|
551
|
+
const restart = applied.providerChanged
|
|
552
|
+
|| patch.agent_base_url != null
|
|
553
|
+
|| patch.agent_api_key != null
|
|
554
|
+
|| patch.agentBaseUrl != null
|
|
555
|
+
|| patch.agentApiKey != null;
|
|
556
|
+
if (restart && daemonCoordinator?.restart) {
|
|
557
|
+
publish("status.set", { text: "settings saved · restarting daemon…", busy: true });
|
|
558
|
+
await daemonCoordinator.restart();
|
|
559
|
+
}
|
|
560
|
+
publish("status.set", { text: "settings saved", busy: false });
|
|
561
|
+
publishProjectsTree();
|
|
562
|
+
return applied;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const tools = createToolMergePublisher((name, payload) => publish(name, payload));
|
|
566
|
+
|
|
567
|
+
function sendInternalAgentWatch(agentId, enabled) {
|
|
568
|
+
const id = String(agentId || "").trim();
|
|
569
|
+
if (!id) return;
|
|
570
|
+
try {
|
|
571
|
+
daemonSend({
|
|
572
|
+
type: IPC_REQUEST_TYPES.BUS_WATCH,
|
|
573
|
+
agent_id: id,
|
|
574
|
+
enabled: enabled !== false,
|
|
575
|
+
});
|
|
576
|
+
} catch {
|
|
577
|
+
// ignore watch errors
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function reconcileInternalWatches() {
|
|
582
|
+
const next = new Set();
|
|
583
|
+
if (multiSession && typeof multiSession.listInternalAgentIds === "function") {
|
|
584
|
+
for (const id of multiSession.listInternalAgentIds()) next.add(id);
|
|
585
|
+
}
|
|
586
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
587
|
+
next.add(stageTarget.agentId);
|
|
588
|
+
}
|
|
589
|
+
for (const id of next) {
|
|
590
|
+
if (!watchedInternalAgents.has(id)) sendInternalAgentWatch(id, true);
|
|
591
|
+
}
|
|
592
|
+
for (const id of watchedInternalAgents) {
|
|
593
|
+
if (!next.has(id)) sendInternalAgentWatch(id, false);
|
|
594
|
+
}
|
|
595
|
+
watchedInternalAgents.clear();
|
|
596
|
+
for (const id of next) watchedInternalAgents.add(id);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const agentSettings = createAgentSettingsController({
|
|
600
|
+
getProjectRoot: () => activeProjectRoot,
|
|
601
|
+
applyPatch: applyAgentSettings,
|
|
602
|
+
publish: (...args) => publish(...args),
|
|
603
|
+
logMessage: (...args) => appendLocal(...args),
|
|
604
|
+
focusMain() {
|
|
605
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
606
|
+
if (multiSession?.isActive()) {
|
|
607
|
+
multiSession.handleFocus({ target: "chat" });
|
|
608
|
+
publish("window.set", multiSession.getSnapshot());
|
|
609
|
+
}
|
|
610
|
+
controller.session.targetAgent = null;
|
|
611
|
+
publish("prompt.set_prefix", { prefix: "› " });
|
|
612
|
+
},
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
async function switchToProjectRoot(targetRoot, switchOpts = {}) {
|
|
616
|
+
const root = canonicalProjectRoot(String(targetRoot || "").trim());
|
|
617
|
+
const archived = desktopArchive.read().projects.some((item) => item.root === root);
|
|
618
|
+
if (archived && !switchOpts.restoreArchived) {
|
|
619
|
+
return { ok: false, error: "This folder is archived. Add it again to restore it." };
|
|
620
|
+
}
|
|
621
|
+
if (!fs.existsSync(getUfooPaths(root).ufooDir)) {
|
|
622
|
+
const repoRoot = path.join(__dirname, "..", "..");
|
|
623
|
+
const init = new env.UfooInit(repoRoot);
|
|
624
|
+
await init.init({ targets: "context,bus", project: root });
|
|
625
|
+
}
|
|
626
|
+
upsertProjectRuntime({
|
|
627
|
+
projectRoot: root,
|
|
628
|
+
projectName: path.basename(root),
|
|
629
|
+
socketPath: initialEndpoint.socketPath,
|
|
630
|
+
status: "running",
|
|
631
|
+
lastSwitchAt: new Date().toISOString(),
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
if (multiSession) multiSession.stop({ clearDrafts: false });
|
|
635
|
+
standaloneSurfaces.clear();
|
|
636
|
+
standaloneReader = null;
|
|
637
|
+
activePendingInteraction = null;
|
|
638
|
+
|
|
639
|
+
const targetEndpoint = resolveDaemonEndpoint(root, { controllerRoot });
|
|
640
|
+
const targetDaemonRoot = targetEndpoint.scope === "global"
|
|
641
|
+
? targetEndpoint.controllerRoot
|
|
642
|
+
: targetEndpoint.projectRoot;
|
|
643
|
+
|
|
644
|
+
if (daemonCoordinator && typeof daemonCoordinator.switchProject === "function") {
|
|
645
|
+
const res = await daemonCoordinator.switchProject({
|
|
646
|
+
projectRoot: root,
|
|
647
|
+
sockPath: targetEndpoint.socketPath,
|
|
648
|
+
daemonRoot: targetDaemonRoot,
|
|
649
|
+
transformRequest: (request) => routeDaemonRequest(targetEndpoint, request),
|
|
650
|
+
autoStart: true,
|
|
651
|
+
});
|
|
652
|
+
if (!res || res.ok !== true) {
|
|
653
|
+
return res || { ok: false, error: "switch failed" };
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
if (archived) desktopArchive.restoreProject(root);
|
|
658
|
+
activeProjectRoot = root;
|
|
659
|
+
globalScope = root === controllerRoot ? "controller" : "project";
|
|
660
|
+
stageTarget = switchOpts.agentId
|
|
661
|
+
? { kind: "worker_single", agentId: String(switchOpts.agentId).trim() }
|
|
662
|
+
: { kind: "project_main", agentId: "" };
|
|
663
|
+
|
|
664
|
+
Object.assign(settings, loadConfig(activeProjectRoot) || {});
|
|
665
|
+
controller.session.targetAgent = null;
|
|
666
|
+
controller.session.agents = [];
|
|
667
|
+
controller.session.metaMap.clear();
|
|
668
|
+
controller.session.labelMap.clear();
|
|
669
|
+
controller.session.footer = "";
|
|
670
|
+
|
|
671
|
+
await refreshRecoverableForActiveProject();
|
|
672
|
+
controller.requestDaemonStatus();
|
|
673
|
+
publish("app.snapshot", buildSnapshot());
|
|
674
|
+
publishProjectsTree();
|
|
675
|
+
publishRightInspectorAll();
|
|
676
|
+
|
|
677
|
+
if (switchOpts.windowMode && ["main", "side", "multi"].includes(switchOpts.windowMode) && stageTarget.kind === "project_main") {
|
|
678
|
+
changeWindowLayout(switchOpts.windowMode);
|
|
679
|
+
} else if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
680
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
681
|
+
}
|
|
682
|
+
return { ok: true, project_root: root };
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
async function switchToControllerRoot() {
|
|
686
|
+
if (multiSession) multiSession.stop({ clearDrafts: false });
|
|
687
|
+
activePendingInteraction = null;
|
|
688
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
689
|
+
|
|
690
|
+
const controllerEndpoint = resolveDaemonEndpoint(controllerRoot, { controllerRoot });
|
|
691
|
+
if (daemonCoordinator && typeof daemonCoordinator.switchProject === "function") {
|
|
692
|
+
const res = await daemonCoordinator.switchProject({
|
|
693
|
+
projectRoot: controllerRoot,
|
|
694
|
+
sockPath: controllerEndpoint.socketPath,
|
|
695
|
+
daemonRoot: controllerEndpoint.scope === "global"
|
|
696
|
+
? controllerEndpoint.controllerRoot
|
|
697
|
+
: controllerEndpoint.projectRoot,
|
|
698
|
+
transformRequest: (request) => routeDaemonRequest(controllerEndpoint, request),
|
|
699
|
+
});
|
|
700
|
+
if (!res || res.ok !== true) return res || { ok: false, error: "switch to controller failed" };
|
|
701
|
+
}
|
|
702
|
+
activeProjectRoot = controllerRoot;
|
|
703
|
+
globalScope = "controller";
|
|
704
|
+
controller.session.targetAgent = null;
|
|
705
|
+
controller.session.agents = [];
|
|
706
|
+
controller.session.metaMap.clear();
|
|
707
|
+
controller.session.labelMap.clear();
|
|
708
|
+
publish("app.snapshot", buildSnapshot());
|
|
709
|
+
publishProjectsTree();
|
|
710
|
+
return { ok: true, project_root: controllerRoot };
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function changeWindowLayout(mode, explicitAgentId = "") {
|
|
714
|
+
if (!multiSession) return { ok: false, error: "Window session not initialised" };
|
|
715
|
+
if (!["main", "side", "multi", "cycle"].includes(mode)) {
|
|
716
|
+
return { ok: false, error: "Invalid window mode" };
|
|
717
|
+
}
|
|
718
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
719
|
+
const result = multiSession.setLayout(mode, explicitAgentId);
|
|
720
|
+
reconcileInternalWatches();
|
|
721
|
+
publishProjectsTree();
|
|
722
|
+
return result;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
const controller = createChatController({
|
|
726
|
+
projectRoot: controllerRoot,
|
|
727
|
+
globalMode: true,
|
|
728
|
+
ports: {
|
|
729
|
+
publish,
|
|
730
|
+
logMessage: (kind, text) => {
|
|
731
|
+
const normalized = kind === "error" ? "error"
|
|
732
|
+
: kind === "user" ? "user"
|
|
733
|
+
: kind === "assistant" ? "assistant"
|
|
734
|
+
: "system";
|
|
735
|
+
appendLocal(normalized, stripTags(text));
|
|
736
|
+
},
|
|
737
|
+
setStatus: (text) => publish("status.set", { text: stripTags(text || "ready") }),
|
|
738
|
+
appendHistory: (type, text, meta = {}) => {
|
|
739
|
+
const { appendChatHistory } = require("../app/chat/historyStore");
|
|
740
|
+
appendChatHistory(activeProjectRoot, type, stripTags(text), meta, historyOptions());
|
|
741
|
+
},
|
|
742
|
+
getHistoryOptions: () => historyOptions(),
|
|
743
|
+
clearLog: () => {
|
|
744
|
+
try {
|
|
745
|
+
const { chatHistoryFilePath } = require("../app/chat/historyStore");
|
|
746
|
+
const file = chatHistoryFilePath(activeProjectRoot, historyOptions());
|
|
747
|
+
if (file && fs.existsSync(file)) fs.writeFileSync(file, "");
|
|
748
|
+
} catch {
|
|
749
|
+
// ignore
|
|
750
|
+
}
|
|
751
|
+
publish("transcript.reset", {});
|
|
752
|
+
},
|
|
753
|
+
restartDaemon: async () => {
|
|
754
|
+
if (daemonCoordinator?.restart) await daemonCoordinator.restart();
|
|
755
|
+
},
|
|
756
|
+
isDaemonRunning: (root) => isRunning(root || activeProjectRoot),
|
|
757
|
+
activateInternalAgent: (agentId) => {
|
|
758
|
+
const id = String(agentId || "").trim();
|
|
759
|
+
if (!isInternalAgentMeta(controller.session.metaMap.get(id))) {
|
|
760
|
+
return { ok: false, error: "Internal agents only" };
|
|
761
|
+
}
|
|
762
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
763
|
+
return multiSession.start({
|
|
764
|
+
kind: "side",
|
|
765
|
+
agentIds: [id],
|
|
766
|
+
focus: { target: "agent", agent_id: id },
|
|
767
|
+
});
|
|
768
|
+
},
|
|
769
|
+
focusMultiPane: async (agentId) => {
|
|
770
|
+
if (multiSession?.isMultiKind?.()) {
|
|
771
|
+
multiSession.syncAgents();
|
|
772
|
+
return Boolean(multiSession.focusAgent(agentId)?.ok);
|
|
773
|
+
}
|
|
774
|
+
const res = multiSession.start({ kind: "side", agentIds: [agentId], focus: { target: "agent", agent_id: agentId } });
|
|
775
|
+
return Boolean(res && res.ok);
|
|
776
|
+
},
|
|
777
|
+
listProjects: () => listUnarchivedProjects().map((r) => ({
|
|
778
|
+
project_root: r.root,
|
|
779
|
+
project_name: r.label,
|
|
780
|
+
status: r.status,
|
|
781
|
+
label: r.label,
|
|
782
|
+
root: r.root,
|
|
783
|
+
})),
|
|
784
|
+
getCurrentProject: () => ({ project_root: activeProjectRoot }),
|
|
785
|
+
getActiveProjectRoot: () => activeProjectRoot,
|
|
786
|
+
switchProject: (target) => switchToProjectRoot(
|
|
787
|
+
typeof target === "object" ? (target.projectRoot || target.project_root || target.root) : target
|
|
788
|
+
),
|
|
789
|
+
setWindowLayout: (args) => changeWindowLayout(parseWindowModeArgs(args)).ok,
|
|
790
|
+
openAgentSettings: (section) => agentSettings.open(section),
|
|
791
|
+
applyAgentModel: (...args) => agentSettings.applyModel(...args),
|
|
792
|
+
applyAgentSettings,
|
|
793
|
+
applyChatSettings: (patch = {}) => {
|
|
794
|
+
if (patch.agentProvider != null) settings.agentProvider = patch.agentProvider;
|
|
795
|
+
publish("settings.snapshot", buildSettingsSnapshot(settings));
|
|
796
|
+
},
|
|
797
|
+
dispatch: (action) => {
|
|
798
|
+
if (!action || typeof action !== "object") return;
|
|
799
|
+
if (action.publisher && isInternalChild(action.publisher)) return;
|
|
800
|
+
if (action.type === "stream/begin") {
|
|
801
|
+
tools.beginScope();
|
|
802
|
+
const speaker = String(action.publisher || "");
|
|
803
|
+
const id = `stream-${speaker || "agent"}-${Date.now()}`;
|
|
804
|
+
streamIds.set(speaker, id);
|
|
805
|
+
streamLabels.set(speaker, action.displayName || speaker);
|
|
806
|
+
publish("stream.start", { id, speaker: action.displayName || speaker });
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
if (action.type === "stream/delta") {
|
|
810
|
+
const key = String(action.publisher || "");
|
|
811
|
+
let id = streamIds.get(key);
|
|
812
|
+
if (!id) {
|
|
813
|
+
id = `stream-${key || "agent"}-${Date.now()}`;
|
|
814
|
+
streamIds.set(key, id);
|
|
815
|
+
publish("stream.start", { id, speaker: key });
|
|
816
|
+
}
|
|
817
|
+
publish("stream.delta", { id, text: String(action.delta || ""), speaker: streamLabels.get(key) || key });
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
if (action.type === "stream/end") {
|
|
821
|
+
tools.flush();
|
|
822
|
+
for (const [key, id] of [...streamIds.entries()]) {
|
|
823
|
+
if (action.publisher && key !== action.publisher) continue;
|
|
824
|
+
publish("stream.done", { id });
|
|
825
|
+
streamIds.delete(key);
|
|
826
|
+
streamLabels.delete(key);
|
|
827
|
+
}
|
|
828
|
+
publish("status.set", { text: "ready", busy: false });
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
if (action.type === "log/clear") {
|
|
832
|
+
publish("transcript.reset", {});
|
|
833
|
+
}
|
|
834
|
+
},
|
|
835
|
+
},
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
multiSession = createRustMultiSession({
|
|
839
|
+
getProjectRoot: () => activeProjectRoot,
|
|
840
|
+
projectRoot: controllerRoot,
|
|
841
|
+
getActiveAgents: () => [...controller.session.metaMap.keys()],
|
|
842
|
+
getAgentMeta: (id) => controller.session.metaMap.get(id) || {},
|
|
843
|
+
resolvePaneOptions: (agentId) => ({
|
|
844
|
+
mode: "internal",
|
|
845
|
+
initialEntries: loadInternalAgentTranscript(activeProjectRoot, agentId, {
|
|
846
|
+
maxEvents: 250,
|
|
847
|
+
maxEntries: 250,
|
|
848
|
+
}),
|
|
849
|
+
}),
|
|
850
|
+
onInternalSubmit: (agentId, message) => {
|
|
851
|
+
const requestId = `pane-send-${crypto.randomUUID()}`;
|
|
852
|
+
internalSubmissions.set(requestId, { agentId, message, projectRoot: activeProjectRoot });
|
|
853
|
+
return daemonSend({
|
|
854
|
+
type: IPC_REQUEST_TYPES.BUS_SEND,
|
|
855
|
+
request_id: requestId,
|
|
856
|
+
target: agentId,
|
|
857
|
+
message: String(message || ""),
|
|
858
|
+
injection_mode: "immediate",
|
|
859
|
+
source: "ufoo-desktop",
|
|
860
|
+
});
|
|
861
|
+
},
|
|
862
|
+
publish,
|
|
863
|
+
publishLossy,
|
|
864
|
+
getLabel: getAgentLabel,
|
|
865
|
+
});
|
|
866
|
+
|
|
867
|
+
function publishRightInspectorAll() {
|
|
868
|
+
if (globalScope === "controller") return;
|
|
869
|
+
try {
|
|
870
|
+
publish("workspace.changes.snapshot", loadWorkspaceChanges(activeProjectRoot));
|
|
871
|
+
publish("workspace.docs.snapshot", loadWorkspaceDocs(activeProjectRoot));
|
|
872
|
+
publish("workspace.context.snapshot", handleWorkspaceContext(activeProjectRoot));
|
|
873
|
+
} catch {
|
|
874
|
+
// ignore initial inspector read errors
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function buildSnapshot() {
|
|
879
|
+
const { loadChatHistory, loadInputHistory } = require("../app/chat/historyStore");
|
|
880
|
+
const history = loadChatHistory(activeProjectRoot, 250, historyOptions());
|
|
881
|
+
const inputHistory = loadInputHistory(activeProjectRoot, 200, historyOptions());
|
|
882
|
+
const agents = controller.getAgentsSnapshot();
|
|
883
|
+
const settingsSnap = buildSettingsSnapshot(loadConfig(activeProjectRoot) || settings);
|
|
884
|
+
const tree = buildProjectsTreePayload();
|
|
885
|
+
return {
|
|
886
|
+
status: "ready",
|
|
887
|
+
package_version: PACKAGE_VERSION,
|
|
888
|
+
footer: agents.footer || "",
|
|
889
|
+
entries: rawHistoryToEntries(history),
|
|
890
|
+
input_history: Array.isArray(inputHistory) ? inputHistory.filter(Boolean) : [],
|
|
891
|
+
agents: agents.agents,
|
|
892
|
+
settings: settingsSnap,
|
|
893
|
+
agent_provider: settingsSnap.agent_provider,
|
|
894
|
+
provider_options: settingsSnap.provider_options,
|
|
895
|
+
global_mode: true,
|
|
896
|
+
controller_root: controllerRoot,
|
|
897
|
+
active_root: activeProjectRoot,
|
|
898
|
+
scope: globalScope,
|
|
899
|
+
stage_target: { ...stageTarget },
|
|
900
|
+
pending_interaction: activePendingInteraction,
|
|
901
|
+
projects: tree.projects,
|
|
902
|
+
cron: agents.cron && agents.cron.tasks ? agents.cron.tasks : [],
|
|
903
|
+
loop: agents.loop || null,
|
|
904
|
+
loop_summary: formatLoopSummary(agents.loop || null),
|
|
905
|
+
window: multiSession ? multiSession.getSnapshot() : { active: false, mode: "main" },
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function applyIncomingHandoff(handoff = {}) {
|
|
910
|
+
if (!handoff) return { ok: false, error: "empty handoff" };
|
|
911
|
+
const targetProject = handoff.projectRoot || activeProjectRoot;
|
|
912
|
+
const isWorker = handoff.target && handoff.target !== "main";
|
|
913
|
+
if (targetProject && targetProject !== controllerRoot) {
|
|
914
|
+
const result = await switchToProjectRoot(targetProject, {
|
|
915
|
+
agentId: isWorker ? handoff.target : "",
|
|
916
|
+
windowMode: !isWorker ? handoff.windowMode : "",
|
|
917
|
+
});
|
|
918
|
+
if (!result.ok) return result;
|
|
919
|
+
}
|
|
920
|
+
if (handoff.docPath && globalScope === "project") {
|
|
921
|
+
publish("workspace.docs.snapshot", loadWorkspaceDocs(activeProjectRoot, { filePath: handoff.docPath }));
|
|
922
|
+
}
|
|
923
|
+
const state = {
|
|
924
|
+
project_root: activeProjectRoot,
|
|
925
|
+
stage_target: { ...stageTarget },
|
|
926
|
+
window_mode: multiSession ? multiSession.getSnapshot().mode : "main",
|
|
927
|
+
doc_path: handoff.docPath || "",
|
|
928
|
+
ts: Date.now(),
|
|
929
|
+
};
|
|
930
|
+
publish("handoff.state", state);
|
|
931
|
+
return { ok: true, ...state };
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
const host = createUiHostServer({
|
|
935
|
+
socketPath: uiSocketPath,
|
|
936
|
+
authToken: uiAuthToken,
|
|
937
|
+
capabilities: [
|
|
938
|
+
"chat",
|
|
939
|
+
"scrollback",
|
|
940
|
+
"prompt",
|
|
941
|
+
MULTI_FRAMES_CAPABILITY,
|
|
942
|
+
WINDOW_MODES_CAPABILITY,
|
|
943
|
+
RAW_MARKDOWN_CAPABILITY,
|
|
944
|
+
DESKTOP_HOST_CAPABILITY,
|
|
945
|
+
],
|
|
946
|
+
onClientReady(socket) {
|
|
947
|
+
const snap = createEnvelope({
|
|
948
|
+
kind: "snapshot",
|
|
949
|
+
name: "app.snapshot",
|
|
950
|
+
seq: host.nextSeq(),
|
|
951
|
+
scope: { surface: "desktop", project_id: activeProjectRoot },
|
|
952
|
+
payload: buildSnapshot(),
|
|
953
|
+
});
|
|
954
|
+
socket.write(encodeMessage(snap));
|
|
955
|
+
multiSession?.publishFrames();
|
|
956
|
+
publishProjectsTree();
|
|
957
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
958
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
959
|
+
}
|
|
960
|
+
publishRightInspectorAll();
|
|
961
|
+
},
|
|
962
|
+
async onCommand(cmd) {
|
|
963
|
+
const name = String(cmd.name || "");
|
|
964
|
+
const payload = cmd.payload && typeof cmd.payload === "object" ? cmd.payload : {};
|
|
965
|
+
|
|
966
|
+
if (name === "app.exit") return { ok: true };
|
|
967
|
+
|
|
968
|
+
if (name === "ui.resync.request") {
|
|
969
|
+
publish("app.snapshot", buildSnapshot());
|
|
970
|
+
multiSession?.publishFrames();
|
|
971
|
+
publishProjectsTree();
|
|
972
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
973
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
974
|
+
}
|
|
975
|
+
return { ok: true };
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
if (name === "project.add") {
|
|
979
|
+
const root = String(payload.root || payload.projectRoot || "").trim();
|
|
980
|
+
if (!root) return { ok: false, error: "Project directory path is required" };
|
|
981
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
|
|
982
|
+
return { ok: false, error: `Directory does not exist: ${root}` };
|
|
983
|
+
}
|
|
984
|
+
return switchToProjectRoot(root, { restoreArchived: true });
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
if (name === "project.archive" || name === "session.archive") {
|
|
988
|
+
const target = String(payload.root || "").trim();
|
|
989
|
+
const id = String(payload.session_id || "").trim();
|
|
990
|
+
if (!target) return { ok: false, error: "Missing project root" };
|
|
991
|
+
let root;
|
|
992
|
+
let missing = false;
|
|
993
|
+
try {
|
|
994
|
+
root = canonicalProjectRoot(target);
|
|
995
|
+
} catch (error) {
|
|
996
|
+
if (name !== "project.archive" || !["ENOENT", "ENOTDIR"].includes(error.code)) throw error;
|
|
997
|
+
root = path.resolve(target);
|
|
998
|
+
missing = true;
|
|
999
|
+
}
|
|
1000
|
+
if (root === controllerRoot) return { ok: false, error: "The Global Router cannot be archived" };
|
|
1001
|
+
if (name === "project.archive") {
|
|
1002
|
+
if (missing) desktopArchive.archiveProject(root);
|
|
1003
|
+
if (activeProjectRoot === root) {
|
|
1004
|
+
const result = await switchToControllerRoot();
|
|
1005
|
+
if (!result.ok && !missing) return result;
|
|
1006
|
+
}
|
|
1007
|
+
if (!missing) desktopArchive.archiveProject(root);
|
|
1008
|
+
} else {
|
|
1009
|
+
if (!id) return { ok: false, error: "Missing session ID" };
|
|
1010
|
+
desktopArchive.archiveSession(root, id);
|
|
1011
|
+
if (activeProjectRoot === root && stageTarget.kind === "worker_single" && stageTarget.agentId === id) {
|
|
1012
|
+
changeWindowLayout("main");
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
publishProjectsTree();
|
|
1016
|
+
return missing ? { ok: true, silent: true } : { ok: true };
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
if (name === "project.switch") {
|
|
1020
|
+
const root = String(payload.root || payload.projectRoot || "").trim();
|
|
1021
|
+
if (!root) return { ok: false, error: "Missing project root" };
|
|
1022
|
+
return switchToProjectRoot(root, {
|
|
1023
|
+
agentId: payload.agent_id || payload.agentId || "",
|
|
1024
|
+
windowMode: payload.window_mode || payload.windowMode || "",
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
if (name === "project.return_controller") {
|
|
1029
|
+
return switchToControllerRoot();
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
if (name === "worker.focus_view") {
|
|
1033
|
+
const targetRoot = String(payload.root || payload.projectRoot || activeProjectRoot).trim();
|
|
1034
|
+
const agentId = String(payload.agent_id || payload.agentId || "").trim();
|
|
1035
|
+
if (targetRoot && canonicalProjectRoot(targetRoot) !== activeProjectRoot) {
|
|
1036
|
+
return switchToProjectRoot(targetRoot, { agentId });
|
|
1037
|
+
}
|
|
1038
|
+
if (!agentId || agentId === "main") {
|
|
1039
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
1040
|
+
reconcileInternalWatches();
|
|
1041
|
+
publishProjectsTree();
|
|
1042
|
+
publish("window.set", multiSession.getSnapshot());
|
|
1043
|
+
multiSession.publishFrames();
|
|
1044
|
+
return { ok: true, stage_target: stageTarget };
|
|
1045
|
+
}
|
|
1046
|
+
stageTarget = { kind: "worker_single", agentId };
|
|
1047
|
+
reconcileInternalWatches();
|
|
1048
|
+
publishProjectsTree();
|
|
1049
|
+
const frame = publishStandaloneWorkerFrame(agentId);
|
|
1050
|
+
return { ok: true, stage_target: stageTarget, frame };
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
if (name === "side.select") {
|
|
1054
|
+
const agentId = String(payload.agent_id || payload.agentId || "").trim();
|
|
1055
|
+
if (!agentId) return { ok: false, error: "agent_id required" };
|
|
1056
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
1057
|
+
const res = multiSession.start({
|
|
1058
|
+
kind: "side",
|
|
1059
|
+
agentIds: [agentId],
|
|
1060
|
+
focus: { target: "agent", agent_id: agentId },
|
|
1061
|
+
});
|
|
1062
|
+
reconcileInternalWatches();
|
|
1063
|
+
publishProjectsTree();
|
|
1064
|
+
return res;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
if (name === "window.set" || name === "window.cycle") {
|
|
1068
|
+
return changeWindowLayout(
|
|
1069
|
+
name === "window.cycle" ? "cycle" : payload.mode,
|
|
1070
|
+
String(payload.agent_id || payload.agentId || "")
|
|
1071
|
+
);
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
if (name === "multi.focus") return multiSession.handleFocus(payload);
|
|
1075
|
+
if (name === "multi.viewport") return multiSession.handleViewport(payload);
|
|
1076
|
+
if (name === "multi.scroll") return multiSession.handleScroll(payload);
|
|
1077
|
+
if (name === "multi.expand") return multiSession.handleExpand(payload);
|
|
1078
|
+
|
|
1079
|
+
if (name === "multi.raw") {
|
|
1080
|
+
if (stageTarget.kind === "worker_single" && payload.agent_id === stageTarget.agentId) {
|
|
1081
|
+
const id = stageTarget.agentId;
|
|
1082
|
+
const text = String(payload.input ?? "");
|
|
1083
|
+
const rev = Number(payload.input_revision) || 0;
|
|
1084
|
+
standaloneDrafts.set(id, { text: payload.submit ? "" : text, revision: rev });
|
|
1085
|
+
if (payload.submit && text.trim()) {
|
|
1086
|
+
const holder = isInternalAgentMeta(controller.session.metaMap.get(id))
|
|
1087
|
+
? ensureStandaloneSurface(id)
|
|
1088
|
+
: null;
|
|
1089
|
+
holder?.surface.accept({ type: "task_submitted", message: text });
|
|
1090
|
+
daemonSend({
|
|
1091
|
+
type: IPC_REQUEST_TYPES.BUS_SEND,
|
|
1092
|
+
request_id: `worker-send-${crypto.randomUUID()}`,
|
|
1093
|
+
target: id,
|
|
1094
|
+
message: text,
|
|
1095
|
+
injection_mode: "immediate",
|
|
1096
|
+
source: "ufoo-desktop-worker",
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
publishStandaloneWorkerFrame(id);
|
|
1100
|
+
return { ok: true, input_revision: rev };
|
|
1101
|
+
}
|
|
1102
|
+
return multiSession.handleRaw(payload);
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
if (name === "multi.cancel" || (name === "task.cancel" && payload.agent_id)) {
|
|
1106
|
+
const agentId = String(payload.agent_id || payload.agentId || "").trim();
|
|
1107
|
+
if (agentId && isInternalAgentMeta(controller.session.metaMap.get(agentId))) {
|
|
1108
|
+
const { cancelInternalTask } = require("../agents/internal/taskControl");
|
|
1109
|
+
await Promise.resolve(cancelInternalTask(activeProjectRoot, agentId)).catch(() => {});
|
|
1110
|
+
return { ok: true, cancelled_agent: agentId };
|
|
1111
|
+
}
|
|
1112
|
+
return multiSession.handleCancel(payload);
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
if (name === "task.cancel") {
|
|
1116
|
+
if (payload.task_run_id) {
|
|
1117
|
+
daemonSend({
|
|
1118
|
+
type: IPC_REQUEST_TYPES.AGENT_RUNTIME,
|
|
1119
|
+
operation: "cancel",
|
|
1120
|
+
task_run_id: String(payload.task_run_id),
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
publish("status.set", { text: "cancel requested", busy: false });
|
|
1124
|
+
publish("stream.done", { id: "cancel" });
|
|
1125
|
+
return { ok: true };
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
if (name === "worker.launch") {
|
|
1129
|
+
const groupAlias = String(payload.group || payload.template || "").trim();
|
|
1130
|
+
if (groupAlias) {
|
|
1131
|
+
daemonSend({
|
|
1132
|
+
type: IPC_REQUEST_TYPES.LAUNCH_GROUP,
|
|
1133
|
+
template: groupAlias,
|
|
1134
|
+
objective: String(payload.objective || ""),
|
|
1135
|
+
internal_only: true,
|
|
1136
|
+
});
|
|
1137
|
+
return { ok: true, launched: "group", template: groupAlias };
|
|
1138
|
+
}
|
|
1139
|
+
const agentType = String(payload.agent || payload.type || "ucode").trim();
|
|
1140
|
+
const request = {
|
|
1141
|
+
type: IPC_REQUEST_TYPES.LAUNCH_AGENT,
|
|
1142
|
+
agent: agentType,
|
|
1143
|
+
count: Math.max(1, Number(payload.count) || 1),
|
|
1144
|
+
nickname: String(payload.nickname || "").trim() || undefined,
|
|
1145
|
+
internal_only: true,
|
|
1146
|
+
};
|
|
1147
|
+
if (payload.root) {
|
|
1148
|
+
const root = canonicalProjectRoot(payload.root);
|
|
1149
|
+
if (root === controllerRoot) return { ok: false, error: "Choose a project to launch a worker" };
|
|
1150
|
+
if (root !== activeProjectRoot) {
|
|
1151
|
+
const result = await switchToProjectRoot(root);
|
|
1152
|
+
if (!result.ok) return result;
|
|
1153
|
+
}
|
|
1154
|
+
const response = await requestDaemon(root, request, { controllerRoot, fullResponse: true, timeoutMs: 30000 });
|
|
1155
|
+
const launch = response.opsResults?.find(({ action }) => action === "launch");
|
|
1156
|
+
if (launch?.ok === false) return { ok: false, error: launch.error || "Worker launch failed" };
|
|
1157
|
+
} else {
|
|
1158
|
+
daemonSend(request);
|
|
1159
|
+
}
|
|
1160
|
+
return { ok: true, launched: "worker", agent: agentType };
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
if (name === "worker.resume") {
|
|
1164
|
+
const targetId = String(payload.id || payload.target || "").trim();
|
|
1165
|
+
if (!targetId) return { ok: false, error: "Recoverable worker or group ID required" };
|
|
1166
|
+
await controller.submitInput(`/resume ${targetId}`);
|
|
1167
|
+
await refreshRecoverableForActiveProject();
|
|
1168
|
+
publishProjectsTree();
|
|
1169
|
+
return { ok: true, resumed: targetId };
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
if (name === "worker.focus_external") {
|
|
1173
|
+
const agentId = String(payload.agent_id || payload.agentId || stageTarget.agentId || "").trim();
|
|
1174
|
+
const meta = getHandoffAgentMeta(agentId);
|
|
1175
|
+
if (!meta || isInternalAgentMeta(meta)) return { ok: false, error: "External worker not found" };
|
|
1176
|
+
return focusExternalAgentHost(activeProjectRoot, meta);
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
if (name === "agent.close") {
|
|
1180
|
+
const agentId = String(payload.agent_id || payload.agentId || "").trim();
|
|
1181
|
+
if (!isInternalAgentMeta(controller.session.metaMap.get(agentId))) {
|
|
1182
|
+
return { ok: false, error: "External agents own their lifecycle" };
|
|
1183
|
+
}
|
|
1184
|
+
daemonSend({ type: IPC_REQUEST_TYPES.CLOSE_AGENT, agent_id: agentId });
|
|
1185
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId === agentId) {
|
|
1186
|
+
stageTarget = { kind: "project_main", agentId: "" };
|
|
1187
|
+
}
|
|
1188
|
+
return { ok: true };
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
if (name === "agent.select") {
|
|
1192
|
+
const agentId = String(payload.agent_id || payload.agentId || "").trim();
|
|
1193
|
+
controller.session.targetAgent = agentId || null;
|
|
1194
|
+
publish("prompt.set_prefix", {
|
|
1195
|
+
prefix: agentId ? `›@${getAgentLabel(agentId)} ` : "› ",
|
|
1196
|
+
});
|
|
1197
|
+
return { ok: true, agent_id: agentId };
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
if (name === "completion.request") {
|
|
1201
|
+
const fmt = require("./format");
|
|
1202
|
+
const { getChatCommandCatalog } = require("../app/chat/commands");
|
|
1203
|
+
const agents = controller.session.agents.slice();
|
|
1204
|
+
const agentLabels = agents.map(getAgentLabel);
|
|
1205
|
+
const dynamic = loadDynamicCompletionSources(activeProjectRoot);
|
|
1206
|
+
const completionRoot = activeProjectRoot;
|
|
1207
|
+
const resumeQuery = /^\/resume(?:\s|$)/.test(String(payload.text || "").trimStart());
|
|
1208
|
+
const resumeTargets = resumeQuery ? await refreshRecoverableForActiveProject() : [];
|
|
1209
|
+
const settingsLists = await agentSettings.completions(String(payload.text || ""));
|
|
1210
|
+
if (completionRoot !== activeProjectRoot) return { ok: true, stale: true };
|
|
1211
|
+
const items = fmt.buildCompletions({
|
|
1212
|
+
text: String(payload.text || ""),
|
|
1213
|
+
agents,
|
|
1214
|
+
agentLabels,
|
|
1215
|
+
...getChatCommandCatalog({ globalMode: true }),
|
|
1216
|
+
groupTemplates: dynamic.groupTemplates,
|
|
1217
|
+
soloProfiles: dynamic.soloProfiles,
|
|
1218
|
+
argumentLists: { ...settingsLists, ...(resumeQuery ? { "/resume": resumeTargets } : {}) },
|
|
1219
|
+
limit: Math.max(25, ...Object.values(settingsLists).map((list) => list.length)),
|
|
1220
|
+
});
|
|
1221
|
+
publish("completions.set", { items, text: String(payload.text || "") });
|
|
1222
|
+
return { ok: true, count: items.length, items };
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
if (name === "settings.open") return agentSettings.open(payload.section || "model");
|
|
1226
|
+
if (name === "settings.set") return applyAgentSettings(payload);
|
|
1227
|
+
if (name === "settings.models") {
|
|
1228
|
+
const root = activeProjectRoot;
|
|
1229
|
+
const current = loadConfig(root);
|
|
1230
|
+
const agentProvider = normalizeAgentProvider(payload.agent_provider ?? current.agentProvider);
|
|
1231
|
+
const defaultModel = defaultAgentModelForProvider(agentProvider);
|
|
1232
|
+
if (agentProvider === "custom" && current.agentProvider !== "custom") {
|
|
1233
|
+
return { ok: false, models: [], default_model: defaultModel };
|
|
1234
|
+
}
|
|
1235
|
+
const agentModel = agentProvider === current.agentProvider ? current.agentModel : defaultModel;
|
|
1236
|
+
const catalog = await listAgentModels(root, { config: { ...current, agentProvider, agentModel } })
|
|
1237
|
+
.catch(() => ({ ok: false, models: [] }));
|
|
1238
|
+
return { ok: catalog.ok, models: catalog.models, default_model: defaultModel };
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
if (name === "interaction.respond") {
|
|
1242
|
+
const settingsReply = await agentSettings.respond(payload);
|
|
1243
|
+
if (settingsReply) return settingsReply;
|
|
1244
|
+
const interactionId = String(payload.id || activePendingInteraction?.id || "").trim();
|
|
1245
|
+
const answerText = String(payload.text ?? payload.answer ?? "").trim();
|
|
1246
|
+
if (interactionId && !payload.cancelled) {
|
|
1247
|
+
daemonSend({
|
|
1248
|
+
type: IPC_REQUEST_TYPES.AGENT_RUNTIME,
|
|
1249
|
+
operation: "resume",
|
|
1250
|
+
interaction_id: interactionId,
|
|
1251
|
+
answer: answerText,
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
activePendingInteraction = null;
|
|
1255
|
+
publish("interaction.clear", { id: interactionId });
|
|
1256
|
+
publishProjectsTree();
|
|
1257
|
+
return { ok: true };
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
if (name === "workspace.changes") {
|
|
1261
|
+
const root = String(payload.projectRoot || activeProjectRoot);
|
|
1262
|
+
const snap = loadWorkspaceChanges(root, payload);
|
|
1263
|
+
publish("workspace.changes.snapshot", snap);
|
|
1264
|
+
return { ok: true, data: snap };
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
if (name === "workspace.docs") {
|
|
1268
|
+
const root = String(payload.projectRoot || activeProjectRoot);
|
|
1269
|
+
const snap = loadWorkspaceDocs(root, payload);
|
|
1270
|
+
publish("workspace.docs.snapshot", snap);
|
|
1271
|
+
return { ok: true, data: snap };
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
if (name === "workspace.context") {
|
|
1275
|
+
const root = String(payload.projectRoot || activeProjectRoot);
|
|
1276
|
+
const snap = handleWorkspaceContext(root, payload);
|
|
1277
|
+
publish("workspace.context.snapshot", snap);
|
|
1278
|
+
return { ok: true, data: snap };
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
if (name === "handoff.to_cli") {
|
|
1282
|
+
const agentId = stageTarget.kind === "worker_single" ? stageTarget.agentId : (payload.agent_id || "");
|
|
1283
|
+
if (agentId) {
|
|
1284
|
+
const meta = getHandoffAgentMeta(agentId);
|
|
1285
|
+
if (!meta) return { ok: false, error: "Worker not found" };
|
|
1286
|
+
if (!isInternalAgentMeta(meta)) return focusExternalAgentHost(activeProjectRoot, meta);
|
|
1287
|
+
}
|
|
1288
|
+
const winMode = multiSession ? multiSession.getSnapshot().mode : "main";
|
|
1289
|
+
return launchCliHandoff({
|
|
1290
|
+
projectRoot: activeProjectRoot,
|
|
1291
|
+
windowMode: payload.window_mode || winMode,
|
|
1292
|
+
agentId,
|
|
1293
|
+
preferredTerminal: payload.terminal || "",
|
|
1294
|
+
dryRun: Boolean(payload.dryRun),
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
if (name === "handoff.open_url") {
|
|
1299
|
+
const parsed = payload.url ? parseHandoffUrl(payload.url) : payload;
|
|
1300
|
+
return applyIncomingHandoff(parsed);
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
if (name === "cli.install_shims") {
|
|
1304
|
+
return installCliShims({
|
|
1305
|
+
coreRoot: payload.coreRoot || path.resolve(__dirname, "..", ".."),
|
|
1306
|
+
nodeExecutable: payload.nodeExecutable || process.execPath,
|
|
1307
|
+
tuiBinary: payload.tuiBinary || process.env.UFOO_TUI_BIN || "",
|
|
1308
|
+
targetDir: payload.targetDir || undefined,
|
|
1309
|
+
updateZshrc: Boolean(payload.updateZshrc),
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
if (name === "cron.stop") {
|
|
1314
|
+
const id = String(payload.id || "").trim();
|
|
1315
|
+
if (!id) return { ok: false, error: "missing cron id" };
|
|
1316
|
+
daemonSend({ type: IPC_REQUEST_TYPES.CRON, operation: "stop", id });
|
|
1317
|
+
controller.requestDaemonStatus();
|
|
1318
|
+
return { ok: true };
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
if (name === "input.submit") {
|
|
1322
|
+
const text = String(payload.text || "");
|
|
1323
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId && !text.trimStart().startsWith("/")) {
|
|
1324
|
+
const workerId = stageTarget.agentId;
|
|
1325
|
+
if (!text.trim()) return { ok: true, routed: "empty" };
|
|
1326
|
+
standaloneDrafts.set(workerId, { text: "", revision: (standaloneDrafts.get(workerId)?.revision || 0) + 1 });
|
|
1327
|
+
if (isInternalAgentMeta(controller.session.metaMap.get(workerId))) {
|
|
1328
|
+
ensureStandaloneSurface(workerId).surface.accept({ type: "task_submitted", message: text });
|
|
1329
|
+
}
|
|
1330
|
+
daemonSend({
|
|
1331
|
+
type: IPC_REQUEST_TYPES.BUS_SEND,
|
|
1332
|
+
request_id: `worker-submit-${crypto.randomUUID()}`,
|
|
1333
|
+
target: workerId,
|
|
1334
|
+
message: text,
|
|
1335
|
+
injection_mode: "immediate",
|
|
1336
|
+
source: "ufoo-desktop-worker",
|
|
1337
|
+
});
|
|
1338
|
+
publishStandaloneWorkerFrame(workerId);
|
|
1339
|
+
return { ok: true, routed: "worker", agent_id: workerId };
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
const routing = resolveSubmittedInputTarget(
|
|
1343
|
+
payload,
|
|
1344
|
+
controller.session.targetAgent,
|
|
1345
|
+
(id) => controller.session.agents.includes(String(id || "").trim())
|
|
1346
|
+
);
|
|
1347
|
+
if (!routing.ok) return routing;
|
|
1348
|
+
controller.session.targetAgent = routing.target;
|
|
1349
|
+
const beforeSubmit = mainSubmissionRev;
|
|
1350
|
+
await controller.submitInput(text);
|
|
1351
|
+
if (!routing.target && beforeSubmit === mainSubmissionRev) {
|
|
1352
|
+
publish("status.set", { text: "ready", busy: false });
|
|
1353
|
+
}
|
|
1354
|
+
return { ok: true, routed: text.trim() ? "submit" : "empty" };
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
return { ok: false, error: `Unsupported command: ${name}` };
|
|
1358
|
+
},
|
|
1359
|
+
});
|
|
1360
|
+
|
|
1361
|
+
hostRef = host;
|
|
1362
|
+
await host.listen();
|
|
1363
|
+
|
|
1364
|
+
const router = createDaemonMessageRouter({
|
|
1365
|
+
escapeBlessed: (v) => String(v || ""),
|
|
1366
|
+
resolveAgentDisplayName: getAgentLabel,
|
|
1367
|
+
stripBlessedTags: stripTags,
|
|
1368
|
+
isOwnRequestId: (id) => ownRequestIds.has(id),
|
|
1369
|
+
onInteractionRequest: (interaction) => {
|
|
1370
|
+
activePendingInteraction = interaction;
|
|
1371
|
+
publish("interaction.request", interaction);
|
|
1372
|
+
publishProjectsTree();
|
|
1373
|
+
},
|
|
1374
|
+
onInteractionClear: (info) => {
|
|
1375
|
+
activePendingInteraction = null;
|
|
1376
|
+
publish("interaction.clear", info || {});
|
|
1377
|
+
publishProjectsTree();
|
|
1378
|
+
},
|
|
1379
|
+
logMessage: (kind, text) => {
|
|
1380
|
+
const normalized = kind === "error" ? "error"
|
|
1381
|
+
: kind === "user" ? "user"
|
|
1382
|
+
: kind === "assistant" ? "assistant"
|
|
1383
|
+
: "system";
|
|
1384
|
+
appendLocal(normalized, stripTags(text));
|
|
1385
|
+
},
|
|
1386
|
+
renderScreen: () => {},
|
|
1387
|
+
updateDashboard: (data) => {
|
|
1388
|
+
controller.applyStatus(data);
|
|
1389
|
+
const payload = buildDashboardPublishPayload(controller, data);
|
|
1390
|
+
publish("agents.snapshot", {
|
|
1391
|
+
agents: payload.agents,
|
|
1392
|
+
footer: payload.footer,
|
|
1393
|
+
});
|
|
1394
|
+
if (multiSession) {
|
|
1395
|
+
try { multiSession.syncAgents(); } catch {}
|
|
1396
|
+
}
|
|
1397
|
+
reconcileInternalWatches();
|
|
1398
|
+
publish("cron.snapshot", {
|
|
1399
|
+
tasks: payload.cron,
|
|
1400
|
+
cron: payload.cron,
|
|
1401
|
+
loop: payload.loop,
|
|
1402
|
+
loop_summary: payload.loop_summary,
|
|
1403
|
+
});
|
|
1404
|
+
publishProjectsTree();
|
|
1405
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
1406
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
1407
|
+
}
|
|
1408
|
+
},
|
|
1409
|
+
requestStatus: () => controller.requestDaemonStatus(),
|
|
1410
|
+
getPending: () => controller.session.pending,
|
|
1411
|
+
setPending: (value) => {
|
|
1412
|
+
controller.session.pending = value || null;
|
|
1413
|
+
publishProjectsTree();
|
|
1414
|
+
},
|
|
1415
|
+
resolveStatusLine: (text, data) => {
|
|
1416
|
+
if (data?.key && isInternalChild(data.key)) return;
|
|
1417
|
+
publish("status.set", { text: stripTags(text || "ready"), busy: false });
|
|
1418
|
+
},
|
|
1419
|
+
enqueueBusStatus: (item) => {
|
|
1420
|
+
if (item?.key && isInternalChild(item.key)) return;
|
|
1421
|
+
publish("status.set", { text: stripTags(typeof item === "object" ? item.text : item), busy: true });
|
|
1422
|
+
},
|
|
1423
|
+
resolveBusStatus: (item) => {
|
|
1424
|
+
if (item?.key && isInternalChild(item.key)) return;
|
|
1425
|
+
publish("status.set", { text: "ready", busy: false });
|
|
1426
|
+
},
|
|
1427
|
+
beginStream: (...args) => controller.getStreamState().beginStream(...args),
|
|
1428
|
+
appendStreamDelta: (...args) => controller.getStreamState().appendStreamDelta(...args),
|
|
1429
|
+
finalizeStream: (...args) => controller.getStreamState().finalizeStream(...args),
|
|
1430
|
+
hasStream: (...args) => controller.getStreamState().hasStream(...args),
|
|
1431
|
+
getPendingState: (...args) => controller.getStreamState().getPendingState(...args),
|
|
1432
|
+
consumePendingDelivery: (...args) => controller.getStreamState().consumePendingDelivery(...args),
|
|
1433
|
+
setTransientAgentState: (agentId, value, extra = {}) => {
|
|
1434
|
+
controller.patchAgentActivity(agentId, {
|
|
1435
|
+
activity_state: value,
|
|
1436
|
+
activity_detail: extra.detail || "",
|
|
1437
|
+
});
|
|
1438
|
+
publishProjectsTree();
|
|
1439
|
+
},
|
|
1440
|
+
clearTransientAgentState: (agentId) => {
|
|
1441
|
+
controller.patchAgentActivity(agentId, {
|
|
1442
|
+
activity_state: "",
|
|
1443
|
+
activity_detail: "",
|
|
1444
|
+
});
|
|
1445
|
+
publishProjectsTree();
|
|
1446
|
+
},
|
|
1447
|
+
});
|
|
1448
|
+
|
|
1449
|
+
const daemonConnection = createDaemonConnection({
|
|
1450
|
+
connectClient: daemonTransport.connectClient.bind(daemonTransport),
|
|
1451
|
+
transformRequest: (request) => routeDaemonRequest(initialEndpoint, request),
|
|
1452
|
+
handleMessage: (msg) => {
|
|
1453
|
+
if (!msg || typeof msg !== "object") return;
|
|
1454
|
+
if ([IPC_RESPONSE_TYPES.BUS_SEND_OK, IPC_RESPONSE_TYPES.ERROR].includes(msg.type)) {
|
|
1455
|
+
const id = msg.request_id || (msg.type === IPC_RESPONSE_TYPES.BUS_SEND_OK
|
|
1456
|
+
? internalSubmissions.keys().next().value
|
|
1457
|
+
: "");
|
|
1458
|
+
const submission = internalSubmissions.get(id);
|
|
1459
|
+
if (submission) {
|
|
1460
|
+
internalSubmissions.delete(id);
|
|
1461
|
+
if (submission.projectRoot === activeProjectRoot && msg.type === IPC_RESPONSE_TYPES.ERROR) {
|
|
1462
|
+
multiSession.acceptEvent(submission.agentId, {
|
|
1463
|
+
type: "submission_failed",
|
|
1464
|
+
message: submission.message,
|
|
1465
|
+
error: `Message delivery failed: ${msg.error || "unknown error"}`,
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
controller.requestDaemonStatus();
|
|
1469
|
+
return;
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
if (msg.type === IPC_RESPONSE_TYPES.STATUS) {
|
|
1473
|
+
const root = msg.data && (msg.data.projectRoot || msg.data.project_root);
|
|
1474
|
+
if (root && canonicalProjectRoot(root) !== canonicalProjectRoot(activeProjectRoot)) return;
|
|
1475
|
+
}
|
|
1476
|
+
if (msg.type === IPC_RESPONSE_TYPES.BUS) {
|
|
1477
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
1478
|
+
const evtData = msg.data || {};
|
|
1479
|
+
if (evtData.event === "agent_surface" && evtData.publisher === stageTarget.agentId) {
|
|
1480
|
+
const holder = ensureStandaloneSurface(stageTarget.agentId);
|
|
1481
|
+
holder.seq = Math.max(holder.seq, evtData.seq || 0);
|
|
1482
|
+
holder.surface.accept(evtData.data?.surface || {});
|
|
1483
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
1484
|
+
} else if (!isInternalAgentMeta(controller.session.metaMap.get(stageTarget.agentId))) {
|
|
1485
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
if (!isInternalDashboardEvent(msg.data || {}, (id) => controller.session.metaMap.get(id))) return;
|
|
1489
|
+
try {
|
|
1490
|
+
writeMultiPaneBusEvent(msg.data || {}, {
|
|
1491
|
+
agentIds: multiSession.listInternalAgentIds?.() || [],
|
|
1492
|
+
getMeta: (id) => controller.session.metaMap.get(id) || {},
|
|
1493
|
+
writeToPane: (id, text) => multiSession.writeToPane(id, text),
|
|
1494
|
+
acceptEvent: (id, event, seq) => multiSession.acceptEvent(id, event, seq),
|
|
1495
|
+
hasStructuredEvents: (id) => multiSession.hasStructuredEvents(id),
|
|
1496
|
+
});
|
|
1497
|
+
} catch {
|
|
1498
|
+
// ignore mirror errors
|
|
1499
|
+
}
|
|
1500
|
+
if (msg.data?.event === "agent_surface") return;
|
|
1501
|
+
}
|
|
1502
|
+
if (msg.type === IPC_RESPONSE_TYPES.BUS_SEND_OK) {
|
|
1503
|
+
controller.requestDaemonStatus();
|
|
1504
|
+
if (stageTarget.kind === "worker_single" && stageTarget.agentId) {
|
|
1505
|
+
publishStandaloneWorkerFrame(stageTarget.agentId);
|
|
1506
|
+
}
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
router.handleMessage(msg);
|
|
1510
|
+
},
|
|
1511
|
+
queueStatusLine: (text) => publish("status.set", { text: stripTags(text) }),
|
|
1512
|
+
resolveStatusLine: (text) => publish("status.set", { text: stripTags(text || "ready") }),
|
|
1513
|
+
logMessage: (kind, text) => appendLocal(kind === "error" ? "error" : "system", stripTags(text)),
|
|
1514
|
+
});
|
|
1515
|
+
|
|
1516
|
+
daemonCoordinator = createDaemonCoordinator({
|
|
1517
|
+
projectRoot: controllerRoot,
|
|
1518
|
+
daemonTransport,
|
|
1519
|
+
daemonConnection,
|
|
1520
|
+
stopDaemon,
|
|
1521
|
+
startDaemon,
|
|
1522
|
+
isDaemonRunning: isRunning,
|
|
1523
|
+
queueStatusLine: (text) => publish("status.set", { text: stripTags(text) }),
|
|
1524
|
+
resolveStatusLine: (text) => publish("status.set", { text: stripTags(text || "ready") }),
|
|
1525
|
+
logMessage: (kind, text) => appendLocal(kind === "error" ? "error" : "system", stripTags(text)),
|
|
1526
|
+
});
|
|
1527
|
+
|
|
1528
|
+
await daemonConnection.connect();
|
|
1529
|
+
daemonSend = (req) => {
|
|
1530
|
+
const reqId = req && (req.request_id || req.id);
|
|
1531
|
+
if (reqId) {
|
|
1532
|
+
ownRequestIds.add(String(reqId));
|
|
1533
|
+
if (ownRequestIds.size > 500) ownRequestIds.delete(ownRequestIds.values().next().value);
|
|
1534
|
+
}
|
|
1535
|
+
if (req.type === IPC_REQUEST_TYPES.PROMPT) mainSubmissionRev += 1;
|
|
1536
|
+
return daemonConnection.send(req);
|
|
1537
|
+
};
|
|
1538
|
+
controller.setSend(daemonSend);
|
|
1539
|
+
controller.start({
|
|
1540
|
+
send: daemonSend,
|
|
1541
|
+
sendStatus: () => daemonSend({ type: IPC_REQUEST_TYPES.STATUS }),
|
|
1542
|
+
statusIntervalMs: 3000,
|
|
1543
|
+
});
|
|
1544
|
+
|
|
1545
|
+
const archivedRoots = new Set(desktopArchive.read().projects.map(({ root }) => root));
|
|
1546
|
+
if (initialProjectRoot !== controllerRoot && !archivedRoots.has(initialProjectRoot) && fs.existsSync(initialProjectRoot)) {
|
|
1547
|
+
await switchToProjectRoot(initialProjectRoot);
|
|
1548
|
+
} else {
|
|
1549
|
+
const [firstProject] = listUnarchivedProjects();
|
|
1550
|
+
if (firstProject && options.autoSelectFirstProject !== false) {
|
|
1551
|
+
await switchToProjectRoot(firstProject.root);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
let handoffServer = null;
|
|
1556
|
+
if (options.enableHandoffServer !== false) {
|
|
1557
|
+
handoffServer = createDesktopHandoffServer({
|
|
1558
|
+
socketPath: options.handoffSocketPath,
|
|
1559
|
+
onHandoff: (parsed) => {
|
|
1560
|
+
void applyIncomingHandoff(parsed);
|
|
1561
|
+
},
|
|
1562
|
+
});
|
|
1563
|
+
await handoffServer.listen().catch(() => {});
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
standalonePollTimer = setInterval(pollStandaloneWorkerSurface, 350);
|
|
1567
|
+
standalonePollTimer.unref?.();
|
|
1568
|
+
treePollTimer = setInterval(() => {
|
|
1569
|
+
void refreshRecoverableForActiveProject().then(() => publishProjectsTree());
|
|
1570
|
+
}, 6000);
|
|
1571
|
+
treePollTimer.unref?.();
|
|
1572
|
+
|
|
1573
|
+
async function close() {
|
|
1574
|
+
clearInterval(standalonePollTimer);
|
|
1575
|
+
clearInterval(treePollTimer);
|
|
1576
|
+
if (handoffServer) await handoffServer.close().catch(() => {});
|
|
1577
|
+
if (multiSession?.isActive()) {
|
|
1578
|
+
try { multiSession.stop(); } catch {}
|
|
1579
|
+
}
|
|
1580
|
+
controller.stop();
|
|
1581
|
+
daemonConnection.markExit();
|
|
1582
|
+
daemonConnection.close();
|
|
1583
|
+
await host.close();
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
return {
|
|
1587
|
+
socketPath: uiSocketPath,
|
|
1588
|
+
authToken: uiAuthToken,
|
|
1589
|
+
handoffSocketPath: handoffServer ? handoffServer.socketPath : "",
|
|
1590
|
+
getActiveProjectRoot: () => activeProjectRoot,
|
|
1591
|
+
getStageTarget: () => ({ ...stageTarget }),
|
|
1592
|
+
applyIncomingHandoff,
|
|
1593
|
+
close,
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
module.exports = {
|
|
1598
|
+
startDesktopUiHost,
|
|
1599
|
+
rawHistoryToEntries,
|
|
1600
|
+
inspectDormantProjectSummary,
|
|
1601
|
+
};
|