Make Claude Code multiplayer. Collaborate on shared conversations and code, powered by DeltaDB.

Delta gives every agent thread a URL. With this plugin, your Claude Code sessions are recorded to Delta along with the Git checkout they work in. Anyone on your team can then open the thread and join it, from their own Claude Code session, from delta.dev, or from the Delta app.
You need Claude Code 2.1.303 or newer. Older versions show a warning but are not blocked. Inside Claude Code, add the marketplace:
/plugin marketplace add zed-industries/delta-claude
Then install the plugin:
/plugin install delta@zed-industries
The plugin uses the delta CLI. If it isn't installed on macOS, Linux, or Windows, the plugin installs it the first time you set up syncing, share, or join, and Delta offers to open your browser to sign in. You don't need to open the Delta app first. When Delta is missing on Windows, setup first asks you in Claude whether to install it. Only choosing Install Delta downloads and runs the official stable installer for your native architecture. Choosing Not now leaves it uninstalled; retry setup, share, or join when ready, or install from delta.dev. It uses the installer's default scope; approve a Windows permission prompt if one appears. If Windows requires a restart, restart before retrying setup. The plugin finds the installed CLI through the registry, without requiring a PATH refresh. Background discovery never installs Delta.
At startup the plugin checks an existing Delta installation for updates in the background, with a ten-second budget. It notifies you when an update is available; it never installs updates or opens a browser as part of this check. A failed check does not stop syncing or sharing.
Run /delta-update (or /delta update) to update the installed Delta app and CLI. A running Delta app, including the one serving synced and shared sessions, restarts to install the update; those sessions briefly disconnect and reconnect on their own, and an app that had a window reopens. On Windows, the installer runs after the Delta CLI exits, and the command waits up to ten more minutes for it; approve the Windows prompt if one appears. If Windows reports that a restart is required, restart Windows before using Delta. If the installer outlasts the wait, it keeps running; let it finish, then run delta update --check before retrying. Download and installation progress appears in the transcript while the command runs. This does not update the Claude plugin itself. The startup notice offers this command only when the CLI can install the update. Otherwise, follow the CLI's platform-specific instructions: for example, run the Windows installer, or update a package-managed installation through its package manager. Older CLIs that lack the update command point to delta.dev.
Run /delta-setup in a repository to choose its team and which sessions sync:
/delta-share.Setup can create a team and invite teammates by email. It saves your choice to .delta/settings.json and keeps that file out of Git, since the choice is yours.
The plugin offers setup once per repository: right after you install it, or the first time you start a session in a repository that isn't set up yet.
If automatic sync needs you to sign in, an interactive session asks before opening your browser. If Delta's beta terms still need accepting, it offers to open them too. You can keep working while you finish; that same session then syncs, including messages recorded while it waited. To stop waiting, run /delta-share again. Headless sessions never open a browser.
/delta-share asks who should see the session: your team, just you, or people you name by email address. /delta-share ada@example.com invites them directly.
Each command also works as /delta <command>, such as /delta share. /delta on its own opens a menu of these actions.
| Command | Description |
|---|---|
/delta-share [<email>…] | Sync the current session and its checkout, and choose who sees it |
/delta-join <link> | Join a shared thread in a fresh session, in the thread's checkout |
/delta-setup | Choose this repository's team and which sessions sync |
/delta-update | Update the installed Delta app and CLI |
/delta-org list | List your Delta teams |
/delta-org current | Show the selected team |
/delta-org switch <ID> | Select a different team |
/delta-org invite <email>… | Invite people to the selected team |
/delta-org manage | Open the selected team's members page on the dashboard |
Sharing and joining need an interactive Claude Code terminal or Desktop Code tab.
Delta stores what a recorded session contains: your conversation, including tool inputs and outputs and Claude's thinking, plus the files in your checkout (staged, unstaged, and untracked files that aren't ignored). Nothing is uploaded until you share or join a session, or the repository's setting syncs it automatically.
A shared or joined session shows you as connected through Claude Code. An open Delta view takes precedence.
The plugin sends product telemetry to Delta: which integration ran each command, the plugin version, and when turns start and finish and how they ended. Telemetry events contain no messages, file paths, tool inputs, or error text.
Live activity telemetry also identifies the external source and the command-line transport into Delta. It does not identify the person's interface. Several updates can belong to one tool call, so event rows are not counts of tool calls or edit operations. Historical imports do not produce these activity events.
Validate the plugin and run its tests:
claude plugin validate .
claude plugin validate .claude-plugin/plugin.json
claude plugin test .
npx --yes --package typescript@7.0.2 tsc -p . --verbatimModuleSyntax
python3 scripts/check-cli-setup.py
Run the shell setup check on macOS, Linux, or WSL. On Windows, also exercise the PowerShell installation orchestration with mocked downloads and installer processes:
powershell.exe -NoLogo -NoProfile -NonInteractive -File scripts/check-windows-setup.ps1
The type check reads the declarations Claude Code writes into .claude-plugin/types/ whenever it loads this folder, as claude --plugin-dir . below does.
To try your changes, start Claude Code with the plugin loaded from this checkout:
claude --plugin-dir .
Copyright (C) 2026 Zed Industries.
Licensed under the GNU Affero General Public License, version 3 only (AGPL-3.0-only). See LICENSE.
hooks/register.tsx 215 lines1import type { HookFailure, On } from 'claude-code'
2import {
3 activate, beginCaptureDecision, decideCapture, forgetSessionStart, newSessionFor, rememberSessionStart,
4 rememberTranscript, reportedStart, startSession,
5} from './setup/activation'
6import { clearProgress, drawBand, forgetBarTheme } from './band/band'
7import {
8 DELTA_USAGE, deltaMenu, installationUpdates, installUpdateHost, JOIN_USAGE, ORG_USAGE, registerCommands,
9 runDeltaCommand,
10} from './setup/commands'
11import { claudeVersionWarning } from './core/compatibility'
12import { completeTurn, recordRow, recordToolCall, startTurn } from './recording/delivery'
13import { forgetContract } from './cli/delta-cli'
14import { withQuestionHints } from './setup/interaction'
15import { releaseOnEnd } from './sharing/join'
16import { admitPrompt } from './recording/prompt'
17import { showAnswer, shownItemId } from './watch/row-delivery'
18import { drawEcho, drawRow } from './watch/rows'
19import {
20 activation, cancelRequestsOf, endActivationOf, forgetRuntime, forgetTranscriptPath, markEnded, report, requests,
21 resetRuntime, type Runtime, stateFor,
22} from './core/session-state'
23import {
24 children, completeChildTurn, createSubagentWorktree, forgetSubagents, recordChildRow, recordChildToolCall,
25 recordsChildren, recordSpawn, removeSubagentWorktree, startChildTurn,
26} from './subagents/subagents'
27import { errorText } from './core/text'
28import { forgetThreadNotes, sendToThread } from './subagents/thread-runs'
29import { forgetTitleReader, recordTitle } from './recording/title'
30import { stopWatching } from './watch/watch'
31
32/**
33 * Write why a hook failed to the debug log, for its `.catch` handler. Every hook but `prompt.submit`
34 * fails open: Claude goes on as if Delta were not installed, so recording can never block a
35 * person's work. A re-entry is no failure, and a handler's own `$` calls reject during one.
36 */
37async function logHookFailure($: Runtime, hook: string, failure: HookFailure) {
38 // Claude Code before 2.1.306 also reports a re-entry here, which is no failure.
39 if (failure.kind !== 'throw' && failure.kind !== 'timeout') return
40 try { await $.ui.log(`Delta's ${hook} hook failed (${failure.kind}): ${failure.message ?? 'no detail'}`, { to: 'debug' }) }
41 // The log is best effort; the handler's answer does not depend on it.
42 catch {}
43}
44
45export function register(on: On) {
46 on('prompt.submit', ($, e, next) => admitPrompt($, e, next)).catch(async ($, e, next) => {
47 await logHookFailure($, 'prompt.submit', next.error)
48 return { drop: 'Delta could not safely prepare this shared turn. Retry after the watcher is ready.' }
49 })
50
51 on('agent.spawn', ($, e, next) => recordSpawn($, e, next))
52 .catch(async ($, e, next) => { await logHookFailure($, 'agent.spawn', next.error); return next(e) })
53
54 on('classic.WorktreeCreate', ($, e, next) => createSubagentWorktree($, e, next))
55 .catch(async ($, e, next) => { await logHookFailure($, 'classic.WorktreeCreate', next.error); return next(e) })
56
57 on('classic.WorktreeRemove', ($, e, next) => removeSubagentWorktree($, e, next))
58 .catch(async ($, e, next) => { await logHookFailure($, 'classic.WorktreeRemove', next.error); return next(e) })
59
60 // Claude 2.1.299+ raises turn.start inside a child agent's or teammate's own loop, with `agentId`
61 // set. That loop is not the shared conversation: only the main loop's turns may bind
62 // `currentTurnId` or open an execution. A recorded subagent's turn is its own thread's.
63 on('turn.start', ($, e, next) => e.agentId !== undefined
64 ? startChildTurn($, e, e.agentId, next) : startTurn($, e, next))
65
66 on('turn.complete', ($, e, next) => e.agentId !== undefined
67 ? completeChildTurn($, e, e.agentId, next) : completeTurn($, e, next))
68
69 on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => drawBand($, e, next))
70
71 // The plugin's own questions draw a hint beside each option, as the option's description.
72 on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
73 const questions = withQuestionHints(e.props.questions)
74 return next(questions ? { ...e, props: { ...e.props, questions } } : e)
75 })
76
77 // The plugin's own `show` echo, which Desktop draws as a user row.
78 on('ui.render', { component: 'UserMessage' }, ($, e, next) => drawEcho($, e, next))
79
80 on('ui.render', { component: 'CommandOutput' }, ($, e, next) => drawRow($, e, next))
81 on('session.end', async ($, e, next) => {
82 const session = e.sessionId
83 await forgetSessionStart($, session)
84 cancelRequestsOf(session, e.reason)
85 forgetSubagents(session)
86 endActivationOf(session)
87 const runtime = stateFor(session)
88 resetRuntime(runtime)
89 await stopWatching(session)
90 forgetContract(session)
91 forgetTitleReader(session)
92 forgetThreadNotes(session)
93 // A joined or shared session keeps reporting through its transition; an ordinary end clears it.
94 if (!requests.join && !requests.share) clearProgress($)
95 forgetRuntime(session, runtime)
96 await markEnded($, session)
97 await releaseOnEnd($, session, e.reason, runtime)
98 // Last, since the hand-off check in releaseOnEnd still reads it.
99 forgetTranscriptPath(session)
100 return next(e)
101 })
102
103 // A changed theme changes the status bar's shade.
104 on('config.set', { key: 'theme' }, async ($, e, next) => {
105 const result = await next(e)
106 forgetBarTheme()
107 $.ui.invalidate('ui.render')
108 return result
109 }).catch(async ($, e, next) => { await logHookFailure($, 'config.set', next.error); return next(e) })
110
111 on('session.start', async ($, e, next) => {
112 const version = await $.session.version().catch(() => undefined)
113 const warning = claudeVersionWarning(version?.base ?? version?.version)
114 if (warning) await $.ui.log(warning, { to: 'transcript' })
115 await registerCommands($)
116 const result = await next(e)
117 $.clock.after(0, () => { void installationUpdates.check(installUpdateHost($)) })
118 const session = await $.session.id()
119 try { await activate($, session) }
120 catch (error) { await report($, error) }
121 // Claude delivers the first prompt only after this hook returns, so a session started for a
122 // hand-off finishes joining here, and its opening line meets a joined session. Waiting in
123 // `prompt.submit` instead would count the join against that hook's 10-second budget, while
124 // the Delta commands the join runs here are `$` calls, which that budget never counts. The
125 // claim reports its own failure.
126 await stateFor(session).handoffClaim
127 // Claude reports a session's start (`classic.SessionStart`) just before this hook, but not to a
128 // plugin enabled in a running session, as right after `/plugin install`. Such a session is
129 // offered setup now rather than at the next startup or `/clear`. The check waits a tick, so a
130 // start report that arrives just after this hook still counts, and a session that ended meanwhile
131 // is offered nothing.
132 $.clock.after(0, () => {
133 if (activation.session !== session || reportedStart(session) || requests.join) return
134 void startSession($, session, true).catch((error) => { void report($, error) })
135 })
136 return result
137 })
138
139 // Claude names a session in its transcript file, not through any hook, so the title is read there
140 // when a turn ends: the title Claude chose for the first prompt, or a `/rename` made since.
141 on('classic.Stop', async ($, e, next) => {
142 const result = await next(e)
143 // A path not remembered now is reported again at the next turn's end.
144 if (typeof e.transcript_path === 'string' && e.transcript_path)
145 void $.session.id().then((session) => rememberTranscript($, session, e.transcript_path)).catch(() => {})
146 // The turn's end never waits for the title, and nothing about the title can fail it.
147 if (typeof e.transcript_path === 'string' && e.transcript_path)
148 void $.session.id().then((session) => recordTitle($, session, e.transcript_path)).catch(() => {})
149 return result
150 }).catch(async ($, e, next) => { await logHookFailure($, 'classic.Stop', next.error); return next(e) })
151
152 on('classic.SessionStart', async ($, e, next) => {
153 rememberSessionStart(e.session_id, typeof e.source === 'string' ? e.source : '',
154 typeof e.transcript_path === 'string' && e.transcript_path ? e.transcript_path : undefined)
155 // A new session's capture boundary opens before anything can reach a hook, and `startSession`
156 // resolves it once the policy and contract decision is made.
157 if (newSessionFor(e.session_id)) beginCaptureDecision(e.session_id)
158 const result = await next(e)
159 if (requests.join) {
160 // A join runs its own transition and never auto-activates, so nothing waits on this session.
161 decideCapture(e.session_id)
162 return result
163 }
164 try { await activate($, e.session_id) }
165 catch (error) { await report($, error) }
166 // Only a new session (startup or clear) is auto-activated; a resume, compaction, or fork keeps
167 // whatever policy it had. The offer and activation never delay a prompt.
168 $.clock.after(0, () => { void startSession($, e.session_id).catch((error) => { void report($, error) }) })
169 return result
170 }).catch(async ($, e, next) => { await logHookFailure($, 'classic.SessionStart', next.error); return next(e) })
171
172 on('command.run', { command: 'delta' }, async ($, e) => {
173 const action = e.args.trim()
174 // The plugin's own rows reach this handler, and nothing else: a person who types the internal
175 // form gets the usage text below. The argument is an item id, never content.
176 const internal = shownItemId(action)
177 // A plugin's own run reads this plugin's name; anyone else who types the internal form is a
178 // person or another plugin, and gets the usage text below.
179 if (internal !== undefined && e.origin?.kind === 'plugin' && e.origin.name === $.plugin.name)
180 return { text: showAnswer(internal) }
181 if (!action) return deltaMenu($, 'menu', DELTA_USAGE, 'delta_subcommand')
182 return runDeltaCommand($, action, 'delta_subcommand')
183 })
184 on('command.run', { command: 'delta-share' }, async ($, e) => runDeltaCommand($, `share ${e.args.trim()}`.trim(), 'dedicated_command'))
185 // Typed without its argument, a command asks for it instead of failing.
186 on('command.run', { command: 'delta-join' }, async ($, e) => e.args.trim()
187 ? runDeltaCommand($, `join ${e.args.trim()}`, 'dedicated_command')
188 : deltaMenu($, 'join', JOIN_USAGE, 'dedicated_command'))
189 on('command.run', { command: 'delta-setup' }, async ($, e) => runDeltaCommand($, `setup ${e.args.trim()}`.trim(), 'dedicated_command'))
190 on('command.run', { command: 'delta-update' }, async ($, e) => runDeltaCommand($, `update ${e.args.trim()}`.trim(), 'dedicated_command'))
191 on('command.run', { command: 'delta-org' }, async ($, e) => e.args.trim()
192 ? runDeltaCommand($, `org ${e.args.trim()}`, 'dedicated_command')
193 : deltaMenu($, 'team', ORG_USAGE, 'dedicated_command'))
194
195 on('session.append', ($, e, next) => e.agentId !== undefined
196 ? recordChildRow($, e, e.agentId, next) : recordRow($, e, next))
197 .catch(async ($, e, next) => { await logHookFailure($, 'session.append', next.error); return next(e) })
198
199 on('session.send', async ($, e, next) => {
200 const session = await $.session.id()
201 if (typeof e.to !== 'string' || !recordsChildren(session)) return next(e)
202 const sender = e.agentId !== undefined && children.has(e.agentId) ? e.agentId : session
203 try {
204 const sent = await sendToThread($, session, sender, e.to, e.text, (to, text) => next({ ...e, to, text }))
205 return sent ?? await next(e)
206 } catch (error) {
207 return { isDelivered: false, reason: `Delta could not run that thread here: ${errorText(error)}` }
208 }
209 }).catch(async ($, e, next) => { await logHookFailure($, 'session.send', next.error); return next(e) })
210
211 on('tool.call', ($, e, next) => e.agentId !== undefined
212 ? recordChildToolCall($, e, e.agentId, next) : recordToolCall($, e, next))
213 .catch(async ($, e, next) => { await logHookFailure($, 'tool.call', next.error); return next(e) })
214}
215hooks/setup/activation.ts 667 lines1/**
2 * Starting a session's recording: activating its binding, continuing a conversation Claude Code moved
3 * to a new session, the setup offer, automatic recording from the repository's policy, and pruning.
4 */
5import { AccessRequiredError, requireAuthentication } from '../cli/auth'
6import { clearProgress, finishProgress, setProgress, type SyncReminder } from '../band/band'
7import { childKey } from '../subagents/children'
8import {
9 collectAcknowledgedOutbox, drain, endDeliveryFailures, recordsOffline, recoverExecution, scheduleOutboxCleanup,
10} from '../recording/delivery'
11import { CONTRACT_TIMEOUT_MS, requireContract, resolveCli, threadCreate } from '../cli/delta-cli'
12import { authenticationHost, claudeInteraction, notifyOnce, setupEnv } from './interaction'
13import { attachWorktree, beginRestoreCheckout, checkoutNeedsMount, mountCheckout } from '../sharing/checkout'
14import { beginRestore, claimHandoff, pendingHandoff, startParticipation } from '../sharing/join'
15import { hasInteractiveSurface } from '../sharing/lifecycle'
16import { listOrganizations, organizationName } from './organizations'
17import { policyPath, type ProjectPolicy, readProjectPolicy, recordsAutomatically } from './project-policy'
18import {
19 activation, type AutoUpload, type Binding, boundDirectory, drawnRowKey, isPaused, key, ledgerKey, load, pauseCheckout,
20 producerOf, rememberTranscriptPath, report, requests, resumeCheckout, type Runtime, save, serial, sessions,
21 type SessionState, stateFor, stillActive, storedBinding, transcriptPathOf,
22} from '../core/session-state'
23import { offerOnboarding, type OnboardingStore, releaseOnboarding } from './setup'
24import { checkoutRoot, joinedBindingAt } from '../sharing/share'
25import { storedChildBinding } from '../subagents/subagents'
26import {
27 classifyCommandFailure, ContractRefusalError, DeltaCommandError, permanentFailureAdvice,
28} from '../cli/thread-commands'
29import { errorText } from '../core/text'
30import { restoreChildren } from '../subagents/thread-runs'
31import { FS_READ_LIMIT, readFrom } from '../recording/title'
32import { followUpload, startConversation, stopConversation } from '../watch/watch'
33
34/** The plugin's folder under Claude's configuration, shared by every Claude process on the machine. */
35export let pluginData = ''
36/** Where recorded conversations stage their records, under the plugin's folder. */
37export let outbox = ''
38
39/** Automatic activation has not finished: the binding exposes its thread only once every step succeeded. */
40export function activationIncomplete(runtime: SessionState): boolean {
41 return !!runtime.binding?.autoUpload && !runtime.binding.thread
42}
43
44/**
45 * A prompt or a resume is an automatic session's repair path: re-run whatever activation steps are
46 * missing, using the upload the session already recorded. Every step is idempotent, so this is safe.
47 */
48export function retryAutomaticActivation($: Runtime, session: string, runtime: SessionState) {
49 const binding = runtime.binding
50 // The activation reports its own failures in the band, and the next prompt retries it.
51 if (binding?.autoUpload && !binding.thread && binding.checkout)
52 void activateAutomatically($, session, binding.checkout, binding.autoUpload).catch(() => {})
53}
54
55export async function activate($: Runtime, session: string, isCurrent = () => true) {
56 const epoch = ++activation.epoch
57 const ownsActivation = () => epoch === activation.epoch && isCurrent()
58 activation.activating = session
59 try {
60 const home = await $.env.get('HOME') ?? await $.env.get('USERPROFILE')
61 const config = await $.env.get('CLAUDE_CONFIG_DIR') ?? (home ? `${home}/.claude` : undefined)
62 if (!ownsActivation()) return
63 if (!config) throw new Error('Cannot locate Claude configuration; set CLAUDE_CONFIG_DIR.')
64 pluginData = `${config}/delta-plugin`
65 outbox = `${pluginData}/outbox`
66 if (activation.session !== session) await stopConversation()
67 if (!ownsActivation()) return
68 activation.session = session
69 let binding = await serial(() => load($, session))
70 if (!ownsActivation()) return
71 // A session that resumes is live again: drop the end marker so bounded cleanup never removes it.
72 if (binding.endedAt !== undefined) {
73 const live = { ...binding }
74 delete live.endedAt
75 await serial(() => save($, live))
76 binding = live
77 }
78 // A conversation Claude Code moved here from a recording session keeps recording, here.
79 if (continuationCandidate(session, binding)) {
80 const parent = await continuedFrom($, session)
81 if (!ownsActivation()) return
82 if (parent) binding = await adoptContinuation($, session, parent.session) ?? binding
83 if (!ownsActivation()) return
84 }
85 const runtime = stateFor(session)
86 runtime.binding = binding
87 runtime.captureFailure ??= binding.captureFailure
88 if (binding.joinTransition) {
89 await report($, new Error(`The join directory transition is incomplete. Run /delta-join ${binding.joinTransition.locator} to retry the saved mount${binding.directory ? ` at ${binding.directory}` : ''}; prompts remain blocked.`))
90 return
91 }
92 // A session Desktop started in a hand-off's folder joins it before its first prompt.
93 if (!binding.snapshot && !binding.joined && !runtime.handoffClaim) {
94 const handoff = await pendingHandoff($, await $.session.cwd())
95 if (!ownsActivation()) return
96 if (handoff) {
97 runtime.handoffClaim = claimHandoff($, session, handoff)
98 return
99 }
100 }
101 endDeliveryFailures(runtime)
102 scheduleOutboxCleanup($, binding)
103 // Bounded store retention: entries for sessions that ended long ago are pruned only when they
104 // hold nothing a later session would need. It never blocks activation.
105 void pruneStore($).catch(() => {})
106 // An automatic session whose activation never finished, for example because Delta was unreachable
107 // when it started, resumes that activation rather than waiting for a thread it does not have yet.
108 if (activationIncomplete(runtime)) {
109 retryAutomaticActivation($, session, runtime)
110 return
111 }
112 // A shared session's own checkout stays synchronized only while this process runs its mount.
113 const needsCheckoutMount = checkoutNeedsMount(session, binding)
114 if (binding.snapshot && boundDirectory(binding)) {
115 pauseCheckout(runtime, 'watcher')
116 try { await requireContract($, session) }
117 catch (error) {
118 if (!ownsActivation()) return
119 const text = `Delta participation is blocked: ${errorText(error)}`
120 // Only an explicit /delta share or /delta join after updating Delta lifts this pause.
121 pauseCheckout(runtime, 'delivery', text)
122 runtime.joinFailure = text
123 setProgress($, text, 'error')
124 await $.ui.log(text, { to: 'transcript' })
125 return
126 }
127 // A session whose mounts this process has not confirmed is resuming: Claude may be anywhere.
128 if (binding.joined && !runtime.mounted) {
129 beginRestore($, session)
130 return
131 }
132 }
133 if (needsCheckoutMount) {
134 beginRestoreCheckout($, session)
135 return
136 }
137 if (binding.snapshot && boundDirectory(binding)) {
138 if (recordsOffline(session, binding)) {
139 // Offline recording does not wait for the watcher: start it in the background and let a
140 // prompt or the outbox proceed meanwhile.
141 resumeCheckout(runtime, 'watcher')
142 void startConversation($, session).catch((error) => { if (ownsActivation()) void report($, error) })
143 } else {
144 try { await startParticipation($, session, binding, ownsActivation) }
145 catch (error) { if (ownsActivation()) await report($, error) }
146 }
147 // An automatic session follows Delta's background upload on its own timer, so the link appears
148 // even when the watcher never becomes ready.
149 if (ownsActivation() && binding.autoUpload) followUpload($, session)
150 if (ownsActivation() && !isPaused(runtime)) await recoverExecution($, session)
151 }
152 if (ownsActivation() && !runtime.captureFailure && binding.thread && binding.pending.length)
153 void drain($, session).catch((error) => report($, error))
154 if (ownsActivation() && binding.children?.length)
155 void restoreChildren($, session, binding).catch((error) => report($, error))
156 } finally {
157 if (epoch === activation.epoch) activation.activating = ''
158 }
159}
160
161/** Resume the recovery steps activation skipped while it waited for a mount. */
162export async function finishRestoredActivation($: Runtime, session: string, binding: Binding, owns: () => boolean) {
163 const runtime = stateFor(session)
164 if (binding.autoUpload) followUpload($, session)
165 if (!isPaused(runtime)) await recoverExecution($, session)
166 if (!owns()) return
167 if (!runtime.captureFailure && binding.pending.length)
168 void drain($, session).catch((error) => report($, error))
169 if (binding.children?.length)
170 void restoreChildren($, session, binding).catch((error) => report($, error))
171}
172
173/** The source `classic.SessionStart` reported for each session, until the session ends. */
174const sessionSources = new Map<string, string>()
175
176/** Remember what Claude reported when a session started: how it started, and its transcript. */
177export function rememberSessionStart(session: string, source: string, transcript: string | undefined) {
178 sessionSources.set(session, source)
179 if (transcript) rememberTranscriptPath(session, transcript)
180}
181
182/** Whether Claude reported this session's start, which it does not to a plugin enabled mid-session. */
183export function reportedStart(session: string): boolean {
184 return sessionSources.has(session)
185}
186
187/** A session that ended forgets how it started and its open setup offer, and releases its capture boundary. */
188export async function forgetSessionStart($: Runtime, session: string) {
189 sessionSources.delete(session)
190 // A setup offer still open when its session ends was never decided, so the next session offers it again.
191 const offer = openOnboarding.get(session)
192 openOnboarding.delete(session)
193 if (offer) {
194 try { await releaseOnboarding(onboardingStore($), offer) }
195 catch { /* the offer then simply stays consumed, as before */ }
196 }
197 // A session that ended can never reach its capture boundary; release anything held on it.
198 decideCapture(session)
199}
200
201/** How much of a transcript's end is searched for the record of a continuation. */
202const CONTINUATION_WINDOW_BYTES = 64 * 1024
203/** A session that ended longer ago than this is not the one a starting session continues. */
204const CONTINUATION_HORIZON_MS = 10 * 60 * 1000
205
206/**
207 * The session a transcript says its conversation continued in. Claude Code appends a
208 * `continued-in` record when it moves a conversation to a background session (`/background`, or
209 * opening the agents overview), and the new session starts with a copy under a new ID. The record
210 * is undocumented and written on a best-effort basis, so its absence proves nothing.
211 */
212async function continuationOf($: Runtime, transcript: string): Promise<string | undefined> {
213 const { size } = await $.fs.stat(transcript)
214 let text = ''
215 try { await readFrom($, transcript, Math.max(0, size - CONTINUATION_WINDOW_BYTES), (piece) => { text += piece }) }
216 catch {
217 if (size > FS_READ_LIMIT) return
218 text = await $.fs.read(transcript) as string
219 }
220 let continuation: string | undefined
221 for (const line of text.split('\n')) {
222 if (!line.includes('"continued-in"')) continue
223 try {
224 const row = JSON.parse(line)
225 if (row?.type === 'continued-in' && typeof row.continuedInSessionId === 'string') continuation = row.continuedInSessionId
226 } catch { /* a partial first line from the window, or another row */ }
227 }
228 return continuation
229}
230
231/**
232 * Whether `session` may continue another session's conversation: Claude Code reports a
233 * continuation's start as a `fork` of the conversation, and it has recorded nothing of its own.
234 */
235export function continuationCandidate(session: string, binding: Binding): boolean {
236 return sessionSources.get(session) === 'fork' && !binding.thread && !binding.snapshot && !binding.joinTransition
237}
238
239/** The recording session whose conversation Claude Code continued as `session`, if any. */
240export async function continuedFrom($: Runtime, session: string): Promise<Binding | undefined> {
241 // A Claude build without `$.store.keys` cannot enumerate the store; the continuation goes unrecorded.
242 let keys: string[]
243 try { keys = await $.store.keys() } catch { return }
244 const now = await $.clock.now()
245 for (const storeKey of keys) {
246 if (!storeKey.startsWith('session:') || storeKey === key(session)) continue
247 const candidate = await storedBinding($, storeKey)
248 if (!candidate?.thread || !candidate.snapshot) continue
249 if (candidate.continuedIn === session) return candidate
250 if (candidate.continuedIn || !candidate.transcript) continue
251 if (candidate.endedAt !== undefined && candidate.endedAt < now - CONTINUATION_HORIZON_MS) continue
252 try { if (await continuationOf($, candidate.transcript) === session) return candidate }
253 catch { /* an unreadable transcript continues nothing */ }
254 }
255}
256
257/**
258 * Make `session` the recorder of the conversation it continues: it takes over the binding, keeps
259 * recording as the same producer from the same sequence, and keeps the mount owner, so restoring
260 * re-mounts the same checkouts under this process. The parent is marked first; from then on it
261 * stages and delivers nothing, so the two never write the same sequence.
262 */
263export async function adoptContinuation($: Runtime, session: string, parentSession: string): Promise<Binding | undefined> {
264 return serial(async () => {
265 const current = await load($, session)
266 if (current.thread || current.snapshot) return
267 const parent = await load($, parentSession)
268 if (!parent.thread || (parent.continuedIn && parent.continuedIn !== session)) return
269 await save($, { ...parent, continuedIn: session })
270 const adopted: Binding = {
271 ...parent, session, producer: producerOf(parent),
272 owner: parent.joined ? parent.owner ?? parent.session : parent.owner,
273 transcript: transcriptPathOf(session),
274 }
275 delete adopted.continuedIn
276 delete adopted.endedAt
277 // Subagent bindings are stored under the session that ran them, which keeps delivering them.
278 delete adopted.children
279 // The copied transcript already shows the remote items the parent added for Claude.
280 const ledger = await $.store.get(ledgerKey(parentSession))
281 if (ledger !== undefined && await $.store.get(ledgerKey(session)) === undefined)
282 await $.store.set(ledgerKey(session), ledger)
283 await save($, adopted)
284 await $.ui.log(`Delta: this conversation continued from Claude session ${parentSession}; recording carries on in this session.`, { to: 'debug' })
285 return adopted
286 })
287}
288
289/** Keep a recording session's transcript path current, since a `/cd` can move the file. */
290export async function rememberTranscript($: Runtime, session: string, transcript: string) {
291 if (!rememberTranscriptPath(session, transcript)) return
292 await serial(async () => {
293 const current = await load($, session)
294 if (current.thread && !current.continuedIn) await save($, current)
295 })
296}
297
298/** Whether this session's conversation moved to another session, which now owns its mounts. */
299export async function handedOff($: Runtime, session: string): Promise<boolean> {
300 const binding = await storedBinding($, key(session))
301 if (!binding?.thread) return false
302 if (binding.continuedIn) return true
303 const transcript = transcriptPathOf(session) ?? binding.transcript
304 if (!transcript) return false
305 let continuation: string | undefined
306 try { continuation = await continuationOf($, transcript) } catch { return false }
307 if (!continuation || continuation === session) return false
308 // Marking here lets the continuation adopt even before its own start finds the record.
309 await serial(async () => save($, { ...await load($, session), continuedIn: continuation }))
310 return true
311}
312
313export function newSessionFor(session: string): boolean {
314 const source = sessionSources.get(session)
315 return source === 'startup' || source === 'clear'
316}
317
318/**
319 * A new session's capture boundary: row capture, `prompt.submit`, and `turn.start` wait on this until
320 * the policy and contract decision is made. Before the decision the session holds no snapshot, so
321 * activity let through early would be dropped; the promise resolves for every outcome, including a
322 * refusal, and the contract check that bounds it is itself bounded by `CONTRACT_TIMEOUT_MS`.
323 */
324type CaptureDecision = { promise: Promise<void>; resolve: () => void }
325const captureDecisions = new Map<string, CaptureDecision>()
326
327/** Open the capture boundary for a session that is about to decide whether it records automatically. */
328export function beginCaptureDecision(session: string) {
329 if (captureDecisions.has(session)) return
330 let resolve!: () => void
331 const promise = new Promise<void>((yes) => { resolve = yes })
332 captureDecisions.set(session, { promise, resolve })
333}
334
335/** Resolve the boundary once made, whatever the outcome; a second call is harmless. */
336export function decideCapture(session: string) {
337 captureDecisions.get(session)?.resolve()
338 captureDecisions.delete(session)
339}
340
341/** Hold new-session activity until its capture boundary exists, or nothing when there is none. */
342export async function captureDecided(session: string): Promise<void> {
343 await captureDecisions.get(session)?.promise
344}
345
346/**
347 * Read a checkout's policy at a session's start: show a policy problem once, auto-activate a new
348 * session when the policy records automatically, and offer setup when nothing configures the repo.
349 * A running session the plugin was just loaded into (`loadedMidSession`) is offered setup like a
350 * new one but never auto-activated, since part of it already happened unrecorded.
351 * Everything here runs off the startup hook's critical path.
352 */
353export async function startSession($: Runtime, session: string, loadedMidSession = false) {
354 const env = setupEnv($)
355 const newSession = newSessionFor(session)
356 let root: string
357 let policy: ProjectPolicy
358 try {
359 try { root = await checkoutRoot($) }
360 // Outside a checkout there is nothing to record or offer.
361 catch { return }
362 const path = policyPath(root)
363 try { policy = readProjectPolicy(await env.readFile(path)).policy }
364 catch (error) {
365 await notifyOnce($, `Delta settings at ${path} couldn't be read (${errorText(error)}). Until it's fixed, only sessions you share with /delta-share sync.`)
366 return
367 }
368 if (policy.problem)
369 await notifyOnce($, `Delta settings at ${path} couldn't be used (${policy.problem}). Until it's fixed, only sessions you share with /delta-share sync. Run /delta-setup to replace it.`)
370 if (newSession && recordsAutomatically(policy) && await joinedBindingAt($, root))
371 await notifyOnce($, `${root} is a worktree of a Delta thread a Claude session joined, so this session isn't recorded automatically. Run /delta-join with that thread's link to record in it.`)
372 else if (newSession && recordsAutomatically(policy))
373 await activateAutomatically($, session, root,
374 { mode: policy.mode === 'private' ? 'private' : 'organization', organization: policy.organization! })
375 } finally {
376 // Nothing below records, so the session's activity never waits on the setup offer's dialog.
377 decideCapture(session)
378 }
379 // Headless sessions get no reminder and are never offered setup; only an interactive surface shows them.
380 if (!hasInteractiveSurface(await $.session.surfaces())) return
381 stateFor(session).reminder = syncReminder(policy)
382 $.ui.invalidate('ui.render')
383 try {
384 await offerOnboarding(env, claudeInteraction($), onboardingStore($), {
385 root, configured: policy.configured, newToPlugin: newSession || loadedMidSession,
386 joined: !!stateFor(session).binding?.joined, joining: !!requests.join,
387 }, (key) => { openOnboarding.set(session, key) })
388 } finally {
389 openOnboarding.delete(session)
390 }
391 // A setup the offer opened may have saved a setting; the band follows it.
392 await refreshReminder($, session)
393}
394
395/** Re-read the checkout's setting after a setup, so the band's reminder follows what was saved. */
396export async function refreshReminder($: Runtime, session: string) {
397 try {
398 const root = await checkoutRoot($)
399 stateFor(session).reminder = syncReminder(readProjectPolicy(await setupEnv($).readFile(policyPath(root))).policy)
400 } catch { /* outside a checkout or unreadable: the band keeps what it had */ }
401 $.ui.invalidate('ui.render')
402}
403
404/** The onboarding marker each session's still-open setup offer holds, cleared if the session ends first. */
405const openOnboarding = new Map<string, string>()
406
407function onboardingStore($: Runtime): OnboardingStore {
408 return {
409 get: (key) => $.store.get(key),
410 set: (key, value) => $.store.set(key, value).then(() => undefined),
411 }
412}
413
414/**
415 * The band's reminder for a session while Delta does not sync it: a checkout with any setting points
416 * to /delta-share, and one never set up to /delta-setup. A syncing session's band says `Syncing`
417 * instead, so an automatic checkout's sessions show this only when they are not syncing, as a session
418 * started before the setting was saved, or one Delta could not start.
419 */
420function syncReminder(policy: ProjectPolicy): SyncReminder {
421 // Someone who chose a setting is not nudged toward setup every session.
422 return policy.configured ? 'manual' : 'not set up'
423}
424
425/** Auto-activations already running in this process, so a repeated startup hook cannot create twice. */
426export const autoActivating = new Map<string, Promise<void>>()
427
428/**
429 * Create the thread a repository's policy asks for, request its upload intent, attach the checkout,
430 * and start recording. Nothing drains or verifies the checkout until create, upload, and attach have
431 * all succeeded: only then is the binding's thread and checkout made visible, so a row or prompt that
432 * arrives mid-activation sees a session that is still simply local. Creation is idempotent by
433 * external id, so an interrupted activation is safely re-run — from the next prompt, or a startup.
434 *
435 * The session's capture boundary is released once the contract gate and snapshot are settled, before
436 * any network step, so a prompt or turn that arrives during create or attach is recorded
437 * rather than dropped. Every await re-checks ownership: a session that ended, or that switched away
438 * while a step was pending, leaves no half-initialized binding behind.
439 */
440function activateAutomatically($: Runtime, session: string, root: string, upload: AutoUpload): Promise<void> {
441 const running = autoActivating.get(session)
442 if (running) return running
443 const ownsActivation = stillActive(session)
444 const task = (async () => {
445 const runtime = stateFor(session)
446 if (activation.session !== session || requests.join) return
447 const existing = await serial(() => load($, session))
448 if (!ownsActivation()) return
449 // A session that already holds a thread, or a binding that is not ours, is never re-created.
450 if (existing.thread || (existing.snapshot && !existing.autoUpload) || existing.joined || existing.joinTransition) return
451 // A fresh session checks the account against the policy alongside the contract, so a repository
452 // this account cannot record to is reported before anything is staged.
453 const misconfiguration = existing.snapshot ? undefined : policyMisconfiguration($, upload.organization)
454 try {
455 // Refuse an incompatible CLI before persisting anything, so it leaves the session manual rather
456 // than holding a half-initialized automatic binding.
457 await requireContract($, session)
458 if (!ownsActivation()) return
459 const refusal = await misconfiguration
460 if (!ownsActivation()) return
461 const interactive = hasInteractiveSurface(await $.session.surfaces())
462 if (!ownsActivation()) return
463 if (refusal && !(refusal === SIGNED_OUT_REFUSAL && interactive)) {
464 await stopAutomaticRecording($, session, root, refusal)
465 return
466 }
467 // The session is new, so its snapshot is already taken: no history is exported, and live capture
468 // starts with the first row. The intent is durable before any network, so a session whose server
469 // is briefly unavailable retries from the next prompt. No thread or checkout is published yet,
470 // so nothing drains against a checkout that is not attached or a thread that is not uploaded.
471 if (!existing.snapshot) {
472 const staged: Binding = { session, snapshot: true, next: 1, pending: [], checkout: root, autoUpload: upload }
473 await serial(() => save($, staged))
474 runtime.binding = staged
475 }
476 if (!ownsActivation()) return
477 // The snapshot exists now, so new-session activity may pass; the network steps stay asynchronous.
478 decideCapture(session)
479 if (interactive) {
480 // Authentication may wait on the browser for minutes. Capture locally first, so the person
481 // can keep working and this same session uploads everything once sign-in finishes.
482 const check = async () => {
483 if (!ownsActivation()) throw new Error('Delta automatic sign-in stopped')
484 }
485 try {
486 await requireAuthentication(await authenticationHost($), await resolveCli($), check, async (text) => {
487 await check()
488 setProgress($, 'Waiting for Delta sign-in…', 'active')
489 await $.ui.log(text, { to: 'transcript' })
490 }, '/delta-share')
491 } catch (error) {
492 if (!ownsActivation()) return
493 // A cancelled or failed login needs an explicit retry, never another browser on each prompt.
494 await stopAutomaticRecording($, session, root, {
495 band: 'Not syncing: Delta sign-in incomplete · /delta-share',
496 // An access requirement already says nothing was synced and how to retry.
497 transcript: error instanceof AccessRequiredError ? error.message
498 : `${errorText(error)} This session isn't syncing. Run /delta-share to retry.`,
499 })
500 return
501 }
502 if (!ownsActivation()) return
503 if (refusal === SIGNED_OUT_REFUSAL) {
504 // Only the signed-in account can answer which organizations it belongs to.
505 const afterSignIn = await policyMisconfiguration($, upload.organization)
506 if (!ownsActivation()) return
507 if (afterSignIn) {
508 await stopAutomaticRecording($, session, root, afterSignIn)
509 return
510 }
511 }
512 }
513 setProgress($, 'Connecting this session to Delta…', 'active')
514 const created = await threadCreate($, {
515 externalId: session, organization: { id: upload.organization, visibility: upload.mode },
516 })
517 if (!ownsActivation()) return
518 const reference = await attachWorktree($, root, created.thread_id, existing.checkoutReference, undefined, session)
519 if (!ownsActivation()) return
520 await serial(async () => save($, { ...await load($, session), checkoutReference: reference, pendingWorktree: undefined }))
521 await mountCheckout($, { session, checkout: root, checkoutReference: reference }, async () => {
522 if (!ownsActivation()) throw new Error('The session ended while its checkout was being mounted')
523 })
524 if (!ownsActivation()) return
525 // Every step succeeded: now the thread and checkout become visible to drain and verification.
526 await serial(async () => save($, {
527 ...await load($, session), thread: created.thread_id, checkout: root, checkoutReference: reference,
528 }))
529 if (!ownsActivation()) return
530 runtime.binding = await serial(() => load($, session))
531 void startConversation($, session).catch((error) => { if (ownsActivation()) void report($, error) })
532 void drain($, session).catch((error) => { if (ownsActivation()) void report($, error) })
533 // The band now follows Delta's background upload until Delta confirms it, whether or not the
534 // watcher becomes ready: a status read is what reports the thread's link.
535 clearProgress($)
536 followUpload($, session)
537 } catch (error) {
538 if (!ownsActivation()) return
539 // Retrying cannot change a permanent answer, so the session stops recording instead of queuing
540 // records that would never be sent.
541 if (classifyCommandFailure(error) === 'permanent') {
542 await stopAutomaticRecording($, session, root, activationRefusal(error, upload.organization))
543 return
544 }
545 // Only a staged session gets this far: everything before staging fails permanently.
546 const text = `Delta couldn't start syncing this session: ${errorText(error)}. Nothing is lost; Delta retries on your next prompt.`
547 setProgress($, text, 'error')
548 await notifyOnce($, text)
549 }
550 })()
551 autoActivating.set(session, task)
552 void task.finally(() => { if (autoActivating.get(session) === task) autoActivating.delete(session) })
553 return task
554}
555
556/** What the band and the transcript say when a repository's policy cannot record this session. */
557type ActivationRefusal = { band: string; transcript: string }
558
559const SIGNED_OUT_REFUSAL: ActivationRefusal = {
560 band: 'Not syncing: sign in with `delta auth login`',
561 transcript: "This repository syncs Claude Code sessions to DeltaDB, but Delta is signed out, so this session isn't syncing. Sign in with `delta auth login`; new sessions then sync automatically.",
562}
563
564function notMemberRefusal(organization: string): ActivationRefusal {
565 const name = organizationName(organization)
566 return {
567 band: "Not syncing: your Delta account isn't in this repo's team · /delta-share",
568 transcript: `This repository syncs sessions to ${name ? `${name} (${organization})` : organization}, which your Delta account isn't a member of, so this session isn't syncing. Use /delta-share to share it with your own team, ask to be added to ${name ?? 'that team'}, or run /delta-setup if the settings name the wrong team.`,
569 }
570}
571
572/**
573 * Check the signed-in account against the organization a policy records to. Only a definite answer
574 * refuses: an empty or unreadable list (Delta not running, memberships not loaded yet) lets
575 * activation proceed, and `thread create` checks membership again.
576 */
577async function policyMisconfiguration($: Runtime, organization: string): Promise<ActivationRefusal | undefined> {
578 try {
579 // Bounded like the contract check it runs beside, since new-session activity waits on both.
580 const organizations = await listOrganizations($, CONTRACT_TIMEOUT_MS)
581 if (organizations.length && !organizations.some((known) => known.id === organization))
582 return notMemberRefusal(organization)
583 } catch (error) {
584 if (error instanceof DeltaCommandError && error.code === 'authentication_required') return SIGNED_OUT_REFUSAL
585 }
586}
587
588/** Describe a permanent activation failure, recognizing the account problems a person can fix. */
589function activationRefusal(error: unknown, organization: string): ActivationRefusal {
590 if (error instanceof DeltaCommandError && error.reason === 'organization_not_member') return notMemberRefusal(organization)
591 if (error instanceof DeltaCommandError && error.code === 'authentication_required') return SIGNED_OUT_REFUSAL
592 if (error instanceof ContractRefusalError)
593 return { band: `Not syncing: ${error.message}`, transcript: `This session isn't syncing: ${error.message}.` }
594 const advice = error instanceof DeltaCommandError
595 ? permanentFailureAdvice(error.code, true, error.reason) : 'Fix the cause, then start a new session'
596 return {
597 band: `Not syncing: ${advice}`,
598 transcript: `Delta couldn't start syncing this session: ${errorText(error)}. This session isn't syncing. ${advice}.`,
599 }
600}
601
602/**
603 * End automatic recording for a session the policy cannot record: drop any staged binding and its
604 * outbox, so the session is simply manual again and nothing retries or grows, then report why. A
605 * later /delta share exports the whole conversation from Claude's transcript, so nothing is lost.
606 *
607 * The band shows the refusal for the whole session. The transcript explains it once per repository
608 * and refusal, remembered in the store, so every new session in a misconfigured repository stays quiet.
609 */
610async function stopAutomaticRecording($: Runtime, session: string, root: string, refusal: ActivationRefusal) {
611 await serial(async () => {
612 const binding = await load($, session)
613 if (!binding.autoUpload || binding.thread) return
614 await $.store.delete(key(session))
615 const runtime = stateFor(session)
616 runtime.binding = await load($, session)
617 runtime.cleanedThrough = undefined
618 // Inside `serial`, so a share that starts next cannot stage a record this removal deletes. The
619 // outbox is only disk, so a failed removal leaves orphans, never a wrong binding.
620 try { await collectAcknowledgedOutbox($, { session, root: outbox, next: binding.next, pending: [] }) }
621 catch (error) {
622 try { await $.ui.log(`Delta outbox removal after stopping automatic recording failed: ${String(error)}`, { to: 'debug' }) }
623 catch { /* the debug log is best effort; the orphaned files harm nothing */ }
624 }
625 })
626 finishProgress($, refusal.band, 'error')
627 const marker = `auto-refused:${await setupEnv($).gitCommonDir() ?? root}`
628 try {
629 if (await $.store.get(marker) === refusal.transcript) return
630 await $.store.set(marker, refusal.transcript)
631 } catch { /* an unreadable marker only repeats the explanation */ }
632 await $.ui.log(refusal.transcript, { to: 'transcript' })
633}
634
635/** How long after a session really ends its store entries may be removed; resuming into them dies past it. */
636const STORE_HORIZON_MS = 30 * 24 * 60 * 60 * 1000
637
638/**
639 * Remove the store entries (`session:` binding and `appended:` ledger) of sessions that really ended
640 * before the horizon and hold nothing a later session would need. A binding without an end marker may
641 * be live in another Claude process, so it is never removed, and neither is any session in use here.
642 *
643 * The store is shared by every Claude process and has no transactions, so each session is read,
644 * checked, and deleted in turn: a resume elsewhere can only be lost in that one read-to-delete window.
645 */
646async function pruneStore($: Runtime) {
647 // A Claude build without `$.store.keys` cannot enumerate the store, so retention is skipped there.
648 let keys: string[]
649 try { keys = await $.store.keys() } catch { return }
650 const now = await $.clock.now()
651 const ids = new Set(keys.flatMap((storeKey) => /^(?:session|appended):(.+)$/.exec(storeKey)?.[1] ?? []))
652 for (const id of ids) {
653 if (sessions.has(id)) continue
654 const binding = await storedBinding($, key(id))
655 if (typeof binding?.endedAt !== 'number' || binding.endedAt > now - STORE_HORIZON_MS ||
656 binding.pending?.length || binding.captureFailure || binding.joinTransition) continue
657 // A subagent's undelivered records keep its session, like the session's own.
658 const recorded = await Promise.all((binding.children ?? []).map((agentId) =>
659 storedChildBinding($, id, agentId)))
660 if (recorded.some((child) => child?.pending.length)) continue
661 for (const agentId of binding.children ?? []) await $.store.delete(childKey(id, agentId))
662 await $.store.delete(key(id))
663 await $.store.delete(ledgerKey(id))
664 for (const storeKey of keys) if (storeKey.startsWith(drawnRowKey(id, ''))) await $.store.delete(storeKey)
665 }
666}
667hooks/band/band.tsx 425 lines1/**
2 * The band above the prompt: what it says about the watched thread, a running share or join, sync
3 * reminders, and its spinner, reconnect and copied-link timers.
4 */
5import type { RenderSurface, TextProps, Timer } from 'claude-code'
6import { conversationWebLink, itemAuthor, THOUGHT_KIND, toolCallParts } from '../watch/conversation'
7import {
8 currentOrganizationId, isPersonalOrganizationId, loadOrganizationDirectory, organizationName,
9} from '../setup/organizations'
10import {
11 activation, type Binding, type HookEvent, type HookNext, report, requests, type Runtime, sessions,
12} from '../core/session-state'
13import {
14 copyText, personColor, personKey, renderBand, SPINNER_FRAMES, type StatusSegment, statusSpinnerRunning,
15 type StatusState,
16} from './status'
17import type { WatchItem } from '../cli/thread-commands'
18import { feed, presence, watchStatus, watchedSession, type RemoteTurn } from '../watch/watch'
19import { drainMessages } from '../watch/rows'
20import { beginRefusalResolution } from '../recording/delivery'
21import { beginShare } from '../sharing/share'
22
23/** A share or join that the band is reporting: running, finished, or failed. */
24type ProgressTone = 'active' | 'done' | 'error'
25/** A share's or join's line in the band: what it says, how it went, and which of its steps it is on. */
26export type Progress = { text: string; tone: ProgressTone; step?: [number, number] }
27
28/**
29 * What the band keeps of its own: the running share's or join's line, held through the operation and
30 * briefly after success, and the band's timers. A watcher restart ends the timers but keeps the line.
31 */
32const bandState: {
33 progress?: Progress
34 /** Clears a finished operation's line; cancelled on teardown and by the next operation. */
35 progressTimer?: Timer
36 /** The animation's frame and redraw timer, live only while a live watch has a running turn. */
37 spinner?: { frame: number; timer: Timer }
38 /** The link was just copied; the timer clears the confirmation. */
39 copiedTimer?: Timer
40} = {}
41
42/** The share or join line the band shows now, if any. */
43export function reportedProgress(): Progress | undefined {
44 return bandState.progress
45}
46
47/** A watcher restart ends the band's timers; a running share or join keeps its line, only its timer ends. */
48export function stopBandTimers() {
49 bandState.copiedTimer?.cancel()
50 bandState.copiedTimer = undefined
51 stopSpinner()
52 bandState.progressTimer?.cancel()
53 bandState.progressTimer = undefined
54}
55/** The band's animation: one braille cycle, redrawn within the engine's per-site throttle. */
56const SPINNER_INTERVAL_MS = 120
57/** How long a finished share or join stays in the band before clearing. */
58const BAND_NOTICE_MS = 4_000
59/** How long another participant's running turn may go without any activity before the band calls it quiet. */
60const QUIET_AFTER_MS = 30_000
61/** A remote thought or tool call shows as what its agent is doing once open this long, so a burst of quick calls does not flicker. */
62const SHOW_ACTIVITY_AFTER_MS = 500
63/** How long the band confirms a copied link. */
64const COPIED_MS = 2_000
65
66/** Drop a finished operation's notice so the band can show what happened next. */
67export function clearDoneNotice() {
68 if (bandState.progress?.tone !== 'done') return
69 bandState.progressTimer?.cancel()
70 bandState.progressTimer = undefined
71 bandState.progress = undefined
72}
73
74/** Run the band's redraw timer only while a live watch has a running turn, or an operation runs. */
75export function syncSpinner($: Runtime) {
76 if (!spinnerRunning()) return stopSpinner()
77 if (bandState.spinner) return
78 const timer = $.clock.every(SPINNER_INTERVAL_MS, () => {
79 const spinner = bandState.spinner
80 if (!spinner || spinner.timer !== timer) return
81 spinner.frame = (spinner.frame + 1) % SPINNER_FRAMES.length
82 $.ui.invalidate('ui.render')
83 })
84 bandState.spinner = { frame: 0, timer }
85}
86
87/** A running share or join animates wherever it runs; a turn animates only on a live watch. */
88function spinnerRunning() {
89 return statusSpinnerRunning({ ...feed, connection: watchStatus().actual, progress: currentProgress() })
90}
91
92function stopSpinner() {
93 bandState.spinner?.timer.cancel()
94 bandState.spinner = undefined
95}
96
97/** Record what a share or join is doing and redraw; the band's animation follows it. */
98export function setProgress($: Runtime, text: string, tone: ProgressTone, step?: [number, number]) {
99 bandState.progressTimer?.cancel()
100 bandState.progressTimer = undefined
101 bandState.progress = { text, tone, step }
102 syncSpinner($)
103 $.ui.invalidate('ui.render')
104}
105
106/** Finish an operation: a success clears after BAND_NOTICE_MS, a failure stays until replaced. */
107export function finishProgress($: Runtime, text: string, tone: 'done' | 'error') {
108 setProgress($, text, tone)
109 if (tone !== 'done') return
110 const timer = $.clock.after(BAND_NOTICE_MS, () => {
111 if (bandState.progressTimer !== timer) return
112 bandState.progressTimer = undefined
113 bandState.progress = undefined
114 syncSpinner($)
115 $.ui.invalidate('ui.render')
116 })
117 bandState.progressTimer = timer
118}
119
120/** Drop an operation's band line, as a torn-down session does. */
121export function clearProgress($: Runtime) {
122 bandState.progressTimer?.cancel()
123 bandState.progressTimer = undefined
124 bandState.progress = undefined
125 syncSpinner($)
126 $.ui.invalidate('ui.render')
127}
128
129/**
130 * Whether the band has a Delta status to draw: a live watch, a share or join step, a failure, or the
131 * reminder of a session Delta does not sync.
132 */
133function statusShown(): boolean {
134 return !!watchedSession() || !!bandState.progress || !!watchStatus().error || !!activeReminder()
135}
136
137/** How the band reminds a session Delta does not sync, by the checkout's setting. */
138export type SyncReminder = 'manual' | 'not set up'
139const REMINDERS: Record<SyncReminder, { text: string; command: string }> = {
140 manual: { text: 'Not syncing', command: '/delta-share' },
141 'not set up': { text: 'Not set up', command: '/delta-setup' },
142}
143
144/**
145 * The active session's reminder, while the band has nothing else to say. A running share or join,
146 * a failure, or an unfinished join takes its place, and a syncing session's band says `Syncing`
147 * instead, so the band always shows the current state.
148 */
149function activeReminder(): { text: string; command: string } | undefined {
150 const runtime = sessions.get(activation.session)
151 if (!runtime?.reminder || currentProgress() || watchStatus().error || runtime.binding?.joinTransition) return
152 return REMINDERS[runtime.reminder]
153}
154
155/**
156 * What another participant's turn is doing: its newest thought or tool call open long enough to
157 * show, how long that has been open, and how many of its other calls are.
158 */
159function remoteActivity(remote: RemoteTurn, now: number): NonNullable<StatusState['agent']>['doing'] {
160 const shown = [...feed.openSince].flatMap(([id, since]) => {
161 const item = feed.view?.items.get(id)
162 const current = !remote.turnId || !item?.turn_id || item.turn_id === remote.turnId
163 return item?.open && current && (item.kind === 'tool_call' || item.kind === THOUGHT_KIND) &&
164 now - since >= SHOW_ACTIVITY_AFTER_MS ? [{ item, since }] : []
165 })
166 const newest = shown.reduce<typeof shown[number] | undefined>(
167 (latest, entry) => !latest || entry.since >= latest.since ? entry : latest, undefined)
168 if (!newest) return
169 const tool = newest.item.kind === 'tool_call'
170 return {
171 text: tool ? toolCallParts(newest.item).name : 'thinking', tool,
172 seconds: (now - newest.since) / 1000,
173 more: shown.filter((entry) => entry !== newest && entry.item.kind === 'tool_call').length,
174 }
175}
176
177/** What the band shows, at the moment it draws. */
178async function statusView($: Runtime): Promise<StatusState> {
179 const session = watchedSession()
180 const state = session ? sessions.get(session) : undefined
181 const watch = watchStatus()
182 const remote = feed.turn.state === 'remote' ? feed.remoteTurn : undefined
183 const now = await $.clock.now()
184 const since = remote?.since ?? now
185 const silent = now - (remote?.heard ?? since)
186 // A turn with an item still open, such as a long command, is working however long it is silent.
187 const open = [...feed.view?.items.values() ?? []].some((item) => item.open)
188 const doing = remote ? remoteActivity(remote, now) : undefined
189 const binding = state?.binding
190 // The visibility label names an organization; read the directory once, and a later redraw fills it.
191 if (binding?.visibility) void loadOrganizationDirectory($)
192 return {
193 ...feed,
194 // A staged automatic session records before its watch starts, while the band shows its connection step.
195 recording: !!sessions.get(session ?? activation.session)?.binding?.snapshot,
196 reminder: activeReminder(),
197 // Within the grace after a drop, the band carries on as if the watch were live.
198 connection: watch.connection,
199 reconnecting: watch.reconnecting,
200 error: watch.error,
201 deliveryPause: state?.pauses.get('delivery') ?? state?.pauses.get('verification'),
202 retryReason: state?.retryTimer ? state.retryReason : undefined,
203 progress: currentProgress(),
204 spinner: bandState.spinner,
205 link: statusLink(),
206 audience: audienceLabel(binding),
207 // A refused offline thread keeps its controls until the person forks the changes or discards them.
208 conflict: state?.refusedOffline ? { fork: 'Fork & Restore', discard: 'Discard' } : undefined,
209 // Sharing waits for Claude's turn to finish, so the control says so rather than ignoring a press.
210 // A personal organization has nobody to share with, so its threads offer no share control.
211 share: binding?.visibility === 'private' && !isPersonalOrganizationId(threadOrganization(binding) ?? currentOrganizationId ?? '') ? {
212 label: requests.shareAfterTurn?.session === activation.session && state?.currentTurnId ? 'Sharing after this turn'
213 : state?.currentTurnId ? 'Share after this turn'
214 : `Share with ${organizationName(threadOrganization(binding)) ?? 'organization'}`,
215 } : undefined,
216 people: presence.roster(),
217 children: feed.children,
218 childrenStale: watch.actual !== 'live',
219 agent: remote ? {
220 seconds: (now - since) / 1000,
221 ...!open && silent >= QUIET_AFTER_MS ? { quiet: silent / 1000 } : {},
222 ...doing ? { doing } : {},
223 } : undefined,
224 copied: !!bandState.copiedTimer,
225 }
226}
227
228/**
229 * Who can see the thread, apart from whether it has a link: `Synced with <org>` for a thread only
230 * its owner sees (a private one, or any in a personal organization, which has no other members),
231 * `Shared with <org>`, or `Unlisted`.
232 */
233function audienceLabel(binding: Binding | undefined): string | undefined {
234 if (!binding?.visibility) return undefined
235 if (binding.visibility === 'unlisted') return 'Unlisted'
236 const organization = threadOrganization(binding) ?? currentOrganizationId
237 const name = organizationName(organization) ?? 'your team'
238 return binding.visibility === 'private' || isPersonalOrganizationId(organization ?? '')
239 ? `Synced with ${name}` : `Shared with ${name}`
240}
241
242/**
243 * The organization a session's thread uploads to. The organization the plugin created the thread
244 * under names it, since the CLI's status can report none even for a thread created with one.
245 * Undefined for a thread shared without a saved team, or joined, which the caller names by the
246 * current organization.
247 */
248export function threadOrganization(binding: Binding): string | undefined {
249 return binding.autoUpload?.organization ?? binding.organization ?? binding.upload?.organization_id ?? undefined
250}
251
252/**
253 * Delta's background upload of an automatic session, drawn on the band's row like a share's steps:
254 * its first upload until Delta confirms it, then only a failure. Activation only requests the upload,
255 * and Delta registers the thread a moment before it confirms the content, so the link is offered
256 * once the upload is confirmed; later per-turn syncs are not shown.
257 */
258function uploadProgress(binding: Binding | undefined): StatusState['progress'] {
259 if (!binding?.autoUpload || !binding.thread) return undefined
260 const upload = binding.upload
261 if (upload?.state === 'failed')
262 return { text: `Sync failed: ${upload.error?.message ?? upload.error?.reason ?? 'unknown reason'}`, tone: 'error' }
263 if (binding.uploaded) return undefined
264 // Delta reports a failure it retries itself as queued with its error, which is progress, not a failure.
265 if (upload?.state === 'queued' && upload.error)
266 return { text: `Retrying sync: ${upload.error.message || upload.error.reason || upload.error.code}`, tone: 'active' }
267 return { text: upload?.state === 'queued' ? 'Waiting to sync…' : 'Syncing to DeltaDB…', tone: 'active' }
268}
269
270/** The operation the band draws: a share, join, or activation step, else an automatic session's upload. */
271function currentProgress(): StatusState['progress'] {
272 const session = watchedSession()
273 return bandState.progress ?? uploadProgress(session ? sessions.get(session)?.binding : undefined)
274}
275
276/**
277 * The shared thread's link: the watched session's saved binding, which every status inspection keeps
278 * current. A URL says a thread exists, not that others can see it; the audience is shown apart.
279 * Absent until status reports one, and while a share or join still runs the band shows it dim, without
280 * offering it.
281 */
282function statusLink(): string | undefined {
283 const session = watchedSession()
284 if (!session) return
285 return conversationWebLink(sessions.get(session)?.binding?.url)
286}
287
288/** The status bar's shade for each kind of theme: a step off the terminal's own background. */
289const BAR_SHADES = { dark: '#303030', light: '#e8e8e8' }
290/** The shade for the person's theme, read once and again whenever they change it. */
291let barTheme: keyof typeof BAR_SHADES | undefined
292
293/** A changed theme changes the shade; the next draw reads it again. */
294export function forgetBarTheme() {
295 barTheme = undefined
296}
297
298/**
299 * The status bar's shade for the person's theme. A terminal that cannot show it as given rounds it
300 * to a color it has; at worst the shade is lost and the band reads as a plain row.
301 */
302async function barShade($: Runtime): Promise<string> {
303 if (!barTheme) {
304 const theme = (await $.config.list()).find((row) => row.key === 'theme')?.value
305 barTheme = typeof theme === 'string' && theme.startsWith('light') ? 'light' : 'dark'
306 }
307 return BAR_SHADES[barTheme]
308}
309
310/** Copy the link to the surface the press came from, and confirm it only once the clipboard took it. */
311async function copyLink($: Runtime, link: string, surface: RenderSurface) {
312 const result = await $.ui.copy({ text: link, surface })
313 if (!result.isCopied) {
314 await $.ui.log(`Delta: couldn't copy the link: ${result.reason}`, { to: 'debug' })
315 return
316 }
317 bandState.copiedTimer?.cancel()
318 const timer = $.clock.after(COPIED_MS, () => {
319 if (bandState.copiedTimer !== timer) return
320 bandState.copiedTimer = undefined
321 $.ui.invalidate('ui.render')
322 })
323 bandState.copiedTimer = timer
324 $.ui.invalidate('ui.render')
325}
326
327/** Only the props a segment actually sets, so the surface never sees an undefined style. */
328function segmentProps(segment: StatusSegment): TextProps {
329 const props: TextProps = {}
330 if (segment.color !== undefined) props.color = segment.color
331 if (segment.bold) props.bold = true
332 if (segment.dim) props.dimColor = true
333 if (segment.inverse) props.inverse = true
334 return props
335}
336
337/** The color the band gives an item's author, so a person reads the same everywhere. */
338export function authorColor(item: WatchItem): string {
339 return personColor(personKey(item.author ?? { user_id: null, name: itemAuthor(item) }))
340}
341
342/**
343 * The band above the prompt: the connection, the thread's link to click or copy, and who is here or
344 * whose agent is working. It draws only while a Delta conversation is active, yields to a survey,
345 * and takes at most the band's rows. Draining the queued message rows here also gives them the hook
346 * context their own command needs.
347 */
348export async function drawBand(
349 $: Runtime,
350 e: HookEvent<'ui.render', { component: 'AbovePrompt' }>,
351 next: HookNext<'ui.render', { component: 'AbovePrompt' }>,
352) {
353 await drainMessages($)
354 if (!statusShown() || e.props.hasSurvey) return next(e)
355 const maxRows = Math.max(0, e.props.maxRows)
356 if (maxRows === 0) return next(e)
357 const terminal = e.surface === 'terminal'
358 const columns = Math.max(0, e.props.bodyColumns)
359 const band = renderBand(await statusView($), { columns, terminal, rows: maxRows })
360 const { Box, Text, Link, Button } = $.ui.resolve(e)
361 const spans = (segments: StatusSegment[]) =>
362 segments.map((segment, index) => <Text key={String(index)} {...segmentProps(segment)}>{segment.text}</Text>)
363 const { text, href, ownRow, copy } = band.link ?? {}
364 // A followable link is a real hyperlink on every surface, so a terminal can open it however it
365 // handles clicks. The terminal's Link takes no label: where Claude does not treat the terminal as
366 // hyperlink-capable, a labelled Link prints its label and then its URL, the same text twice, while
367 // an unlabelled one prints the URL once. While a share or join runs, the link is shown dim and not
368 // offered.
369 let link = null
370 if (text && href) link = terminal ? <Link href={href} /> : <Link href={href} label={text} />
371 else if (text) link = <Text {...segmentProps({ text, dim: true })}>{text}</Text>
372 let copier = null
373 if (href && copy?.copied) copier = <Text color="green">{copyText(copy)}</Text>
374 // Taking the band's focus lands on the copy control, so Enter copies; a hotkey hint would read
375 // as though the key worked from the prompt, where it only types.
376 else if (href && copy) copier = <Button key="copy" plain dimColor autoFocus label={copy.label}
377 onPress={(press) => { void copyLink($, href, press.surface).catch((error) => report($, error)) }} />
378 // A private thread offers the same publication `/delta share` runs; the band does not repeat it
379 // once the thread is shared with the organization.
380 const sharer = band.share ? <Button key="share" plain dimColor label={band.share.label}
381 onPress={() => { const session = watchedSession(); if (session) beginShare($, session) }} /> : null
382 // A refused offline thread offers the person the choice that resolves it.
383 const conflict = band.conflict ? [
384 <Button key="fork" plain dimColor label={band.conflict.fork}
385 onPress={() => { const session = watchedSession(); if (session) beginRefusalResolution($, session, 'fork') }} />,
386 <Button key="discard" plain dimColor label={band.conflict.discard}
387 onPress={() => { const session = watchedSession(); if (session) beginRefusalResolution($, session, 'discard') }} />,
388 ] : []
389 // Every control is set apart by the same gap the band's other segments use.
390 const controls = [copier, sharer, ...conflict].filter((control) => control !== null)
391 .flatMap((control, index) => index ? [<Text key={`gap-${index}`}>{' '}</Text>, control] : [control])
392 const inline = link && !ownRow
393 const rows = [
394 <Box key="band" flexDirection="row" justifyContent="space-between" columnGap={2}>
395 <Box flexDirection="row">
396 <Text wrap="truncate-end">
397 <Text {...segmentProps(band.mark)}>{band.mark.text}</Text>
398 {spans(band.label)}
399 {inline ? ' ' : ''}{inline ? link : null}
400 {band.audience?.length ? <Text>{' '}{spans(band.audience)}</Text> : null}
401 {controls.length ? ' ' : ''}
402 </Text>
403 {controls}
404 </Box>
405 {band.right.length ? <Text wrap="truncate-end">{spans(band.right)}</Text> : null}
406 </Box>,
407 link && ownRow ? <Text key="link">{' '}{link}</Text> : null,
408 band.detail && maxRows >= 2 ? <Text key="detail" wrap="truncate-end">{' '}{spans(band.detail)}</Text> : null,
409 ].filter((part) => part !== null)
410 // Another participant's working agent reads like Claude's own working line: unshaded, above the
411 // band, where its finished calls then land in the transcript.
412 const activity = band.activity ? <Text key="activity" wrap="truncate-end">{spans(band.activity)}</Text> : null
413 const childActivity = band.childActivity ? <Text key="children" wrap="truncate-end">{spans(band.childActivity)}</Text> : null
414 // The desktop's own card sets the band apart. The terminal shades it, a status bar the width of
415 // the band, so it reads as part of the input area rather than another transcript row.
416 if (!terminal) return <Box flexDirection="column">{activity}{childActivity}{rows}</Box>
417 const bar = <Box key="bar" flexDirection="column" width={columns} paddingX={1} backgroundColor={await barShade($)}>{rows}</Box>
418 if (!activity && !childActivity) return bar
419 return <Box flexDirection="column" width={columns}>
420 {activity ? <Box paddingX={1}>{activity}</Box> : null}
421 {childActivity ? <Box paddingX={1}>{childActivity}</Box> : null}
422 {bar}
423 </Box>
424}
425hooks/setup/commands.ts 146 lines1/**
2 * The `/delta` command and its dedicated forms: parsing, the menu, and running each action.
3 */
4import { activate, refreshReminder } from './activation'
5import { setProgress } from '../band/band'
6import { type CommandForm, orgCommand } from '../cli/delta-cli'
7import { chooseDeltaAction, type MenuStart } from './delta-menu'
8import { InstallationUpdates, type UpdateHost } from '../cli/install-update'
9import { claudeInteraction, offerToStopWaiting, setupEnv } from './interaction'
10import { startJoin } from '../sharing/join'
11import { isOneOf } from '../core/json'
12import { hasInteractiveSurface } from '../sharing/lifecycle'
13import { currentOrganizationId, listOrganizations } from './organizations'
14import { activation, recoveryCommand, requests, type Runtime, stateFor } from '../core/session-state'
15import {
16 DASHBOARD_URL, emailsIn, HEADLESS_REFUSAL, InteractionDismissedError, InteractionUnavailableError, membersUrl,
17 openMembersPage, type Organization, runSetupWizard,
18} from './setup'
19import { shareFailureText, startShare } from '../sharing/share'
20import { errorText } from '../core/text'
21
22/** Run `/delta setup` for the active session and answer with what it did. */
23async function setupCommand($: Runtime): Promise<string> {
24 if (!hasInteractiveSurface(await $.session.surfaces())) return HEADLESS_REFUSAL
25 const outcome = await runSetupWizard(setupEnv($), claudeInteraction($))
26 if (outcome.status === 'wrote') await refreshReminder($, await $.session.id())
27 return outcome.text
28}
29
30/** Every `/delta` action, for a surface that can't show the menu and for an action it doesn't know. */
31export const DELTA_USAGE = 'Usage: /delta share [<email>…] | /delta join <shared-link-or-thread> | /delta setup | /delta update | /delta org list | /delta org current | /delta org switch <ID> | /delta org invite <email>… | /delta org manage'
32/** `/delta-join` typed without its link. */
33export const JOIN_USAGE = 'Usage: /delta-join <link>. Paste the Delta link someone shared with you, such as /delta-join https://delta.dev/join/…, or a thread ID.'
34/** `/delta-org` typed without an action. */
35export const ORG_USAGE = 'Usage: /delta-org list (your teams), /delta-org current (the selected one), /delta-org switch <ID>, /delta-org invite <email>… (invite people to the selected one), or /delta-org manage (open the selected one on the dashboard).'
36
37/** Add `/delta`, and a command of its own for each of its actions, to Claude's slash-command menu. */
38export async function registerCommands($: Runtime) {
39 await $.command.register({ name: 'delta', description: 'Share or join a Delta session, set up syncing, choose a team, or update Delta', argumentHint: 'share [<email>…] | join <shared-link-or-thread> | setup | update | org list | org current | org switch <ID> | org manage' })
40 // Plugin commands cannot declare subcommands, so each `/delta` action is also its own command and
41 // appears in the slash-command menu.
42 await $.command.register({ name: 'delta-share', description: 'Delta: sync this session and its code to DeltaDB, and choose who sees it', argumentHint: '[<email>…]' })
43 // Claude's menu shows a command's description but not its argument hint, so the description carries the format.
44 await $.command.register({ name: 'delta-join', description: 'Delta: join a shared conversation. Needs its link: /delta-join <link>', argumentHint: '<shared-link-or-thread>' })
45 await $.command.register({ name: 'delta-setup', description: 'Delta: choose which sessions in this repository sync to DeltaDB' })
46 await $.command.register({ name: 'delta-update', description: 'Delta: update the installed Delta app and CLI' })
47 await $.command.register({ name: 'delta-org', description: 'Delta: manage your team. /delta-org list, current, switch <ID>, invite <email>, or manage', argumentHint: 'list | current | switch <ID> | invite <email>… | manage' })
48}
49
50/**
51 * Answer a command typed without what it needs, such as bare `/delta`, with a menu of its actions,
52 * and run the chosen one. A surface that can't ask gets `usage` instead, and choosing nothing adds
53 * nothing to the transcript.
54 */
55export async function deltaMenu($: Runtime, start: MenuStart, usage: string, form: CommandForm): Promise<{ text?: string }> {
56 if (!hasInteractiveSurface(await $.session.surfaces())) return { text: usage }
57 let action: string | undefined
58 try { action = await chooseDeltaAction(claudeInteraction($), start) }
59 catch (error) {
60 if (error instanceof InteractionDismissedError) return {}
61 if (error instanceof InteractionUnavailableError) return { text: usage }
62 throw error
63 }
64 return action ? runDeltaCommand($, action, form) : {}
65}
66
67/** Open the selected organization's members page on the dashboard; a headless session gets the link. */
68async function manageOrganization($: Runtime): Promise<string> {
69 let organization: Organization | undefined
70 try { organization = (await listOrganizations($)).find((known) => known.current) }
71 catch (error) { return `Delta couldn't read your current team (${errorText(error)}). Manage your teams here: ${DASHBOARD_URL}` }
72 if (!organization) return `Delta has no team selected. Manage your teams here: ${DASHBOARD_URL}`
73 const interactive = hasInteractiveSurface(await $.session.surfaces())
74 return openMembersPage({ openLink: async (url) => interactive && setupEnv($).openLink(url) }, organization)
75}
76
77export function installUpdateHost($: Runtime): UpdateHost {
78 return {
79 run: (argv, init) => $.process.run(argv, init),
80 spawn: (init) => $.process.spawn(init),
81 windows: async () => await $.env.get('OS') === 'Windows_NT',
82 exists: (path) => $.fs.exists(path),
83 after: (milliseconds, callback) => $.clock.after(milliseconds, callback),
84 log: async (text, to) => { await $.ui.log(text, { to }) },
85 }
86}
87
88/** Run one `/delta` action, such as `share` or `join <link>`, from `/delta` or its menu command. */
89export async function runDeltaCommand($: Runtime, action: string, form: CommandForm): Promise<{ text?: string }> {
90 if (action === 'update') return { text: await installationUpdates.update(installUpdateHost($), form) }
91 if (action === 'org manage') return { text: await manageOrganization($) }
92 // A share, join, or setup started now would sign in again beside the wait, so it asks about that instead.
93 if (/^(?:setup|share|join)\b/.test(action) && await offerToStopWaiting($)) return {}
94 // The setup wizard only writes the checkout's policy; it needs no session binding or activation.
95 if (action === 'setup') return { text: await setupCommand($) }
96 const locator = /^join\s+(\S+)$/.exec(action)?.[1]
97 const organization = /^org\s+(?:(list|current)|(switch)\s+(\S+))$/.exec(action)
98 const invite = /^org\s+invite\b\s*(.*)$/.exec(action)?.[1]
99 // `/delta share` asks who should see the session; addresses typed after it answer that up front.
100 const shareArguments = /^share(?:\s+(.*))?$/.exec(action)?.[1] ?? ''
101 const shareEmails = emailsIn(shareArguments)
102 const shareAction = /^share\b/.test(action) && (!shareArguments.trim() || shareEmails.length > 0)
103 if (!shareAction && !locator && !organization && invite === undefined)
104 return { text: DELTA_USAGE }
105 if (requests.join) return { text: 'A Delta join is already in progress. Wait for its result.' }
106 if (requests.share) return { text: 'A Delta share is already in progress. Wait for its result.' }
107 if (organization)
108 return orgCommand($, isOneOf(organization[1], ['list', 'current']) ? organization[1] : { switch: organization[3]! })
109 if (invite !== undefined) {
110 const emails = emailsIn(invite)
111 if (!emails.length) {
112 // The current organization is known once anything has listed them; otherwise link the dashboard itself.
113 const members = currentOrganizationId ? membersUrl(currentOrganizationId) : DASHBOARD_URL
114 return { text: `Usage: /delta-org invite <email> [<email>…]. Invites people to your current Delta team. To invite many people at once, use the dashboard: ${members}` }
115 }
116 return orgCommand($, { invite: emails })
117 }
118 const session = await $.session.id()
119 try {
120 if (session !== activation.session || !stateFor(session).binding) await activate($, session)
121 // Sharing and joining report through the band and ask through dialogs, which only these surfaces have.
122 if (!hasInteractiveSurface(await $.session.surfaces()))
123 return { text: `${locator ? '/delta-join' : '/delta-share'} needs an interactive Claude Code terminal or Desktop Code tab. Print mode, SDK sessions, and cloud runners aren't supported.` }
124 if (locator) {
125 if (stateFor(session).currentTurnId || stateFor(session).promptEntering)
126 return { text: 'Wait for the current Claude turn to finish before joining.' }
127 startJoin($, { session, cwd: await $.session.cwd(), locator, form })
128 // Progress belongs to the band; a command with no text adds no transcript row.
129 return {}
130 }
131 if (stateFor(session).currentTurnId)
132 return { text: 'Wait for the current Claude turn to finish before sharing.' }
133 startShare($, { session, cwd: await $.session.cwd(), form, choose: { emails: shareEmails } })
134 // Progress belongs to the band; a command with no text adds no transcript row.
135 return {}
136 }
137 catch (error) {
138 // Only activation can fail here; the share or join itself runs on the clock and reports there.
139 const text = shareFailureText(error, locator ? `/delta-join ${locator}` : recoveryCommand(stateFor(session).binding))
140 setProgress($, text, 'error')
141 return { text }
142 }
143}
144
145export const installationUpdates = new InstallationUpdates()
146hooks/core/compatibility.ts 23 lines1/** The oldest supported host, also pinned in CI and documented in the README. */
2export const MINIMUM_CLAUDE_VERSION = '2.1.303'
3
4/** Warn without blocking startup when the host is older than the supported minimum. */
5export function claudeVersionWarning(version: string | undefined): string | undefined {
6 const parsed = version?.match(/^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/)
7 if (!parsed)
8 return `Warning: Delta couldn't determine the Claude Code version. Delta supports Claude Code ${MINIMUM_CLAUDE_VERSION} or newer and will continue without a compatibility check.`
9
10 const minimum = MINIMUM_CLAUDE_VERSION.split('.').map(Number)
11 for (let index = 0; index < minimum.length; index++) {
12 const component = Number(parsed[index + 1])
13 if (component > minimum[index]!) return
14 if (component < minimum[index]!)
15 return unsupportedVersionWarning(version!)
16 }
17 if (parsed[4]) return unsupportedVersionWarning(version!)
18}
19
20function unsupportedVersionWarning(version: string): string {
21 return `Warning: Delta supports Claude Code ${MINIMUM_CLAUDE_VERSION} or newer; you are running ${version}. Update Claude Code. Delta will continue, but some features may not work.`
22}
23hooks/recording/delivery.ts 891 lines1/**
2 * Recording a session into its thread: staging records in the outbox, delivering them in order with
3 * retries, turn executions, checkout verification, capture failures, and refused offline changes.
4 */
5import type { ApiMessage } from 'claude-code'
6import { activationIncomplete, captureDecided, outbox } from '../setup/activation'
7import type { Entry } from '../subagents/children'
8import { capturedMessage, isOmittedTool, messageUpdates, resultUpdate, toolInfo, type Update } from './content'
9import { deliveryFailure, deliveryRetryDelay } from './delivery-policy'
10import { requireContract, threadAppend, threadDiscard, threadFork, threadStatus, verifiedContract } from '../cli/delta-cli'
11import { isAskingOwnQuestion, notifyOnce } from '../setup/interaction'
12import { isJsonObject } from '../core/json'
13import {
14 acknowledgedOutboxFiles, acknowledgedPrefix, appendBatch, outboxChunks, outboxRemoval, pendingRecordTurn,
15} from './outbox'
16import { pathKey, samePath } from '../core/paths'
17import {
18 activation, type Binding, boundDirectory, digest, type HookEvent, type HookNext, isPaused, load, pauseCheckout,
19 producerOf, recoveryAdvice, recoveryCommand, report, requests, resumeCheckout, type Runtime, save, serial, sessions,
20 type SessionState, stateFor, stillActive,
21} from '../core/session-state'
22import { children, deliverChild, stopReasonOf } from '../subagents/subagents'
23import {
24 appendFailure, classifyCommandFailure, DeltaCommandError, DeltaSendError, JoinNotReadyError, permanentFailureAdvice,
25 type ThreadTurn, validateJoinedMounts, validateThreadCheckout, validateThreadFrontier,
26} from '../cli/thread-commands'
27import { errorText } from '../core/text'
28import type { ToolRecords } from './tool-records'
29import { liveFor, rememberStatus } from '../watch/watch'
30import { settleRemote, storeShownRow } from '../watch/rows'
31import { scheduleMove } from '../sharing/join'
32import { shownCommandRewrite } from '../watch/row-delivery'
33import { beginAppend, beginShare, endAppend, waitForSnapshot } from '../sharing/share'
34
35export type RecordBody = { update: Update; turnSequence?: number }
36export type CleanupPlan = { session: string; root: string; next: number; pending: { sequence: number; files: string[] }[] }
37const LIVE_ACTIVITY_ORIGIN = {
38 work_origin: 'external_agent',
39 interaction_surface: 'cli',
40} as const
41type LiveActivityKind = 'user_message' | 'agent_message' | 'agent_thought' | 'tool_call' | 'edit'
42let drainTask: Promise<void> | undefined
43/** A Keep or Discard the band started, so its two controls cannot both run at once. */
44let resolving = false
45/**
46 * Whether this session records offline, with `append --acknowledge local` answering without the
47 * server. An automatic or shared session does once its CLI is verified: it writes to its own thread,
48 * and Delta's background uploader pushes what it acknowledged locally. A joined session writes into
49 * someone else's thread, so it keeps server-confirmed delivery and holds Claude while Delta is
50 * unreachable.
51 */
52export function recordsOffline(session: string, binding: Binding | undefined): boolean {
53 return !!binding && !binding.joined && verifiedContract(session) !== undefined
54}
55
56export function rememberToolResults(tools: ToolRecords, message: ApiMessage) {
57 for (const block of message.content) {
58 if (block.type === 'tool_result' && typeof block.tool_use_id === 'string')
59 tools.toolResults.set(block.tool_use_id, block)
60 else if (block.type === 'tool_use' && typeof block.id === 'string' && isOmittedTool(block.name))
61 tools.omitted.add(block.id)
62 }
63}
64
65/** Whether `turnId` is the hand-off's one-word turn, which the thread never records. */
66function isLocalTurn(runtime: SessionState, turnId: string): boolean {
67 return runtime.localTurn?.turnId === turnId
68}
69
70/**
71 * The turn a row of Claude's own output belongs to, or undefined while that turn's start is not
72 * yet staged. `turn.start` writes a turn's scoped running record and is the only thing that
73 * assigns it a sequence; output that reaches a hook first waits for it (see `heldRows`) instead
74 * of naming the turn before it, which Delta fences as stale output for a finished turn.
75 */
76function contentTurn(runtime: SessionState): number | undefined {
77 const execution = runtime.binding?.execution
78 const running = runtime.currentTurnId
79 if (running !== undefined) {
80 // Only the running turn's own staged start may carry its output.
81 if (execution?.turnId === running) return execution.sequence
82 // A turn that lost the thread keeps the sequence it had, so Delta fences its late output.
83 if (runtime.lostTurns.has(running)) return runtime.binding?.lastTurnSequence
84 return undefined
85 }
86 // No turn runs: late output keeps its turn's sequence, or the latest start's.
87 return execution?.sequence ?? runtime.binding?.lastTurnSequence
88}
89
90/** Hold rows until the running turn's start fixes the sequence they carry. */
91function holdRows(runtime: SessionState, updates: Update[], turnId?: string) {
92 runtime.heldRows = [...(runtime.heldRows ?? []), ...updates.map((update) => ({
93 update,
94 turnId,
95 toolId: update.sessionUpdate === 'tool_call_update' && typeof update.toolCallId === 'string'
96 ? update.toolCallId : undefined,
97 }))]
98}
99
100/** Mark a row observed live in this Claude host, without changing imported history. */
101export function liveActivity(update: Update): Update {
102 let activityKind: LiveActivityKind | undefined
103 if (update.sessionUpdate === 'user_message' || update.sessionUpdate === 'agent_message' ||
104 update.sessionUpdate === 'agent_thought') activityKind = update.sessionUpdate
105 else if (update.sessionUpdate === 'tool_call_update') {
106 const structuredEdit = Array.isArray(update.content) &&
107 update.content.some((item) => isJsonObject(item) && item.type === 'diff')
108 activityKind = structuredEdit ? 'edit' : 'tool_call'
109 }
110 if (!activityKind) return update
111 const metadata = isJsonObject(update._meta) ? update._meta : {}
112 const delta = isJsonObject(metadata.delta) ? metadata.delta : {}
113 return {
114 ...update,
115 _meta: { ...metadata, delta: { ...delta, ...LIVE_ACTIVITY_ORIGIN, activity_kind: activityKind } },
116 }
117}
118
119export async function stageRecord($: Runtime, binding: Binding, body: RecordBody): Promise<Binding> {
120 // The continuing session stages under the same producer; a second writer would reuse its sequences.
121 if (binding.continuedIn)
122 throw new Error(`this conversation continues in Claude session ${binding.continuedIn}, which records it`)
123 return stageOutboxRecord($, producerOf(binding), binding, body)
124}
125
126/** Stage one record in the outbox folder `folder`, which holds one recorded conversation's records. */
127export async function stageOutboxRecord<T extends { next: number; pending: Entry[] }>(
128 $: Runtime, folder: string, binding: T, body: RecordBody,
129): Promise<T> {
130 const sequence = binding.next
131 const line = JSON.stringify({ schemaVersion: 1, sequence, ...body }) + '\n'
132 const files: string[] = []
133 for (const chunk of outboxChunks(line, sequence)) {
134 const path = `${outbox}/${folder}/${sequence}-${files.length}.json`
135 await $.fs.write(path, chunk)
136 files.push(path)
137 }
138 // Only reference fully written immutable files. An interrupted write leaves orphans.
139 binding.pending.push({ sequence, files, digest: await digest(line) })
140 binding.next = sequence + 1
141 return binding
142}
143
144async function writeRecord($: Runtime, binding: Binding, body: RecordBody): Promise<Binding> {
145 const next = await stageRecord($, binding, body)
146 await save($, next)
147 return next
148}
149
150async function readRecord($: Runtime, entry: Entry): Promise<string> {
151 const line = (await Promise.all(entry.files.map((path) => $.fs.read(path) as Promise<string>))).join('')
152 if (await digest(line) !== entry.digest)
153 throw new Error(`outbox record ${entry.sequence} changed on disk; sharing paused`)
154 return line
155}
156
157export async function collectAcknowledgedOutbox($: Runtime, plan: CleanupPlan) {
158 const { session, root, next, pending } = plan
159 if (!/^[A-Za-z0-9_-]+$/.test(session)) throw new Error('Invalid outbox session directory')
160 const frontier = pending.reduce((value, entry) => Math.min(value, entry.sequence), next)
161 if (frontier <= 1) return
162 const directory = `${root}/${session}`
163 if (!await $.fs.exists(directory)) return
164 const files = acknowledgedOutboxFiles(directory, next, pending, await $.fs.list(directory))
165 const windows = await $.env.get('OS') === 'Windows_NT'
166 // Keep command lines bounded, including Windows' smaller process argument limit.
167 for (let offset = 0; offset < files.length; offset += 64) {
168 const removal = outboxRemoval(files.slice(offset, offset + 64), windows)
169 const result = await $.process.run(removal.argv, { stdin: removal.stdin, timeoutMs: 30_000 })
170 if (result.exitCode !== 0)
171 throw new Error(result.stderr.trim() || `file removal exited ${result.exitCode}`)
172 }
173}
174
175/** Schedule from an acknowledged saved binding, never from mutable staging state. */
176export function scheduleOutboxCleanup($: Runtime, binding: Binding) {
177 const runtime = sessions.get(binding.session)
178 // The outbox folder belongs to the session the conversation continued in.
179 if (!runtime || binding.continuedIn) return
180 runtime.cleanupPlan = {
181 session: producerOf(binding), root: outbox, next: binding.next,
182 pending: binding.pending.map((entry) => ({ sequence: entry.sequence, files: [...entry.files] })),
183 }
184 if (runtime.cleanupTask) return
185 const task = cleanupOutbox($, binding.session)
186 runtime.cleanupTask = task
187 void task.finally(() => {
188 if (runtime.cleanupTask === task) runtime.cleanupTask = undefined
189 }).catch((error) => reportCleanupIssue($, binding.session, `Delta outbox cleanup failed: ${errorText(error)}`))
190}
191
192async function reportCleanupIssue($: Runtime, session: string, message: string) {
193 const runtime = stateFor(session)
194 const changed = runtime.cleanupError !== message
195 runtime.cleanupError = message
196 // The error is retained even if the host rejects a diagnostic call.
197 // Neither cleanup nor its reporting can be a prerequisite for delivery.
198 try { $.ui.invalidate('ui.render') } catch {}
199 try { if (changed) await $.ui.log(message, { to: 'transcript' }) }
200 catch {}
201}
202
203async function cleanupOutbox($: Runtime, session: string) {
204 const runtime = stateFor(session)
205 while (runtime.cleanupPlan) {
206 const plan = runtime.cleanupPlan
207 runtime.cleanupPlan = undefined
208 const frontier = plan.pending.reduce((value, entry) => Math.min(value, entry.sequence), plan.next)
209 if (frontier <= (runtime.cleanedThrough ?? 1)) continue
210 try {
211 await collectAcknowledgedOutbox($, plan)
212 runtime.cleanedThrough = frontier
213 const hadError = runtime.cleanupError !== undefined
214 runtime.cleanupError = undefined
215 // A redraw is best effort; the band reads the cleared error at its next draw anyway.
216 try { if (hadError) $.ui.invalidate('ui.render') } catch {}
217 } catch (error) {
218 const message = `Delivered Delta records could not be removed from the local outbox: ${errorText(error)}. Delivery can continue; cleanup retries on later acknowledgments or session activation.`
219 await reportCleanupIssue($, session, message)
220 return
221 }
222 }
223}
224
225/**
226 * Whether Claude works in `directory`: it is the session's project root and the shell is there or
227 * below it. Claude's own `cd` in a Bash call moves the shell's directory within the project, so a
228 * subdirectory is still the same checkout.
229 */
230export async function isInDirectory($: Runtime, directory: string) {
231 const root = await $.session.root()
232 if (!samePath(root, directory)) return false
233 const current = await $.session.cwd()
234 const cwd = pathKey(current, root, directory)
235 directory = pathKey(directory, root)
236 return cwd === directory || cwd.startsWith(directory.endsWith('/') ? directory : `${directory}/`)
237}
238
239/** A joined session runs only with Claude in its directory, so Claude's tools reach every mounted worktree. */
240async function requireJoinedDirectory($: Runtime, binding: Binding) {
241 if (await $.session.id() !== binding.session || !binding.directory || !await isInDirectory($, binding.directory))
242 throw new JoinNotReadyError(`This joined session must run in ${binding.directory}. Run /cd ${binding.directory}, then ${recoveryCommand(binding)}; no other checkout will be attached`)
243}
244
245/** Status observes the common owner's mounts; watcher lifetime is not checkout ownership. */
246export async function verifyCheckout($: Runtime, binding: Binding) {
247 if (!boundDirectory(binding))
248 throw new Error('the checkout has not been attached; saved messages remain queued')
249 if (binding.joined) await requireJoinedDirectory($, binding)
250 const status = await threadStatus($, binding.locator ?? binding.thread!, producerOf(binding))
251 validateThreadFrontier(status, binding)
252 if (binding.joined) validateJoinedMounts(status, binding.mounts ?? [])
253 else validateThreadCheckout(status, binding)
254 if (binding.joined) {
255 try { await requireJoinedDirectory($, binding) }
256 catch { throw new Error('The joined session or directory changed during checkout inspection; participation was not enabled') }
257 }
258 const runtime = sessions.get(binding.session)
259 if (runtime) {
260 resumeCheckout(runtime, 'verification')
261 runtime.joinFailure = undefined
262 }
263 await rememberStatus($, binding.session, status)
264 return status
265}
266
267/**
268 * Resolves true only when every pending record was delivered; stopping early because of a pause or
269 * session change is not success. Rejects with the refusal, and appends nothing, when the CLI's
270 * recording contract is one this plugin does not speak.
271 */
272async function drainPending($: Runtime, session: string): Promise<boolean> {
273 const delivering = () => activation.session === session && sessions.has(session) && !isPaused(sessions.get(session)!)
274 while (delivering()) {
275 const binding = await serial(async () => load($, session))
276 // A conversation that continued in another session delivers from there.
277 if (!binding.thread || !binding.pending.length || binding.continuedIn) return true
278 // A recovered outbox checks the CLI's contract before its first append, so an incompatible CLI
279 // records nothing. An answer that arrives after the session ended or was activated again belongs
280 // to that earlier lifetime: it neither appends nor reports, and the current one checks for itself.
281 const current = stillActive(session)
282 try { await requireContract($, session) }
283 catch (error) {
284 if (!delivering() || !current()) return false
285 throw error
286 }
287 if (!delivering() || !current()) return false
288 try { await verifyCheckout($, binding) }
289 catch (error) {
290 // An unanswered check says nothing about the checkout. A session that records offline still
291 // delivers, acknowledged locally, and checks the checkout again once the server answers;
292 // any other session waits, and drain decides how long to keep asking.
293 const state = sessions.get(session)
294 const permanent = classifyCommandFailure(error) === 'permanent'
295 if (state && permanent) pauseCheckout(state, 'verification')
296 if (permanent || !recordsOffline(session, binding)) throw error
297 }
298 const { count, fenced, failure } = await appendPending($, {
299 reference: binding.locator ?? binding.thread, thread: binding.thread, externalId: producerOf(binding),
300 local: recordsOffline(session, binding),
301 }, binding.pending)
302 if (count) {
303 await serial(async () => {
304 const current = await load($, session)
305 const acknowledged = { ...current, pending: current.pending.slice(count) }
306 await save($, acknowledged)
307 scheduleOutboxCleanup($, acknowledged)
308 })
309 }
310 // A `fenced` receipt names the turn Delta already superseded. A fence for the running turn
311 // stops it now, even if the watcher is lagging or disconnected; a fence for any other
312 // sequence, including an earlier turn's late output, changes nothing. Delivery never waits
313 // on the stop, so a slow or failed abort cannot hold up the outbox.
314 const running = binding.execution?.sequence
315 if (running !== undefined && fenced.includes(running))
316 void loseExecution($, session, running, 'Shared execution was superseded').catch((error) => report($, error))
317 if (failure) throw failure
318 }
319 return false
320}
321
322/**
323 * Send the leading pending records to `target.reference` in one bounded append, as `externalId`.
324 *
325 * Returns how many leading records Delta acknowledged, the turns it fenced among them, and why the
326 * rest were not acknowledged. Throws only when the append's outcome is unknown, so nothing counts as
327 * acknowledged.
328 */
329export async function appendPending(
330 $: Runtime,
331 target: { reference: string; thread: string; externalId: string; local: boolean },
332 pending: readonly Entry[],
333): Promise<{ count: number; fenced: number[]; failure?: DeltaCommandError }> {
334 // Keep stdout well below process.run's 4 MiB capture limit.
335 const batch: Entry[] = []
336 const turnSequences: (number | undefined)[] = []
337 let collected = { input: '', bytes: 0, count: 0 }
338 for (const entry of pending) {
339 const line = await readRecord($, entry)
340 const turnSequence = pendingRecordTurn(line, entry.sequence)
341 const next = appendBatch(collected, line)
342 if (!next) break
343 collected = next
344 batch.push(entry)
345 turnSequences.push(turnSequence)
346 if (collected.bytes >= 2_000_000) break
347 }
348 const result = await threadAppend($, target, collected.input)
349 const { count, fenced } = acknowledgedPrefix(result.stdout, target.thread,
350 batch.map((entry, index) => ({ sequence: entry.sequence, turnSequence: turnSequences[index] })))
351 const failure = result.exitCode !== 0 ? appendFailure(result.stdout, result.stderr, result.exitCode)
352 : count !== batch.length ? new DeltaCommandError('invalid_acknowledgment', 'the append acknowledgment did not match the records sent')
353 : undefined
354 return { count, fenced, failure }
355}
356
357/** A turn's scoped running record, naming this plugin's version and where Claude runs when known. */
358export async function runningUpdate($: Runtime): Promise<Update> {
359 let producerVersion: string | undefined
360 let executionLocation: 'local' | 'remote' | undefined
361 try {
362 const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))
363 if (typeof manifest.version === 'string' && manifest.version.length <= 32 &&
364 /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(manifest.version))
365 producerVersion = manifest.version
366 } catch (error) { await report($, error) }
367 try {
368 const remote = await $.env.get('CLAUDE_CODE_REMOTE')
369 if (remote === 'true') executionLocation = 'remote'
370 else if (remote === 'false') executionLocation = 'local'
371 } catch (error) { await report($, error) }
372 return {
373 sessionUpdate: 'state_update', state: 'running',
374 ...producerVersion || executionLocation ? { _meta: { delta: {
375 ...producerVersion ? { producer_version: producerVersion } : {},
376 ...executionLocation ? { execution_location: executionLocation } : {},
377 } } } : {},
378 }
379}
380
381async function beginExecution($: Runtime, session: string, turnId: string) {
382 await serial(async () => {
383 const running = await runningUpdate($)
384 let binding = await load($, session)
385 // A delayed completion must not close this new turn. Finish only the stored
386 // predecessor, then persist the new start and local identity in one manifest.
387 if (binding.execution && !binding.execution.endSequence) {
388 binding = await stageRecord($, binding, {
389 turnSequence: binding.execution.sequence, update: { sessionUpdate: 'state_update', state: 'idle' },
390 })
391 }
392 const sequence = binding.next
393 binding = await stageRecord($, binding, { turnSequence: sequence, update: running })
394 binding.execution = { sequence, turnId }
395 binding.lastTurnSequence = sequence
396 // The composer prompt that started this turn, and any output that reached a hook before this
397 // start was written, are recorded under the sequence it just fixed, so each names a real turn.
398 // Output held for an earlier turn is dropped: its turn ended without owning this start, and
399 // Delta fences it rather than letting it name a turn it does not belong to.
400 const runtime = stateFor(session)
401 const rows = runtime.heldRows
402 if (rows?.length) {
403 runtime.heldRows = undefined
404 for (const { update, toolId, turnId: owner } of rows) {
405 if (owner !== undefined && owner !== turnId) continue
406 if (toolId && !runtime.tools.toolTurns.has(toolId)) runtime.tools.toolTurns.set(toolId, sequence)
407 binding = await stageRecord($, binding, { update, turnSequence: sequence })
408 }
409 }
410 await save($, binding)
411 runtime.nativeTurns.set(turnId, sequence)
412 })
413}
414
415/**
416 * How long a turn completion hook waits for its finish to reach the thread.
417 *
418 * The host gives a hook about ten seconds and skips one that runs past that budget, so the wait is
419 * kept comfortably under it: a normal append is delivered before the hook returns, and a host that
420 * exits right after the reply has still delivered it. A slower append keeps draining in the
421 * background, and the outbox retries it on the next activation.
422 */
423const TURN_COMPLETE_DELIVERY_BUDGET_MS = 5_000
424
425/**
426 * Stage a turn's idle finish and clear its execution, then deliver it.
427 *
428 * The finish is durable before this returns. A turn completion hook bounds its delivery to
429 * {@link TURN_COMPLETE_DELIVERY_BUDGET_MS}, then continues in the background, so the hook returns
430 * within the host's budget and the outbox carries the finish on a later activation. Recovery and
431 * shutdown paths keep waiting, so their pending records are delivered.
432 */
433async function endExecution(
434 $: Runtime,
435 session: string,
436 sequence: number,
437 isCurrent = () => true,
438 delivery: 'await' | 'bounded' | 'background' = 'await',
439 stopReason?: 'end_turn' | 'cancelled' | 'refusal' | 'error',
440) {
441 await serial(async () => {
442 if (!isCurrent()) return
443 let binding = await load($, session)
444 const execution = binding.execution
445 if (!isCurrent() || !execution || execution.sequence !== sequence) return
446 if (!execution.endSequence) {
447 binding = await stageRecord($, binding, {
448 turnSequence: sequence, update: {
449 sessionUpdate: 'state_update', state: 'idle',
450 ...stopReason ? { stopReason } : {},
451 ...stopReason === 'error' ? { error: { code: -32603, message: 'External producer reported an error' } } : {},
452 },
453 })
454 }
455 delete binding.execution
456 await save($, binding, isCurrent)
457 })
458 if (!isCurrent()) return
459 if (delivery === 'await') await drain($, session)
460 else if (delivery === 'background') void drain($, session).catch((error) => report($, error))
461 else await deliverWithin($, session, TURN_COMPLETE_DELIVERY_BUDGET_MS)
462}
463
464/** Delivers within `budgetMs`, letting the outbox finish a slower append in the background. */
465async function deliverWithin($: Runtime, session: string, budgetMs: number): Promise<void> {
466 const cancelled = new AbortController()
467 const delivery = drain($, session).catch((error) => report($, error))
468 const expiry = $.clock.sleep(budgetMs, { signal: cancelled.signal }).catch(() => undefined)
469 await Promise.race([delivery, expiry])
470 cancelled.abort()
471}
472
473export async function loseExecution($: Runtime, session: string, sequence: number, reason: string, isCurrent = () => true) {
474 const runtime = stateFor(session)
475 let turnId = runtime.binding?.execution?.sequence === sequence ? runtime.binding.execution.turnId : undefined
476 try {
477 await serial(async () => {
478 if (!isCurrent()) return
479 const binding = await load($, session)
480 if (!isCurrent() || binding.execution?.sequence !== sequence) { turnId = undefined; return }
481 turnId = binding.execution.turnId
482 await save($, { ...binding, execution: { ...binding.execution, lost: true } }, isCurrent)
483 })
484 } catch (error) { await report($, error) }
485 if (!isCurrent()) return
486 // Remember the loss so late output keeps this turn's sequence (which Delta fences) instead of
487 // waiting for the next turn's start.
488 if (turnId) runtime.lostTurns.add(turnId)
489 if (!turnId || runtime.nativeTurns.get(turnId) !== sequence)
490 return endExecution($, session, sequence, isCurrent)
491 if (runtime.aborting.has(turnId)) return
492 runtime.aborting.add(turnId)
493 try {
494 await $.turn.abort({ turnId })
495 if (!isCurrent()) return
496 await $.ui.log(`${reason}; stopped Claude turn ${turnId}. Already performed tool effects are not rolled back.`, { to: 'transcript' })
497 } finally {
498 try { await endExecution($, session, sequence, isCurrent) }
499 // Hold the guard until the finish is durable, so a duplicate supersession or a fenced receipt
500 // for the same turn that is already in flight cannot abort it a second time.
501 finally { runtime.aborting.delete(turnId) }
502 }
503}
504
505export async function observeTurn($: Runtime, session: string, turn: ThreadTurn, isCurrent = () => true) {
506 const execution = stateFor(session).binding?.execution
507 if (!isCurrent() || !execution || execution.sequence !== turn.sequence || execution.endSequence) return
508 if (turn.status === 'superseded')
509 await loseExecution($, session, turn.sequence, 'Shared execution was superseded', isCurrent)
510}
511
512export async function recoverExecution($: Runtime, session: string) {
513 const runtime = stateFor(session)
514 const execution = (await serial(() => load($, session))).execution
515 if (!execution) return
516 if (execution.turnId && runtime.nativeTurns.has(execution.turnId) && !execution.lost && !execution.endSequence) return
517 // Saved Claude IDs are not authority to abort a turn in a new host process.
518 // Only a turn observed locally in this module can still be running here.
519 if (execution.turnId && runtime.nativeTurns.get(execution.turnId) === execution.sequence)
520 await $.turn.abort({ turnId: execution.turnId })
521 await endExecution($, session, execution.sequence)
522}
523
524export async function drain($: Runtime, session: string): Promise<void> {
525 if (activation.session !== session || isPaused(stateFor(session))) return
526 if (drainTask) {
527 await drainTask
528 if (activation.session !== session || isPaused(stateFor(session))) return
529 if ((await serial(() => load($, session))).pending.length) return drain($, session)
530 return
531 }
532 const task = drainPending($, session).then(async (delivered) => {
533 const state = sessions.get(session)
534 if (!delivered || activation.session !== session || !state) return
535 endDeliveryFailures(state)
536 // The session's thread exists now, so children that waited for it can be created.
537 for (const child of children.values()) {
538 if (child.session === session && child.waitingForParent) void deliverChild($, child)
539 }
540 if (!state.captureFailure && !isPaused(state)) $.ui.status(undefined)
541 // A delivery that succeeds again clears any pinned failure notice.
542 $.ui.invalidate('ui.render')
543 }, (error) => failDelivery($, session, error))
544 drainTask = task
545 try { await task }
546 finally { if (drainTask === task) drainTask = undefined }
547}
548
549/**
550 * Classify a failed drain, schedule its retry or pause sharing, and show the user why.
551 * Failures that are not Delta command errors, such as a changed outbox file, pass through unchanged.
552 * Queued records keep their sequence, so an unchanged retry is always safe.
553 */
554async function failDelivery($: Runtime, session: string, error: unknown): Promise<never> {
555 if (!(error instanceof DeltaCommandError)) throw error
556 const state = sessions.get(session)
557 // A session that ended or was replaced must not retry, pause, or speak in the active one's transcript.
558 if (!state || activation.session !== session) throw new DeltaSendError(error.message, false)
559 const decision = deliveryFailure(state, error, state.pauses.has('verification'))
560 const { retry: willRetry } = decision
561 Object.assign(state, decision.state)
562 const failure = new DeltaSendError(error.message, willRetry)
563 // The server refused this thread's recorded changes; an offline session keeps its records queued
564 // and the band offers the person Fork & Restore or Discard instead of advice to repair a cause.
565 const refused = error.code === 'reload_required' && recordsOffline(session, state.binding)
566 if (refused) state.refusedOffline = true
567 const pausedText = refused
568 ? "Delta couldn't publish this thread's offline changes."
569 : `Delta sharing paused: ${failure.message}. The message stays queued. ${permanentFailureAdvice(error.code, !!state.binding?.autoUpload, error.reason)}, then ${recoveryAdvice(state.binding)}.`
570 if (!willRetry) {
571 pauseCheckout(state, decision.pause, pausedText)
572 } else scheduleSendRetry($, session, error.hints.retryAfterMs)
573 state.retryReason = willRetry ? failure.message : undefined
574 const text = willRetry ? `${failure.message}. The message stays queued and sending will be retried.` : pausedText
575 // The band is the status surface: it shows the retry or the pause until delivery recovers.
576 $.ui.invalidate('ui.render')
577 // A repeating failure is shown once however its message varies; the band stays current.
578 if (decision.show) {
579 await $.ui.log(text, { to: 'transcript' })
580 }
581 throw failure
582}
583
584export function endDeliveryFailures(state: SessionState) {
585 state.retryAttempts = 0
586 state.deliveryNotice = undefined
587 state.retryReason = undefined
588 state.refusedOffline = false
589 state.retryTimer?.cancel()
590 state.retryTimer = undefined
591}
592
593/** The CLI's `retryAfterMs` can lengthen the exponential backoff but never shorten it, so a tiny hint cannot spin. */
594function scheduleSendRetry($: Runtime, session: string, retryAfterMs?: number) {
595 const state = sessions.get(session)
596 if (!state || activation.session !== session || state.retryTimer) return
597 const delay = deliveryRetryDelay(state.retryAttempts++, retryAfterMs)
598 // A timer rather than a sleep: the hook that hit the failure may finish long before the retry.
599 state.retryTimer = $.clock.after(delay, () => {
600 state.retryTimer = undefined
601 if (activation.session === session) void drain($, session).catch((error) => report($, error))
602 })
603}
604
605async function recordCaptureFailure($: Runtime, session: string, error: unknown) {
606 const state = stateFor(session)
607 state.captureFailure = errorText(error)
608 try {
609 await serial(async () => save($, { ...await load($, session), captureFailure: state.captureFailure }))
610 } catch {
611 // An unavailable store cannot preserve its own failure across a process restart.
612 }
613 const execution = state.binding?.execution
614 if (execution) {
615 try { await loseExecution($, session, execution.sequence, 'Local conversation capture failed') }
616 catch (failure) { await report($, failure) }
617 }
618 await report($, error)
619}
620
621async function persistUpdates($: Runtime, session: string, updates: Update[], turnSequence?: number) {
622 const unsaved = stateFor(session).unsaved
623 try {
624 await serial(async () => {
625 if (unsaved.length) {
626 unsaved.push({ updates, turnSequence })
627 return
628 }
629 let state = await load($, session)
630 for (const [index, update] of updates.entries()) {
631 try { state = await writeRecord($, state, { update, turnSequence }) }
632 catch (error) {
633 unsaved.push({ updates: updates.slice(index), turnSequence })
634 throw error
635 }
636 }
637 })
638 } catch (error) { await recordCaptureFailure($, session, error) }
639}
640
641export async function flushUnsaved($: Runtime, session: string) {
642 const runtime = stateFor(session)
643 const unsaved = runtime.unsaved
644 while (unsaved.length) {
645 const first = unsaved[0]
646 if (!first) break
647 await serial(async () => {
648 let state = await load($, session)
649 while (first.updates.length) {
650 const update = first.updates[0]
651 if (!update) break
652 state = await writeRecord($, state, { update, turnSequence: first.turnSequence })
653 first.updates.shift()
654 }
655 unsaved.shift()
656 })
657 }
658 if (runtime.captureFailure) {
659 await serial(async () => {
660 const state = await load($, session)
661 delete state.captureFailure
662 await save($, state)
663 })
664 runtime.captureFailure = undefined
665 }
666}
667
668/**
669 * Begin the person's choice for a refused offline thread, from the band's controls. The command runs
670 * off the hook, and its result clears the refusal so the queued records can drain.
671 */
672export function beginRefusalResolution($: Runtime, session: string, kind: 'fork' | 'discard'): boolean {
673 if (resolving || !stateFor(session).refusedOffline) return false
674 resolving = true
675 $.clock.after(0, async () => {
676 try { await resolveRefusal($, session, kind) }
677 catch (error) { await reportRefusal($, session, error) }
678 finally { resolving = false }
679 })
680 return true
681}
682
683/**
684 * Run the person's choice for the local changes Delta refused: **Fork & Restore** forks them into a
685 * kept thread and then discards them from the original, while **Discard** discards them outright.
686 * Either way the original is the server's view again when it finishes, a fork is named once, and the
687 * queued records drain into the original.
688 */
689async function resolveRefusal($: Runtime, session: string, kind: 'fork' | 'discard'): Promise<void> {
690 const state = sessions.get(session)
691 if (!state || activation.session !== session) return
692 const thread = (await serial(() => load($, session))).thread
693 if (!thread) return
694 // Fork first: it copies the refused changes into a kept thread, and the discard then resets the original.
695 const forked = kind === 'fork' ? await threadFork($, thread) : undefined
696 await threadDiscard($, thread)
697 endDeliveryFailures(state)
698 resumeCheckout(state, 'delivery')
699 $.ui.invalidate('ui.render')
700 if (forked)
701 await notifyOnce($, `Delta kept this thread's offline changes in the new thread "${forked.thread_id}"; this thread carries on without them.`)
702 await $.ui.log(kind === 'fork' ? "Delta forked this thread's offline changes into a kept thread." : "Delta discarded this thread's offline changes.", { to: 'debug' })
703 void drain($, session).catch((error) => report($, error))
704}
705
706/** Show why the person's Fork & Restore or Discard did not resolve the refusal; the controls stay available. */
707async function reportRefusal($: Runtime, session: string, error: unknown) {
708 const state = sessions.get(session)
709 if (!state || activation.session !== session) return
710 await $.ui.log(`Delta could not resolve this thread's offline changes: ${errorText(error)}. The records stay queued.`, { to: 'transcript' })
711 // A redraw is best effort; the band shows the refusal again at its next draw.
712 try { $.ui.invalidate('ui.render') } catch {}
713}
714
715/**
716 * The main loop's turn started: bind it as the current turn and open its execution, or lose the
717 * execution at once when observation or capture is unavailable.
718 */
719export async function startTurn($: Runtime, e: HookEvent<'turn.start'>, next: HookNext<'turn.start'>) {
720 const session = await $.session.id()
721 await captureDecided(session)
722 const runtime = stateFor(session)
723 runtime.currentTurnId = e.turnId
724 if (runtime.localTurn && !runtime.localTurn.turnId) runtime.localTurn.turnId = e.turnId
725 if (!runtime.binding?.snapshot || isLocalTurn(runtime, e.turnId)) return next(e)
726 try {
727 await beginExecution($, session, e.turnId)
728 // A session that records offline keeps its turn while the watcher is down, and a delivery pause
729 // stops delivery rather than Claude: observation and delivery are not required to record, and a
730 // transient refusal queues rather than stopping the turn. A verification pause still stops it.
731 const offline = recordsOffline(session, runtime.binding)
732 const blockingPause = offline ? runtime.pauses.has('verification') : isPaused(runtime)
733 const observationDown = !offline && !activationIncomplete(runtime) &&
734 !liveFor(session)
735 if (blockingPause || runtime.captureFailure || observationDown)
736 await loseExecution($, session, runtime.nativeTurns.get(e.turnId)!, 'Delta observation or capture is unavailable')
737 else void drain($, session).catch((error) => report($, error))
738 } catch (error) {
739 // A hook's return value cannot prevent this turn. Cancel the local ID when
740 // its durable start/binding could not be saved; never run uncorrelated output.
741 await $.turn.abort({ turnId: e.turnId })
742 await recordCaptureFailure($, session, error)
743 }
744 return next(e)
745}
746
747/**
748 * The main loop's turn ended: stage its finish, then release the remote rows held while it ran, move
749 * Claude if it must, and start a share asked for during the turn.
750 */
751export async function completeTurn($: Runtime, e: HookEvent<'turn.complete'>, next: HookNext<'turn.complete'>) {
752 const session = await $.session.id()
753 const runtime = stateFor(session)
754 const sequence = runtime.nativeTurns.get(e.turnId) ??
755 (runtime.binding?.execution?.turnId === e.turnId ? runtime.binding.execution.sequence : undefined)
756 if (runtime.currentTurnId === e.turnId) runtime.currentTurnId = undefined
757 if (isLocalTurn(runtime, e.turnId)) runtime.localTurn = undefined
758 runtime.promptEntering = false
759 runtime.nativeTurns.delete(e.turnId)
760 const result = await next(e)
761 if (sequence !== undefined) runtime.tools.forgetUnpaired(sequence)
762 if (sequence !== undefined) {
763 try { await endExecution($, session, sequence, () => true, 'bounded', stopReasonOf(e)) }
764 catch (error) { await report($, error) }
765 }
766 // Release the remote rows held back while this turn ran now that its finish is staged: delivered
767 // within the budget, or queued in the outbox behind any later records. Each
768 // row waits for a redraw to be drawn, and drawing is the host's business after the hook returns,
769 // so this runs on its own rather than holding a host that may exit at the turn's end. A later
770 // prompt or live event reuses the same settling task, so nothing settles or draws twice.
771 if (runtime.currentTurnId === undefined) {
772 void settleRemote($, session)?.catch((error) => report($, error))
773 scheduleMove($, session)
774 if (requests.shareAfterTurn?.session === session) {
775 const { audience } = requests.shareAfterTurn
776 requests.shareAfterTurn = undefined
777 beginShare($, session, audience)
778 }
779 }
780 return result
781}
782
783/** A row the main conversation kept is recorded, or held for the turn it belongs to. */
784export async function recordRow($: Runtime, e: HookEvent<'session.append'>, next: HookNext<'session.append'>) {
785 // The plugin's own `show` run is stored rewritten, so neither the model nor a resumed session's
786 // copy of these rows names the internal command or its item id. Its output row names the item
787 // until then, which is how the row is tied to what it draws.
788 const shown = shownCommandRewrite($.plugin.name, e)
789 if (shown !== undefined) {
790 const stored = await next({ ...e, message: { ...e.message, content: shown.content } })
791 if (!('deny' in stored)) await storeShownRow($, stored.uuid, shown)
792 return stored
793 }
794 if (!capturedMessage(e.message, e.door)) return next(e)
795 const session = await $.session.id()
796 // A row from a brand-new session waits for its capture boundary, so a prompt or its output that
797 // reaches a hook before the snapshot is staged is recorded under the session's new thread.
798 await captureDecided(session)
799 const runtime = stateFor(session)
800 // The hand-off's one-word turn, its prompt included, stays out of the thread.
801 if (runtime.localTurn) return next(e)
802 // A composer prompt is this person's own input. Its turn's start record is
803 // only written at turn.start, after this row, so the row is held to be
804 // recorded under that turn; a prompt sent into a running turn names it now.
805 const ownPrompt = e.door === 'prompt' && e.message.role === 'user'
806 const assistant = e.message.role === 'assistant'
807 await beginAppend()
808 try {
809 const stored = await next(e)
810 if (!('deny' in stored) && runtime.binding?.snapshot) {
811 const message = capturedMessage(stored.message, e.door)
812 if (message) {
813 rememberToolResults(runtime.tools, message)
814 const updates = messageUpdates(message, stored.uuid, runtime.tools.structuredResults,
815 { root: boundDirectory(runtime.binding), omitted: runtime.tools.omitted }).map(liveActivity)
816 // Output from the turn Claude is running waits for that turn's scoped start record, so
817 // it names its own turn rather than the turn before it. The prompt starting a turn is
818 // held the same way, because its start record is written after its row.
819 const turnSequence = assistant ? contentTurn(runtime)
820 : ownPrompt ? runtime.binding?.execution?.sequence : undefined
821 const hold = ownPrompt ? !runtime.binding?.execution
822 : assistant && turnSequence === undefined && runtime.currentTurnId !== undefined
823 if (hold) {
824 // A composer prompt is held for whichever turn starts next; output is held for the
825 // turn Claude is running, and dropped if that turn never owns its start.
826 holdRows(runtime, updates, ownPrompt ? undefined : runtime.currentTurnId)
827 } else {
828 for (const update of updates) {
829 const tool = update.sessionUpdate === 'tool_call_update' && typeof update.toolCallId === 'string'
830 ? update.toolCallId : undefined
831 if (tool && !runtime.tools.toolTurns.has(tool)) runtime.tools.toolTurns.set(tool, turnSequence)
832 await persistUpdates($, session, [update], tool ? runtime.tools.toolTurns.get(tool) : turnSequence)
833 }
834 }
835 for (const block of message.content) {
836 if (block.type === 'tool_result' && typeof block.tool_use_id === 'string')
837 runtime.tools.settle(block.tool_use_id, 'row')
838 }
839 if (!hold && !runtime.captureFailure && runtime.binding.thread)
840 void drain($, session).catch((error) => report($, error))
841 }
842 }
843 return stored
844 } finally {
845 endAppend()
846 }
847}
848
849/** The main conversation's tool call: its result is recorded under the turn that made the call. */
850export async function recordToolCall($: Runtime, e: HookEvent<'tool.call'>, next: HookNext<'tool.call'>) {
851 if (isAskingOwnQuestion() && e.tool === 'AskUserQuestion') return next(e)
852 const session = await $.session.id()
853 const runtime = stateFor(session)
854 if (runtime.localTurn) return next(e)
855 // The turn this call belongs to is fixed now, so a later result row keeps it even after the
856 // turn ends. While Claude runs a turn whose scoped start is not yet written, the call waits
857 // for that start so it does not name the turn before it.
858 const turnSequence = contentTurn(runtime)
859 if (e.tool_use_id && turnSequence !== undefined) runtime.tools.toolTurns.set(e.tool_use_id, turnSequence)
860 const hold = turnSequence === undefined && runtime.currentTurnId !== undefined
861 if (e.tool_use_id && isOmittedTool(e.tool)) runtime.tools.omitted.add(e.tool_use_id)
862 try {
863 const result = await next(e)
864 await waitForSnapshot()
865 if (!runtime.binding?.snapshot || !e.tool_use_id || runtime.tools.omitted.has(e.tool_use_id) ||
866 !('result' in result) || result.result === undefined) return result
867 const root = boundDirectory(runtime.binding)
868 const update = resultUpdate(e.tool_use_id, e.tool, result.result, !!result.isError, root)
869 runtime.tools.structuredResults.set(e.tool_use_id, update)
870 const row = runtime.tools.toolResults.get(e.tool_use_id)
871 const updates = (row
872 ? messageUpdates({ role: 'user', content: [row] }, `tool-result:${e.tool_use_id}`, runtime.tools.structuredResults)
873 // Keep structured output visible in Delta without closing before the model's result text arrives.
874 // The call's input row may not be stored yet, so this record names the call itself; the event
875 // carries the tool's arguments beside its reserved keys.
876 : [{ ...update, status: 'in_progress', name: e.tool,
877 ...toolInfo(e.tool, e, root) }]).map(liveActivity)
878 if (hold) holdRows(runtime, updates, runtime.currentTurnId)
879 else await persistUpdates($, session, updates, turnSequence)
880 if (!hold && !runtime.captureFailure && runtime.binding.thread)
881 void drain($, session).catch((error) => report($, error))
882 return result
883 } finally {
884 if (e.tool_use_id) {
885 // Only a shared session ever records the result row that would pair with this call.
886 if (runtime.binding?.snapshot) runtime.tools.settle(e.tool_use_id, 'call')
887 else runtime.tools.forget(e.tool_use_id)
888 }
889 }
890}
891hooks/cli/delta-cli.ts 527 lines1/**
2 * Running the Delta CLI for a session: finding the executable, the thread contract version the CLI
3 * and this plugin agreed on, and one function per CLI operation the plugin uses, named after its
4 * subcommand (`threadCreate` runs `delta thread create`). Each builds its arguments, runs them, and
5 * returns the answer already checked. Only sign-in (`auth.ts`) and updates (`install-update.ts`),
6 * which run through hosts their tests substitute, build a Delta command line anywhere else.
7 */
8import type { ProcessRunResult, ProcessSpawnResult } from 'claude-code'
9import { DeltaCli } from './cli'
10import {
11 checkoutStillSyncing, checkResult, type CreationReceipt, localWorktreesAt, type MembershipReceipt, type PublicationReceipt,
12 validateAttachmentReceipt, validateCreationReceipt, validatePublicationReceipt, validateWorktreeCreationReceipt,
13 validateWorktreeMembershipReceipt, type WorktreeCreationReceipt,
14} from './command-outcomes'
15import { readCommandStream, readMountReady } from './command-reader'
16import { isJsonObject, type JsonObject } from '../core/json'
17import { type Runtime, stillActive } from '../core/session-state'
18import { claudeInteraction } from '../setup/interaction'
19import {
20 createdOrganizationFrom, type InviteResult, inviteResultsFrom, type Organization, organizationsFrom,
21} from '../setup/setup'
22import { threadInvitationsFrom } from '../sharing/share-audience'
23import { errorText } from '../core/text'
24import {
25 contractRefusal, ContractRefusalError, contractVersion, DeltaCommandError, type ForkedThread, type MountedThread,
26 parseThreadContract, parseThreadFork, parseThreadMount, parseThreadStatus, parseWatchEvent, PRODUCER_NAME,
27 type ThreadContract, type WatchEvent,
28} from './thread-commands'
29
30/**
31 * Marks a command as run by Claude Code, for Delta's telemetry of which integration ran each command.
32 * Every Delta command this plugin runs carries it, sign-in's included.
33 */
34export const INTEGRATION_ENV = { DELTA_CLI_INTEGRATION: 'claude_code' }
35
36/** How a person ran a share or join: `/delta share` (`delta_subcommand`) or `/delta-share` (`dedicated_command`). */
37export type CommandForm = 'delta_subcommand' | 'dedicated_command'
38
39/** The CLI environment that labels the command a share or join reports with how it was run, for Delta's telemetry. */
40function commandFormEnv(form: CommandForm | undefined): Record<string, string> {
41 return form ? { DELTA_CLI_COMMAND_FORM: form } : {}
42}
43const cli = new DeltaCli()
44/** `thread contract` answers from the CLI binary without starting delta-app, so this bound only catches a wedged process. */
45export const CONTRACT_TIMEOUT_MS = 30_000
46/** A mount may materialize several large checkouts before it answers. */
47const MOUNT_TIMEOUT_MS = 600_000
48/**
49 * The contract version negotiated with each session's CLI build, once it answered a range this plugin
50 * speaks; a refusal is never remembered. A capability newer than `PLUGIN_CONTRACT_MIN` is gated on it.
51 */
52const contractVerified = new Map<string, number>()
53
54/** The contract version this session's CLI agreed to, once it did. */
55export function verifiedContract(session: string): number | undefined {
56 return contractVerified.get(session)
57}
58
59/** Remember a version for a session that runs against a CLI build this process already verified. */
60export function rememberContract(session: string, version: number) {
61 contractVerified.set(session, version)
62}
63
64/** A resumed session re-checks the CLI's contract, as a fresh process's first participation does. */
65export function forgetContract(session: string) {
66 contractVerified.delete(session)
67}
68
69/**
70 * The Delta CLI's executable. Given `install`, a missing CLI is installed, with its progress reported
71 * through `install`; without it, a missing CLI is an error, so only an explicit command installs.
72 */
73export async function resolveCli($: Runtime, install?: (progress: string) => void) {
74 return cli.resolve((argv, init) => $.process.run(argv, { ...init, env: { ...init?.env, ...INTEGRATION_ENV } }),
75 install !== undefined,
76 install, await $.env.get('OS') === 'Windows_NT'
77 ? {
78 exists: (path) => $.fs.exists(path),
79 confirmInstall: async () => {
80 const answer = await claudeInteraction($).ask(
81 'Delta is not installed. Download and run the official Windows installer? It installs the Delta app and CLI and may ask for Windows administrator permission.',
82 { options: ['Install Delta', 'Not now'], header: 'Delta setup' },
83 )
84 return answer === 'Install Delta'
85 },
86 } : false)
87}
88
89/**
90 * Run `delta --json …args` as Claude Code, reading its output as it streams rather than through
91 * process.run's capture limit. `name` names the command in its errors.
92 */
93async function readCommand($: Runtime, args: string[], name: string, options: {
94 signal?: AbortSignal; timeoutMs?: number; env?: Record<string, string>
95} = {}): Promise<string> {
96 const { signal = new AbortController().signal, timeoutMs = 120_000, env } = options
97 if (signal.aborted) throw new Error(`Delta ${name} cancelled`)
98 let stream: ReturnType<Runtime['process']['spawn']>
99 try {
100 const executable = await resolveCli($)
101 if (signal.aborted) throw new Error(`Delta ${name} cancelled`)
102 stream = $.process.spawn({ argv: [executable, '--json', ...args], env: { ...env, ...INTEGRATION_ENV } })
103 }
104 catch (error) { throw new DeltaCommandError('process_failed', `${name}: cannot run Delta CLI (${errorText(error)})`) }
105 return readCommandStream(stream, name, signal,
106 (milliseconds, deadline) => $.clock.sleep(milliseconds, { signal: deadline }), timeoutMs)
107}
108
109/**
110 * Refuse to record against a CLI whose recording contract this plugin does not speak, and return
111 * the newest version both speak. Runs once per session; a refusal or a process failure is not
112 * remembered, so updating Delta and retrying re-checks. Nor is an answer that arrives after the
113 * session ended or was activated again, even under the same ID, so a resumed session renegotiates.
114 */
115export async function requireContract($: Runtime, session: string): Promise<number> {
116 const verified = contractVerified.get(session)
117 if (verified !== undefined) return verified
118 const current = stillActive(session)
119 const range = await threadContract($)
120 const refusal = contractRefusal(range)
121 if (refusal) throw new ContractRefusalError(refusal)
122 // contractRefusal refuses an undefined range, so the range is defined here.
123 const version = contractVersion(range!)
124 if (current()) contractVerified.set(session, version)
125 return version
126}
127
128/**
129 * Ask the CLI which recording contract versions it speaks, using the same invocation the recording
130 * helpers use. It answers locally, so the answer needs no delta-app. Unlike `command`, the exit code
131 * and empty stdout are inspected first, so a CLI that predates the subcommand (clap's error on
132 * stderr, nonzero exit, no JSON) reads as `undefined` rather than a generic malformed-output failure.
133 */
134export async function threadContract($: Runtime): Promise<ThreadContract | undefined> {
135 let result: ProcessRunResult
136 try {
137 result = await runJson($, ['thread', 'contract'], { timeoutMs: CONTRACT_TIMEOUT_MS })
138 } catch (error) {
139 // The same failure a share or a status read reports when the CLI is missing or cannot start.
140 throw new Error(`thread contract: cannot run Delta CLI (${errorText(error)}). Repair the selected Delta CLI and retry.`)
141 }
142 if (result.isStdoutTruncated || result.isStderrTruncated)
143 throw new Error('thread contract: Delta CLI output truncated; no contract assumed')
144 if (result.exitCode !== 0 && !result.stdout.trim()) return undefined
145 return parseThreadContract(result.stdout)
146}
147
148/**
149 * Run `delta --json …args` as Claude Code with `runJson`, returning its checked JSON answer. `name`
150 * names the command in its errors.
151 */
152async function command($: Runtime, args: string[], name: string, options: {
153 check?: () => Promise<void>; timeoutMs?: number; env?: Record<string, string>
154} = {}) {
155 let result: ProcessRunResult
156 try {
157 result = await runJson($, args, { ...options, timeoutMs: options.timeoutMs ?? 120_000 })
158 } catch (error) {
159 throw new Error(`${name}: cannot run Delta CLI (${errorText(error)}). Install the matching new Delta CLI and app, and put delta on PATH.`)
160 }
161 return checkResult(result, name)
162}
163
164/**
165 * Run `delta --json …args` as Claude Code. `check` runs once the CLI is found, before the command;
166 * a failure to find the CLI, pass the check or run the command is thrown as it is.
167 */
168async function runJson($: Runtime, args: string[], options: {
169 timeoutMs: number; stdin?: string; env?: Record<string, string>; check?: () => Promise<void>
170}): Promise<ProcessRunResult> {
171 const { timeoutMs, stdin, env, check } = options
172 const executable = await resolveCli($)
173 if (check) await check()
174 return $.process.run([executable, '--json', ...args], {
175 ...stdin !== undefined ? { stdin } : {}, timeoutMs, env: { ...env, ...INTEGRATION_ENV },
176 })
177}
178
179/**
180 * Let the CLI own organization selection and its human-readable result: `org list`, `org current`,
181 * `org switch`, or `org invite` into the current organization.
182 */
183export async function orgCommand(
184 $: Runtime, request: 'list' | 'current' | { switch: string } | { invite: string[] },
185) {
186 const args = typeof request === 'string' ? [request]
187 : 'switch' in request ? ['switch', '--', request.switch] : ['invite', '--', ...request.invite]
188 try {
189 const executable = await resolveCli($)
190 const result = await $.process.run([executable, 'org', ...args], {
191 timeoutMs: 120_000, env: { ...INTEGRATION_ENV },
192 })
193 if (result.isStdoutTruncated || result.isStderrTruncated)
194 throw new Error('Delta team output was truncated; check the selection with /delta-org current.')
195 if (result.exitCode !== 0)
196 throw new Error(result.stderr.trim() || result.stdout.trim() || `Delta exited with code ${result.exitCode}`)
197 return { text: result.stdout.trim() }
198 } catch (error) {
199 return { text: `Delta team command failed: ${errorText(error)}` }
200 }
201}
202
203/** The account's organizations, from `delta --json org list`. */
204export async function orgList($: Runtime, timeoutMs?: number): Promise<Organization[]> {
205 return organizationsFrom(await command($, ['org', 'list'], 'org list', { timeoutMs }))
206}
207
208/** Create a team organization named `name`. */
209export async function orgCreate($: Runtime, name: string): Promise<Organization> {
210 return createdOrganizationFrom(await command($, ['org', 'create', '--', name], 'org create'))
211}
212
213/** Invite `emails` to `organization`, with each address's outcome. */
214export async function orgInvite($: Runtime, organization: string, emails: string[]): Promise<InviteResult[]> {
215 return inviteResultsFrom(await command($, ['org', 'invite', '--org', organization, '--', ...emails], 'org invite'))
216}
217
218/** The signed-in account's GitHub login, from `delta --json auth status`. */
219export async function authStatus($: Runtime): Promise<{ login: string | undefined }> {
220 const { account } = await command($, ['auth', 'status'], 'auth status')
221 return { login: isJsonObject(account) && typeof account.login === 'string' ? account.login : undefined }
222}
223
224/**
225 * Create, or find, the thread `externalId` records into. `organization` creates it under that
226 * organization with that visibility; `parent` makes it a subagent's thread, named and with its
227 * parent's worktrees or forks of them. `check` runs once the CLI is found, before the command.
228 */
229export async function threadCreate($: Runtime, creation: {
230 externalId: string
231 organization?: { id: string; visibility: 'private' | 'organization' }
232 parent?: { reference: string; name: string; worktrees?: 'shared' | 'isolated' }
233 check?: () => Promise<void>
234}): Promise<JsonObject & CreationReceipt> {
235 const { externalId, organization, parent, check } = creation
236 const created = await command($, ['thread', 'create', '--source', 'claude-code', '--external-id', externalId,
237 ...organization ? ['--organization', organization.id, '--visibility', organization.visibility] : [],
238 ...parent ? ['--parent', parent.reference, '--name', parent.name] : [],
239 ...parent?.worktrees ? [`--${parent.worktrees}-worktrees`] : []], 'thread create', { check })
240 validateCreationReceipt(created)
241 return created
242}
243
244/** Sync diagnostics can exceed process.run's 4 MiB stdout capture limit, so status streams with a bound. */
245export async function threadStatus(
246 $: Runtime, thread: string, session: string, signal = new AbortController().signal,
247) {
248 return parseThreadStatus(await readCommand($, ['thread', 'status', thread,
249 '--source', 'claude-code', '--external-id', session], 'thread status', { signal }))
250}
251
252/** Publish `thread` to its organization, returning the link Delta gave it. */
253export async function threadShare(
254 $: Runtime, thread: string, options: { form?: CommandForm; check?: () => Promise<void> } = {},
255): Promise<JsonObject & PublicationReceipt> {
256 const shared = await command($, ['thread', 'share', thread, '--visibility', 'organization'], 'thread share',
257 { check: options.check, env: commandFormEnv(options.form) })
258 validatePublicationReceipt(shared, thread)
259 return shared
260}
261
262/** Invite `emails` to `thread`, which uploads it privately if it is not on the server yet. */
263export async function threadInvite(
264 $: Runtime, thread: string, emails: string[], options: { form?: CommandForm; check?: () => Promise<void> } = {},
265): Promise<{ url: string; results: InviteResult[] }> {
266 return threadInvitationsFrom(await command($, ['thread', 'invite', thread, '--', ...emails],
267 'thread invite', { check: options.check, env: commandFormEnv(options.form) }), thread)
268}
269
270/**
271 * A running `thread mount` or `worktree mount`. Delta keeps the mounts while the process runs and
272 * releases them once it ends, so stopping it is how the plugin lets go of them.
273 */
274type MountProcess = {
275 session: string
276 /** `thread:<thread>:<owner>` or `worktree:<session>:<directory>`. */
277 key: string
278 stream: ReturnType<Runtime['process']['spawn']>
279 abort: AbortController
280 /** The worktree a `worktree mount` keeps mounted, once it is ready. */
281 reference?: string
282 stopping: boolean
283}
284/** The ready mount process of each key; a later one replaces it. */
285const mountProcesses = new Map<string, MountProcess>()
286/** Every mount process not yet stopped, still preparing or ready. */
287const liveMountProcesses = new Set<MountProcess>()
288
289/** End a mount process, which tells Delta to release what it mounted. */
290async function stopMountProcess(process: MountProcess) {
291 if (process.stopping) return
292 process.stopping = true
293 process.abort.abort()
294 liveMountProcesses.delete(process)
295 if (mountProcesses.get(process.key) === process) mountProcesses.delete(process.key)
296 await process.stream.return?.({ code: null, signal: 'SIGTERM' })
297}
298
299/**
300 * Start a mount command for `session` and wait for its readiness line, leaving it running. It replaces
301 * the ready process of the same key. `check` runs once the CLI is found and again once it is ready.
302 */
303async function mountCommand<T>($: Runtime, mount: {
304 session: string; key: string; args: string[]; name: string; env?: Record<string, string>
305 check?: () => Promise<void>
306}, parseReady: (line: string) => T): Promise<T> {
307 const { session, key, args, name, env, check } = mount
308 const executable = await resolveCli($)
309 if (check) await check()
310 const stream = $.process.spawn({ argv: [executable, '--json', ...args], env: { ...env, ...INTEGRATION_ENV } })
311 const process: MountProcess = { session, key, stream, stopping: false, abort: new AbortController() }
312 liveMountProcesses.add(process)
313 try {
314 // A first mount can materialize large checkouts, which the CLI waits for.
315 const { line } = await readMountReady(stream, name, process.abort.signal,
316 (milliseconds, deadline) => $.clock.sleep(milliseconds, { signal: deadline }), MOUNT_TIMEOUT_MS)
317 const ready = parseReady(line)
318 if (check) await check()
319 const prior = mountProcesses.get(key)
320 mountProcesses.set(key, process)
321 if (prior) await stopMountProcess(prior)
322 return ready
323 } catch (error) {
324 await stopMountProcess(process)
325 throw error
326 }
327}
328
329/**
330 * Mount every worktree of the thread `locator` names for `owner`, for as long as `session` keeps the
331 * command running; `join` reports the mount as a join, run as `form`. `thread` keys the process.
332 */
333export async function threadMount($: Runtime, mount: {
334 session: string; thread: string; locator: string; owner: string; join?: boolean; form?: CommandForm
335}): Promise<MountedThread> {
336 const { session, thread, locator, owner, join } = mount
337 return mountCommand($, {
338 session, key: `thread:${thread}:${owner}`, name: 'thread mount',
339 args: ['thread', 'mount', locator, '--owner', owner, ...join ? ['--join'] : []],
340 env: join ? commandFormEnv(mount.form) : {},
341 }, (line) => parseThreadMount(line, owner))
342}
343
344/** Stop the mount processes `session` started, ready or still preparing. */
345export async function stopSessionMounts(session: string) {
346 await Promise.all([...liveMountProcesses].filter((process) => process.session === session).map(stopMountProcess))
347}
348
349/** Stop `owner`'s thread mount processes, if this plugin process still holds them. */
350export async function stopThreadMounts(owner: string) {
351 await Promise.all([...liveMountProcesses]
352 .filter((process) => process.key.startsWith('thread:') && process.key.endsWith(`:${owner}`))
353 .map(stopMountProcess))
354}
355
356/** Fork a refused thread's offline changes into a kept thread. */
357export async function threadFork($: Runtime, thread: string): Promise<ForkedThread> {
358 return parseThreadFork((await runRefusalCommand($, 'fork', thread)).stdout)
359}
360
361/** Discard a refused thread's offline changes, so it is the server's view again. */
362export async function threadDiscard($: Runtime, thread: string): Promise<JsonObject> {
363 return checkResult(await runRefusalCommand($, 'discard', thread), 'thread discard')
364}
365
366/** Run one `thread fork` or `thread discard` for a refused thread, failing with a typed error on a broken run. */
367async function runRefusalCommand($: Runtime, kind: 'fork' | 'discard', thread: string): Promise<ProcessRunResult> {
368 const args = kind === 'fork' ? ['thread', 'fork', thread] : ['thread', 'discard', thread, '--force']
369 let result: ProcessRunResult
370 try {
371 result = await runJson($, args, { timeoutMs: 120_000 })
372 } catch (error) { throw new DeltaCommandError('process_failed', `thread ${kind} did not finish (${errorText(error)})`) }
373 if (result.isStdoutTruncated || result.isStderrTruncated)
374 throw new DeltaCommandError('command_failed', `thread ${kind} output was truncated`)
375 return result
376}
377
378/**
379 * Append the JSON lines `input` to `target.reference` as the producer `target.externalId`; `local`
380 * asks for a local acknowledgment. Returns the untruncated run, whose acknowledgments the caller
381 * reads against the records it sent.
382 */
383export async function threadAppend(
384 $: Runtime, target: { reference: string; externalId: string; local: boolean }, input: string,
385): Promise<ProcessRunResult> {
386 // Every append names the producer, retries included, so attribution never depends on a live watch.
387 const args = ['thread', 'append', target.reference, '--source', 'claude-code', '--external-id', target.externalId,
388 ...target.local ? ['--acknowledge', 'local'] : [], '--producer-name', PRODUCER_NAME]
389 // A CLI that cannot be found fails as itself; only a run that does not finish is a process failure.
390 await resolveCli($)
391 let result: ProcessRunResult
392 try {
393 result = await runJson($, args, { stdin: input, timeoutMs: 120_000 })
394 } catch (error) { throw new DeltaCommandError('process_failed', `append did not finish (${errorText(error)})`) }
395 if (result.isStdoutTruncated || result.isStderrTruncated)
396 throw new DeltaCommandError('command_failed', 'append output was truncated, so no acknowledgment is assumed')
397 return result
398}
399
400/**
401 * Start watching the thread `reference`, as the producer `externalId` when given; `participate`
402 * also shows the signed-in person taking part through Claude Code while the watch runs. `proceed`
403 * runs once the CLI is found, and a `false` answer starts nothing and returns undefined.
404 */
405export async function threadWatch(
406 $: Runtime, reference: string,
407 options: { externalId?: string; participate?: boolean; proceed?: () => boolean | Promise<boolean> } = {},
408): Promise<ReturnType<Runtime['process']['spawn']> | undefined> {
409 const { externalId, participate, proceed } = options
410 const argv = [await resolveCli($), '--json', 'thread', 'watch', reference,
411 ...externalId ? ['--source', 'claude-code', '--external-id', externalId] : [],
412 ...participate ? ['--participate', PRODUCER_NAME] : []]
413 if (proceed && !await proceed()) return undefined
414 return $.process.spawn({ argv, env: { ...INTEGRATION_ENV } })
415}
416
417/** The longest `thread watch` line read; a snapshot item arrives whole on one line. */
418const MAX_WATCH_LINE = 16 * 1024 * 1024
419
420/**
421 * The events a `thread watch` process prints, one JSON line each on stdout, until it exits, returning
422 * how it exited. Its stderr goes to `stderr`. A line naming an event this plugin does not know is
423 * skipped, and an error event is thrown.
424 */
425export async function* watchEvents(
426 stream: ReturnType<Runtime['process']['spawn']>, stderr?: (text: string) => void,
427): AsyncGenerator<WatchEvent, ProcessSpawnResult> {
428 let pending = ''
429 for (;;) {
430 const piece = await stream.next()
431 if (piece.done) return piece.value
432 if (piece.value.stream === 'stderr') {
433 stderr?.(piece.value.text)
434 continue
435 }
436 pending += piece.value.text
437 if (pending.length > MAX_WATCH_LINE) throw new Error('Delta watch event exceeds the watcher limit')
438 let end: number
439 while ((end = pending.indexOf('\n')) >= 0) {
440 const line = pending.slice(0, end)
441 pending = pending.slice(end + 1)
442 const event = line.trim() ? parseWatchEvent(line) : undefined
443 if (event?.type === 'error') throw event.error
444 if (event) yield event
445 }
446 }
447}
448
449/** The shell command line that merges the forked thread `reference` into the thread `into`. */
450export async function threadMergeCommandLine($: Runtime, reference: string, into: string): Promise<string> {
451 return `${shellQuote(await resolveCli($))} thread merge ${shellQuote(reference)} --into ${shellQuote(into)}`
452}
453
454/** A word for a POSIX shell, quoted unless it is plainly safe as it is. */
455function shellQuote(word: string): string {
456 return /^[\w@%+=:,./#-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`
457}
458
459/** The references of the local worktrees checked out at `directory`, from `worktree list`. */
460export async function worktreeList($: Runtime, directory: string, check?: () => Promise<void>): Promise<string[]> {
461 return localWorktreesAt(await command($, ['worktree', 'list'], 'worktree list', { check }), directory)
462}
463
464/** Create a local worktree for the checkout `directory`; nothing is attached or mounted yet. */
465export async function worktreeCreate(
466 $: Runtime, directory: string, check?: () => Promise<void>,
467): Promise<JsonObject & WorktreeCreationReceipt> {
468 const created = await command($, ['worktree', 'create', directory], 'worktree create', { check })
469 validateWorktreeCreationReceipt(created)
470 return created
471}
472
473/** Make the worktree `reference` a member of `thread`, without mounting it. */
474export async function worktreeAttach(
475 $: Runtime, reference: string, thread: string, check?: () => Promise<void>,
476): Promise<JsonObject & MembershipReceipt> {
477 const attached = await command($, ['worktree', 'attach', reference, '--thread', thread], 'worktree attach', { check })
478 validateWorktreeMembershipReceipt(attached, thread, reference)
479 return attached
480}
481
482/**
483 * Keep the existing checkout `directory` synchronized as the worktree `reference` for as long as
484 * `session` keeps the command running. A process already running for it is reused.
485 */
486export async function worktreeMount($: Runtime, mount: {
487 session: string; reference: string; directory: string; check?: () => Promise<void>
488}): Promise<{ reference: string; directory: string }> {
489 const { session, reference, directory, check } = mount
490 const key = `worktree:${session}:${directory}`
491 const existing = mountProcesses.get(key)
492 if (existing && !existing.stopping && existing.reference === reference) return { reference, directory }
493 const mounted = await mountCommand($, {
494 session, key, name: 'worktree mount', check,
495 args: ['worktree', 'mount', reference, directory, '--existing-checkout'],
496 }, (line) => {
497 const result: unknown = JSON.parse(line)
498 if (!isJsonObject(result)) throw new Error('Invalid checkout attachment receipt; saved records remain queued')
499 validateAttachmentReceipt(result, directory)
500 return { reference: result.reference, directory: result.directory }
501 })
502 const process = mountProcesses.get(key)
503 if (process) process.reference = mounted.reference
504 return mounted
505}
506
507/** Whether `session` has a ready `worktree mount` for the checkout `directory`. */
508export function hasWorktreeMount(session: string, directory: string): boolean {
509 return mountProcesses.has(`worktree:${session}:${directory}`)
510}
511
512/**
513 * Stop `session`'s `worktree mount` processes for the checkout `directory`, still preparing or ready,
514 * and say whether there were any.
515 */
516export async function stopWorktreeMount(session: string, directory: string): Promise<boolean> {
517 const key = `worktree:${session}:${directory}`
518 const processes = [...liveMountProcesses].filter((process) => process.key === key)
519 await Promise.all(processes.map(stopMountProcess))
520 return processes.length > 0
521}
522
523/** Whether Delta still syncs the checkout `directory`, from a `worktree list` answered within `timeoutMs`. */
524export async function checkoutSyncing($: Runtime, directory: string, timeoutMs: number): Promise<boolean> {
525 return checkoutStillSyncing(await command($, ['worktree', 'list'], 'worktree list', { timeoutMs }), directory)
526}
527hooks/setup/interaction.ts 234 lines1/**
2 * What the setup wizard, sign-in and onboarding need from the session: Claude's question dialog, the
3 * browser, and the host bindings they run against.
4 */
5import { type AuthenticationHost, type BrowserWait, requireAuthentication } from '../cli/auth'
6import { clearProgress, reportedProgress, type Progress, setProgress } from '../band/band'
7import { authStatus, INTEGRATION_ENV, orgInvite, resolveCli, threadContract } from '../cli/delta-cli'
8import { createOrganization, listOrganizations } from './organizations'
9import { samePath } from '../core/paths'
10import { activation, type Runtime, stateFor, stillActive } from '../core/session-state'
11import {
12 type AskOption, type AskOptions, type Interaction, InteractionDismissedError, InteractionUnavailableError,
13 type SetupEnv,
14} from './setup'
15import { beginShare, checkoutRoot, gitRemotes, sessionSyncs } from '../sharing/share'
16import { errorText } from '../core/text'
17
18/** The sign-in waiting on the person's browser, which running a Delta command again offers to stop. */
19let browserWait: { on: BrowserWait; stop: AbortController } | undefined
20
21/** Sign-in's view of the session. */
22export async function authenticationHost($: Runtime): Promise<AuthenticationHost> {
23 const windows = await $.env.get('OS') === 'Windows_NT'
24 const stop = new AbortController()
25 let progress: Progress | undefined
26 return {
27 windows,
28 sleep: (milliseconds, signal) => $.clock.sleep(milliseconds, { signal }),
29 spawn: (argv) => $.process.spawn({ argv, env: { ...INTEGRATION_ENV } }),
30 ask: (question, options) => claudeInteraction($).ask(question, { options, header: 'Delta' }),
31 open: (url) => openInBrowser($, url, windows),
32 waiting: (waitingFor) => {
33 if (waitingFor) {
34 browserWait = { on: waitingFor, stop }
35 setProgress($, waitingFor === 'terms' ? "Waiting for Delta's beta terms…" : 'Waiting for Delta sign-in…', 'active')
36 progress = reportedProgress()
37 return
38 }
39 if (browserWait?.stop === stop) browserWait = undefined
40 // What follows sets its own progress; a band still showing the wait would outlive it.
41 if (progress && reportedProgress() === progress) clearProgress($)
42 },
43 stop: stop.signal,
44 }
45}
46
47/**
48 * Offer to stop a sign-in waiting on the browser, answering whether one was waiting. Whatever waited
49 * reports the outcome itself, so the command that asked adds nothing of its own.
50 */
51export async function offerToStopWaiting($: Runtime): Promise<boolean> {
52 const wait = browserWait
53 if (!wait) return false
54 const stop = 'Stop waiting'
55 const answer = await claudeInteraction($).ask(wait.on === 'terms'
56 ? 'Delta is waiting for you to accept its beta terms in your browser. Stop waiting?'
57 : 'Delta is waiting for you to finish signing in with your browser. Stop waiting?',
58 { options: [stop, 'Keep waiting'], header: 'Delta' }).catch(() => undefined)
59 if (answer === stop) wait.stop.abort()
60 return true
61}
62
63/** How long opening a link may take; the opener returns once it has handed the link on. */
64export const OPEN_TIMEOUT_MS = 5_000
65
66/**
67 * Open a web page in the person's browser, answering whether it opened. macOS has `open`; elsewhere
68 * that name is missing or another program, so its failure falls back to the desktop's `xdg-open`.
69 */
70async function openInBrowser($: Runtime, url: string, windows: boolean): Promise<boolean> {
71 const attempts = windows ? [['rundll32', 'url.dll,FileProtocolHandler', url]] : [['open', url], ['xdg-open', url]]
72 for (const argv of attempts) {
73 const opened = await $.process.run(argv, { timeoutMs: OPEN_TIMEOUT_MS }).catch(() => ({ exitCode: 1 }))
74 if (opened.exitCode === 0) return true
75 }
76 return false
77}
78
79/** The host bindings the setup wizard and onboarding run against. */
80export function setupEnv($: Runtime): SetupEnv {
81 const session = activation.session
82 const active = stillActive(session)
83 let cwd: string | undefined
84 const check = async () => {
85 if (!active() || await $.session.id() !== session ||
86 (cwd !== undefined && !samePath(await $.session.cwd(), cwd)))
87 throw new Error('The Claude session or folder changed during setup; the obsolete setup was stopped')
88 }
89 return {
90 checkoutRoot: async () => {
91 cwd = await $.session.cwd()
92 await check()
93 return checkoutRoot($)
94 },
95 // Linked worktrees share the common directory, so they share one onboarding marker. Git before
96 // 2.31 has no `--path-format`, so the directory is resolved against the checkout root instead.
97 gitCommonDir: async () => {
98 try {
99 const root = await checkoutRoot($)
100 const result = await $.process.run(['git', 'rev-parse', '--git-common-dir'], { cwd: root })
101 if (result.exitCode !== 0 || result.isStdoutTruncated) return undefined
102 const lines = result.stdout.trim().split('\n')
103 if (lines.length !== 1 || !lines[0]) return undefined
104 return /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(lines[0]) ? lines[0] : `${root}/${lines[0]}`
105 } catch { return undefined }
106 },
107 remotes: async () => gitRemotes($, await checkoutRoot($)),
108 // Opening links from a plugin needs macOS's `open`; anywhere else the person opens it.
109 openLink: async (url) => {
110 const opened = await $.process.run(['open', url], { timeoutMs: 10_000 }).catch(() => undefined)
111 return opened?.exitCode === 0
112 },
113 contract: async () => {
114 let progress: Progress | undefined
115 try {
116 await check()
117 await resolveCli($, (text) => {
118 setProgress($, text, 'active')
119 progress = reportedProgress()
120 })
121 await check()
122 const contract = await threadContract($)
123 await check()
124 return contract
125 } finally {
126 if (progress && reportedProgress() === progress) clearProgress($)
127 }
128 },
129 authenticate: async (notice) => {
130 await requireAuthentication(await authenticationHost($), await resolveCli($), check, notice, '/delta-setup')
131 await check()
132 },
133 organizations: () => listOrganizations($),
134 login: async () => (await authStatus($)).login,
135 createOrganization: (name) => createOrganization($, name),
136 inviteMembers: (organization, emails) => orgInvite($, organization, emails),
137 readFile: async (path) => await $.fs.exists(path) ? await $.fs.read(path) : undefined,
138 writeFile: (path, text) => $.fs.write(path, text) as Promise<void>,
139 // A joined thread is someone else's shared thread; an organization or unlisted one is already
140 // visible beyond this account.
141 sessionAudience: async () => {
142 const binding = stateFor(await $.session.id()).binding
143 if (binding?.joined || (binding?.visibility && binding.visibility !== 'private')) return 'shared'
144 return sessionSyncs(binding) ? 'private' : 'none'
145 },
146 shareSession: async (audience) => beginShare($, await $.session.id(), { kind: audience }),
147 }
148}
149
150/**
151 * How many of the plugin's own questions are open. `$.ui.ask` runs as an `AskUserQuestion` tool call,
152 * which is the plugin talking to the person, not the conversation, so it is never recorded.
153 */
154let ownQuestions = 0
155
156/** Whether one of the plugin's own questions is open, so its `AskUserQuestion` call is not recorded. */
157export function isAskingOwnQuestion(): boolean {
158 return ownQuestions > 0
159}
160
161/**
162 * The option hints of the plugin's own open questions, by question text. `$.ui.ask` takes labels
163 * only, so the `AskUserQuestion` render hook adds these as the options' descriptions.
164 */
165const questionHints = new Map<string, Readonly<Record<string, string>>>()
166
167/**
168 * Add the hints of the plugin's own open questions to the dialog's options, as their descriptions.
169 * Claude Code draws the original when a rewrite doesn't fit the question's schema, so anything
170 * unexpected is passed on unchanged; another plugin's or Claude's own question has no hints.
171 */
172export function withQuestionHints(questions: unknown[]): unknown[] | undefined {
173 let changed = false
174 const hinted = questions.map((question) => {
175 const hints = questionHints.get((question as { question?: unknown })?.question as string)
176 const options = (question as { options?: unknown })?.options
177 if (!hints || !Array.isArray(options)) return question
178 changed = true
179 return {
180 ...question as object,
181 options: options.map((option) => {
182 const hint = hints[(option as { label?: string })?.label ?? '']
183 return hint ? { ...option, description: hint } : option
184 }),
185 }
186 })
187 return changed ? hinted : undefined
188}
189
190/** `Array.isArray` does not narrow a readonly array out of a union, so `AskOptions` needs its own guard. */
191function isOptionList(options: AskOptions): options is readonly AskOption[] {
192 return Array.isArray(options)
193}
194
195/** The interactive surface the wizard speaks through: `$.ui.ask`, when this Claude build has it. */
196export function claudeInteraction($: Runtime): Interaction {
197 return {
198 async ask(question, options) {
199 let answer: unknown
200 const { descriptions, ...asked } = isOptionList(options) ? { options, descriptions: undefined } : options
201 ownQuestions++
202 if (descriptions) questionHints.set(question, descriptions)
203 try { answer = await $.ui.ask(question, asked as never) }
204 catch (error) {
205 // A missing method is a build without the question API; a dismissed dialog rejects too.
206 if (error instanceof TypeError) throw new InteractionUnavailableError(errorText(error))
207 throw new InteractionDismissedError(errorText(error))
208 }
209 finally {
210 ownQuestions--
211 if (questionHints.get(question) === descriptions) questionHints.delete(question)
212 }
213 if (answer === undefined || answer === null || answer === '') throw new InteractionDismissedError('dismissed')
214 if (typeof answer === 'string') return answer
215 const wrapped = answer as { label?: string; value?: string }
216 return wrapped.label ?? wrapped.value ?? ''
217 },
218 log: async (text, to) => {
219 // The transcript flattens an embedded newline to U+FFFD (see `showToPerson`), so a multi-line
220 // message, like the policy file setup previews, goes out one entry per line.
221 if (to !== 'transcript') return await $.ui.log(text, to ? { to } : undefined)
222 for (const line of text.replace(/\n+$/, '').split('\n')) await $.ui.log(line, { to })
223 },
224 }
225}
226
227/** Log a notice to the transcript at most once per process. */
228const noticesShown = new Set<string>()
229export async function notifyOnce($: Runtime, text: string) {
230 if (noticesShown.has(text)) return
231 noticesShown.add(text)
232 await $.ui.log(text, { to: 'transcript' })
233}
234hooks/sharing/join.ts 589 lines1/**
2 * `/delta join` and what a joined session keeps up: mounting the thread's worktrees, moving Claude
3 * into them, Desktop hand-offs, and restoring and releasing mounts.
4 */
5import { activate, finishRestoredActivation, handedOff, pluginData } from '../setup/activation'
6import { AccessRequiredError, requireAuthentication } from '../cli/auth'
7import { finishProgress, setProgress } from '../band/band'
8import { drain, endDeliveryFailures, flushUnsaved, isInDirectory, recoverExecution, verifyCheckout } from '../recording/delivery'
9import { deliveryRetryDelay } from '../recording/delivery-policy'
10import {
11 type CommandForm, rememberContract, requireContract, resolveCli, stopSessionMounts, stopThreadMounts, threadMount,
12 threadStatus,
13} from '../cli/delta-cli'
14import { type Handoff, HANDOFF_EXPIRY_MS, HANDOFF_PROMPT, newSessionLink, parseHandoff } from './handoff'
15import { authenticationHost, OPEN_TIMEOUT_MS } from '../setup/interaction'
16import {
17 activeBackgroundAgents, joinPreflight, missingJoinCommands, releasesMounts, worktreeChanges,
18} from './lifecycle'
19import { samePath } from '../core/paths'
20import {
21 activation, type Binding, isPaused, key, load, recoveryCommand, report, requests, resumeCheckout, type Runtime, save,
22 serial, sessions, type SessionState, stateFor, storedBinding,
23} from '../core/session-state'
24import {
25 classifyCommandFailure, DeltaCommandError, type MountedThread, type ThreadState,
26} from '../cli/thread-commands'
27import { errorText } from '../core/text'
28import { isRetrying, isCurrentReady, startConversation, statusFields, stopConversation } from '../watch/watch'
29import { deliverNote, rowsHeld } from '../watch/rows'
30import { releaseThreadMounts } from '../subagents/thread-runs'
31
32/** A join to finish in a session; `owner` names a mount another session made for it to take over. */
33export type JoinPlan = { session: string; cwd: string; locator: string; thread: string; owner?: string }
34export type JoinRequest = {
35 session: string; cwd: string; locator: string; fresh?: string; clearing?: boolean; cancelled?: boolean
36 contractVersion?: number; form?: CommandForm
37}
38/** How often an offered hand-off is checked; the claiming session is another process. */
39const HANDOFF_POLL_MS = 2_000
40
41/**
42 * Start a join: it is in progress from now, reported through the band, and runs on the clock, since
43 * a timer leaves the active command before invoking commands that wait for idle.
44 */
45export function startJoin($: Runtime, request: JoinRequest) {
46 requests.join = request
47 setProgress($, 'Checking access to the shared thread…', 'active')
48 $.clock.after(0, () => joinSession($, request))
49}
50
51async function joinSession($: Runtime, request: JoinRequest) {
52 let plan: JoinPlan | undefined
53 let fresh: string | undefined
54 try {
55 await assertJoinSession($, request.session, request)
56 if (!samePath(await $.session.cwd(), request.cwd))
57 throw new Error('The session or folder changed while join was queued; retry from the intended session')
58 const pending = await load($, request.session)
59 const runtime = stateFor(request.session)
60 if (runtime.currentTurnId || runtime.promptEntering)
61 throw new Error('Wait for Claude to become idle before joining')
62 if (runtime.restoring || runtime.restoringCheckout)
63 throw new Error("Wait for Delta to finish restoring this session's worktrees before joining")
64 if (activeBackgroundAgents(await $.agent.list()))
65 throw new Error('Stop background agents and teammates before joining; an idle main turn is not sufficient')
66 // Refuse a CLI this plugin cannot record against before any transition, mount, or clear.
67 await resolveCli($, (text) => setProgress($, text, 'active'))
68 // `/clear` ends the old session and removes its cached contract before the fresh session mounts.
69 request.contractVersion = await requireContract($, request.session)
70 const check = async () => {
71 await assertJoinSession($, request.session, request)
72 if (await $.session.cwd() !== request.cwd)
73 throw new Error('The folder changed during sign-in; retry join from the intended folder')
74 }
75 await requireAuthentication(await authenticationHost($), await resolveCli($), check, async (text) => {
76 await check()
77 setProgress($, 'Waiting for Delta sign-in…', 'active')
78 await $.ui.log(text, { to: 'transcript' })
79 })
80 await check()
81 if (pending.joinTransition) {
82 plan = pending.joinTransition
83 fresh = request.session
84 request.fresh = fresh
85 if (plan.locator !== request.locator) throw new Error('Retry the pending join with its original locator')
86 await completeJoin($, fresh, plan, request)
87 return
88 }
89 let status = pending.joined ? await readJoinStatus($, request) : undefined
90 await assertJoinSession($, request.session, request)
91 if (pending.joined && status?.thread_id === pending.thread) {
92 // Resolve aliases by canonical identity; never replace this producer with an empty frontier.
93 setProgress($, 'Reconnecting to the shared thread…', 'active')
94 await restoreMounts($, request.session, () => assertJoinSession($, request.session, request))
95 await verifyCheckout($, await load($, request.session))
96 await assertJoinSession($, request.session, request)
97 if (runtime.unsaved.length) await flushUnsaved($, request.session)
98 const binding = await load($, request.session)
99 await assertJoinSession($, request.session, request)
100 if (runtime.captureFailure || binding.captureFailure)
101 throw new Error(`a stored Claude row could not be saved locally (${runtime.captureFailure ?? binding.captureFailure}); restore the outbox before retrying`)
102 resumeCheckout(runtime, 'delivery')
103 endDeliveryFailures(runtime)
104 if (isRetrying()) await stopConversation()
105 await assertJoinSession($, request.session, request)
106 await startConversation($, request.session)
107 await recoverExecution($, request.session)
108 await drain($, request.session)
109 await assertJoinSession($, request.session, request)
110 await verifyCheckout($, await load($, request.session))
111 if (isPaused(runtime) || runtime.unsaved.length)
112 throw new Error('Joined participation remains paused; saved records remain queued')
113 // The band reports the rejoin through the finished notice; the transcript keeps only conversation.
114 $.ui.log(`Reconnected to the joined Delta thread in Claude session ${request.session}; the checkout and producer state were preserved.`, { to: 'debug' })
115 finishProgress($, 'Joined the shared thread', 'done')
116 return
117 }
118 // Claude Code Desktop has no `/cd`, applies its own folder tool's move only when a model turn
119 // ends, which a join run from a command never has, and never moves a worktree session at all.
120 // So a Desktop join starts a new session in the thread's folder instead.
121 const handsOff = (await $.session.surfaces()).includes('desktop')
122 // `/delta join` is the request, and the fresh session leaves this one resumable, so the only
123 // question is Claude's own folder trust prompt.
124 if (!handsOff) await requireJoinCommands($, ['clear', 'cd'])
125 await assertJoinSession($, request.session, request)
126 status ??= await readJoinStatus($, request)
127 await assertJoinSession($, request.session, request)
128 if (joinPreflight(status) === 'access')
129 throw new Error('Joining requires authenticated access to an already shared thread; check your Delta sign-in and link')
130 // Only the fresh session can own the mount, so mounting waits for it. Refuse here what a mount
131 // could never satisfy, while the old session is still untouched.
132 if (joinPreflight(status) === 'empty')
133 throw new Error('This thread has no worktree to join')
134 if (handsOff) {
135 const handoff = await pendingHandoff($, request.cwd)
136 if (handoff?.thread === status.thread_id) await takeOverHandoff($, request, handoff)
137 else await offerHandoff($, request, status)
138 return
139 }
140 plan = { session: request.session, cwd: request.cwd, locator: request.locator, thread: status.thread_id }
141 if (await $.session.id() !== request.session || !samePath(await $.session.cwd(), request.cwd))
142 throw new Error('The session or folder changed during the access check; nothing was changed')
143 if (activeBackgroundAgents(await $.agent.list()))
144 throw new Error('A background agent started during the access check; stop it before retrying')
145 await assertJoinSession($, request.session, request)
146 setProgress($, 'Starting a fresh Claude session…', 'active')
147 request.clearing = true
148 try { await $.command.run({ command: 'clear' }) }
149 finally { request.clearing = false }
150 fresh = await $.session.id()
151 if (fresh === request.session) {
152 fresh = undefined
153 throw new Error('Claude did not create a fresh session after /clear; the old binding was not replaced')
154 }
155 request.fresh = fresh
156 await assertJoinSession($, fresh, request)
157 if ((await load($, fresh)).snapshot)
158 throw new Error('The new Claude session already has a binding; it was not replaced')
159 // Persist a blocking retry state, not a completed binding in the wrong directory.
160 const target = fresh
161 const transition = plan
162 await serial(async () => {
163 await assertJoinSession($, target, request)
164 await save($, { session: target, snapshot: false, next: 1, pending: [], joinTransition: transition }, () => !request.cancelled)
165 })
166 await completeJoin($, fresh, plan, request)
167 } catch (error) {
168 if (request.cancelled) return
169 const invalidLocator = error instanceof DeltaCommandError && error.code === 'invalid_reference'
170 // Sign-in runs before the session changes, so an access requirement leaves nothing to preserve.
171 const text = error instanceof AccessRequiredError && !fresh ? error.message : `Delta join failed: ${errorText(error)}. ${invalidLocator
172 ? `The ${fresh ? 'fresh session' : 'previous session and folder'} was preserved. Use the thread's share link with /delta-join instead of retrying this locator.`
173 : fresh
174 ? `Fresh session ${fresh} was preserved. Retry /delta-join ${plan?.locator ?? request.locator} to finish the saved transition; the previous session is ${plan?.session ?? request.session} at ${plan?.cwd ?? request.cwd}.`
175 : `The previous session and folder were preserved. Retry /delta-join ${request.locator}.`}`
176 if (fresh) stateFor(fresh).joinFailure = text
177 setProgress($, text, 'error')
178 await $.ui.log(text, { to: 'transcript' })
179 } finally {
180 if (requests.join === request) requests.join = undefined
181 }
182}
183
184/** How long a join waits out failures Delta marks retryable, such as a daemon still connecting. */
185const JOIN_RETRY_BUDGET_MS = 30_000
186
187/**
188 * Reads the thread's status for a join, retrying failures Delta marks retryable.
189 *
190 * A join often runs right after the session starts, when Delta's daemon may still be connecting
191 * and answers `disconnected`; a person waiting on the join should not have to retry that.
192 */
193async function readJoinStatus($: Runtime, request: JoinRequest) {
194 const deadline = await $.clock.now() + JOIN_RETRY_BUDGET_MS
195 for (let attempt = 0; ; attempt++) {
196 try { return await threadStatus($, request.locator, request.session) }
197 catch (error) {
198 const delay = deliveryRetryDelay(attempt, error instanceof DeltaCommandError ? error.hints.retryAfterMs : undefined)
199 if (classifyCommandFailure(error) !== 'transient' || await $.clock.now() + delay > deadline) throw error
200 setProgress($, 'Waiting for Delta to connect…', 'active')
201 await $.clock.sleep(delay)
202 await assertJoinSession($, request.session, request)
203 }
204 }
205}
206
207async function assertJoinSession($: Runtime, session: string, request: JoinRequest) {
208 if (request.cancelled || await $.session.id() !== session)
209 throw new Error('The Claude session changed during join; the obsolete transition was stopped')
210}
211
212/** Check actual host capabilities before any destructive session transition. */
213async function requireJoinCommands($: Runtime, names: string[]) {
214 const commands = await $.command.list()
215 const missing = missingJoinCommands(names, commands)
216 if (missing.length)
217 throw new Error(`This Claude host does not expose the built-in ${missing.map((name) => `/${name}`).join(' and ')} command required to join; the saved session and mount plan were preserved`)
218}
219
220/** Complete only the saved fresh session's transition, never clear again on retry. */
221async function completeJoin($: Runtime, session: string, plan: JoinPlan, request: JoinRequest) {
222 // This session runs against the same CLI build `join` already verified for this process; `/clear`
223 // removed the old session's verification before this fresh one started.
224 rememberContract(session, request.contractVersion!)
225 const check = () => assertJoinSession($, session, request)
226 await check()
227 setProgress($, "Mounting the thread's worktrees…", 'active')
228 const mounted = await mountThread(
229 $, { session, thread: plan.thread, locator: plan.locator, owner: plan.owner },
230 { reportJoin: !plan.owner, form: request.form },
231 )
232 await check()
233 requireMounted(mounted, plan.thread)
234 // Remember the verified destination even if Claude refuses /cd; the retry notice must name it.
235 await serial(async () => {
236 await check()
237 await save($, { ...await load($, session), directory: mounted.directory }, () => !request.cancelled)
238 })
239 await enterDirectory($, session, mounted.directory, check)
240 const binding: Binding = {
241 session, thread: plan.thread, locator: plan.locator, joined: true,
242 owner: plan.owner ?? session, directory: mounted.directory, mounts: mounted.worktrees,
243 // snapshot means live recording is enabled, not that old history must be exported.
244 snapshot: true, next: 1, pending: [],
245 }
246 const status = await verifyCheckout($, binding)
247 await check()
248 Object.assign(binding, statusFields(status))
249 await serial(async () => {
250 await check()
251 await save($, binding, () => !request.cancelled)
252 })
253 stateFor(session).mounted = true
254 await check()
255 // Neither session.start nor classic.SessionStart is relied upon after clear/cd.
256 setProgress($, 'Connecting to the shared thread…', 'active')
257 await activate($, session, () => !request.cancelled)
258 await check()
259 await startConversation($, session)
260 // The band reports the join through the finished notice; the way back to the previous session stays in the debug log.
261 $.ui.log(plan.owner
262 ? `Joined Delta in Claude session ${session} at ${mounted.directory}, taking over mount owner ${plan.owner}.`
263 : `Joined Delta in fresh Claude session ${session} at ${mounted.directory}. Resume the previous session with claude --resume ${plan.session} from ${plan.cwd}.`,
264 { to: 'debug' })
265 finishProgress($, 'Joined the shared thread', 'done')
266}
267
268/**
269 * Keep the checkout of every worktree of a joined thread mounted for this session, as its thread's
270 * attachments change, until this plugin process stops the mount.
271 */
272export async function mountThread(
273 $: Runtime,
274 binding: { session: string; thread?: string; locator?: string; owner?: string },
275 options: { reportJoin?: boolean; form?: CommandForm } = {},
276): Promise<MountedThread> {
277 const locator = binding.locator ?? binding.thread
278 if (!locator) throw new Error('This session has no thread to mount')
279 return threadMount($, {
280 session: binding.session, thread: binding.thread ?? locator, locator, owner: binding.owner ?? binding.session,
281 join: !!options.reportJoin, form: options.form,
282 })
283}
284
285function handoffPath(owner: string) { return `${pluginData}/handoffs/${owner}.json` }
286
287/**
288 * Hand a Desktop tab's join to a new Desktop session: mount the thread under an owner of its own,
289 * record the hand-off, and open Desktop's new-session screen on the thread folder. Nothing in this
290 * tab changes.
291 */
292async function offerHandoff($: Runtime, request: JoinRequest, status: ThreadState) {
293 const owner = `desktop-${crypto.randomUUID()}`
294 const check = () => assertJoinSession($, request.session, request)
295 setProgress($, "Mounting the thread's worktrees…", 'active')
296 const mounted = await mountThread(
297 $, { session: request.session, thread: status.thread_id, locator: request.locator, owner },
298 { reportJoin: true, form: request.form },
299 )
300 const handoff: Handoff = {
301 owner, thread: status.thread_id, locator: request.locator, directory: mounted.directory,
302 created: await $.clock.now(),
303 }
304 try {
305 await check()
306 requireMounted(mounted, status.thread_id)
307 await $.fs.write(handoffPath(owner), JSON.stringify(handoff))
308 const link = newSessionLink(mounted.directory, HANDOFF_PROMPT)
309 const opened = await $.process.run(['open', link], { timeoutMs: OPEN_TIMEOUT_MS }).catch((error) => ({ exitCode: 1, stderr: errorText(error) }))
310 stateFor(request.session).offered = handoff
311 const thread = status.title?.trim() ? `“${status.title.trim()}”` : 'the thread'
312 if (opened.exitCode === 0)
313 setProgress($, `Press Enter in the new Claude Code Desktop session to join ${thread} there; this tab stays as it is. Desktop may ask you to trust the thread's folder. It waits 5 minutes.`, 'active')
314 else {
315 // Opening links from a plugin needs macOS's `open`; anywhere else the person opens it.
316 setProgress($, `Open the link in this transcript, then press Enter in the new session to join ${thread} there. It waits 5 minutes.`, 'active')
317 await $.ui.log(`Open this link to start a Claude Code session in the Delta thread's folder: ${link}`, { to: 'transcript' })
318 }
319 $.clock.after(HANDOFF_POLL_MS, () => watchHandoff($, request.session, handoff))
320 } catch (error) {
321 await releaseHandoff($, handoff)
322 throw error
323 }
324}
325
326/** Follow an offered hand-off until a new session claims it, or release it once it expires. */
327async function watchHandoff($: Runtime, session: string, handoff: Handoff) {
328 const runtime = stateFor(session)
329 if (runtime.offered !== handoff) return
330 if (!await $.fs.exists(handoffPath(handoff.owner))) {
331 runtime.offered = undefined
332 finishProgress($, 'Opened the thread in a new session', 'done')
333 return
334 }
335 if (await $.clock.now() - handoff.created < HANDOFF_EXPIRY_MS) {
336 $.clock.after(HANDOFF_POLL_MS, () => watchHandoff($, session, handoff))
337 return
338 }
339 runtime.offered = undefined
340 await releaseHandoff($, handoff)
341 const text = `No session joined the Delta thread within 5 minutes, so Delta released its checkouts. Run /delta-join ${handoff.locator} to bring it back.`
342 finishProgress($, text, 'done')
343 await $.ui.log(text, { to: 'transcript' })
344}
345
346/**
347 * Release a hand-off's mount and record. With `onlyUnclaimed`, a record a new session already
348 * removed means that session owns the mount now, and nothing is released.
349 */
350async function releaseHandoff($: Runtime, handoff: Handoff, onlyUnclaimed = false) {
351 if (onlyUnclaimed && !await $.fs.exists(handoffPath(handoff.owner)).catch(() => true)) return
352 await $.process.run(['rm', '-f', '--', handoffPath(handoff.owner)]).catch(() => undefined)
353 await unmountThread($, handoff.locator, handoff.owner)
354}
355
356/** The hand-off offered for a session starting in `directory`, if any. */
357export async function pendingHandoff($: Runtime, directory: string): Promise<Handoff | undefined> {
358 const folder = `${pluginData}/handoffs`
359 if (!await $.fs.exists(folder)) return
360 for (const entry of await $.fs.list(folder)) {
361 if (!entry.name.endsWith('.json')) continue
362 let text: string
363 try { text = await $.fs.read(`${folder}/${entry.name}`) as string } catch { continue }
364 const handoff = parseHandoff(text)
365 if (handoff && samePath(handoff.directory, directory)) return handoff
366 }
367}
368
369/**
370 * Join a hand-off in the session that started in its folder, before the first prompt arrives.
371 * Failure is reported in the band and transcript, and holds prompts until /delta join is retried.
372 */
373export async function claimHandoff($: Runtime, session: string, handoff: Handoff) {
374 const request: JoinRequest = { session, cwd: handoff.directory, locator: handoff.locator }
375 try {
376 setProgress($, 'Joining the shared thread…', 'active')
377 request.contractVersion = await requireContract($, session)
378 await takeOverHandoff($, request, handoff)
379 } catch (error) {
380 if (request.cancelled) return
381 const text = `Delta couldn't join the thread in this session: ${errorText(error)}. Run /delta-join ${handoff.locator} to retry.`
382 stateFor(session).joinFailure = text
383 setProgress($, text, 'error')
384 await $.ui.log(text, { to: 'transcript' })
385 }
386}
387
388/**
389 * Join in the session a hand-off started in the thread's folder: claim the record first, so the
390 * offering tab's expiry cannot release the mount, then take the mount over under the same owner
391 * and join without clearing or moving.
392 */
393async function takeOverHandoff($: Runtime, request: JoinRequest, handoff: Handoff) {
394 await $.process.run(['rm', '-f', '--', handoffPath(handoff.owner)])
395 await completeJoin($, request.session, {
396 session: request.session, cwd: request.cwd, locator: handoff.locator, thread: handoff.thread, owner: handoff.owner,
397 }, request)
398}
399
400/** What a mount that joining or restoring can use: the right thread, and something to work in. */
401export function requireMounted(mounted: MountedThread, thread: string | undefined) {
402 if (mounted.thread_id !== thread) throw new Error('Delta mounted a different thread; no session transition was attempted')
403 if (!mounted.worktrees.length) throw new Error('This thread has no worktree to join')
404}
405
406/**
407 * Move Claude into a mount's directory unless it is already there. Claude resumes in the directory
408 * it was launched from, and `/cd` is the only way a plugin changes the session's directory.
409 */
410async function enterDirectory($: Runtime, session: string, directory: string, check: () => Promise<void>) {
411 if (await isInDirectory($, directory)) return
412 await requireJoinCommands($, ['cd'])
413 await check()
414 setProgress($, "Waiting for you to trust the thread's folder…", 'active')
415 // Claude's trust prompt names only a path, so say what the folder is and which answer joins.
416 await $.ui.log(
417 `Delta put this thread's code in its own folder for this session. Claude Code asks before working in a new folder: choose "Yes, move here" to continue. "No, stay put" pauses Delta in this session until you run /delta-join again.`,
418 { to: 'transcript' })
419 await $.command.run({ command: 'cd', args: directory })
420 await check()
421 if (await $.session.id() !== session || !samePath(await $.session.cwd(), directory) ||
422 !samePath(await $.session.root(), directory))
423 throw new Error('Claude did not keep the session in the exact mounted directory; participation remains paused')
424}
425
426/**
427 * Mount a joined session's worktrees again and put Claude in their directory. Mounting is
428 * idempotent: it restores what was removed after the session's owner process last ran, and it
429 * returns the directory Claude should work in now.
430 */
431async function restoreMounts($: Runtime, session: string, check: () => Promise<void>) {
432 const binding = await serial(() => load($, session))
433 await check()
434 const mounted = await mountThread($, binding)
435 await check()
436 requireMounted(mounted, binding.thread)
437 await enterDirectory($, session, mounted.directory, check)
438 await serial(async () => {
439 await check()
440 await save($, { ...await load($, session), owner: binding.owner ?? session, directory: mounted.directory, mounts: mounted.worktrees })
441 })
442 stateFor(session).mounted = true
443}
444
445/**
446 * Restore a resumed joined session in the background: prompts wait, and the band shows progress.
447 * Mounting and `/cd` leave the session hook first, as join's do, since `/cd` waits for the idle prompt.
448 */
449export function beginRestore($: Runtime, session: string) {
450 const runtime = stateFor(session)
451 if (runtime.restoring) return
452 runtime.restoring = true
453 setProgress($, "Restoring the thread's worktrees…", 'active')
454 const owns = () => activation.session === session && sessions.get(session) === runtime
455 $.clock.after(0, async () => {
456 try {
457 await restoreMounts($, session, async () => {
458 if (!owns()) throw new Error('The session ended while its worktrees were being restored')
459 })
460 const binding = await serial(() => load($, session))
461 await startParticipation($, session, binding, owns)
462 if (!owns()) return
463 finishProgress($, `Restored ${binding.mounts?.length ?? 0} worktree${binding.mounts?.length === 1 ? '' : 's'}`, 'done')
464 await finishRestoredActivation($, session, binding, owns)
465 } catch (error) {
466 if (!owns()) return
467 const text = `Delta couldn't restore this session's worktrees: ${errorText(error)}. Retry ${recoveryCommand(runtime.binding)}; the prompt was not submitted.`
468 runtime.joinFailure = text
469 setProgress($, text, 'error')
470 await $.ui.log(text, { to: 'transcript' })
471 } finally {
472 runtime.restoring = undefined
473 }
474 })
475}
476
477/** End this session's mount commands; Delta owns the bounded cleanup after they disconnect. */
478async function releaseMounts($: Runtime, session: string) {
479 try { await stopSessionMounts(session) }
480 catch (error) { await $.ui.log(`Delta mount process did not stop: ${String(error)}`, { to: 'debug' }) }
481}
482
483/** Stop `owner`'s mount of `thread`, if this plugin process still holds it; a failure is only logged. */
484export async function unmountThread($: Runtime, thread: string, owner: string) {
485 try { await stopThreadMounts(owner) }
486 catch (error) { await $.ui.log(`Delta could not stop ${thread}'s mount: ${String(error)}`, { to: 'debug' }) }
487}
488
489/** The worktrees of a joined thread changed: re-mount, then tell Claude and the person. */
490export function refreshMounts($: Runtime, session: string, listed: { reference: string }[]) {
491 const runtime = stateFor(session)
492 runtime.mountRefresh = (runtime.mountRefresh ?? Promise.resolve())
493 .then(() => applyWorktrees($, session, listed))
494 .catch((error) => {
495 if (activation.session !== session) return
496 const text = `Delta couldn't update this session's worktrees: ${errorText(error)}`
497 setProgress($, text, 'error')
498 return $.ui.log(text, { to: 'transcript' })
499 })
500}
501
502async function applyWorktrees($: Runtime, session: string, listed: { reference: string }[]) {
503 const runtime = stateFor(session)
504 if (activation.session !== session || !runtime.mounted) return
505 const binding = await serial(() => load($, session))
506 const previous = binding.mounts
507 if (!binding.joined || !previous) return
508 // Every reconnect reports the current list; most of those change nothing.
509 if (listed.length === previous.length && listed.every((tree) => previous.some((mount) => mount.reference === tree.reference))) return
510 const mounted = await mountThread($, binding)
511 if (activation.session !== session || mounted.thread_id !== binding.thread) return
512 await serial(async () => save($, { ...await load($, session), mounts: mounted.worktrees }))
513 const { added, removed, moves } = worktreeChanges(previous, binding.directory, mounted)
514 if (!added.length && !removed.length) return
515 const names = (trees: { name: string }[]) => trees.map((tree) => tree.name).join(', ')
516 const changes = [added.length ? `added ${names(added)}` : '', removed.length ? `removed ${names(removed)}` : ''].filter(Boolean).join('; ')
517 finishProgress($, `Thread worktrees changed: ${changes}${moves ? ' · moving to the thread folder' : ''}`, 'done')
518 await deliverNote($, session, [
519 `[Delta] This thread's worktrees changed (${changes}). They are now:`,
520 ...mounted.worktrees.map((tree) => `- ${tree.name}: ${tree.directory}`),
521 moves ? `Delta will move this session to ${mounted.directory}, which links to each of them, once the current turn ends.`
522 : `This session's directory is ${binding.directory}.`,
523 ].join('\n'))
524 if (moves) {
525 runtime.moveTo = mounted.directory
526 scheduleMove($, session)
527 }
528}
529
530export function scheduleMove($: Runtime, session: string) {
531 const runtime = stateFor(session)
532 if (!runtime.moveTo || runtime.moving || rowsHeld(session)) return
533 runtime.moving = true
534 $.clock.after(0, () => moveSession($, session))
535}
536
537/** Move Claude from a worktree's checkout to the thread folder, between turns. */
538async function moveSession($: Runtime, session: string) {
539 const runtime = stateFor(session)
540 const directory = runtime.moveTo
541 try {
542 // A turn that began since is the one whose end moves the session.
543 if (!directory || activation.session !== session || rowsHeld(session)) return
544 const binding = await serial(() => load($, session))
545 if (!binding.directory || !await isInDirectory($, binding.directory)) { runtime.moveTo = undefined; return }
546 const check = async () => { if (activation.session !== session) throw new Error('The session ended during the move') }
547 await enterDirectory($, session, directory, check)
548 await serial(async () => save($, { ...await load($, session), directory }))
549 runtime.moveTo = undefined
550 resumeCheckout(runtime, 'verification')
551 finishProgress($, 'Moved to the thread folder', 'done')
552 await deliverNote($, session, `[Delta] This session's directory is now ${directory}. It links to each worktree of the thread.`)
553 void drain($, session).catch((error) => report($, error))
554 } catch (error) {
555 runtime.moveTo = undefined
556 if (activation.session !== session) return
557 const text = `Delta couldn't move Claude to the thread folder ${directory}: ${errorText(error)}. The session stays where it is; /cd there to work across every worktree.`
558 setProgress($, text, 'error')
559 await $.ui.log(text, { to: 'transcript' })
560 } finally {
561 runtime.moving = undefined
562 }
563}
564
565/** Check a joined session's mounts, then watch the thread; the watch lifts the watcher pause once live. */
566export async function startParticipation($: Runtime, session: string, binding: Binding, owns: () => boolean) {
567 if (binding.joined) await verifyCheckout($, binding)
568 if (!owns()) return
569 const ready = await startConversation($, session)
570 if (owns() && isCurrentReady(ready)) resumeCheckout(stateFor(session), 'watcher')
571}
572
573/**
574 * Exiting ends the session's use of its checkouts. A clear is the join's own transition and a resume
575 * only switches sessions, so neither releases them. A conversation that moved to another session
576 * keeps its checkouts there; its subagents' stay with this session and are released. An offered
577 * hand-off nobody opened goes with the tab that offered it.
578 */
579export async function releaseOnEnd($: Runtime, session: string, reason: string, runtime: SessionState) {
580 if (releasesMounts(reason)) {
581 if (!await handedOff($, session)) await releaseMounts($, session)
582 const ended = await storedBinding($, key(session)).catch(() => undefined)
583 await releaseThreadMounts($, session, ended?.children ?? [])
584 }
585 const offered = runtime.offered
586 runtime.offered = undefined
587 if (offered && releasesMounts(reason)) await releaseHandoff($, offered, true)
588}
589hooks/recording/prompt.ts 143 lines1/** Admitting a prompt into a recorded session: what must be ready before the turn it starts is recorded. */
2
3import {
4 activate, activationIncomplete, adoptContinuation, captureDecided, continuationCandidate, continuedFrom,
5 retryAutomaticActivation,
6} from '../setup/activation'
7import { recordsOffline, verifyCheckout } from './delivery'
8import { beginRestoreCheckout, checkoutNeedsMount } from '../sharing/checkout'
9import { HANDOFF_ACKNOWLEDGEMENT, HANDOFF_PROMPT } from '../sharing/handoff'
10import { ownsSteering, promptGate } from '../sharing/lifecycle'
11import {
12 activation, type HookEvent, type HookNext, isPaused, pauseCheckout, pauseNotice, recoveryAdvice, requests,
13 resumeCheckout, type Runtime, stateFor,
14} from '../core/session-state'
15import { errorText } from '../core/text'
16import { classifyCommandFailure, JoinNotReadyError } from '../cli/thread-commands'
17import { liveFor, startConversation } from '../watch/watch'
18import { settleRemote, settling } from '../watch/rows'
19
20/**
21 * Admit a prompt into a recorded session, or drop it with why: a hand-off's opening line becomes a
22 * local turn, a running join or share refuses it, and a recorded session's watcher, checkout and
23 * capture must be ready before the turn it starts is recorded.
24 */
25export async function admitPrompt($: Runtime, e: HookEvent<'prompt.submit'>, next: HookNext<'prompt.submit'>) {
26 // A hand-off's opening line only started this session, which has joined by now. It becomes a
27 // one-word turn that the thread never records, rather than a message to the thread or a
28 // dropped prompt Desktop would show as blocked.
29 const opening = stateFor(await $.session.id())
30 if (opening.handoffClaim) {
31 const claim = opening.handoffClaim
32 await claim
33 if (opening.handoffClaim === claim) opening.handoffClaim = undefined
34 if (!opening.joinFailure && !e.turnId && e.text.trim() === HANDOFF_PROMPT) {
35 opening.localTurn = {}
36 return next({ ...e, text: HANDOFF_ACKNOWLEDGEMENT })
37 }
38 }
39 const operation = promptGate({ joining: !!requests.join, sharing: !!requests.share })
40 if (operation === 'joining') return { drop: 'Delta is joining in a fresh session. Wait for the join result before submitting a prompt.' }
41 if (operation === 'sharing') return { drop: 'Delta is sharing this session. Wait for the share result before submitting a prompt.' }
42 const session = await $.session.id()
43 const runtime = stateFor(session)
44 if (runtime.joinFailure) return { drop: `${runtime.joinFailure} The prompt was not submitted.` }
45 // A new session's prompt waits for its capture boundary, so a prompt typed right after `/clear` or
46 // sent headlessly is recorded rather than lost before the snapshot exists.
47 await captureDecided(session)
48 // A hot reload can install this hook without replaying session.start.
49 if (activation.session !== session || !runtime.binding) {
50 try { await activate($, session) }
51 catch (error) {
52 return { drop: `Delta conversation initialization failed: ${errorText(error)}. The prompt was not submitted.` }
53 }
54 }
55 const transition = runtime.binding?.joinTransition
56 const blocked = promptGate({
57 transition: !!transition, snapshot: !!runtime.binding?.snapshot,
58 restoring: !!runtime.restoring, movePending: !!runtime.moveTo, steering: !!e.turnId,
59 })
60 if (blocked === 'transition' && transition)
61 return { drop: `The Delta join directory transition is incomplete. Run /delta-join ${transition.locator} to retry; the prompt was not submitted.` }
62 if (blocked === 'restoring')
63 return { drop: "Delta is restoring this thread's worktrees. Wait for the band to say they are restored, then try again. The prompt was not submitted." }
64 if (blocked === 'moving')
65 return { drop: 'Delta is moving Claude to the thread folder between turns. Try again in a moment. The prompt was not submitted.' }
66 // Claude Code can start a continuation before the parent's transcript names it; look once more.
67 if (runtime.binding && continuationCandidate(session, runtime.binding) && !runtime.continuationRechecked) {
68 runtime.continuationRechecked = true
69 const parent = await continuedFrom($, session)
70 if (parent && await adoptContinuation($, session, parent.session)) {
71 try { await activate($, session) }
72 catch (error) { return { drop: `Delta couldn't continue recording this conversation: ${errorText(error)}. The prompt was not submitted.` } }
73 if (runtime.restoring) return { drop: "Delta is restoring this thread's worktrees for the continued conversation. Wait for the band to say they are restored, then try again. The prompt was not submitted." }
74 }
75 }
76 if (!runtime.binding?.snapshot) return next(e)
77 // A session that records offline does not wait for the watcher and never drops a prompt for a
78 // delivery pause: the pause stops delivery, and this prompt retries delivery and any incomplete
79 // automatic activation once. A poison record simply stays queued, its notice shown once.
80 const offline = recordsOffline(session, runtime.binding)
81 // An unfinished automatic activation records locally and retries from here, whether or not the
82 // CLI has answered its contract yet; there is no thread to watch or verify until it completes.
83 const incomplete = activationIncomplete(runtime)
84 if (offline || incomplete) {
85 if (runtime.pauses.has('delivery')) resumeCheckout(runtime, 'delivery')
86 retryAutomaticActivation($, session, runtime)
87 // A checkout whose mount failed to come back, or ended, is restored again in the background.
88 if (offline && !incomplete && checkoutNeedsMount(session, runtime.binding)) beginRestoreCheckout($, session)
89 } else if (runtime.pauses.has('delivery')) {
90 // Watching again cannot lift a refusal, so do not restart the watcher for one.
91 return { drop: `${runtime.pauses.get('delivery') ?? pauseNotice(runtime)} The prompt was not submitted.` }
92 }
93 // A session that does not record offline still recovers the watcher here and refuses if it cannot.
94 if (!offline && !incomplete && (!runtime.binding.thread || isPaused(runtime) || !liveFor(session))) {
95 try { await startConversation($, session) }
96 catch (error) { return { drop: `The Delta watcher is not ready: ${errorText(error)}. ${recoveryAdvice(runtime.binding)}.` } }
97 }
98 if (e.turnId) {
99 const execution = runtime.binding.execution
100 if (!ownsSteering(execution, e.turnId))
101 return { drop: 'This Claude turn no longer owns the shared conversation.' }
102 return next(e)
103 }
104 try {
105 if (runtime.captureFailure || runtime.binding.captureFailure)
106 throw new Error(`local conversation capture is paused; ${recoveryAdvice(runtime.binding)} before continuing`)
107 // A prompt that arrives mid-activation records locally while create, upload, and attach finish,
108 // and one that arrives while the checkout's mount is restored records locally until it is.
109 if (!activationIncomplete(runtime) && !runtime.restoringCheckout) {
110 await verifyCheckout($, runtime.binding)
111 if (isPaused(runtime)) throw new Error(pauseNotice(runtime))
112 }
113 } catch (error) {
114 // Offline, an unanswered checkout check says nothing about the checkout: the records stay
115 // queued and retry, so the prompt proceeds rather than being dropped. A non-retryable refusal
116 // or a local persistence failure still stops it.
117 if (!(offline && classifyCommandFailure(error) === 'transient' && !isPaused(runtime))) {
118 const text = `Delta is not ready for this prompt: ${errorText(error)}. The prompt was not submitted.`
119 // The band names a worktree or directory that is not ready, until a prompt finds it ready.
120 if (error instanceof JoinNotReadyError) pauseCheckout(runtime, 'verification', error.message)
121 return { drop: text }
122 }
123 }
124 // Remote activity that already completed precedes the prompt; later rows wait for its turn.
125 // Like a native Delta send, the turn this prompt starts takes over any running remote turn.
126 await settleRemote($, session)
127 let result: Awaited<ReturnType<typeof next>>
128 try {
129 runtime.promptEntering = true
130 await settling
131 result = await next(e)
132 } catch (error) {
133 runtime.promptEntering = false
134 void settleRemote($, session)
135 throw error
136 }
137 if (result.drop !== undefined) {
138 runtime.promptEntering = false
139 void settleRemote($, session)
140 }
141 return result
142}
143hooks/watch/row-delivery.ts 124 lines1import { isThoughtItem } from './conversation'
2import type { WatchItem } from '../cli/thread-commands'
3
4type DrawResult = { deny?: string }
5type DrawTimer = { cancel(): void }
6export type PendingDraw = { session: string; id: string; settle(result: DrawResult): void }
7
8/** Thinking is announced once on live completion and never becomes a model row. */
9export function announceThought(before: WatchItem | undefined, item: WatchItem, snapshotDone: boolean): boolean {
10 return isThoughtItem(item) && !item.open && snapshotDone && (!before || before.open)
11}
12
13/** A successful person-visible draw is remembered even if its model row must retry. */
14export class DrawnRows {
15 private items = new Set<string>()
16
17 drawOnce(id: string, draw: () => Promise<DrawResult>): Promise<DrawResult> | undefined {
18 if (this.items.has(id)) return
19 return draw().then((result) => {
20 if (result.deny === undefined) this.items.add(id)
21 return result
22 })
23 }
24}
25
26/**
27 * Queue rows until a hook can draw them, retaining order across held turns. A row is drawn once
28 * the transcript stored the output row naming its item, which `confirm` reports; until then, and
29 * past the wait, it is not.
30 */
31export class DrawQueue {
32 private pending: PendingDraw[] = []
33 private unsettled = new Set<PendingDraw>()
34 get length() { return this.pending.length }
35 shift() { return this.pending.shift() }
36
37 /** The transcript stored the output row that draws `id`. */
38 confirm(id: string) {
39 for (const entry of this.unsettled) if (entry.id === id) entry.settle({})
40 }
41
42 wait(session: string, id: string, held: () => boolean,
43 after: (milliseconds: number, action: () => void) => DrawTimer): Promise<DrawResult> {
44 return new Promise((resolve) => {
45 let added = false
46 let timer: DrawTimer | undefined
47 const entry: PendingDraw = { session, id, settle: (result) => {
48 if (added) return
49 added = true
50 this.unsettled.delete(entry)
51 timer?.cancel()
52 resolve(result)
53 } }
54 this.unsettled.add(entry)
55 const arm = () => {
56 timer = after(2000, () => {
57 if (held()) arm()
58 else {
59 this.pending = this.pending.filter((queued) => queued !== entry)
60 entry.settle({ deny: 'the transcript drew no command output row' })
61 }
62 })
63 }
64 arm()
65 this.pending.push(entry)
66 })
67 }
68
69 drop() {
70 const queued = this.pending
71 this.pending = []
72 for (const entry of queued) entry.settle({ deny: 'the Delta watcher stopped before the row was drawn' })
73 }
74}
75
76/** The engine's words for a stored row left with no content, as the plugin's emptied echo is. */
77export const EMPTY_ROW_TEXT = '(no content)'
78
79/** What the stored output row of the plugin's own `show` run reads, for the model and a resumed session. */
80export const SHOW_ANSWER = '.'
81const SHOW_OUTPUT_ROW = `<local-command-stdout>${SHOW_ANSWER}</local-command-stdout>`
82
83/**
84 * The plugin's answer to its own `show <id>` run. The answer becomes the run's output row, which
85 * is the one place a run's own data is documented to reach, so it names the item; the rewrite
86 * below reads the item out and stores the row as {@link SHOW_ANSWER} alone.
87 */
88export function showAnswer(id: string): string {
89 return `${SHOW_ANSWER} ${id}`
90}
91
92/** Identify the item in an internal command without interpreting its content. */
93export function shownItemId(args: string): string | undefined {
94 return /^show\s+(\S+)$/.exec(args.trim())?.[1]
95}
96
97/**
98 * Rewrite only this plugin's hidden command echo and output, not unrelated command rows: the echo
99 * is stored empty and marked `echo`, and the output as {@link SHOW_ANSWER}, with the item it draws
100 * returned beside it. The plugin runs its own `/delta` only to draw, so an echo of that run is
101 * hidden whatever arguments the transcript kept for it.
102 */
103export function shownCommandRewrite(plugin: string, row: {
104 door: string
105 origin?: unknown
106 message: { type: string; name?: string; role?: string; content: readonly { type: string; text?: string }[] }
107}): { content: { type: 'text'; text: string }[]; item?: string; echo?: true } | undefined {
108 if (row.door !== 'command') return
109 const text = row.message.content.flatMap((block) =>
110 block.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n')
111 const origin = row.origin as { kind?: string; name?: string } | undefined
112 if (row.message.role === 'user' && origin?.kind === 'plugin' && origin.name === plugin &&
113 /<command-name>\/delta<\/command-name>/.test(text) && /<command-args>(?:show\s+\S+)?<\/command-args>/.test(text))
114 return { content: [], echo: true }
115 if (row.message.type !== 'system' || row.message.name !== 'local_command') return
116 const output = /^<local-command-stdout>(?:(\S+): )?(.*)<\/local-command-stdout>$/s.exec(text)
117 if (!output || (output[1] !== undefined && output[1] !== plugin)) return
118 const answer = output[2]!
119 if (answer === SHOW_ANSWER) return { content: [{ type: 'text', text: SHOW_OUTPUT_ROW }] }
120 // The engine names the plugin that answered, so only this plugin's answer names an item.
121 const item = output[1] === plugin ? new RegExp(`^\\${SHOW_ANSWER} (\\S+)$`).exec(answer)?.[1] : undefined
122 if (item !== undefined) return { content: [{ type: 'text', text: SHOW_OUTPUT_ROW }], item }
123}
124hooks/watch/rows.tsx 330 lines1/**
2 * The watched thread's items and comments in Claude's transcript: rows queued while Claude's own turn
3 * runs, then drawn one at a time as the plugin's own command output.
4 */
5
6import { authorColor } from '../band/band'
7import {
8 addRows, commentAction, commentAuthor, commentDisplay, commentMarkdown, commentQuote, isDrawnItem, isEventItem,
9 itemAuthor, itemDisplay, itemMarkdown, keyedComment, type PendingRow,
10} from './conversation'
11import { DrawQueue, EMPTY_ROW_TEXT, shownItemId } from './row-delivery'
12import { drawnRowKey, type HookEvent, type HookNext, ledgerKey, type Runtime, stateFor } from '../core/session-state'
13import { personColor, personKey, toolRowParts } from '../band/status'
14import { errorText } from '../core/text'
15import { feed, watchedSession } from './watch'
16
17/** Rows waiting to be drawn into Claude's transcript, one at a time. */
18const drawQueue = new DrawQueue()
19let drawing = false
20/** A stored row of the plugin's own `show` run: the item its output row draws, or its echo. */
21type ShownRow = string | { echo: true }
22/** What each stored row of the plugin's own `show` run is, by the row's message id. */
23const shownRows = new Map<string, ShownRow>()
24/** The pass adding the watched thread's completed items to Claude's transcript, while one runs. */
25export let settling: Promise<void> | undefined
26/** The last notice a failed pass showed, so the same failure is shown once. */
27let settleNotice: string | undefined
28/** The answer the engine gives a plugin's command when no `command.run` hook of its own answered it. */
29const UNANSWERED_COMMAND = /no command\.run hook answered it/
30
31/** Rows wait while Claude's own turn runs or a local prompt is entering, so they never land inside a turn. */
32export function rowsHeld(session: string) {
33 const runtime = stateFor(session)
34 return !!runtime.currentTurnId || !!runtime.promptEntering
35}
36
37/**
38 * The transcript draws one `$.ui.log` entry per call and flattens an embedded newline to U+FFFD, so
39 * a person-visible item goes out one entry per paragraph, keeping the line breaks it should have.
40 */
41export function showToPerson($: Runtime, text: string) {
42 for (const line of text.split('\n')) $.ui.log(line, { to: 'transcript' })
43}
44
45/** A hidden row for Claude's context, held back while a turn runs so it never lands inside one. */
46export async function deliverNote($: Runtime, session: string, text: string) {
47 const runtime = stateFor(session)
48 runtime.notes.push(text)
49 if (!rowsHeld(session)) await flushNotes($, session)
50}
51
52/** Add the notes held for a session to Claude's context, in order. */
53async function flushNotes($: Runtime, session: string) {
54 const runtime = stateFor(session)
55 for (const text of runtime.notes.splice(0)) {
56 $.ui.log(`Adding a row to Claude's context: ${text.split('\n', 1)[0]}`, { to: 'debug' })
57 try { await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } }) }
58 catch (error) { $.ui.log(`Couldn't add a Delta worktree update to Claude's context: ${String(error)}`, { to: 'debug' }) }
59 }
60}
61
62/**
63 * Draw a completed message as the output row of the plugin's own `show <id>` command, which is the
64 * only plugin-producible transcript row that draws markdown and that redraws with our own tree.
65 *
66 * The engine runs a plugin's own call with the calling hook alone skipped, and a call from the
67 * plugin's background code carries no calling hook, so it skips the plugin's own `command.run` hook
68 * altogether. The row therefore waits for a redraw: a `ui.render` hook is a hook context, and the
69 * command it raises inside one is answered.
70 */
71function drawMessage($: Runtime, session: string, id: string): Promise<{ deny?: string }> {
72 const result = drawQueue.wait(session, id, () => rowsHeld(session),
73 (milliseconds, action) => $.clock.after(milliseconds, action))
74 $.ui.invalidate('ui.render')
75 return result
76}
77
78/**
79 * Abandon the rows a stopped conversation was still waiting to draw. They were not added, so the
80 * next snapshot offers them again; a stopped watch reports nothing about them. Returns the pass
81 * still running, whose save must finish before a new watch loads or writes the ledger.
82 */
83export function stopRows(): Promise<void> | undefined {
84 drawQueue.drop()
85 const running = settling
86 settling = undefined
87 settleNotice = undefined
88 return running
89}
90
91/**
92 * Run the queued message rows' commands, oldest first, from a hook context. Rows wait while a local
93 * turn runs, and the queue keeps its order across redraws. A row is drawn once its output row is
94 * stored, which the `session.append` hook confirms; a command that fails or goes unanswered settles
95 * its row as not drawn.
96 */
97export async function drainMessages($: Runtime) {
98 const session = watchedSession()
99 if (drawing || !session || !feed.view) return
100 drawing = true
101 try {
102 while (drawQueue.length) {
103 if (watchedSession() !== session || rowsHeld(session)) break
104 const entry = drawQueue.shift()!
105 let answer: string | undefined
106 try { answer = (await $.command.run({ command: 'delta', args: `show ${entry.id}` })).text }
107 catch (error) { entry.settle({ deny: errorText(error) }); continue }
108 if (answer === undefined || UNANSWERED_COMMAND.test(answer))
109 entry.settle({ deny: "this host did not run the plugin's own command" })
110 else $.ui.log(`Ran the plugin's own command to draw the Delta item ${entry.id}.`, { to: 'debug' })
111 }
112 } finally {
113 drawing = false
114 }
115 if (drawQueue.length) $.ui.invalidate('ui.render')
116}
117
118/**
119 * Add one model-visible row, and draw a message's copy for the person beside it.
120 *
121 * The model reads the plugin's own `session.append` row for every kind, so a message is drawn for
122 * the person in addition to it, never instead of it. Neither the drawn row nor the model's row is
123 * written twice: an item this session already drew is not drawn again, so a retried row repeats
124 * neither. A host that will not draw the command output row leaves the model's row alone and shows
125 * the person the plain notice.
126 */
127async function appendRow($: Runtime, session: string, row: PendingRow): Promise<{ deny?: string }> {
128 const id = row.commandItem
129 const runtime = stateFor(session)
130 if (id !== undefined) {
131 const drawing = runtime.drawn.drawOnce(id, () => drawMessage($, session, id))
132 if (drawing) {
133 const refusal = await drawing
134 if (refusal.deny === undefined)
135 $.ui.log(`Drew the Delta item ${id} as a command output row.`, { to: 'debug' })
136 else fallbackNotice($, row, refusal.deny)
137 }
138 }
139 return $.session.append({ message: { type: 'user', content: [{ type: 'text', text: row.text }] } })
140}
141
142/** Show a message or comment the plain way, when its command output row is refused; the model's row stands. */
143function fallbackNotice($: Runtime, row: PendingRow, reason: string) {
144 const view = feed.view
145 const commentId = keyedComment(row.id)
146 const comment = commentId === undefined ? undefined : view?.comments.get(commentId)
147 const item = view?.items.get(row.id)
148 const display = !view ? undefined
149 : comment ? commentDisplay(comment, view.commentParent(comment), view.commentTarget(comment), view.thread)
150 : item ? itemDisplay(item, view.thread) : undefined
151 if (display) showToPerson($, display)
152 $.ui.log(`Couldn't draw this Delta message as a command row (${reason}).`, { to: 'debug' })
153}
154
155/**
156 * Add completed remote items to Claude's transcript as model-visible rows, without starting a
157 * turn, and correct rows for items that later changed or disappeared. Held rows resume when the
158 * prompt is dropped or its turn completes.
159 */
160export function settleRemote($: Runtime, session: string): Promise<void> | undefined {
161 if (settling || watchedSession() !== session) return settling
162 const revision = feed.revision
163 const owns = () => feed.revision === revision && watchedSession() === session
164 let task: Promise<void> | undefined = undefined
165 task = (async () => {
166 // Start after `task` is assigned, so a run with nothing to do still clears `settling`.
167 await undefined
168 try {
169 if (!rowsHeld(session)) await flushNotes($, session)
170 const view = feed.view
171 if (view) await addRows(view, {
172 append: (row) => appendRow($, session, row),
173 save: (ledger) => $.store.set(ledgerKey(session), ledger),
174 held: () => rowsHeld(session),
175 current: owns,
176 announce: (text) => showToPerson($, text),
177 debug: (text) => $.ui.log(text, { to: 'debug' }),
178 fail: (reason) => settleFailure($, reason),
179 })
180 } finally {
181 if (settling === task) settling = undefined
182 }
183 if (owns() && feed.view && !feed.view.settled && !rowsHeld(session)) await settleRemote($, session)
184 })()
185 settling = task
186 return task
187}
188
189function settleFailure($: Runtime, reason: string) {
190 // Print and SDK sessions keep no conversation a plugin can add rows to; nothing retries that.
191 const notice = /keeps no conversation/.test(reason)
192 ? `Couldn't add Delta activity to Claude's context: ${reason}. Remote Delta activity isn't available in print or SDK sessions.`
193 : `Couldn't add Delta activity to Claude's context: ${reason}. It is offered again when the watcher reconnects.`
194 if (settleNotice === notice) return
195 settleNotice = notice
196 $.ui.log(notice)
197}
198
199/**
200 * A row of the plugin's own `show` run was stored as `row`: settle the draw of the item its output
201 * row shows, and remember what the row is.
202 */
203export async function storeShownRow($: Runtime, row: string, shown: { item?: string; echo?: boolean }) {
204 if (shown.item !== undefined) {
205 drawQueue.confirm(shown.item)
206 await rememberShownRow($, row, shown.item)
207 }
208 if (shown.echo) await rememberShownRow($, row, { echo: true })
209}
210
211/**
212 * Remember what a stored row of the plugin's own `show` run is, so it draws the same after a restart
213 * or resume; one the store refuses is still remembered by this process.
214 */
215async function rememberShownRow($: Runtime, row: string, shown: ShownRow) {
216 shownRows.set(row, shown)
217 try { await $.store.set(drawnRowKey(await $.session.id(), row), shown) }
218 catch (error) { $.ui.log(`Couldn't remember a drawn Delta row (${String(error)}).`, { to: 'debug' }) }
219}
220
221/** What a stored row of the plugin's own `show` run is, by the row's message id. */
222async function shownRow($: Runtime, row: string): Promise<ShownRow | undefined> {
223 const known = shownRows.get(row)
224 if (known !== undefined) return known
225 try {
226 // Only this plugin writes these keys, and it writes a ShownRow; the value is checked below.
227 const stored = await $.store.get(drawnRowKey(await $.session.id(), row)) as ShownRow | undefined
228 if (typeof stored === 'string' || stored?.echo === true) {
229 shownRows.set(row, stored)
230 return stored
231 }
232 } catch { /* not known by its id */ }
233}
234
235/**
236 * The item an output row of the plugin's own `show` run draws: by the row's message id, the one
237 * identity the engine documents for a drawn row, else by the run's arguments, which rows stored
238 * by earlier versions of the plugin carry.
239 */
240async function drawnRowItem($: Runtime, row: string, args: string): Promise<string | undefined> {
241 const shown = await shownRow($, row)
242 return typeof shown === 'string' ? shown : shownItemId(args)
243}
244
245/**
246 * The plugin's own `show` echo, which Desktop draws as a user row, draws as nothing. It is known by its
247 * id: Desktop reports every row's origin as the SDK's. Only empty rows are looked up, as the echo is one.
248 */
249export async function drawEcho(
250 $: Runtime,
251 e: HookEvent<'ui.render', { component: 'UserMessage' }>,
252 next: HookNext<'ui.render', { component: 'UserMessage' }>,
253) {
254 if (e.props.text !== EMPTY_ROW_TEXT || typeof await shownRow($, e.requestId) !== 'object') return next(e)
255 const { Box } = $.ui.resolve(e)
256 return <Box />
257}
258
259/**
260 * The plugin's own command output row: a remote message, event, tool call or comment draws here, from
261 * this plugin's own data rather than the row's stored text, which carries none of it.
262 */
263export async function drawRow(
264 $: Runtime,
265 e: HookEvent<'ui.render', { component: 'CommandOutput' }>,
266 next: HookNext<'ui.render', { component: 'CommandOutput' }>,
267) {
268 if (e.props.command !== 'delta') return next(e)
269 const id = await drawnRowItem($, e.requestId, e.props.args)
270 if (id === undefined) return next(e)
271 const view = feed.view
272 const item = view?.items.get(id)
273 const { Box, Text, Markdown } = $.ui.resolve(e)
274 if (view?.wasRemoved(id)) return <Box />
275 const commentId = keyedComment(id)
276 if (commentId !== undefined) {
277 const comment = view?.comments.get(commentId)
278 if (!view || !comment) return <Text dimColor>A Delta comment that is not in this session.</Text>
279 // What the comment refers to is earlier material: dim, behind a gutter, elided. The comment
280 // itself is new and draws in full, like a message.
281 const parent = view.commentParent(comment)
282 const target = view.commentTarget(comment)
283 const reply = comment.chain !== comment.id
284 const quoted = commentQuote(comment, parent, target, view.items, (e.viewport?.columns ?? 80) - 2)
285 return <Box flexDirection="column">
286 <Text wrap="truncate-end">
287 {reply ? <Text dimColor>{'↳ '}</Text> : null}
288 <Text bold color={personColor(personKey(comment.author))}>{commentAuthor(comment)}</Text>
289 <Text dimColor>{` ${commentAction(comment, parent, target)}${comment.routed_to ? ' · sent to a subthread' : ''}`}</Text>
290 </Text>
291 {quoted.map((line, index) => <Text key={`quote-${index}`} dimColor wrap="truncate-end">
292 {'│ '}{line.before}
293 <Text {...line.emphasis && (line.before || line.after) ? { underline: true } : {}}>{line.marked}</Text>
294 {line.after}
295 </Text>)}
296 <Markdown key="delta-comment" text={commentMarkdown(comment, view.thread)} />
297 </Box>
298 }
299 // After a restart, the stored row can draw before the watch supplies its content.
300 if (!view || !item) return <Text dimColor>A Delta item that is not in this session.</Text>
301 // An item with nothing left to draw, such as an agent message that only held a comment reply.
302 if (!isDrawnItem(item)) return <Box />
303 if (isEventItem(item)) return <Box flexDirection="column">
304 <Text dimColor>Delta activity</Text>
305 <Markdown key="delta-event" text={itemMarkdown(item, view.thread)} />
306 </Box>
307 // An author keeps the color the band gives them; a person's message and their agent's are told apart by label.
308 const agent = item.kind !== 'user_message'
309 if (item.kind === 'tool_call') {
310 // One line, like Claude's own tool rows: the tool in bold, its key input dim, a failure in red.
311 // A single Text of spans never wraps a part on its own; the input gives way first, in its
312 // middle, so its start and its end (a path's file, a command's last argument) both stay.
313 const { name, author, status, statusText, shown } = toolRowParts(item, e.viewport?.columns ?? 80)
314 return <Text wrap="truncate-end">
315 <Text bold color={authorColor(item)}>{author}</Text>
316 <Text dimColor>{' › '}</Text>
317 <Text bold>{name}</Text>
318 {shown ? <Text dimColor>{` ${shown}`}</Text> : null}
319 {statusText ? <Text color={status === 'failed' ? 'red' : 'yellow'}>{statusText}</Text> : null}
320 </Text>
321 }
322 return <Box flexDirection="column">
323 <Box flexDirection="row" columnGap={1}>
324 <Text bold color={authorColor(item)}>{itemAuthor(item)}</Text>
325 <Text dimColor>{agent ? '(agent)' : '(person)'}</Text>
326 </Box>
327 <Markdown key="delta-message" text={itemMarkdown(item, view.thread)} />
328 </Box>
329}
330