@kabmo-labs/kabmo 0.24.0 → 0.25.0
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/dist/client/index.html +1 -1
- package/dist/client/index.js +579 -510
- package/dist/client/static/js/index-bc9aa4mx.css +1 -0
- package/dist/client/static/js/{index-jcr5twtp.js → index-ga8cbpt4.js} +1072 -1174
- package/package.json +2 -4
- package/src/cli/lib/args.js +24 -1
- package/src/cli/lib/args.test.js +16 -0
- package/src/cli/lib/commands/session.js +233 -0
- package/src/cli/lib/commands/session.test.js +103 -0
- package/src/cli/main.js +1 -1
- package/src/client/components/common/ComposerPicker.tsx +3 -0
- package/src/client/components/common/code-surface/shiki.test.ts +82 -0
- package/src/client/components/common/code-surface/shiki.ts +28 -7
- package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
- package/src/client/components/common/session-actions-menu/index.tsx +33 -2
- package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
- package/src/client/components/common/session-row/index.tsx +27 -1
- package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
- package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
- package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
- package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +36 -5
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
- package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -35
- package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
- package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
- package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
- package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
- package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
- package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
- package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
- package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
- package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
- package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
- package/src/client/components/workspace/chat-timeline/index.tsx +3 -1
- package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
- package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
- package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
- package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
- package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
- package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
- package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
- package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
- package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
- package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
- package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
- package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
- package/src/client/data/settings/omp-schema.json +1 -1
- package/src/client/data/theme/terminal.test.ts +25 -0
- package/src/client/data/theme/terminal.ts +96 -79
- package/src/client/hooks/chat/composer/items.test.ts +12 -26
- package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
- package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
- package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
- package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
- package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
- package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
- package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
- package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
- package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
- package/src/client/hooks/chat/timeline/send.test.ts +3 -1
- package/src/client/hooks/chat/timeline/send.ts +51 -50
- package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
- package/src/client/hooks/models/use-harness-update.test.ts +193 -0
- package/src/client/hooks/models/use-harness-update.ts +202 -0
- package/src/client/hooks/workspace/child-expansion.ts +33 -0
- package/src/client/hooks/workspace/terminal/index.ts +17 -3
- package/src/client/hooks/workspace/terminal/socket.ts +9 -4
- package/src/client/lib/session-tree.test.ts +50 -0
- package/src/client/lib/session-tree.ts +59 -0
- package/src/client/tailwind.css +17 -11
- package/src/server/index.ts +2 -0
- package/src/server/lib/auth/guard.ts +10 -0
- package/src/server/lib/btw/session-copy.server.ts +6 -44
- package/src/server/lib/btw/session-copy.test.ts +2 -1
- package/src/server/lib/db/schema.ts +4 -0
- package/src/server/lib/db/seed-terminal.test.ts +1 -1
- package/src/server/lib/db/seed.test.ts +1 -1
- package/src/server/lib/harness/acp/background-work.test.ts +262 -0
- package/src/server/lib/harness/acp/background-work.ts +320 -0
- package/src/server/lib/harness/acp/client.ts +2 -2
- package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
- package/src/server/lib/harness/acp/gateway-env.ts +70 -0
- package/src/server/lib/harness/acp/prompt.test.ts +20 -0
- package/src/server/lib/harness/acp/prompt.ts +19 -3
- package/src/server/lib/harness/acp/session-background.test.ts +129 -0
- package/src/server/lib/harness/acp/session-exit.ts +31 -0
- package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
- package/src/server/lib/harness/acp/session-handshake.ts +27 -1
- package/src/server/lib/harness/acp/session-listeners.ts +31 -0
- package/src/server/lib/harness/acp/session-requests.ts +47 -0
- package/src/server/lib/harness/acp/session-turns.ts +20 -5
- package/src/server/lib/harness/acp/session.test-util.ts +23 -1
- package/src/server/lib/harness/acp/session.ts +59 -59
- package/src/server/lib/harness/acp/turn.test.ts +81 -0
- package/src/server/lib/harness/acp/turn.ts +26 -9
- package/src/server/lib/harness/acp/verbs.ts +12 -2
- package/src/server/lib/harness/launch.ts +3 -1
- package/src/server/lib/harness/spawn.server.ts +15 -2
- package/src/server/lib/harness/update-job-store.test.ts +126 -0
- package/src/server/lib/harness/update-job-store.ts +109 -0
- package/src/server/lib/harness/update-job.server.ts +203 -0
- package/src/server/lib/harness/update-worker.test.ts +153 -0
- package/src/server/lib/harness/update-worker.ts +197 -0
- package/src/server/lib/lifecycle/paths.ts +23 -0
- package/src/server/lib/omp/rpc/manager.ts +5 -5
- package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
- package/src/server/lib/omp/rpc/session-registry.ts +14 -2
- package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
- package/src/server/lib/omp/session/delete-flow.server.ts +47 -0
- package/src/server/lib/omp/session/delete.server.ts +5 -0
- package/src/server/lib/omp/session/rewind-file.ts +39 -21
- package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
- package/src/server/lib/omp/session/transcript-copy.ts +123 -0
- package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
- package/src/server/lib/sessions/agent-token.server.ts +134 -0
- package/src/server/lib/sessions/answers.server.test.ts +33 -0
- package/src/server/lib/sessions/answers.server.ts +37 -0
- package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
- package/src/server/lib/sessions/dispatch.server.ts +128 -0
- package/src/server/lib/sessions/fork.server.test.ts +209 -0
- package/src/server/lib/sessions/fork.server.ts +304 -0
- package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
- package/src/server/lib/sessions/lifecycle.server.ts +71 -0
- package/src/server/lib/sessions/notify.server.test.ts +112 -0
- package/src/server/lib/sessions/notify.server.ts +212 -0
- package/src/server/lib/sessions/relation-types.ts +76 -0
- package/src/server/lib/sessions/relations.server.test.ts +207 -0
- package/src/server/lib/sessions/relations.server.ts +337 -0
- package/src/server/lib/sessions/resolve.server.ts +106 -0
- package/src/server/lib/sessions/schema.server.ts +82 -0
- package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
- package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
- package/src/server/lib/sessions/spawn.server.test.ts +196 -0
- package/src/server/lib/sessions/spawn.server.ts +310 -0
- package/src/server/lib/terminal/attach-replay.test.ts +2 -2
- package/src/server/lib/terminal/output.test.ts +2 -2
- package/src/server/lib/terminal/output.ts +1 -1
- package/src/server/lib/terminal/resize.test.ts +99 -0
- package/src/server/lib/terminal/runtime.server.ts +26 -6
- package/src/server/lib/terminal/send-result.test.ts +18 -1
- package/src/server/lib/terminal/send-result.ts +26 -2
- package/src/server/lib/terminal/session.server.ts +6 -6
- package/src/server/lib/usage/new-api.test.ts +92 -0
- package/src/server/lib/usage/new-api.ts +131 -0
- package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
- package/src/server/lib/usage/provider-key.ts +33 -0
- package/src/server/lib/usage/providers.server.ts +10 -3
- package/src/server/lib/usage/vendor-balance.server.ts +4 -53
- package/src/server/lib/usage/vendor-http.ts +41 -0
- package/src/server/lib/usage/window.ts +55 -0
- package/src/server/routes/agent/command.ts +14 -1
- package/src/server/routes/agent/harness-command.ts +6 -0
- package/src/server/routes/agent/new.ts +15 -0
- package/src/server/routes/harness/add-provider.test.ts +9 -1
- package/src/server/routes/harness/import-action.ts +4 -0
- package/src/server/routes/harness/import.test.ts +1 -1
- package/src/server/routes/harness/index.ts +5 -1
- package/src/server/routes/harness/update-status.ts +26 -0
- package/src/server/routes/harness/update.test.ts +119 -0
- package/src/server/routes/harness/update.ts +59 -147
- package/src/server/routes/sessions/answer.ts +24 -0
- package/src/server/routes/sessions/batch-delete.ts +11 -5
- package/src/server/routes/sessions/delete.ts +4 -2
- package/src/server/routes/sessions/fork.ts +74 -0
- package/src/server/routes/sessions/index.ts +14 -0
- package/src/server/routes/sessions/relations.ts +85 -0
- package/src/server/routes/sessions/session.ts +4 -0
- package/src/server/routes/sessions/spawn.ts +134 -0
- package/src/server/routes/terminal/ws.ts +3 -3
- package/src/shared/lib/chat/composer/client.ts +31 -2
- package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
- package/src/shared/lib/chat/composer/delegation.ts +206 -0
- package/src/shared/lib/chat/notice-text.ts +1 -1
- package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
- package/src/shared/lib/code/ansi.ts +1 -1
- package/src/shared/lib/fonts/nerd-symbols.css +4 -3
- package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
- package/src/shared/lib/harness/provider-facts.test.ts +27 -0
- package/src/shared/lib/harness/providers.ts +35 -1
- package/src/shared/lib/harness/update-job.ts +33 -0
- package/src/shared/lib/harness/update-plan.test.ts +21 -6
- package/src/shared/lib/harness/update-plan.ts +12 -4
- package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
- package/src/shared/lib/omp/session/wait-idle.ts +12 -2
- package/src/shared/lib/theme/catalog.test.ts +13 -9
- package/src/shared/lib/theme/color.test.ts +2 -2
- package/src/shared/lib/theme/color.ts +4 -4
- package/src/shared/lib/theme/theme.test.ts +1 -1
- package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
- package/src/shared/lib/workspace/terminal/input.ts +33 -0
- package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
- package/src/shared/lib/workspace/terminal/keys.ts +7 -7
- package/src/shared/types/chat.ts +1 -1
- package/src/shared/types/harness-update.ts +65 -0
- package/src/shared/types/omp/agent.ts +19 -2
- package/src/shared/types/workspace.ts +4 -0
- package/src/test-support/fake-omp-fork.ts +16 -2
- package/src/test-support/harness-table.test-util.ts +15 -1
- package/dist/client/static/js/index-z3w7n85q.css +0 -1
- package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
- package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Fork a session: a new session that starts with the source's history.
|
|
8
|
+
*
|
|
9
|
+
* The two transports answer this differently, and neither is a rewrite of the
|
|
10
|
+
* source:
|
|
11
|
+
*
|
|
12
|
+
* - omp: copy the transcript, cut it at the anchor's turn start, rewrite the
|
|
13
|
+
* header id and title, write a new `<ts>_<id>.jsonl`, then resume that file.
|
|
14
|
+
* The source bytes are never touched.
|
|
15
|
+
* - ACP: ask the agent for `session/fork`. The agent owns the history, so the
|
|
16
|
+
* returned session id is the child; Kabmo records the source edge and does
|
|
17
|
+
* not pretend to hold a local transcript.
|
|
18
|
+
*
|
|
19
|
+
* A fork is NOT a child: it writes `source_session_id` + `origin_kind`, never
|
|
20
|
+
* `parent_session_id`, so it stays out of the parent tree and sends no outcome
|
|
21
|
+
* notification. A user can reparent it afterwards.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import * as path from 'node:path';
|
|
25
|
+
import { loadPersistedAccessMode } from '@/shared/lib/omp/config/access-mode.server';
|
|
26
|
+
import { startRpcSession } from '@/server/lib/omp/rpc/session-registry';
|
|
27
|
+
import { startAcpSession } from '@/server/lib/harness/spawn.server';
|
|
28
|
+
import { freshProbe } from '@/server/lib/harness/probe-cache.server';
|
|
29
|
+
import { clearSessionFileCaches } from '@/server/lib/omp/session/files';
|
|
30
|
+
import { findSessionFileById } from '@/server/lib/omp/session/locator';
|
|
31
|
+
import { buildTruncatedBody, isRewindCutPoint } from '@/server/lib/omp/session/rewind-file';
|
|
32
|
+
import {
|
|
33
|
+
branchTranscript,
|
|
34
|
+
completeLines,
|
|
35
|
+
parseJsonObject,
|
|
36
|
+
transcriptTitle,
|
|
37
|
+
} from '@/server/lib/omp/session/transcript-copy';
|
|
38
|
+
import type { HarnessId } from '@/shared/lib/harness/catalog';
|
|
39
|
+
import type { SelectedModel } from '@/shared/types/models';
|
|
40
|
+
import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
|
|
41
|
+
import {
|
|
42
|
+
createSessionRelation,
|
|
43
|
+
deleteSessionRelations,
|
|
44
|
+
listForkRelations,
|
|
45
|
+
} from '@/server/lib/sessions/relations.server';
|
|
46
|
+
import { isSessionArchived, resolveSessionRef, sessionExists } from '@/server/lib/sessions/resolve.server';
|
|
47
|
+
import {
|
|
48
|
+
agentEnvironment,
|
|
49
|
+
createAgentToken,
|
|
50
|
+
rememberAgentToken,
|
|
51
|
+
} from '@/server/lib/sessions/agent-token.server';
|
|
52
|
+
|
|
53
|
+
export type SessionForkErrorCode =
|
|
54
|
+
| 'source_not_found'
|
|
55
|
+
| 'source_archived'
|
|
56
|
+
| 'cwd_required'
|
|
57
|
+
| 'anchor_not_found'
|
|
58
|
+
| 'fork_unsupported'
|
|
59
|
+
| 'fork_requires_checkpoint'
|
|
60
|
+
| 'fork_failed';
|
|
61
|
+
|
|
62
|
+
export class SessionForkError extends Error {
|
|
63
|
+
constructor(
|
|
64
|
+
readonly code: SessionForkErrorCode,
|
|
65
|
+
message: string,
|
|
66
|
+
) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = 'SessionForkError';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface ForkedSession {
|
|
73
|
+
readonly sessionId: string;
|
|
74
|
+
send(command: Record<string, unknown>): Promise<unknown>;
|
|
75
|
+
destroyAndWait(): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ForkSessionDeps {
|
|
79
|
+
startRpc(
|
|
80
|
+
sessionId: string,
|
|
81
|
+
sessionFile: string,
|
|
82
|
+
cwd: string,
|
|
83
|
+
accessMode: ApprovalMode,
|
|
84
|
+
model: SelectedModel | null,
|
|
85
|
+
env: Record<string, string>,
|
|
86
|
+
): Promise<{ session: ForkedSession; realSessionId: string }>;
|
|
87
|
+
startAcp(request: {
|
|
88
|
+
harness: HarnessId;
|
|
89
|
+
sessionId: string;
|
|
90
|
+
forkAgentSessionId: string;
|
|
91
|
+
cwd: string;
|
|
92
|
+
accessMode: ApprovalMode;
|
|
93
|
+
model: SelectedModel | null;
|
|
94
|
+
thinkingLevel: string | null;
|
|
95
|
+
env: Record<string, string>;
|
|
96
|
+
}): Promise<{ session: ForkedSession; realSessionId: string }>;
|
|
97
|
+
probeForkSupported(harness: HarnessId): Promise<boolean>;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const defaultDeps: ForkSessionDeps = {
|
|
101
|
+
async startRpc(sessionId, sessionFile, cwd, accessMode, model, env) {
|
|
102
|
+
return startRpcSession(sessionId, sessionFile, cwd, cwd, accessMode, env, model ?? undefined);
|
|
103
|
+
},
|
|
104
|
+
startAcp: (request) => startAcpSession(request),
|
|
105
|
+
async probeForkSupported(harness) {
|
|
106
|
+
const probe = await freshProbe(harness);
|
|
107
|
+
return probe?.capabilities.forkSession === true;
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
export interface ForkSessionInput {
|
|
112
|
+
sourceSessionId: string;
|
|
113
|
+
/** A message/entry id; the fork cuts at the start of its turn. Omit for tip. */
|
|
114
|
+
anchorEntryId?: string | null;
|
|
115
|
+
prompt?: string | null;
|
|
116
|
+
title?: string | null;
|
|
117
|
+
cwd?: string | null;
|
|
118
|
+
visibility?: 'visible' | 'hidden';
|
|
119
|
+
lifecycleOwnerSessionId?: string | null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface ForkSessionResult {
|
|
123
|
+
sessionId: string;
|
|
124
|
+
sourceSessionId: string;
|
|
125
|
+
originKind: 'fork';
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The record index the cut lands on.
|
|
130
|
+
*
|
|
131
|
+
* An anchor on a user turn branches BEFORE it (that is "do not send this
|
|
132
|
+
* message"). An anchor anywhere else — an assistant reply, a tool call —
|
|
133
|
+
* branches AFTER the turn that contains it, so the reply the user pointed at is
|
|
134
|
+
* part of the fork. No anchor (or an id the file does not carry) is the tip.
|
|
135
|
+
*/
|
|
136
|
+
function cutIndexFor(records: Array<Record<string, unknown> | null>, anchorEntryId: string | null): number | null {
|
|
137
|
+
if (!anchorEntryId) return null;
|
|
138
|
+
const anchorIndex = records.findIndex((record) => record?.id === anchorEntryId);
|
|
139
|
+
if (anchorIndex === -1) return null;
|
|
140
|
+
|
|
141
|
+
let turnStart = -1;
|
|
142
|
+
for (let index = anchorIndex; index >= 0; index -= 1) {
|
|
143
|
+
if (isRewindCutPoint(records[index])) {
|
|
144
|
+
turnStart = index;
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (turnStart === -1) {
|
|
149
|
+
const headerIndex = records.findIndex((record) => record?.type === 'session');
|
|
150
|
+
return headerIndex === -1 ? 0 : headerIndex + 1;
|
|
151
|
+
}
|
|
152
|
+
if (isRewindCutPoint(records[anchorIndex])) return turnStart;
|
|
153
|
+
|
|
154
|
+
const nextTurn = records.findIndex(
|
|
155
|
+
(record, index) => index > anchorIndex && isRewindCutPoint(record),
|
|
156
|
+
);
|
|
157
|
+
return nextTurn === -1 ? records.length : nextTurn;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function newBranchTitle(sourceTitle: string, sourceSessionId: string, forkCount: number): string {
|
|
161
|
+
return `(${forkCount}) ${sourceTitle.trim() || sourceSessionId}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function writeBranchFile(input: {
|
|
165
|
+
sourceFile: string;
|
|
166
|
+
lines: string[];
|
|
167
|
+
newId: string;
|
|
168
|
+
timestamp: string;
|
|
169
|
+
title: string;
|
|
170
|
+
}): Promise<string> {
|
|
171
|
+
const body = branchTranscript({
|
|
172
|
+
lines: input.lines,
|
|
173
|
+
newId: input.newId,
|
|
174
|
+
timestamp: input.timestamp,
|
|
175
|
+
title: input.title,
|
|
176
|
+
parentSessionFile: input.sourceFile,
|
|
177
|
+
});
|
|
178
|
+
const fileName = `${input.timestamp.replace(/[:.]/g, '-')}_${input.newId}.jsonl`;
|
|
179
|
+
const target = path.join(path.dirname(input.sourceFile), fileName);
|
|
180
|
+
if (await Bun.file(target).exists()) {
|
|
181
|
+
throw new SessionForkError('fork_failed', `A session file already exists at ${fileName}`);
|
|
182
|
+
}
|
|
183
|
+
await Bun.write(target, body);
|
|
184
|
+
clearSessionFileCaches();
|
|
185
|
+
return target;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Fork a session at its tip or at an anchored turn. */
|
|
189
|
+
export async function forkSession(
|
|
190
|
+
input: ForkSessionInput,
|
|
191
|
+
deps: ForkSessionDeps = defaultDeps,
|
|
192
|
+
): Promise<ForkSessionResult> {
|
|
193
|
+
if (!(await sessionExists(input.sourceSessionId))) {
|
|
194
|
+
throw new SessionForkError('source_not_found', 'Source session not found');
|
|
195
|
+
}
|
|
196
|
+
if (await isSessionArchived(input.sourceSessionId)) {
|
|
197
|
+
throw new SessionForkError('source_archived', 'Cannot fork an archived session');
|
|
198
|
+
}
|
|
199
|
+
const source = await resolveSessionRef(input.sourceSessionId);
|
|
200
|
+
const cwd = input.cwd || source.cwd;
|
|
201
|
+
if (!cwd) throw new SessionForkError('cwd_required', 'The source has no working directory');
|
|
202
|
+
|
|
203
|
+
const accessMode = await loadPersistedAccessMode();
|
|
204
|
+
const token = createAgentToken();
|
|
205
|
+
const env = agentEnvironment(token);
|
|
206
|
+
const forkCount = (await listForkRelations(input.sourceSessionId)).length + 1;
|
|
207
|
+
const sourceFile = await findSessionFileById(input.sourceSessionId);
|
|
208
|
+
let started: { session: ForkedSession; realSessionId: string };
|
|
209
|
+
let createdFile: string | null = null;
|
|
210
|
+
|
|
211
|
+
if (sourceFile) {
|
|
212
|
+
const raw = await Bun.file(sourceFile).text();
|
|
213
|
+
const lines = completeLines(raw);
|
|
214
|
+
const records = lines.map((line) => parseJsonObject(line));
|
|
215
|
+
// An id the file does not carry is usually an overlay-only row (a builtin
|
|
216
|
+
// command's message). Silently forking at the tip would hand back history
|
|
217
|
+
// the user did not point at, so it is a refusal with a code.
|
|
218
|
+
if (input.anchorEntryId && !records.some((record) => record?.id === input.anchorEntryId)) {
|
|
219
|
+
throw new SessionForkError(
|
|
220
|
+
'anchor_not_found',
|
|
221
|
+
`The transcript has no entry ${input.anchorEntryId}`,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
const cutIndex = cutIndexFor(records, input.anchorEntryId ?? null);
|
|
225
|
+
const kept =
|
|
226
|
+
cutIndex === null
|
|
227
|
+
? lines
|
|
228
|
+
: completeLines(buildTruncatedBody(records, cutIndex).body);
|
|
229
|
+
const newId = crypto.randomUUID();
|
|
230
|
+
const timestamp = new Date().toISOString();
|
|
231
|
+
const title =
|
|
232
|
+
input.title?.trim() || newBranchTitle(transcriptTitle(lines), input.sourceSessionId, forkCount);
|
|
233
|
+
createdFile = await writeBranchFile({ sourceFile, lines: kept, newId, timestamp, title });
|
|
234
|
+
try {
|
|
235
|
+
started = await deps.startRpc(newId, createdFile, cwd, accessMode, null, env);
|
|
236
|
+
} catch (error) {
|
|
237
|
+
await Bun.file(createdFile).delete().catch(() => {});
|
|
238
|
+
throw new SessionForkError(
|
|
239
|
+
'fork_failed',
|
|
240
|
+
error instanceof Error ? error.message : 'Could not resume the fork',
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
} else {
|
|
244
|
+
const harness = source.harness;
|
|
245
|
+
if (!harness || harness === 'omp-rpc') {
|
|
246
|
+
throw new SessionForkError('fork_unsupported', 'This session has no transcript to fork');
|
|
247
|
+
}
|
|
248
|
+
if (!(await deps.probeForkSupported(harness))) {
|
|
249
|
+
throw new SessionForkError('fork_unsupported', `${harness} does not support session/fork`);
|
|
250
|
+
}
|
|
251
|
+
try {
|
|
252
|
+
started = await deps.startAcp({
|
|
253
|
+
harness,
|
|
254
|
+
sessionId: `__new__${Bun.randomUUIDv7()}`,
|
|
255
|
+
forkAgentSessionId: source.agentSessionId || input.sourceSessionId,
|
|
256
|
+
cwd,
|
|
257
|
+
accessMode,
|
|
258
|
+
model: null,
|
|
259
|
+
thinkingLevel: null,
|
|
260
|
+
env,
|
|
261
|
+
});
|
|
262
|
+
} catch (error) {
|
|
263
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
264
|
+
// zcode advertises session/fork but refuses until the workspace has a
|
|
265
|
+
// checkpoint. That is a state requirement, not a missing capability, and
|
|
266
|
+
// the user can satisfy it by making a change first.
|
|
267
|
+
if (/workspace checkpoint/i.test(detail)) {
|
|
268
|
+
throw new SessionForkError(
|
|
269
|
+
'fork_requires_checkpoint',
|
|
270
|
+
'This harness needs a workspace checkpoint before it can fork: make a change in the source session first.',
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
throw new SessionForkError('fork_failed', detail || 'The agent refused session/fork');
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
try {
|
|
278
|
+
await rememberAgentToken(started.realSessionId, token);
|
|
279
|
+
await createSessionRelation({
|
|
280
|
+
sessionId: started.realSessionId,
|
|
281
|
+
sourceSessionId: input.sourceSessionId,
|
|
282
|
+
originKind: 'fork',
|
|
283
|
+
lifecycleOwnerSessionId: input.lifecycleOwnerSessionId ?? null,
|
|
284
|
+
visibility: input.visibility ?? 'visible',
|
|
285
|
+
});
|
|
286
|
+
if (input.prompt?.trim()) {
|
|
287
|
+
await started.session.send({ type: 'prompt', message: input.prompt.trim() });
|
|
288
|
+
}
|
|
289
|
+
} catch (error) {
|
|
290
|
+
await started.session.destroyAndWait().catch(() => {});
|
|
291
|
+
await deleteSessionRelations(started.realSessionId).catch(() => {});
|
|
292
|
+
if (createdFile) await Bun.file(createdFile).delete().catch(() => {});
|
|
293
|
+
throw new SessionForkError(
|
|
294
|
+
'fork_failed',
|
|
295
|
+
error instanceof Error ? error.message : 'Could not record the fork',
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
return {
|
|
300
|
+
sessionId: started.realSessionId,
|
|
301
|
+
sourceSessionId: input.sourceSessionId,
|
|
302
|
+
originKind: 'fork',
|
|
303
|
+
};
|
|
304
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
7
|
+
import { isolateDb, releaseDb } from '@/test-support/isolated-db';
|
|
8
|
+
import { getDb } from '@/server/db.server';
|
|
9
|
+
import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
|
|
10
|
+
import { createSessionRelation } from '@/server/lib/sessions/relations.server';
|
|
11
|
+
import {
|
|
12
|
+
archiveDependents,
|
|
13
|
+
collectDependents,
|
|
14
|
+
dependentsDeepestFirst,
|
|
15
|
+
} from '@/server/lib/sessions/lifecycle.server';
|
|
16
|
+
|
|
17
|
+
beforeEach(async () => {
|
|
18
|
+
await isolateDb();
|
|
19
|
+
await ensureSessionRelationsSchema(await getDb());
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
afterEach(async () => {
|
|
23
|
+
await releaseDb();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('session lifecycle cascade', () => {
|
|
27
|
+
test('follows both the parent and the owner edge, once each', async () => {
|
|
28
|
+
await createSessionRelation({ sessionId: 'root' });
|
|
29
|
+
await createSessionRelation({ sessionId: 'child', parentSessionId: 'root' });
|
|
30
|
+
await createSessionRelation({
|
|
31
|
+
sessionId: 'grandchild',
|
|
32
|
+
parentSessionId: 'child',
|
|
33
|
+
lifecycleOwnerSessionId: 'root',
|
|
34
|
+
});
|
|
35
|
+
await createSessionRelation({
|
|
36
|
+
sessionId: 'worker',
|
|
37
|
+
lifecycleOwnerSessionId: 'root',
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const dependents = await collectDependents('root');
|
|
41
|
+
expect(new Set(dependents)).toEqual(new Set(['child', 'grandchild', 'worker']));
|
|
42
|
+
expect(dependents).toHaveLength(3);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('a fork is not a dependent of its source', async () => {
|
|
46
|
+
await createSessionRelation({ sessionId: 'root' });
|
|
47
|
+
await createSessionRelation({
|
|
48
|
+
sessionId: 'fork-1',
|
|
49
|
+
sourceSessionId: 'root',
|
|
50
|
+
originKind: 'fork',
|
|
51
|
+
});
|
|
52
|
+
expect(await collectDependents('root')).toEqual([]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('archiveDependents writes only the rows that were not archived', async () => {
|
|
56
|
+
await createSessionRelation({ sessionId: 'root' });
|
|
57
|
+
await createSessionRelation({ sessionId: 'child', parentSessionId: 'root' });
|
|
58
|
+
await createSessionRelation({ sessionId: 'grandchild', parentSessionId: 'child' });
|
|
59
|
+
const db = await getDb();
|
|
60
|
+
await db.run('INSERT INTO archived_sessions (session_id) VALUES (?)', ['child']);
|
|
61
|
+
|
|
62
|
+
expect(await archiveDependents('root')).toEqual(['grandchild']);
|
|
63
|
+
const rows = (await db.all('SELECT session_id FROM archived_sessions ORDER BY session_id')) as {
|
|
64
|
+
session_id: string;
|
|
65
|
+
}[];
|
|
66
|
+
expect(rows.map((row) => row.session_id)).toEqual(['child', 'grandchild']);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('deepest-first is the reverse of the walk', async () => {
|
|
70
|
+
await createSessionRelation({ sessionId: 'root' });
|
|
71
|
+
await createSessionRelation({ sessionId: 'child', parentSessionId: 'root' });
|
|
72
|
+
await createSessionRelation({ sessionId: 'grandchild', parentSessionId: 'child' });
|
|
73
|
+
expect(await dependentsDeepestFirst('root')).toEqual(['grandchild', 'child']);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The sessions that follow an owner into the archive, or out of existence.
|
|
8
|
+
*
|
|
9
|
+
* Two edges cascade and they are independent: the sidebar parent
|
|
10
|
+
* (`parent_session_id`) and cleanup ownership (`lifecycle_owner_session_id`).
|
|
11
|
+
* A session can be one without the other, and a fork is neither — a source edge
|
|
12
|
+
* never makes a session a dependent, so deleting or archiving a source leaves
|
|
13
|
+
* its forks alone.
|
|
14
|
+
*
|
|
15
|
+
* Collection is breadth-first with a visited set: the two edges may point at
|
|
16
|
+
* the same session, and a corrupted cycle must not hang a delete.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { getDb } from '@/server/db.server';
|
|
20
|
+
import { listChildRelations, listOwnedRelations } from '@/server/lib/sessions/relations.server';
|
|
21
|
+
|
|
22
|
+
/** Every dependent descendant, parents first, deduplicated, excluding the root. */
|
|
23
|
+
export async function collectDependents(sessionId: string): Promise<string[]> {
|
|
24
|
+
const seen = new Set<string>([sessionId]);
|
|
25
|
+
const ordered: string[] = [];
|
|
26
|
+
const queue = [sessionId];
|
|
27
|
+
while (queue.length > 0) {
|
|
28
|
+
const current = queue.shift();
|
|
29
|
+
if (!current) continue;
|
|
30
|
+
const [children, owned] = await Promise.all([
|
|
31
|
+
listChildRelations(current),
|
|
32
|
+
listOwnedRelations(current),
|
|
33
|
+
]);
|
|
34
|
+
for (const relation of [...children, ...owned]) {
|
|
35
|
+
const id = relation.sessionId;
|
|
36
|
+
if (seen.has(id)) continue;
|
|
37
|
+
seen.add(id);
|
|
38
|
+
ordered.push(id);
|
|
39
|
+
queue.push(id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return ordered;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Archive every dependent of a session. Returns the ids this call archived.
|
|
47
|
+
*
|
|
48
|
+
* Unarchiving is deliberately NOT the reverse: the reference product restores
|
|
49
|
+
* explicitly, owner first, because auto-restoring a fan-out would resurrect
|
|
50
|
+
* work the user archived one session at a time.
|
|
51
|
+
*/
|
|
52
|
+
export async function archiveDependents(sessionId: string): Promise<string[]> {
|
|
53
|
+
const dependents = await collectDependents(sessionId);
|
|
54
|
+
if (dependents.length === 0) return [];
|
|
55
|
+
const db = await getDb();
|
|
56
|
+
const archived: string[] = [];
|
|
57
|
+
for (const id of dependents) {
|
|
58
|
+
const result = await db.run(
|
|
59
|
+
'INSERT OR IGNORE INTO archived_sessions (session_id) VALUES (?)',
|
|
60
|
+
[id],
|
|
61
|
+
);
|
|
62
|
+
if (result.changes > 0) archived.push(id);
|
|
63
|
+
}
|
|
64
|
+
return archived;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Deepest-first, so a parent is removed after the sessions that name it. */
|
|
68
|
+
export async function dependentsDeepestFirst(sessionId: string): Promise<string[]> {
|
|
69
|
+
const dependents = await collectDependents(sessionId);
|
|
70
|
+
return dependents.reverse();
|
|
71
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Child outcomes: filtering, coalescing and the one queue row they become.
|
|
8
|
+
*
|
|
9
|
+
* The window is exercised through `materializeNotice` rather than by waiting
|
|
10
|
+
* two seconds; the timer itself is cancelled in `afterEach` so a suite does not
|
|
11
|
+
* leak a flush into the next case.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
15
|
+
import { isolateDb, releaseDb } from '@/test-support/isolated-db';
|
|
16
|
+
import { getDb } from '@/server/db.server';
|
|
17
|
+
import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
|
|
18
|
+
import {
|
|
19
|
+
createSessionRelation,
|
|
20
|
+
setParentNotifications,
|
|
21
|
+
} from '@/server/lib/sessions/relations.server';
|
|
22
|
+
import {
|
|
23
|
+
cancelNoticeTimer,
|
|
24
|
+
materializeNotice,
|
|
25
|
+
noteChildOutcome,
|
|
26
|
+
} from '@/server/lib/sessions/notify.server';
|
|
27
|
+
import { listQueue } from '@/server/lib/queue/store.server';
|
|
28
|
+
|
|
29
|
+
const parents = new Set<string>();
|
|
30
|
+
|
|
31
|
+
beforeEach(async () => {
|
|
32
|
+
parents.clear();
|
|
33
|
+
await isolateDb();
|
|
34
|
+
await ensureSessionRelationsSchema(await getDb());
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
afterEach(async () => {
|
|
38
|
+
for (const parent of parents) cancelNoticeTimer(parent);
|
|
39
|
+
await releaseDb();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
async function childOf(
|
|
43
|
+
sessionId: string,
|
|
44
|
+
parentSessionId: string,
|
|
45
|
+
preference?: 'auto' | 'stuck' | 'off',
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
await createSessionRelation({ sessionId, parentSessionId });
|
|
48
|
+
if (preference) await setParentNotifications(sessionId, preference);
|
|
49
|
+
parents.add(parentSessionId);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
describe('child outcome notices', () => {
|
|
53
|
+
test('two children collapse into one row, not two turns', async () => {
|
|
54
|
+
await childOf('c1', 'p');
|
|
55
|
+
await childOf('c2', 'p');
|
|
56
|
+
await noteChildOutcome({ sessionId: 'c1', status: 'completed', output: 'first done' });
|
|
57
|
+
await noteChildOutcome({ sessionId: 'c2', status: 'completed', output: 'second done' });
|
|
58
|
+
|
|
59
|
+
const text = await materializeNotice('p');
|
|
60
|
+
expect(text).toContain('Child session updates');
|
|
61
|
+
expect(text).toContain('c1');
|
|
62
|
+
expect(text).toContain('c2');
|
|
63
|
+
expect(await listQueue('p')).toHaveLength(1);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test('a repeated outcome for one child replaces the earlier line', async () => {
|
|
67
|
+
await childOf('c1', 'p');
|
|
68
|
+
await noteChildOutcome({ sessionId: 'c1', status: 'interrupted' });
|
|
69
|
+
await noteChildOutcome({ sessionId: 'c1', status: 'completed', output: 'finished later' });
|
|
70
|
+
|
|
71
|
+
const text = await materializeNotice('p');
|
|
72
|
+
expect(text).not.toBeNull();
|
|
73
|
+
if (text === null) throw new Error('expected a notice');
|
|
74
|
+
expect(text).toContain('completed');
|
|
75
|
+
expect(text).not.toContain('interrupted');
|
|
76
|
+
expect(text.match(/c1/g)).toHaveLength(1);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('off writes nothing; stuck skips a completed turn', async () => {
|
|
80
|
+
await childOf('quiet', 'p', 'off');
|
|
81
|
+
await noteChildOutcome({ sessionId: 'quiet', status: 'completed', output: 'x' });
|
|
82
|
+
expect(await materializeNotice('p')).toBeNull();
|
|
83
|
+
|
|
84
|
+
await childOf('stuck-child', 'p', 'stuck');
|
|
85
|
+
await noteChildOutcome({ sessionId: 'stuck-child', status: 'completed', output: 'x' });
|
|
86
|
+
expect(await materializeNotice('p')).toBeNull();
|
|
87
|
+
|
|
88
|
+
await noteChildOutcome({ sessionId: 'stuck-child', status: 'failed', failure: 'boom' });
|
|
89
|
+
expect(await materializeNotice('p')).toContain('boom');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('a fork and a root session are both silent', async () => {
|
|
93
|
+
await createSessionRelation({
|
|
94
|
+
sessionId: 'fork-1',
|
|
95
|
+
sourceSessionId: 'source',
|
|
96
|
+
originKind: 'fork',
|
|
97
|
+
});
|
|
98
|
+
await createSessionRelation({ sessionId: 'root' });
|
|
99
|
+
await noteChildOutcome({ sessionId: 'fork-1', status: 'completed', output: 'x' });
|
|
100
|
+
await noteChildOutcome({ sessionId: 'root', status: 'completed', output: 'x' });
|
|
101
|
+
expect(await materializeNotice('source')).toBeNull();
|
|
102
|
+
expect(await materializeNotice('root')).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test('a second materialize cannot duplicate the row', async () => {
|
|
106
|
+
await childOf('c1', 'p');
|
|
107
|
+
await noteChildOutcome({ sessionId: 'c1', status: 'completed', output: 'done' });
|
|
108
|
+
expect(await materializeNotice('p')).not.toBeNull();
|
|
109
|
+
expect(await materializeNotice('p')).toBeNull();
|
|
110
|
+
expect(await listQueue('p')).toHaveLength(1);
|
|
111
|
+
});
|
|
112
|
+
});
|