Skip to content

Commit 44cd1dd

Browse files
Svampenclaude
andcommitted
fix(#116): follow opencode /new and session switches, and Claude forks
opencode kept the first session id it captured forever, so a /new or a pick in the /sessions picker left the harness resuming and labelling the old conversation. session.created now carries parentID, so a new ROOT session is followed and a task-tool child is never captured or followed. The picker publishes no event upstream (anomalyco/opencode#5409), so the first user message in a different root session is the switch signal; the adapter decides root vs child from session.created/session.updated, else asks the server (GET /session/<id>, 2 s, raced against cancel) and follows nothing on failure. A follow overwrites Harness.sessionId without touching the phase, since opencode's own busy/idle stays authoritative. Claude's SessionStart source=fork carries the fork's new id and transcript, so it is now followed like clear and resume. SessionEnd is still not consumed: SessionStart already reports every switch, and exit is seen as PTY exit. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QsftqvDBcjrsDEV573QFbo
1 parent 6f04384 commit 44cd1dd

8 files changed

Lines changed: 737 additions & 48 deletions

‎app/src-tauri/src/harness_events_opencode.rs‎

Lines changed: 422 additions & 16 deletions
Large diffs are not rendered by default.

‎app/src/App.tsx‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,11 @@ interface HarnessBodyProps {
396396
// sessionID from the `session.created` event. App.tsx wires it
397397
// to setHarnessSessionId; `undefined` for non-opencode harnesses.
398398
onSessionCaptured: ((sessionId: string) => void) | undefined;
399+
// #116: L2c-2 decided the harness followed its TUI onto a different
400+
// root session (`/new` or a `/sessions` pick). App.tsx wires it to
401+
// replaceHarnessSessionId, same as Claude's clear/resume/fork
402+
// follow; `undefined` for non-opencode harnesses.
403+
onSessionFollowed: ((sessionId: string) => void) | undefined;
399404
}
400405

401406
const HarnessBody = ({
@@ -408,6 +413,7 @@ const HarnessBody = ({
408413
roomId,
409414
opencodePort,
410415
onSessionCaptured,
416+
onSessionFollowed,
411417
}: HarnessBodyProps) => {
412418
if (harness.cmd && harness.cwd !== undefined) {
413419
// mountKey changes on cmd content OR spawnGen — the trigger for a
@@ -429,6 +435,7 @@ const HarnessBody = ({
429435
agent={harness.agent}
430436
opencodePort={opencodePort}
431437
onSessionCaptured={onSessionCaptured}
438+
onSessionFollowed={onSessionFollowed}
432439
fontSize={fontSize}
433440
copyOnSelect={copyOnSelect}
434441
defaultShell={defaultShell}
@@ -490,6 +497,9 @@ interface HarnessColumnProps {
490497
// SSE-captured opencode session-id callback (per harness, room
491498
// scope already bound by App).
492499
onOpencodeSessionCaptured: (harnessId: string, sessionId: string) => void;
500+
// #116: opencode followed its TUI onto a different root session
501+
// (per harness, room scope already bound by App).
502+
onOpencodeSessionFollowed: (harnessId: string, sessionId: string) => void;
493503
}
494504

495505
const HarnessColumn = ({
@@ -509,6 +519,7 @@ const HarnessColumn = ({
509519
onHarnessCmdChange,
510520
opencodePorts,
511521
onOpencodeSessionCaptured,
522+
onOpencodeSessionFollowed,
512523
}: HarnessColumnProps) => {
513524
const tablistRef = useRef<HTMLDivElement | null>(null);
514525

@@ -628,6 +639,7 @@ const HarnessColumn = ({
628639
roomId={room.id}
629640
opencodePort={opencodePorts.get(h.id)}
630641
onSessionCaptured={(sid) => onOpencodeSessionCaptured(h.id, sid)}
642+
onSessionFollowed={(sid) => onOpencodeSessionFollowed(h.id, sid)}
631643
/>
632644
) : (
633645
<FilesBody harnessId={h.id} cwd={h.cwd ?? room.cwd ?? ""} visible={visible} />
@@ -2406,11 +2418,12 @@ export default function App() {
24062418
// a no-op for an id Skein doesn't have a record for.
24072419
//
24082420
// #116: the same hook is the ONLY signal Skein gets that a
2409-
// mid-session `/clear` or in-tool `/resume` moved a harness onto a
2421+
// mid-session `/clear`, in-tool `/resume` or a fork (`/branch`,
2422+
// `/fork`, `--fork-session`, desktop rewind) moved a harness onto a
24102423
// different conversation — Claude's JSONL gives no other sign.
24112424
// `followedSession` (sessionTracking.ts) filters to `source ===
2412-
// "clear"` or `"resume"` reporting a genuinely different id; when it
2413-
// does, the harness's stored sessionId is overwritten
2425+
// "clear"`, `"resume"` or `"fork"` reporting a genuinely different
2426+
// id; when it does, the harness's stored sessionId is overwritten
24142427
// (`replaceHarnessSessionId`, first-writer-wins would never adopt it)
24152428
// so a future resume/reopen picks up the new conversation, and
24162429
// `harnessActivity.sessionSwitched` forgets the old session's
@@ -3082,12 +3095,15 @@ export default function App() {
30823095
};
30833096

30843097
// #116 step two: overwrite a harness's sessionId after Claude's own
3085-
// `/clear` hook reports the conversation moved onto a new id. This is
3086-
// deliberately NOT `setHarnessSessionId` above — that one is
3087-
// first-writer-wins to survive opencode's create-vs-poll capture
3088-
// race, but a `/clear` report is authoritative: the old id is
3089-
// definitely gone, so the new one must win even though `sessionId`
3090-
// is already set. `cmd` is untouched here — it's part of
3098+
// `/clear`/`/resume`/fork hook reports the conversation moved onto a
3099+
// new id — and (step four) after opencode's own adapter decides the
3100+
// harness followed its TUI onto a different root session (`/new` or
3101+
// a `/sessions` pick). This is deliberately NOT `setHarnessSessionId`
3102+
// above — that one is first-writer-wins to survive opencode's
3103+
// create-vs-poll capture race, but both these reports are
3104+
// authoritative: the old id is definitely gone (Claude) or definitely
3105+
// superseded (opencode), so the new one must win even though
3106+
// `sessionId` is already set. `cmd` is untouched here — it's part of
30913107
// LiveTerminal's mountKey, so changing it would respawn the PTY;
30923108
// `resumeCmd` (harnessCmd.ts) rebuilds the argv from `sessionId` on
30933109
// the next boot/reopen, which is what makes the new conversation the
@@ -3721,6 +3737,9 @@ export default function App() {
37213737
onOpencodeSessionCaptured={(harnessId, sid) =>
37223738
setHarnessSessionId(r.id, harnessId, sid)
37233739
}
3740+
onOpencodeSessionFollowed={(harnessId, sid) =>
3741+
replaceHarnessSessionId(r.id, harnessId, sid)
3742+
}
37243743
/>
37253744
</div>
37263745
))}

‎app/src/LiveTerminal.tsx‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,13 @@ interface LiveTerminalProps {
109109
// persist the captured sessionId on the harness for resume.
110110
// `undefined` for non-opencode harnesses.
111111
onSessionCaptured: ((sessionId: string) => void) | undefined;
112+
// #116: fired when the L2c-2 adapter decides the harness followed
113+
// its TUI onto a DIFFERENT root session (`/new`, or an existing
114+
// session picked via `/sessions`) — see `followedOpencodeSession`
115+
// in `sessionTracking.ts`. Caller wires this to overwrite the
116+
// stored sessionId, same as Claude's clear/resume/fork follow.
117+
// `undefined` for non-opencode harnesses.
118+
onSessionFollowed: ((sessionId: string) => void) | undefined;
112119
fontSize: number;
113120
// #158: copy a mouse selection to the clipboard the moment it's made
114121
// (Settings → "Copy on select", default true). Read through a ref
@@ -143,6 +150,7 @@ export const LiveTerminal = ({
143150
agent,
144151
opencodePort,
145152
onSessionCaptured,
153+
onSessionFollowed,
146154
fontSize,
147155
copyOnSelect,
148156
defaultShell,
@@ -180,7 +188,12 @@ export const LiveTerminal = ({
180188
// the exhaustive-deps note below), so its attach closure must read the
181189
// CURRENT sessionId at attach time — including one that lands between
182190
// render and the effect actually spawning the PTY — not the value
183-
// captured when the effect was defined.
191+
// captured when the effect was defined. Step four reuses this same
192+
// ref as the opencode adapter's LIVE getter, passed straight into
193+
// `attachOpencodeEvents`: that adapter is attached once per PTY, but
194+
// the harness's own sessionId changes under it whenever `/new` or a
195+
// `/sessions` pick is followed, so a value closed over at attach
196+
// time would go stale the first time that happens.
184197
const sessionIdRef = useRef(sessionId);
185198
sessionIdRef.current = sessionId;
186199
// #116 step two: the Claude JSONL adapter's unsubscribe, paired with
@@ -737,6 +750,11 @@ export const LiveTerminal = ({
737750
opencodePort,
738751
sessionId,
739752
onSessionCaptured,
753+
// #116: live, not the `sessionId` closed over above —
754+
// this harness's session id can change under a
755+
// long-lived adapter (`/new`, a `/sessions` pick).
756+
() => sessionIdRef.current,
757+
onSessionFollowed,
740758
);
741759
}
742760
dataDisposable = term.onData((data) => {

‎app/src/harnessActivity.delegation.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,24 @@ describe("sessionSwitched (#116)", () => {
297297
subagents.forget(id);
298298
});
299299

300+
it("running moves to waiting with the session-fork source", () => {
301+
const id = runningHarness();
302+
const transitions: Array<{ to: string; source: string }> = [];
303+
const unsubscribe = harnessActivity.subscribeTransitions((tid, _from, to, source) => {
304+
if (tid === id) transitions.push({ to, source });
305+
});
306+
307+
harnessActivity.sessionSwitched(id, "fork");
308+
309+
expect(harnessActivity.get(id)?.phase).toBe("waiting");
310+
expect(transitions).toEqual([
311+
{ to: "waiting", source: TRANSITION_SOURCE.L2c1ClaudeSessionFork },
312+
]);
313+
unsubscribe();
314+
harnessActivity.forget(id);
315+
subagents.forget(id);
316+
});
317+
300318
it("permission stays permission", () => {
301319
const id = runningHarness();
302320
harnessActivity.setPermissionFromAdapter(id, TRANSITION_SOURCE.L2c1ClaudePermission, "Bash");

‎app/src/harnessActivity.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,11 @@ export const TRANSITION_SOURCE = {
334334
// itself the same way) re-points onto a different session id — see
335335
// `sessionSwitched`.
336336
L2c1ClaudeSessionResume: "l2c1-claude-session-resume",
337+
// #116: a `/branch`, `/fork`, `--fork-session` or desktop rewind
338+
// reports its own dedicated `source: "fork"` from Claude Code
339+
// v2.1.214 on, carrying the newly forked session id — see
340+
// `sessionSwitched`.
341+
L2c1ClaudeSessionFork: "l2c1-claude-session-fork",
337342
// #298: a subagent's own tool result proves the gate its permission
338343
// prompt held is gone, even though the main transcript never sees
339344
// it. See `clearPermission`.
@@ -787,7 +792,7 @@ export const harnessActivity = {
787792
/// left alone: `permission` outranks it (#86), and `exited` /
788793
/// `spawning` / `idle` / `waiting` aren't this event's business.
789794
/// No-op for an unknown id.
790-
sessionSwitched(id: string, source: "clear" | "resume"): void {
795+
sessionSwitched(id: string, source: "clear" | "resume" | "fork"): void {
791796
const cur = store.get(id);
792797
if (!cur) return;
793798
subagents.forget(id);
@@ -798,7 +803,9 @@ export const harnessActivity = {
798803
"waiting",
799804
source === "clear"
800805
? TRANSITION_SOURCE.L2c1ClaudeSessionClear
801-
: TRANSITION_SOURCE.L2c1ClaudeSessionResume,
806+
: source === "resume"
807+
? TRANSITION_SOURCE.L2c1ClaudeSessionResume
808+
: TRANSITION_SOURCE.L2c1ClaudeSessionFork,
802809
);
803810
},
804811

‎app/src/harnessEvents.ts‎

Lines changed: 82 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { Channel, invoke } from "@tauri-apps/api/core";
1818
import { TRANSITION_SOURCE, type TransitionSource, harnessActivity } from "./harnessActivity.ts";
1919
import { observedAgents } from "./harnessAgent.ts";
2020
import { type PendingPhase, pendingPrompts } from "./pendingPrompts.ts";
21+
import { followedOpencodeSession } from "./sessionTracking.ts";
2122
import { subagents } from "./subagents.ts";
2223

2324
/// Mirror of the Rust enum. `kind` is the serde tag from
@@ -235,7 +236,14 @@ const translate = (harnessId: string, event: ClaudeEvent): void => {
235236
/// the frontend catches up.
236237
export type OpencodeEvent =
237238
| { kind: "connected" }
238-
| { kind: "session_created"; session_id: string }
239+
// #116: `parent_id` is non-null for a subagent child session — never
240+
// a conversation to capture or follow. `null` marks a root session.
241+
| { kind: "session_created"; session_id: string; parent_id: string | null }
242+
// #116: a user message landed in a ROOT session (backend-verified
243+
// not a child) — the only signal the `/sessions` picker gives when
244+
// it switches onto an EXISTING session, since it publishes nothing
245+
// of its own. See `followedOpencodeSession` in `sessionTracking.ts`.
246+
| { kind: "root_session_prompted"; session_id: string }
239247
| { kind: "session_busy" }
240248
| { kind: "session_idle" }
241249
| { kind: "message_delta" }
@@ -265,6 +273,23 @@ export type OpencodeEvent =
265273
/// poll stays as a fallback — see `captureOpencodeSessionId` for
266274
/// the relationship.
267275
///
276+
/// `getSessionId` reads the harness's CURRENT session id, live, at
277+
/// the moment each event is translated — not the value captured when
278+
/// this adapter attached. The adapter is attached once per PTY, but
279+
/// the harness's own sessionId can change under it (#116: `/new` or a
280+
/// `/sessions` pick), so a value closed over at attach time would go
281+
/// stale the first time that happens.
282+
///
283+
/// `onSessionFollowed` fires when `followedOpencodeSession` decides
284+
/// the harness moved onto a different root session (`/new` or an
285+
/// existing session picked via `/sessions`) — see that function for
286+
/// the two signals this is built from. The caller wires it to
287+
/// `replaceHarnessSessionId`, same as Claude's `/clear`/`/resume`/fork
288+
/// follow. Deliberately NOT routed through `harnessActivity` here: a
289+
/// "switch" is detected by a user prompt arriving, and opencode's own
290+
/// busy/idle SSE (port-scoped, already authoritative) is what should
291+
/// keep driving the phase.
292+
///
268293
/// Soft-fail: any Rust-side rejection (port closed, IPC dropped)
269294
/// detaches authoritative + warns. The harness keeps running on
270295
/// L2a.
@@ -275,14 +300,16 @@ export function attachOpencodeEvents(
275300
port: number,
276301
sessionId: string | undefined,
277302
onSessionCaptured: ((sessionId: string) => void) | undefined,
303+
getSessionId: () => string | undefined,
304+
onSessionFollowed: ((sessionId: string) => void) | undefined,
278305
): () => void {
279306
const channel = new Channel<OpencodeEvent>();
280307
let closed = false;
281308
channel.onmessage = (event) => {
282309
// #259: see attachClaudeEvents. `connected` arrives first, so a
283310
// stream that is up disarms the watchdog before any prompt.
284311
if (!closed) harnessActivity.adapterDelivered(harnessId);
285-
translateOpencode(harnessId, event, onSessionCaptured);
312+
translateOpencode(harnessId, event, onSessionCaptured, getSessionId, onSessionFollowed);
286313
};
287314

288315
// See attachClaudeEvents for why this happens synchronously.
@@ -343,6 +370,8 @@ const translateOpencode = (
343370
harnessId: string,
344371
event: OpencodeEvent,
345372
onSessionCaptured: ((sessionId: string) => void) | undefined,
373+
getSessionId: () => string | undefined,
374+
onSessionFollowed: ((sessionId: string) => void) | undefined,
346375
): void => {
347376
switch (event.kind) {
348377
case "connected":
@@ -366,13 +395,58 @@ const translateOpencode = (
366395
pendingPrompts.forget(harnessId);
367396
harnessActivity.attachAuthoritativeSource(harnessId);
368397
return;
369-
case "session_created":
370-
// SSE-driven session-id capture (replaces chapter 5
371-
// phase 2b's sqlite poll on the happy path). The
372-
// callback short-circuits the sqlite fallback once
373-
// invoked.
374-
onSessionCaptured?.(event.session_id);
398+
case "session_created": {
399+
// #116: a child session (subagent, non-null parent_id) is
400+
// never a conversation to capture OR follow — Skein has no
401+
// business tracking it as the harness's own session id.
402+
if (event.parent_id !== null) return;
403+
const current = getSessionId();
404+
if (current === undefined) {
405+
// SSE-driven session-id capture (replaces chapter 5
406+
// phase 2b's sqlite poll on the happy path). The
407+
// callback short-circuits the sqlite fallback once
408+
// invoked.
409+
onSessionCaptured?.(event.session_id);
410+
return;
411+
}
412+
const followed = followedOpencodeSession(current, {
413+
kind: "session_created",
414+
sessionId: event.session_id,
415+
parentId: event.parent_id,
416+
});
417+
if (followed) {
418+
console.info(
419+
`[skein] opencode ${harnessId} followed onto ${followed.sessionId} (${followed.source})`,
420+
);
421+
onSessionFollowed?.(followed.sessionId);
422+
}
375423
return;
424+
}
425+
case "root_session_prompted": {
426+
// #116: the `/sessions` picker publishes nothing when it
427+
// switches onto an EXISTING root session — the first user
428+
// prompt landing there is the earliest honest signal. See
429+
// `followedOpencodeSession`.
430+
const current = getSessionId();
431+
if (current === undefined) {
432+
// No session captured yet: treat this as the initial
433+
// capture, not a follow — same reasoning as
434+
// `session_created`'s `current === undefined` arm.
435+
onSessionCaptured?.(event.session_id);
436+
return;
437+
}
438+
const followed = followedOpencodeSession(current, {
439+
kind: "root_session_prompted",
440+
sessionId: event.session_id,
441+
});
442+
if (followed) {
443+
console.info(
444+
`[skein] opencode ${harnessId} followed onto ${followed.sessionId} (${followed.source})`,
445+
);
446+
onSessionFollowed?.(followed.sessionId);
447+
}
448+
return;
449+
}
376450
case "session_busy":
377451
// #86: "still working" — must not clear a pending
378452
// permission, so no `clearsPermission` (defaults to false).

0 commit comments

Comments
 (0)