Skip to content

Commit 5ffadff

Browse files
author
Peter Steinberger
committed
fix(sessions): preserve transcript and child ownership
1 parent e051a7b commit 5ffadff

13 files changed

Lines changed: 477 additions & 13 deletions

‎src/agents/subagent-announce-output.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,52 @@ describe("readSubagentOutput", () => {
190190
);
191191
});
192192

193+
it("does not replay an older assistant reply after a newer user turn", async () => {
194+
installOutputDeps({
195+
messages: [
196+
{ role: "assistant", content: [{ type: "text", text: "Completed the old task." }] },
197+
{ role: "user", content: [{ type: "text", text: "Start the next task." }] },
198+
],
199+
});
200+
201+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBeUndefined();
202+
});
203+
204+
it("does not treat a projected inter-session input as an assistant completion", async () => {
205+
installOutputDeps({
206+
messages: [
207+
{ role: "assistant", content: [{ type: "text", text: "Completed the old task." }] },
208+
{
209+
role: "assistant",
210+
provenance: { kind: "inter_session", sourceSessionKey: "agent:main:main" },
211+
content: [{ type: "text", text: "Start the next task." }],
212+
},
213+
],
214+
});
215+
216+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBeUndefined();
217+
});
218+
219+
it("reports only tool calls belonging to the latest user turn", async () => {
220+
installOutputDeps({
221+
messages: [
222+
{
223+
role: "assistant",
224+
content: [{ type: "toolCall", id: "old-call", name: "read", arguments: {} }],
225+
},
226+
{ role: "user", content: [{ type: "text", text: "Start the next task." }] },
227+
{
228+
role: "assistant",
229+
content: [{ type: "toolCall", id: "current-call", name: "exec", arguments: {} }],
230+
},
231+
],
232+
});
233+
234+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBe(
235+
"1 tool call(s) made without visible output.",
236+
);
237+
});
238+
193239
it("does not fall back to tool output when the last assistant turn is empty", async () => {
194240
installOutputDeps({
195241
messages: [
@@ -398,6 +444,29 @@ describe("buildChildCompletionFindings", () => {
398444
expect(findings).toContain("1. visible task");
399445
expect(findings).not.toContain("2. visible task");
400446
});
447+
448+
it("orders same-timestamp child completions by stable session identity", () => {
449+
const laterKey = {
450+
childSessionKey: "agent:main:subagent:z",
451+
task: "Z task",
452+
createdAt: 1_000,
453+
endedAt: 2_000,
454+
completion: { resultText: "Z result" },
455+
outcome: { status: "ok" as const },
456+
};
457+
const earlierKey = {
458+
...laterKey,
459+
childSessionKey: "agent:main:subagent:a",
460+
task: "A task",
461+
completion: { resultText: "A result" },
462+
};
463+
464+
const forward = buildChildCompletionFindings([laterKey, earlierKey]);
465+
const reverse = buildChildCompletionFindings([earlierKey, laterKey]);
466+
467+
expect(forward).toBe(reverse);
468+
expect(forward).toMatch(/1\. A task[\s\S]*2\. Z task/);
469+
});
401470
});
402471

403472
describe("applySubagentWaitOutcome", () => {

‎src/agents/subagent-announce-output.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,23 @@ function summarizeSubagentOutputHistory(messages: Array<unknown>): SubagentOutpu
146146
continue;
147147
}
148148
const role = (message as { role?: unknown }).role;
149+
const provenance = (message as { provenance?: unknown }).provenance;
150+
if (
151+
role === "user" ||
152+
(provenance &&
153+
typeof provenance === "object" &&
154+
!Array.isArray(provenance) &&
155+
(provenance as { kind?: unknown }).kind === "inter_session")
156+
) {
157+
// A fresh input owns a new turn; never announce an older turn's reply
158+
// when the current run fails or completes without visible output.
159+
snapshot.latestAssistantText = undefined;
160+
snapshot.latestSilentText = undefined;
161+
snapshot.latestToolCallCount = undefined;
162+
snapshot.waitingForContinuation = false;
163+
previousAssistantCalledYield = false;
164+
continue;
165+
}
149166
if (role === "assistant") {
150167
if (assistantCallsSessionsYield(message)) {
151168
snapshot.latestAssistantText = undefined;
@@ -400,7 +417,16 @@ export function buildChildCompletionFindings(
400417
}
401418
const aEnded = typeof a.endedAt === "number" ? a.endedAt : Number.MAX_SAFE_INTEGER;
402419
const bEnded = typeof b.endedAt === "number" ? b.endedAt : Number.MAX_SAFE_INTEGER;
403-
return aEnded - bEnded;
420+
if (aEnded !== bEnded) {
421+
return aEnded - bEnded;
422+
}
423+
// Parallel children commonly share millisecond timestamps; their stable
424+
// session identity keeps parent-visible findings and prompt bytes ordered.
425+
return a.childSessionKey < b.childSessionKey
426+
? -1
427+
: a.childSessionKey > b.childSessionKey
428+
? 1
429+
: 0;
404430
});
405431

406432
const sections: string[] = [];

‎src/gateway/session-utils-core.ts‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,19 @@ function addChildSessionKey(
418418
childSessionsByKey.set(parentKey, [childKey]);
419419
}
420420

421+
export function isCurrentSessionChildOwner(params: {
422+
entry: Pick<SessionEntry, "parentSessionKey">;
423+
ownerSessionKey: string;
424+
controllerSessionKey: string | undefined;
425+
}): boolean {
426+
// Live control supersedes stale spawnedBy, but explicit navigation lineage
427+
// remains authoritative so dashboard parents can discover controlled children.
428+
return (
429+
params.controllerSessionKey === params.ownerSessionKey ||
430+
normalizeOptionalString(params.entry.parentSessionKey) === params.ownerSessionKey
431+
);
432+
}
433+
421434
export function buildStoreChildSessionIndex(
422435
store: Record<string, SessionEntry>,
423436
now = Date.now(),
@@ -457,7 +470,14 @@ export function buildStoreChildSessionIndex(
457470
continue;
458471
}
459472
for (const parentKey of parentKeys) {
460-
if (latestControllerSessionKey && latestControllerSessionKey !== parentKey) {
473+
if (
474+
latestControllerSessionKey &&
475+
!isCurrentSessionChildOwner({
476+
entry,
477+
ownerSessionKey: parentKey,
478+
controllerSessionKey: latestControllerSessionKey,
479+
})
480+
) {
461481
continue;
462482
}
463483
addChildSessionKey(childSessionsByKey, parentKey, key);
@@ -483,7 +503,13 @@ export function resolveStoreChildSessionKeysFromCandidates(params: {
483503
const latestControllerSessionKey =
484504
normalizeOptionalString(latest.controllerSessionKey) ||
485505
normalizeOptionalString(latest.requesterSessionKey);
486-
if (latestControllerSessionKey !== params.key) {
506+
if (
507+
!isCurrentSessionChildOwner({
508+
entry,
509+
ownerSessionKey: params.key,
510+
controllerSessionKey: latestControllerSessionKey,
511+
})
512+
) {
487513
continue;
488514
}
489515
if (

‎src/gateway/session-utils-list.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import type {
3232
import {
3333
deriveSessionTitle,
3434
isFinitePositiveTimestamp,
35+
isCurrentSessionChildOwner,
3536
shouldKeepStoreOnlyChildLink,
3637
} from "./session-utils-core.js";
3738
import { getSessionDefaults } from "./session-utils-model.js";
@@ -241,8 +242,13 @@ function filterSessionEntries(params: {
241242
? filterRowContext.subagentRuns.getDisplaySubagentRun(key)
242243
: getSessionDisplaySubagentRunByChildSessionKey(key);
243244
const keepSpawned = latest
244-
? (normalizeOptionalString(latest.controllerSessionKey) ||
245-
normalizeOptionalString(latest.requesterSessionKey)) === spawnedBy &&
245+
? isCurrentSessionChildOwner({
246+
entry,
247+
ownerSessionKey: spawnedBy,
248+
controllerSessionKey:
249+
normalizeOptionalString(latest.controllerSessionKey) ||
250+
normalizeOptionalString(latest.requesterSessionKey),
251+
}) &&
246252
shouldKeepSubagentRunChildLink(latest, {
247253
activeDescendants: filterRowContext
248254
? filterRowContext.subagentRuns.countActiveDescendantRuns(key)

‎src/gateway/session-utils.single-row-cache.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,21 @@ function runningChildSession(
135135
};
136136
}
137137

138+
function runningControlledChildSession(
139+
sessionId: string,
140+
spawnedBy: string,
141+
now: number,
142+
parentSessionKey?: string,
143+
): SessionEntry {
144+
return {
145+
sessionId,
146+
spawnedBy,
147+
...(parentSessionKey ? { parentSessionKey } : {}),
148+
updatedAt: now,
149+
status: "running",
150+
};
151+
}
152+
138153
async function seedSessionEntries(
139154
storePath: string,
140155
store: Record<string, SessionEntry>,
@@ -234,6 +249,13 @@ describe("single gateway session row child-session cache", () => {
234249
"/tmp/openclaw-single-row-cache-fresh-registry",
235250
async ({ now, storePath }) => {
236251
const fixture = createMovingChildFixture(now);
252+
// This fixture moves runtime control only; an explicit parent would
253+
// instead declare durable navigation lineage that must remain linked.
254+
fixture.store[fixture.child] = runningControlledChildSession(
255+
"child",
256+
fixture.oldParent,
257+
now,
258+
);
237259
await seedSessionEntries(storePath, fixture.store);
238260

239261
setSubagentControllerRun(fixture.child, fixture.oldParent, now);
@@ -247,6 +269,36 @@ describe("single gateway session row child-session cache", () => {
247269
);
248270
});
249271

272+
test("keeps independent navigation lineage while cached runtime control moves", async () => {
273+
await withSingleRowCacheStore(
274+
"openclaw-single-row-cache-navigation-owner-",
275+
"/tmp/openclaw-single-row-cache-navigation-owner",
276+
async ({ now, storePath }) => {
277+
const fixture = createMovingChildFixture(now);
278+
const navigationParent = "agent:main:dashboard:navigation-parent";
279+
fixture.store[navigationParent] = parentSession("navigation-parent", now);
280+
fixture.store[fixture.child] = runningControlledChildSession(
281+
"child",
282+
fixture.oldParent,
283+
now,
284+
navigationParent,
285+
);
286+
await seedSessionEntries(storePath, fixture.store);
287+
288+
setSubagentControllerRun(fixture.child, fixture.oldParent, now);
289+
expect(loadGatewaySessionRow(navigationParent, { now })?.childSessions).toEqual([
290+
fixture.child,
291+
]);
292+
293+
setSubagentControllerRun(fixture.child, fixture.newParent, now + 25);
294+
expect(loadGatewaySessionRow(navigationParent, { now: now + 50 })?.childSessions).toEqual([
295+
fixture.child,
296+
]);
297+
expectChildMovedToNewParent(fixture, now);
298+
},
299+
);
300+
});
301+
250302
test("builds shared subagent metadata context for single-row session lists", async () => {
251303
await withSingleRowCacheStore(
252304
"openclaw-single-row-list-context-",

‎src/gateway/session-utils.subagent.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
2525
import { withStateDirEnv } from "../test-helpers/state-dir-env.js";
2626
import { withEnv } from "../test-utils/env.js";
27+
import { buildSingleRowStoreChildSessionsByKey } from "./session-utils-projection.js";
2728
import {
2829
listSessionsFromStore,
2930
loadCombinedSessionStoreForGateway,
@@ -174,6 +175,81 @@ describe("listSessionsFromStore subagent metadata", () => {
174175
expect(row.previousSessionId).toBe("sess-previous");
175176
});
176177

178+
test("discovers controlled children through both navigation and runtime owners", () => {
179+
const now = Date.now();
180+
const navigationParentKey = "agent:main:dashboard:navigation-parent";
181+
const controlParentKey = "agent:main:subagent:runtime-controller";
182+
const staleParentKey = "agent:main:subagent:stale-controller";
183+
const childSessionKey = "agent:main:subagent:controlled-child";
184+
const store: Record<string, SessionEntry> = {
185+
[navigationParentKey]: {
186+
sessionId: "sess-navigation-parent",
187+
updatedAt: now - 2_000,
188+
} as SessionEntry,
189+
[controlParentKey]: {
190+
sessionId: "sess-runtime-controller",
191+
updatedAt: now - 1_000,
192+
} as SessionEntry,
193+
[childSessionKey]: {
194+
sessionId: "sess-controlled-child",
195+
updatedAt: now,
196+
spawnedBy: staleParentKey,
197+
parentSessionKey: navigationParentKey,
198+
} as SessionEntry,
199+
};
200+
201+
addSubagentRunForTests({
202+
runId: "run-controlled-child-dual-owner",
203+
childSessionKey,
204+
controllerSessionKey: controlParentKey,
205+
requesterSessionKey: controlParentKey,
206+
requesterDisplayKey: "runtime-controller",
207+
task: "controlled child",
208+
cleanup: "keep",
209+
createdAt: now - 5_000,
210+
startedAt: now - 4_000,
211+
});
212+
213+
const listForOwner = (ownerSessionKey: string) =>
214+
listSessionsFromStore({
215+
cfg,
216+
storePath: "/tmp/sessions.json",
217+
store,
218+
opts: { spawnedBy: ownerSessionKey },
219+
});
220+
221+
const navigationChildren = listForOwner(navigationParentKey).sessions;
222+
expect(navigationChildren.map((session) => session.key)).toEqual([childSessionKey]);
223+
expect(navigationChildren[0]?.parentSessionKey).toBe(navigationParentKey);
224+
expect(navigationChildren[0]?.controlOwnerSessionKey).toBe(controlParentKey);
225+
expect(listForOwner(controlParentKey).sessions.map((session) => session.key)).toEqual([
226+
childSessionKey,
227+
]);
228+
expect(listForOwner(staleParentKey).sessions).toEqual([]);
229+
230+
const all = listSessionsFromStore({
231+
cfg,
232+
storePath: "/tmp/sessions.json",
233+
store,
234+
opts: {},
235+
});
236+
expect(
237+
all.sessions.find((session) => session.key === navigationParentKey)?.childSessions,
238+
).toEqual([childSessionKey]);
239+
expect(all.sessions.find((session) => session.key === controlParentKey)?.childSessions).toEqual(
240+
[childSessionKey],
241+
);
242+
243+
expect(
244+
buildSingleRowStoreChildSessionsByKey({
245+
store,
246+
storePath: "/tmp/sessions.json",
247+
key: navigationParentKey,
248+
now,
249+
}).get(navigationParentKey),
250+
).toEqual([childSessionKey]);
251+
});
252+
177253
test("includes subagent status timing and direct child session keys", () => {
178254
const now = Date.now();
179255
const store: Record<string, SessionEntry> = {

‎ui/src/components/app-sidebar-child-session-data.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import type { GatewayBrowserClient } from "../api/gateway.ts";
22
import type { GatewaySessionRow, SessionsListResult } from "../api/types.ts";
33
import type { SessionCapability } from "../lib/sessions/index.ts";
4-
import { areUiSessionKeysEquivalent } from "../lib/sessions/session-key.ts";
4+
import {
5+
areUiSessionKeysEquivalent,
6+
resolveUiSessionNavigationParentKey,
7+
} from "../lib/sessions/session-key.ts";
58
export { fetchChildSessionRows } from "../lib/sessions/child-session-data.ts";
69

710
const MAX_SESSION_LINEAGE_DEPTH = 16;
@@ -57,7 +60,7 @@ export async function fetchSessionLineage(params: {
5760
params.knownRows.set(row.key, row);
5861
}
5962
topmostRow = row;
60-
const parentKey = (row.spawnedBy ?? row.parentSessionKey)?.trim();
63+
const parentKey = resolveUiSessionNavigationParentKey(row);
6164
if (!parentKey) {
6265
break;
6366
}

0 commit comments

Comments
 (0)