-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.ts
More file actions
2076 lines (1850 loc) · 72.8 KB
/
Copy pathserver.ts
File metadata and controls
2076 lines (1850 loc) · 72.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from "node:crypto";
import { join, resolve } from "node:path";
import { mkdirSync } from "node:fs";
import { networkInterfaces } from "node:os";
import pkg from "../../package.json";
import {
AgentIdParamsSchema,
AgentsSendMessageRequestSchema,
apiPaths,
AvailableBranchesQuerySchema,
CreateWorktreeRequestSchema,
NotificationIdParamsSchema,
type OneshotConfig,
OpenWorktreeRequestSchema,
PostWorktreeToLinearRequestSchema,
type PostWorktreeToLinearTarget,
PullMainRequestSchema,
RunIdParamsSchema,
SendWorktreePromptRequestSchema,
SetWorktreeArchivedRequestSchema,
SetWorktreeLabelRequestSchema,
ToggleEnabledRequestSchema,
UpsertCustomAgentRequestSchema,
WorktreeNameParamsSchema,
} from "@webmux/api-contract";
import { log } from "./lib/log";
import {
attach,
detach,
interruptPrompt,
write,
resize,
selectPane,
sendKeys,
getScrollback,
setCallbacks,
clearCallbacks,
cleanupStaleSessions,
sendPrompt as sendTerminalPrompt,
type TerminalAttachTarget,
} from "./adapters/terminal";
import { loadControlToken } from "./adapters/control-token";
import { ClaudeCliClient } from "./adapters/claude-cli";
import { CodexAppServerClient } from "./adapters/codex-app-server";
import {
getDefaultProfileName,
persistLocalCustomAgent,
persistLocalGitHubConfig,
persistLocalLinearConfig,
removeLocalCustomAgent,
type ProjectConfig,
} from "./adapters/config";
import { jsonResponse, errorResponse } from "./lib/http";
import { isRecord, isStringArray } from "./lib/type-guards";
import { parseJsonBody, parseParams, parseQuery } from "./api-validation";
import { hasRecentDashboardActivity, touchDashboardActivity } from "./services/dashboard-activity";
import { buildArchivedWorktreePathSet, normalizeArchivePath } from "./services/archive-service";
import { resolveAgentChatSupport, resolveAgentTerminalSubmitDelayMs } from "./services/agent-chat-service";
import { validateCustomAgentInput } from "./services/agent-validation-service";
import { getAgentDefinition, isBuiltInAgentId, listAgentDetails, listAgentSummaries, normalizeCustomAgentId } from "./services/agent-registry";
import {
attachToIssue,
branchMatchesIssue,
buildLinearIssuesResponse,
buildLinearPickupMarkdown,
createIssueComment,
createLinearIssue,
deriveLinearIssueTitle,
fetchAssignedIssues,
fetchIssueWithAttachments,
fetchTeamByKey,
uploadAttachmentFile,
} from "./services/linear-service";
import {
buildSeedFromLinear,
defaultSeedFromLinearDeps,
exportConversationToLinear,
type ExportConversationDependencies,
type ExportConversationInput,
} from "./services/conversation-export-service";
import { buildCreateWorktreeTargets, LifecycleError } from "./services/lifecycle-service";
import { buildNativeTerminalLaunch, buildNativeTerminalTmuxCommand } from "./services/native-terminal-service";
import { startPrMonitor, syncPrStatus } from "./services/pr-service";
import { startLinearAutoCreateMonitor, resetProcessedIssues } from "./services/linear-auto-create-service";
import { startOneshotWatcher } from "./services/oneshot-watcher-service";
import { runAutoRemove, type AutoRemoveDependencies } from "./services/auto-remove-service";
import { pullMainBranch, forcePullMainBranch, startAutoPullMonitor } from "./services/auto-pull-service";
import {
buildAgentsUiMessageDeltaEvent,
readAgentsNotificationThreadId,
shouldRefreshAgentsConversationSnapshot,
} from "./services/agents-ui-stream-service";
import { classifyAgentsTerminalWorktreeError } from "./services/agents-ui-action-service";
import { buildProjectSnapshot } from "./services/snapshot-service";
import { ClaudeConversationService } from "./services/claude-conversation-service";
import { WorktreeConversationService } from "./services/worktree-conversation-service";
import { parseRuntimeEvent } from "./domain/events";
import type { AgentsUiConversationEvent, AgentsUiWorktreeConversationResponse } from "./domain/agents-ui";
import type { OneshotMeta, ProjectSnapshot, WorktreeSnapshot } from "./domain/model";
import { deriveInstancePrefix, isValidBranchName, isValidInstancePrefix, isValidWorktreeName } from "./domain/policies";
import { createWebmuxRuntime } from "./runtime";
import { createInstanceRegistry, type InstanceEntry } from "./adapters/instance-registry";
import { resolvePeerRedirect } from "./domain/peer-routing";
const PORT = parseInt(Bun.env.PORT || "5111", 10);
const STATIC_DIR = Bun.env.WEBMUX_STATIC_DIR || "";
const runtime = createWebmuxRuntime({
port: PORT,
projectDir: Bun.env.WEBMUX_PROJECT_DIR || process.cwd(),
});
const PROJECT_DIR = runtime.projectDir;
const config: ProjectConfig = runtime.config;
const git = runtime.git;
const archiveStateService = runtime.archiveStateService;
const tmux = runtime.tmux;
const projectRuntime = runtime.projectRuntime;
const worktreeCreationTracker = runtime.worktreeCreationTracker;
const runtimeNotifications = runtime.runtimeNotifications;
const reconciliationService = runtime.reconciliationService;
const codexAppServerClient = new CodexAppServerClient({
clientName: "webmux-agents",
clientVersion: "0.0.0",
});
const claudeCliClient = new ClaudeCliClient();
const worktreeConversationService = new WorktreeConversationService({
appServer: codexAppServerClient,
git,
});
const claudeConversationService = new ClaudeConversationService({
claude: claudeCliClient,
git,
});
const removingBranches = new Set<string>();
const lifecycleService = runtime.lifecycleService;
let linearAutoCreateEnabled = config.integrations.linear.autoCreateWorktrees;
let stopLinearAutoCreate: (() => void) | null = null;
let autoRemoveOnMergeEnabled = config.integrations.github.autoRemoveOnMerge;
/** Create a worktree in oneshot mode for the given Linear issue and arm the
* server-side watcher to post results back + close the session when done. Returns
* the resolved working branch — the seed may pick `attachmentPayload.branch ??
* pr.branch ?? issue.branchName`, so the caller (e.g. the pickup-comment poster)
* must use this value, not `issue.branchName`. */
async function runOneshotForIssue(issueId: string): Promise<{ branch: string }> {
const seed = await buildSeedFromLinear({ issueId }, defaultSeedFromLinearDeps);
if (!seed.ok) {
throw new Error(`Linear seed failed for ${issueId}: ${seed.error}`);
}
const branch = seed.data.branch;
if (!branch) {
throw new Error(`Linear seed for ${issueId} did not resolve to a branch`);
}
const mode = seed.data.source !== "none" ? "existing" : "new";
const prompt = seed.data.conversationMarkdown?.trim() ?? "";
await lifecycleService.createWorktree({
mode,
branch,
...(prompt ? { prompt } : {}),
source: "oneshot",
oneshot: {
autoCloseOnDone: true,
postToLinearOnDone: { kind: "issue", issueId },
},
});
return { branch };
}
/** Safe to call multiple times — the guard prevents duplicate monitors. */
function startLinearAutoCreate(): void {
if (stopLinearAutoCreate) return;
const watchTeamKeys = config.integrations.linear.watchTeams;
stopLinearAutoCreate = startLinearAutoCreateMonitor({
lifecycleService,
git,
projectRoot: PROJECT_DIR,
runOneshotForIssue,
onOneshotPickedUp: postLinearOneshotPickupComment,
...(watchTeamKeys && watchTeamKeys.length > 0 ? { watchTeamKeys } : {}),
});
}
/** Post the structured pickup comment on the Linear issue when the auto-create watcher
* picks up a `webmux_oneshot` issue, so external automation can see the autonomous run
* started. `branch` is the *actual* working branch (which can differ from
* `issue.branchName` — see `runOneshotForIssue`). Failures are logged and swallowed —
* pickup itself must not depend on this. Markdown is built by the pure
* `buildLinearPickupMarkdown` in `linear-service.ts` so the grep-able prefix has a
* unit-test contract. */
async function postLinearOneshotPickupComment(input: {
issue: { id: string; identifier: string };
branch: string;
}): Promise<void> {
const body = buildLinearPickupMarkdown({
branch: input.branch,
pickedUpAt: new Date(),
});
const result = await createIssueComment({ issueId: input.issue.id, body });
if (!result.ok) {
log.warn(`[linear-auto-create] failed to post pickup comment for ${input.issue.identifier}: ${result.error}`);
return;
}
log.info(`[linear-auto-create] posted pickup comment for ${input.issue.identifier}: ${result.data.url}`);
}
/** Map the wire-side `OneshotConfig` (all-optional fields) to the persisted
* `OneshotMeta` shape (autoCloseOnDone has a definite boolean). Default is
* `true` — callers must opt out explicitly. */
function normalizeOneshotConfig(input: OneshotConfig | undefined): OneshotMeta | undefined {
if (!input) return undefined;
return {
autoCloseOnDone: input.autoCloseOnDone ?? true,
...(input.postToLinearOnDone ? { postToLinearOnDone: input.postToLinearOnDone } : {}),
};
}
/** Clear the worktree's oneshot watch state, if armed. Called from every
* user-interaction endpoint so any browser action ("the human took over")
* short-circuits the server-side auto-close + Linear post-back. Also updates
* the in-memory runtime state so the next snapshot reflects the disarm without
* waiting for a reconciliation pass — the CLI relies on that for its
* user-took-over exit path. */
async function disarmOneshotIfArmed(branch: string, reason: string): Promise<void> {
try {
const disarmed = await lifecycleService.disarmOneshot(branch);
if (!disarmed) return;
log.info(`[oneshot-watcher] ${branch}: disarmed by ${reason}`);
const state = projectRuntime.getWorktreeByBranch(branch);
if (state) projectRuntime.setOneshot(state.worktreeId, null);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
log.warn(`[oneshot-watcher] disarm failed for ${branch} (${reason}): ${msg}`);
}
}
function stopLinearAutoCreateMonitor(): void {
if (stopLinearAutoCreate) {
stopLinearAutoCreate();
stopLinearAutoCreate = null;
}
}
const autoRemoveDeps: AutoRemoveDependencies = {
lifecycleService,
git,
projectRoot: PROJECT_DIR,
notifications: runtimeNotifications,
isRemoving: (branch: string) => removingBranches.has(branch),
markRemoving: (branch: string) => removingBranches.add(branch),
unmarkRemoving: (branch: string) => removingBranches.delete(branch),
};
function getFrontendConfig(): {
name: string;
services: ProjectConfig["services"];
profiles: Array<{ name: string; systemPrompt?: string }>;
agents: ReturnType<typeof listAgentSummaries>;
defaultProfileName: string;
defaultAgentId: ProjectConfig["workspace"]["defaultAgent"];
autoName: boolean;
linearCreateTicketOption: boolean;
startupEnvs: ProjectConfig["startupEnvs"];
linkedRepos: Array<{ alias: string; dir?: string }>;
linearAutoCreateWorktrees: boolean;
autoRemoveOnMerge: boolean;
projectDir: string;
mainBranch: string;
} {
const defaultProfileName = getDefaultProfileName(config);
const orderedProfileEntries = Object.entries(config.profiles).sort(([left], [right]) => {
if (left === defaultProfileName) return -1;
if (right === defaultProfileName) return 1;
return 0;
});
return {
name: config.name,
services: config.services,
profiles: orderedProfileEntries.map(([name, profile]) => ({
name,
...(profile.systemPrompt ? { systemPrompt: profile.systemPrompt } : {}),
})),
agents: listAgentSummaries(config),
defaultProfileName,
defaultAgentId: config.workspace.defaultAgent,
autoName: config.autoName !== null,
linearCreateTicketOption: config.integrations.linear.enabled && config.integrations.linear.createTicketOption,
startupEnvs: config.startupEnvs,
linkedRepos: config.integrations.github.linkedRepos.map((lr) => ({
alias: lr.alias,
...(lr.dir ? { dir: resolve(PROJECT_DIR, lr.dir) } : {}),
})),
linearAutoCreateWorktrees: linearAutoCreateEnabled,
autoRemoveOnMerge: autoRemoveOnMergeEnabled,
projectDir: PROJECT_DIR,
mainBranch: config.workspace.mainBranch,
};
}
// --- WebSocket protocol types ---
interface TerminalWsData {
kind: "terminal";
branch: string;
worktreeId: string | null;
attachId: string | null;
attached: boolean;
}
interface AgentsWsData {
kind: "agents";
branch: string;
conversationId: string | null;
unsubscribe: (() => void) | null;
}
type WsData = TerminalWsData | AgentsWsData;
type ParamsRequest = Request & { params: Record<string, string> };
type WsInboundMessage =
| { type: "input"; data: string }
| { type: "sendKeys"; hexBytes: string[] }
| { type: "selectPane"; pane: number }
| { type: "resize"; cols: number; rows: number; initialPane?: number };
type WsOutboundMessage =
| { type: "output"; data: string }
| { type: "exit"; exitCode: number }
| { type: "error"; message: string }
| { type: "scrollback"; data: string };
function parseWsMessage(raw: string | Buffer): WsInboundMessage | null {
try {
const str = typeof raw === "string" ? raw : new TextDecoder().decode(raw);
const msg: unknown = JSON.parse(str);
if (!isRecord(msg)) return null;
const m = msg;
switch (m.type) {
case "input":
return typeof m.data === "string" ? { type: "input", data: m.data } : null;
case "sendKeys":
return isStringArray(m.hexBytes)
? { type: "sendKeys", hexBytes: m.hexBytes }
: null;
case "selectPane":
return typeof m.pane === "number" ? { type: "selectPane", pane: m.pane } : null;
case "resize":
return typeof m.cols === "number" && typeof m.rows === "number"
? {
type: "resize",
cols: m.cols,
rows: m.rows,
initialPane: typeof m.initialPane === "number" ? m.initialPane : undefined,
}
: null;
default:
return null;
}
} catch {
return null;
}
}
// --- HTTP helpers ---
/** Send a WsOutboundMessage. Hot-path messages (output/scrollback) use a
* single-character prefix to avoid JSON encode/decode overhead. */
function sendWs(ws: { send: (data: string) => void }, msg: WsOutboundMessage): void {
switch (msg.type) {
case "output":
ws.send("o" + msg.data);
break;
case "scrollback":
ws.send("s" + msg.data);
break;
default:
ws.send(JSON.stringify(msg));
}
}
function sendAgentsWs(ws: { readyState: number; send: (data: string) => void }, msg: AgentsUiConversationEvent): void {
if (ws.readyState <= 1) {
ws.send(JSON.stringify(msg));
}
}
/** Wrap an async API handler to catch and log unhandled errors. */
function catching(label: string, fn: () => Promise<Response>): Promise<Response> {
return fn().catch((err: unknown) => {
if (err instanceof LifecycleError) {
return errorResponse(err.message, err.status);
}
const msg = err instanceof Error ? err.message : String(err);
log.error(`[api:error] ${label}: ${msg}`);
return errorResponse(msg);
});
}
function ensureBranchNotRemoving(branch: string): void {
if (removingBranches.has(branch)) {
throw new LifecycleError(`Worktree is being removed: ${branch}`, 409);
}
}
function ensureBranchNotCreating(branch: string): void {
if (worktreeCreationTracker.has(branch)) {
throw new LifecycleError(`Worktree is being created: ${branch}`, 409);
}
}
function ensureBranchNotBusy(branch: string): void {
ensureBranchNotRemoving(branch);
ensureBranchNotCreating(branch);
}
async function withRemovingBranch<T>(branch: string, fn: () => Promise<T>): Promise<T> {
ensureBranchNotBusy(branch);
removingBranches.add(branch);
try {
return await fn();
} finally {
removingBranches.delete(branch);
}
}
async function resolveTerminalWorktree(branch: string): Promise<{
worktreeId: string;
attachTarget: TerminalAttachTarget;
agentName: WorktreeSnapshot["agentName"];
}> {
ensureBranchNotBusy(branch);
let state = projectRuntime.getWorktreeByBranch(branch);
if (!state || !state.session.exists || !state.session.sessionName) {
await reconciliationService.reconcile(PROJECT_DIR);
state = projectRuntime.getWorktreeByBranch(branch);
}
if (!state) {
throw new Error(`Worktree not found: ${branch}`);
}
if (!state.session.exists || !state.session.sessionName) {
throw new Error(`No open tmux window found for worktree: ${branch}`);
}
return {
worktreeId: state.worktreeId,
attachTarget: {
ownerSessionName: state.session.sessionName,
windowName: state.session.windowName,
},
agentName: state.agentName,
};
}
async function resolveAgentsTerminalWorktree(branch: string): Promise<{
ok: true;
data: {
worktreeId: string;
attachTarget: TerminalAttachTarget;
};
} | {
ok: false;
response: Response;
}> {
try {
return {
ok: true,
data: await resolveTerminalWorktree(branch),
};
} catch (error) {
const classified = classifyAgentsTerminalWorktreeError(error);
if (!classified) throw error;
return {
ok: false,
response: errorResponse(classified.error, classified.status),
};
}
}
async function apiGetNativeTerminalLaunch(branch: string): Promise<Response> {
touchDashboardActivity();
ensureBranchNotBusy(branch);
await reconciliationService.reconcile(PROJECT_DIR);
const launch = buildNativeTerminalLaunch({
branch,
state: projectRuntime.getWorktreeByBranch(branch),
tmuxCommand: buildNativeTerminalTmuxCommand(Bun.env),
sessionPrefix: `wm-native-${PORT}-`,
});
if (!launch.ok) {
return errorResponse(launch.message, launch.reason === "not_found" ? 404 : 409);
}
return jsonResponse(launch.data);
}
function getAttachedSessionId(
data: TerminalWsData,
ws: { readyState: number; send: (data: string) => void },
): string | null {
if (data.attached && data.attachId) {
return data.attachId;
}
sendWs(ws, { type: "error", message: "Terminal not attached" });
return null;
}
async function hasValidControlToken(req: Request): Promise<boolean> {
const authHeader = req.headers.get("Authorization");
const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null;
return token === await loadControlToken();
}
// --- Process helpers ---
async function getWorktreeGitDirs(): Promise<Map<string, string>> {
const gitDirs = new Map<string, string>();
const projectRoot = resolve(PROJECT_DIR);
for (const entry of git.listLiveWorktrees(projectRoot)) {
if (entry.bare || resolve(entry.path) === projectRoot || !entry.branch) continue;
gitDirs.set(entry.branch, git.resolveWorktreeGitDir(entry.path));
}
return gitDirs;
}
function makeCallbacks(ws: { send: (data: string) => void; readyState: number }): {
onData: (data: string) => void;
onExit: (exitCode: number) => void;
} {
return {
onData: (data: string) => {
if (ws.readyState <= 1) sendWs(ws, { type: "output", data });
},
onExit: (exitCode: number) => {
if (ws.readyState <= 1) sendWs(ws, { type: "exit", exitCode });
},
};
}
async function readProjectSnapshot(): Promise<ProjectSnapshot> {
const linearApiKey = Bun.env.LINEAR_API_KEY;
const linearIssuesPromise = config.integrations.linear.enabled && linearApiKey?.trim()
? fetchAssignedIssues()
: Promise.resolve({ ok: true as const, data: [] });
await reconciliationService.reconcile(PROJECT_DIR);
const archiveState = await archiveStateService.prune(projectRuntime.listWorktrees().map((worktree) => worktree.path));
const linearResult = await linearIssuesPromise;
const archivedPaths = buildArchivedWorktreePathSet(archiveState);
const linearIssues = linearResult.ok ? linearResult.data : [];
return buildProjectSnapshot({
projectName: config.name,
mainBranch: config.workspace.mainBranch,
runtime: projectRuntime,
creatingWorktrees: worktreeCreationTracker.list(),
notifications: runtimeNotifications.list(),
isArchived: (path) => archivedPaths.has(normalizeArchivePath(path)),
findLinearIssue: (branch) => {
const match = linearIssues.find((issue) => branchMatchesIssue(branch, issue.branchName));
return match
? {
identifier: match.identifier,
url: match.url,
state: match.state,
}
: null;
},
findAgentLabel: (agentId) => {
if (!agentId) return null;
return getAgentDefinition(config, agentId)?.label ?? agentId;
},
});
}
// --- API handler functions (thin I/O layer, testable by injecting deps) ---
async function apiGetProject(): Promise<Response> {
touchDashboardActivity();
return jsonResponse(await readProjectSnapshot());
}
async function apiGetWorktrees(): Promise<Response> {
touchDashboardActivity();
return jsonResponse({
worktrees: (await readProjectSnapshot()).worktrees,
});
}
function findSnapshotWorktree(snapshot: ProjectSnapshot, branch: string): WorktreeSnapshot | null {
return snapshot.worktrees.find((worktree) => worktree.branch === branch) ?? null;
}
async function resolveAgentsWorktree(branch: string): Promise<{
ok: true;
worktree: WorktreeSnapshot;
} | {
ok: false;
response: Response;
}> {
const snapshot = await readProjectSnapshot();
const worktree = findSnapshotWorktree(snapshot, branch);
if (!worktree) {
return {
ok: false,
response: errorResponse(`Worktree not found: ${branch}`, 404),
};
}
return {
ok: true,
worktree,
};
}
function resolveWorktreeAgentChatSupport(worktree: WorktreeSnapshot, action: "chat" | "interrupt") {
return resolveAgentChatSupport({
agentId: worktree.agentName,
agentLabel: worktree.agentLabel,
agent: worktree.agentName ? getAgentDefinition(config, worktree.agentName) : null,
action,
});
}
function resolveWorktreeTerminalSubmitDelayMs(agentName: WorktreeSnapshot["agentName"]): number {
return resolveAgentTerminalSubmitDelayMs({
agentId: agentName,
agent: agentName ? getAgentDefinition(config, agentName) : null,
});
}
async function apiAttachAgentsWorktree(branch: string): Promise<Response> {
touchDashboardActivity();
const resolved = await resolveAgentsWorktree(branch);
if (!resolved.ok) return resolved.response;
const chatSupport = resolveWorktreeAgentChatSupport(resolved.worktree, "chat");
if (!chatSupport.ok) {
return errorResponse(chatSupport.error, chatSupport.status);
}
const result = chatSupport.data.provider === "claude"
? await claudeConversationService.attachWorktreeConversation(resolved.worktree)
: await worktreeConversationService.attachWorktreeConversation(resolved.worktree);
return result.ok
? jsonResponse(result.data)
: errorResponse(result.error, result.status);
}
async function apiGetAgentsWorktreeHistory(branch: string): Promise<Response> {
touchDashboardActivity();
const resolved = await resolveAgentsWorktree(branch);
if (!resolved.ok) return resolved.response;
const chatSupport = resolveWorktreeAgentChatSupport(resolved.worktree, "chat");
if (!chatSupport.ok) {
return errorResponse(chatSupport.error, chatSupport.status);
}
const result = chatSupport.data.provider === "claude"
? await claudeConversationService.readWorktreeConversation(resolved.worktree)
: await worktreeConversationService.readWorktreeConversation(resolved.worktree);
return result.ok
? jsonResponse(result.data)
: errorResponse(result.error, result.status);
}
async function apiSendAgentsWorktreeMessage(branch: string, req: Request): Promise<Response> {
touchDashboardActivity();
await disarmOneshotIfArmed(branch, "agents-send-message");
const parsed = await parseJsonBody(req, AgentsSendMessageRequestSchema);
if (!parsed.ok) return parsed.response;
const resolved = await resolveAgentsWorktree(branch);
if (!resolved.ok) return resolved.response;
if (!resolved.worktree.mux) {
return errorResponse("Open this worktree in the main dashboard before sending messages here", 409);
}
const chatSupport = resolveWorktreeAgentChatSupport(resolved.worktree, "chat");
if (!chatSupport.ok) {
return errorResponse(chatSupport.error, chatSupport.status);
}
const conversationResult = chatSupport.data.provider === "claude"
? await claudeConversationService.readWorktreeConversation(resolved.worktree)
: await worktreeConversationService.readWorktreeConversation(resolved.worktree);
if (!conversationResult.ok) {
return errorResponse(conversationResult.error, conversationResult.status);
}
const terminalWorktree = await resolveAgentsTerminalWorktree(branch);
if (!terminalWorktree.ok) return terminalWorktree.response;
const sendResult = await sendTerminalPrompt(
terminalWorktree.data.worktreeId,
terminalWorktree.data.attachTarget,
parsed.data.text,
0,
undefined,
chatSupport.data.submitDelayMs,
);
if (!sendResult.ok) {
return errorResponse(sendResult.error, 503);
}
// tmux send has no real turn id yet; history replaces this optimistic placeholder on refresh.
return jsonResponse({
conversationId: conversationResult.data.conversation.conversationId,
turnId: `tmux:${crypto.randomUUID()}`,
running: true,
});
}
async function apiInterruptAgentsWorktree(branch: string): Promise<Response> {
touchDashboardActivity();
await disarmOneshotIfArmed(branch, "agents-interrupt");
const resolved = await resolveAgentsWorktree(branch);
if (!resolved.ok) return resolved.response;
if (!resolved.worktree.mux) {
return errorResponse("Open this worktree in the main dashboard before interrupting it here", 409);
}
const chatSupport = resolveWorktreeAgentChatSupport(resolved.worktree, "interrupt");
if (!chatSupport.ok) {
return errorResponse(chatSupport.error, chatSupport.status);
}
const conversationResult = chatSupport.data.provider === "claude"
? await claudeConversationService.readWorktreeConversation(resolved.worktree)
: await worktreeConversationService.readWorktreeConversation(resolved.worktree);
if (!conversationResult.ok) {
return errorResponse(conversationResult.error, conversationResult.status);
}
const terminalWorktree = await resolveAgentsTerminalWorktree(branch);
if (!terminalWorktree.ok) return terminalWorktree.response;
const interruptResult = await interruptPrompt(terminalWorktree.data.attachTarget, 0);
if (!interruptResult.ok) {
return errorResponse(interruptResult.error, 503);
}
return jsonResponse({
conversationId: conversationResult.data.conversation.conversationId,
turnId: conversationResult.data.conversation.activeTurnId ?? `tmux:${crypto.randomUUID()}`,
interrupted: true,
});
}
async function loadAgentsConversationSnapshot(
branch: string,
): Promise<{
ok: true;
data: AgentsUiWorktreeConversationResponse;
} | {
ok: false;
message: string;
}> {
const resolved = await resolveAgentsWorktree(branch);
if (!resolved.ok) {
return {
ok: false,
message: await readErrorMessage(resolved.response),
};
}
const chatSupport = resolveWorktreeAgentChatSupport(resolved.worktree, "chat");
if (!chatSupport.ok) {
return {
ok: false,
message: chatSupport.error,
};
}
const result = chatSupport.data.provider === "claude"
? await claudeConversationService.readWorktreeConversation(resolved.worktree)
: await worktreeConversationService.readWorktreeConversation(resolved.worktree);
return result.ok
? { ok: true, data: result.data }
: { ok: false, message: result.error };
}
async function readErrorMessage(response: Response): Promise<string> {
const contentType = response.headers.get("Content-Type") ?? "";
if (contentType.includes("application/json")) {
try {
const body: unknown = await response.json();
if (isRecord(body) && typeof body.error === "string" && body.error.length > 0) {
return body.error;
}
} catch {
// Ignore parse failures and fall through to raw text.
}
}
const text = await response.text();
return text.length > 0 ? text : `HTTP ${response.status}`;
}
async function openAgentsSocket(
ws: { readyState: number; send: (data: string) => void; close: (code?: number, reason?: string) => void },
data: AgentsWsData,
): Promise<void> {
const snapshot = await loadAgentsConversationSnapshot(data.branch);
if (!snapshot.ok) {
sendAgentsWs(ws, { type: "error", message: snapshot.message });
ws.close(1011, snapshot.message.slice(0, 123));
return;
}
data.conversationId = snapshot.data.conversation.conversationId;
sendAgentsWs(ws, {
type: "snapshot",
data: snapshot.data,
});
if (snapshot.data.conversation.provider !== "codexAppServer") {
return;
}
data.unsubscribe = codexAppServerClient.onNotification((notification) => {
const notificationThreadId = readAgentsNotificationThreadId(notification);
if (!notificationThreadId || notificationThreadId !== data.conversationId) return;
const deltaEvent = buildAgentsUiMessageDeltaEvent(notification);
if (deltaEvent) {
sendAgentsWs(ws, deltaEvent);
return;
}
if (!shouldRefreshAgentsConversationSnapshot(notification)) return;
void (async () => {
const nextSnapshot = await loadAgentsConversationSnapshot(data.branch);
if (!nextSnapshot.ok) {
sendAgentsWs(ws, { type: "error", message: nextSnapshot.message });
return;
}
data.conversationId = nextSnapshot.data.conversation.conversationId;
sendAgentsWs(ws, {
type: "snapshot",
data: nextSnapshot.data,
});
})();
});
}
async function apiRuntimeEvent(req: Request): Promise<Response> {
if (!await hasValidControlToken(req)) {
return new Response("Unauthorized", { status: 401 });
}
let raw: unknown;
try {
raw = await req.json();
} catch {
return errorResponse("Invalid JSON", 400);
}
const event = parseRuntimeEvent(raw);
if (!event) return errorResponse("Invalid runtime event body", 400);
try {
projectRuntime.applyEvent(event);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes("Unknown worktree id")) {
await reconciliationService.reconcile(PROJECT_DIR);
try {
projectRuntime.applyEvent(event);
} catch (retryError) {
const retryMessage = retryError instanceof Error ? retryError.message : String(retryError);
if (retryMessage.includes("Unknown worktree id")) {
return errorResponse(retryMessage, 404);
}
throw retryError;
}
} else {
throw error;
}
}
const notification = runtimeNotifications.recordEvent(event);
return jsonResponse({
ok: true,
...(notification ? { notification } : {}),
});
}
async function apiListBranches(req: Request): Promise<Response> {
const parsed = parseQuery(req, AvailableBranchesQuerySchema);
if (!parsed.ok) return parsed.response;
const includeRemote = parsed.data.includeRemote === true;
return jsonResponse({
branches: lifecycleService.listAvailableBranches({ includeRemote }),
});
}
async function apiListBaseBranches(): Promise<Response> {
return jsonResponse({
branches: lifecycleService.listBaseBranches(),
});
}
async function apiCreateWorktree(req: Request): Promise<Response> {
const parsed = await parseJsonBody(req, CreateWorktreeRequestSchema);
if (!parsed.ok) return parsed.response;
const body = parsed.data;
const envOverrides = body.envOverrides && Object.keys(body.envOverrides).length > 0 ? body.envOverrides : undefined;
const branch = body.branch?.trim() ? body.branch.trim() : undefined;
const baseBranch = body.baseBranch?.trim() ? body.baseBranch.trim() : undefined;
const prompt = body.prompt?.trim() ? body.prompt.trim() : undefined;
const profile = body.profile;
const agent = body.agent;
const agents = body.agents;
const createLinearTicket = body.createLinearTicket === true;
const linearTitle = body.linearTitle?.trim() ? body.linearTitle.trim() : undefined;
// CreateWorktreeRequestSchema already trims, uppercases, and validates the
// team key shape — body.linearTeamKey is either a valid key or undefined.
const linearTeamKey = body.linearTeamKey;
const mode = body.mode;
const selectedAgents = agents
? agents
: agent
? [agent]
: [config.workspace.defaultAgent];
if (baseBranch && !isValidBranchName(baseBranch)) {
return errorResponse("Invalid base branch name", 400);
}
if (createLinearTicket && mode === "existing") {
return errorResponse("Linear ticket creation is only supported for new branches", 400);
}
if (baseBranch && mode === "existing") {
return errorResponse("Base branch is only supported for new branches", 400);
}
if (createLinearTicket && !config.integrations.linear.enabled) {
return errorResponse("Linear integration is disabled", 400);
}
if (createLinearTicket && !config.integrations.linear.createTicketOption) {
return errorResponse("Linear ticket creation is not enabled for this project", 400);
}
if (createLinearTicket && !prompt) {
return errorResponse("Prompt is required when creating a Linear ticket", 400);
}
let resolvedBranch = branch;
let resolvedPrompt = prompt;
let resolvedMode = mode;
if (body.fromLinear) {
if (createLinearTicket) {
return errorResponse("fromLinear cannot be combined with createLinearTicket", 400);
}
let conversationContext = body.fromLinear.conversationContext?.trim() ?? "";
let seedBranch: string | null = null;
if (!conversationContext || !resolvedBranch) {
// Fall back to fetching the seed server-side when the client didn't pre-resolve it.
// The CLI's `webmux oneshot --linear` path resolves the seed in-process before
// calling this endpoint and passes `conversationContext` + `branch` directly,
// so this fetch only fires for dashboard/REST callers (no double round-trip).
const seedResult = await buildSeedFromLinear(
{ issueId: body.fromLinear.issueId },
defaultSeedFromLinearDeps,
);
if (!seedResult.ok) {
return errorResponse(`Linear seed lookup failed: ${seedResult.error}`, seedResult.status);
}
if (!conversationContext && seedResult.data.conversationMarkdown) {
conversationContext = seedResult.data.conversationMarkdown;
}
seedBranch = seedResult.data.branch;
if (!resolvedBranch && seedBranch) {
resolvedBranch = seedBranch;
// Use "existing" mode when the seed pointed to a real branch (avoids fresh-create).
if (seedResult.data.source !== "none") resolvedMode = "existing";
}
}
if (conversationContext) {
resolvedPrompt = resolvedPrompt
? `${conversationContext}\n\n---\n\n${resolvedPrompt}`
: conversationContext;
}
}
if (createLinearTicket) {
const title = deriveLinearIssueTitle(linearTitle, prompt);
if (!title) {
return errorResponse("Linear ticket title could not be derived from the prompt", 400);
}
if (!linearTeamKey) {
return errorResponse(
"Linear team is required to create a ticket. Provide `linearTeamKey` (e.g. \"ENG\").",
400,