Skip to content

Commit b8c7d68

Browse files
committed
fix(ui): require exact active run ownership
1 parent 54ebb30 commit b8c7d68

8 files changed

Lines changed: 119 additions & 37 deletions

File tree

‎docs/gateway/clients.md‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,11 +145,18 @@ current in-memory run state:
145145
rows with the returned `messages` projection.
146146
3. If `inFlightRun` is present, adopt its `runId`, buffered `text`, and optional
147147
`plan`. Adopt the run even when `text` is empty.
148-
4. Read `sessionInfo.hasActiveRun` and `sessionInfo.activeRunIds`. Prefer exact
149-
membership in `activeRunIds` when deciding whether a retained run still owns
150-
the streaming UI. A true `hasActiveRun` with no listed ID can represent another
151-
active runtime projection.
152-
5. Reconcile subsequent `agent` events by `payload.runId` and `payload.seq`.
148+
4. Treat `sessionInfo.hasActiveRun` as aggregate direct-session activity.
149+
`activeRunIds`, when present, contains known exact active run identities and
150+
can be empty while aggregate activity is still true. Omission means the field
151+
was not projected and provides no identity information. In incremental merge
152+
events, replace the cached list when the field is present; an empty array is
153+
the tombstone that clears prior exact identities. Correlate only a run ID the
154+
client owns locally or received from a request, history response, or event,
155+
and never select the first list entry as an owner.
156+
5. Show an observer headline or run-inspector link only when the observer digest's
157+
exact `runId` is present in `activeRunIds`. Aggregate activity alone does not
158+
make a retained digest current.
159+
6. Reconcile subsequent `agent` events by `payload.runId` and `payload.seq`.
153160
Maintain the highest accepted sequence independently for each run, ignore an
154161
already-seen or lower sequence, and treat a forward gap as a reason to reload
155162
authoritative history.

‎docs/gateway/protocol.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,7 @@ methods. Treat this as feature discovery, not a full enumeration of
643643
</Accordion>
644644

645645
<Accordion title="Session control">
646-
- `sessions.list` returns the current session index, including per-row `agentRuntime` metadata when an agent runtime backend is configured. When cloud-worker placement is enabled or durable recovery state exists, session rows also include a closed `placement` state (`local`, `requested`, `provisioning`, `syncing`, `starting`, `active`, `draining`, `reconciling`, `reclaimed`, or `failed`) plus state-specific environment, owner-epoch, workspace, bundle, ACK-cursor, or recovery fields. Active placements may include an advisory `diskSpace` sample with `status` (`ok`, `warning`, or `critical`), `availableBytes`, `totalBytes`, and `observedAtMs`. Rows carry ownership projections — write-once `createdActor`, the mutable `owner` (actor plus `assignedBy`/`assignedAt`), a bounded `participants` list (owner excluded, up to 4 actors), and the full `participantCount`; actor display labels and avatars are resolved from current profiles and agent identities at read time. Pass `creatorId` to filter by immutable `createdActor.id`; pass `ownerId` to filter by the current assignable owner, falling back to `createdActor` when no owner is assigned. The complete `owners` facet is independent of pagination and remains unfiltered by either query, so clients can render the full owner picker. Authenticated callers can pass `involvingMe: true` to keep only sessions the caller owns or has prompted, evaluated against the full participant history (profile-backed human participants only).
646+
- `sessions.list` returns the current session index, including per-row `agentRuntime` metadata when an agent runtime backend is configured. `hasActiveRun` is the authoritative aggregate direct-session activity fact. When projected, `activeRunIds` contains known exact active run identities and may be empty while aggregate activity remains true. Omission means exact identities were not projected and is not a replacement value. Incremental merge events can send an empty array as the replacement tombstone that clears previously cached identities. Clients correlate only exact IDs they own locally or received from requests, history, or events and never select the first list entry as an owner. When cloud-worker placement is enabled or durable recovery state exists, session rows also include a closed `placement` state (`local`, `requested`, `provisioning`, `syncing`, `starting`, `active`, `draining`, `reconciling`, `reclaimed`, or `failed`) plus state-specific environment, owner-epoch, workspace, bundle, ACK-cursor, or recovery fields. Active placements may include an advisory `diskSpace` sample with `status` (`ok`, `warning`, or `critical`), `availableBytes`, `totalBytes`, and `observedAtMs`. Rows carry ownership projections — write-once `createdActor`, the mutable `owner` (actor plus `assignedBy`/`assignedAt`), a bounded `participants` list (owner excluded, up to 4 actors), and the full `participantCount`; actor display labels and avatars are resolved from current profiles and agent identities at read time. Pass `creatorId` to filter by immutable `createdActor.id`; pass `ownerId` to filter by the current assignable owner, falling back to `createdActor` when no owner is assigned. The complete `owners` facet is independent of pagination and remains unfiltered by either query, so clients can render the full owner picker. Authenticated callers can pass `involvingMe: true` to keep only sessions the caller owns or has prompted, evaluated against the full participant history (profile-backed human participants only).
647647
- `sessions.subscribe` enables session change events for the current WebSocket client. The subscription ends when that client disconnects.
648648
- `sessions.messages.subscribe` and `sessions.messages.unsubscribe` toggle transcript/message event subscriptions for one session. Pass `includeApprovals: true` to also receive sanitized `session.approval` lifecycle events for approvals whose persisted audience includes that exact session and whose reviewer binding authorizes the subscribing client. The subscribe response then includes a bounded pending `approvalReplay`; it is authoritative when `truncated` is false. The opt-in is per subscribe call, not sticky: re-subscribing to the same session without `includeApprovals: true` removes an existing approval subscription. In addition to normal session-read authority, this opt-in requires `operator.admin`, or `operator.approvals` on a paired device.
649649
- `sessions.preview` returns bounded transcript previews for specific session keys.
@@ -661,7 +661,7 @@ methods. Treat this as feature discovery, not a full enumeration of
661661
- `sessions.assignOwner` (`operator.write`) reassigns the session's mutable owner to a person or configured agent (`{ key, owner: { type, id } }`). It requires an identified caller (authenticated profile or trusted agent identity), authorizes by session visibility, and records `assignedBy`/`assignedAt` on the row's `owner` field. The write-once `createdActor` and creator-anchored sharing authority are unchanged; see [Multi-user mode](/concepts/multi-user#assigning-an-owner).
662662
- `sessions.reset`, `sessions.delete`, and `sessions.compact` perform session maintenance.
663663
- `sessions.get` returns the full stored session row.
664-
- Chat execution still uses `chat.history`, `chat.send`, `chat.abort`, and `chat.inject`. `chat.history` is display-normalized for UI clients: inline directive tags are stripped from visible text, plain-text tool-call XML payloads (`<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, `<function_calls>...</function_calls>`, and truncated tool-call blocks) and leaked ASCII/full-width model control tokens are stripped, pure silent-token assistant rows (exact `NO_REPLY` / `no_reply`) are omitted, and oversized rows can be replaced with placeholders.
664+
- Chat execution still uses `chat.history`, `chat.send`, `chat.abort`, and `chat.inject`. Its `sessionInfo` uses the same aggregate `hasActiveRun` and optional known-exact `activeRunIds` semantics as `sessions.list`. `chat.history` is display-normalized for UI clients: inline directive tags are stripped from visible text, plain-text tool-call XML payloads (`<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, `<function_calls>...</function_calls>`, and truncated tool-call blocks) and leaked ASCII/full-width model control tokens are stripped, pure silent-token assistant rows (exact `NO_REPLY` / `no_reply`) are omitted, and oversized rows can be replaced with placeholders.
665665
Tail responses can include an opaque `deltaCursor`. Pass it back as `cursor` to `chat.history` or `chat.startup` instead of `offset` or `messageId`. A successful catch-up returns `{ kind: "delta", messages, deltaCursor, sessionInfo }`; replay each `messages` entry through the same reducer as a live `session.message` payload. `{ kind: "reset" }` means the cursor is invalid, stale, belongs to another session, crossed a reset or compaction, or is too far behind; fetch a normal tail page. Catch-up never returns a partial page or continuation: more than 200 raw events or the 1 MB payload budget resets to a tail fetch.
666666
- `chat.message.get` is the additive bounded full-message reader for a single visible transcript entry. Pass `sessionKey`, optional `agentId` when session selection is agent-scoped, and a transcript `messageId` previously surfaced through `chat.history`; the gateway returns the same display-normalized projection without the lightweight history truncation cap when the stored entry is still available and not oversized.
667667
- `chat.toolTitles` returns short purpose titles for tool calls rendered in the Control UI (batched, max 24 items with bounded inputs). The feature is opt-in via `gateway.controlUi.toolTitles` (default off); disabled gateways answer `{ titles: {}, disabled: true }` with no model call so clients stop asking. When enabled, titles use standard utility-model routing: an explicitly configured `utilityModel` (an operator decision that, like all utility tasks, may send bounded task content to the chosen provider), else the session provider's declared small-model default so no new egress destination appears implicitly; an empty `utilityModel` disables them entirely. Titles never fall back to the primary model. Results cache in the per-agent state database keyed by tool name + input, so repeated views never re-bill the same calls.
@@ -755,7 +755,11 @@ methods. Treat this as feature discovery, not a full enumeration of
755755
- `session.observer`: safe live session headline and status digest. A model-authored
756756
preamble can update the headline immediately; utility-model assessments replace
757757
it later when available. Web, iOS, and Android use the same run-scoped digest.
758-
- `sessions.changed`: session index or metadata changed.
758+
Clients show its headline or inspector link only while the digest's exact `runId`
759+
is present in `activeRunIds`.
760+
- `sessions.changed`: session index or metadata changed. Active-run fields use the
761+
same aggregate and known-exact semantics as `sessions.list`; a present empty
762+
`activeRunIds` replaces and clears the client's cached exact-identity list.
759763
- `presence`: system presence snapshot updates.
760764
- `tick`: periodic keepalive/liveness event.
761765
- `health`: gateway health snapshot update.

‎ui/src/lib/observer-digest.test.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
// @vitest-environment node
22
import { describe, expect, it } from "vitest";
3-
import { isCriticalObserverHealth, projectSessionObserverDigest } from "./observer-digest.ts";
3+
import {
4+
isCriticalObserverHealth,
5+
projectSessionObserverDigest,
6+
resolveChatPaneObserverRunId,
7+
} from "./observer-digest.ts";
48

59
describe("projectSessionObserverDigest", () => {
610
it("binds a session-row projection to its owning session", () => {
@@ -31,3 +35,27 @@ describe("isCriticalObserverHealth", () => {
3135
expect(isCriticalObserverHealth("failed")).toBe(false);
3236
});
3337
});
38+
39+
describe("resolveChatPaneObserverRunId", () => {
40+
it("uses only a local run or the observer digest's exact active membership", () => {
41+
const session = { hasActiveRun: true, activeRunIds: ["other-run", "observer-run"] };
42+
43+
expect(resolveChatPaneObserverRunId({ localRunId: "local-run", session, digest: null })).toBe(
44+
"local-run",
45+
);
46+
expect(
47+
resolveChatPaneObserverRunId({
48+
localRunId: null,
49+
session,
50+
digest: { runId: "observer-run" },
51+
}),
52+
).toBe("observer-run");
53+
expect(
54+
resolveChatPaneObserverRunId({
55+
localRunId: null,
56+
session,
57+
digest: { runId: "stale-run" },
58+
}),
59+
).toBeNull();
60+
});
61+
});

‎ui/src/lib/observer-digest.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ export function isCriticalObserverHealth(health: unknown): health is "stuck" | "
3333
return health === "stuck" || health === "waiting-on-user";
3434
}
3535

36-
/** Local live run id wins; otherwise the row's server-reported active runs
37-
* identify the run, preferring the one the digest belongs to. */
36+
/** Local live run id wins; otherwise the observer must still own an exact active run. */
3837
export function resolveChatPaneObserverRunId(params: {
3938
localRunId: string | null;
4039
session: { hasActiveRun?: boolean; activeRunIds?: readonly string[] } | undefined;
@@ -43,13 +42,10 @@ export function resolveChatPaneObserverRunId(params: {
4342
if (params.localRunId) {
4443
return params.localRunId;
4544
}
46-
if (!params.session?.hasActiveRun) {
45+
if (!params.session?.hasActiveRun || !params.digest?.runId) {
4746
return null;
4847
}
49-
const activeRunIds = params.session.activeRunIds ?? [];
50-
return params.digest?.runId && activeRunIds.includes(params.digest.runId)
51-
? params.digest.runId
52-
: (activeRunIds[0] ?? null);
48+
return params.session.activeRunIds?.includes(params.digest.runId) ? params.digest.runId : null;
5349
}
5450

5551
export function pickFreshestObserverDigest<T extends ComparableObserverDigest>(

‎ui/src/pages/activity/session-activity-view.test.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,11 @@ describe("session activity live status", () => {
212212
renderSessionActivityView(
213213
props({
214214
rows: [
215-
row("Active session", owner, now, { hasActiveRun: true, observerDigest }),
215+
row("Active session", owner, now, {
216+
activeRunIds: ["fake-run"],
217+
hasActiveRun: true,
218+
observerDigest,
219+
}),
216220
row("Inactive session", owner, now - 1_000, {
217221
observerDigest,
218222
status: "running",
@@ -237,7 +241,7 @@ describe("session activity live status", () => {
237241
expect(inactive?.querySelector(".activity-feed__session-headline")).toBeNull();
238242
});
239243

240-
it("links active rows to their recorded run ids", () => {
244+
it("shows and links only observer digests with exact active-run membership", () => {
241245
const now = Date.now();
242246
const owner = { id: "owner", label: "Owner" };
243247
const base = props();
@@ -289,10 +293,21 @@ describe("session activity live status", () => {
289293
[...container.querySelectorAll<HTMLAnchorElement>(".activity-feed__inspect-run")].map(
290294
(link) => link.getAttribute("href"),
291295
),
292-
).toEqual([
293-
"/control/activity?view=run&run=digest%20run%3Aa%2Fb",
294-
"/control/activity?view=run&run=current-run",
295-
"/control/activity?view=run&run=fallback%20run%3Aa%2Fb",
296-
]);
296+
).toEqual(["/control/activity?view=run&run=digest%20run%3Aa%2Fb"]);
297+
expect(
298+
container
299+
.querySelector('[data-activity-session="Digest run"] .activity-feed__session-headline')
300+
?.textContent?.trim(),
301+
).toBe("Running");
302+
expect(
303+
container.querySelector(
304+
'[data-activity-session="Stale digest"] .activity-feed__session-headline',
305+
),
306+
).toBeNull();
307+
expect(
308+
container.querySelector(
309+
'[data-activity-session="Active run fallback"] .activity-feed__session-headline',
310+
),
311+
).toBeNull();
297312
});
298313
});

‎ui/src/pages/activity/session-activity-view.ts‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -250,17 +250,12 @@ function renderSessionLink(context: ApplicationContext, row: GatewaySessionRow)
250250
const owner = sessionActivityOwner(row);
251251
const ownerName = presenceViewerLabel(owner);
252252
const activityAt = sessionActivityTimestamp(row);
253-
const headline = row.hasActiveRun === true ? row.observerDigest?.headline.trim() : "";
254-
// The observer digest can outlive the run it described (restart/overlap), so its
255-
// runId may reference an obsolete audit record; trust it only when it is still an
256-
// active run, otherwise fall back to the row's own active-run list.
257253
const digestRunId = row.observerDigest?.runId;
258-
const activeRunId =
259-
row.hasActiveRun === true
260-
? digestRunId && row.activeRunIds?.includes(digestRunId)
261-
? digestRunId
262-
: row.activeRunIds?.[0]
254+
const activeObserverRunId =
255+
row.hasActiveRun === true && digestRunId && row.activeRunIds?.includes(digestRunId)
256+
? digestRunId
263257
: undefined;
258+
const headline = activeObserverRunId ? row.observerDigest?.headline.trim() : "";
264259
const scope = row.channel
265260
? t("activityFeed.channelLabel", { value: row.channel })
266261
: row.agentId
@@ -307,10 +302,10 @@ function renderSessionLink(context: ApplicationContext, row: GatewaySessionRow)
307302
: nothing}
308303
</span>
309304
</a>
310-
${activeRunId
305+
${activeObserverRunId
311306
? html`<a
312307
class="activity-feed__inspect-run"
313-
href=${activityRunInspectorHref(activeRunId, context.basePath)}
308+
href=${activityRunInspectorHref(activeObserverRunId, context.basePath)}
314309
>${t("activityFeed.inspectRun")}</a
315310
>`
316311
: nothing}

‎ui/src/pages/chat/chat-projection-run-id.test.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
// @vitest-environment node
2-
import { describe, expect, it } from "vitest";
1+
/* @vitest-environment jsdom */
2+
3+
import { describe, expect, it, vi } from "vitest";
4+
import * as chatThread from "./chat-thread.ts";
5+
import { projectChatTranscript } from "./components/chat-transcript-projection.ts";
6+
import { threadProps } from "./components/chat-transcript.test-support.ts";
37
import { resolveChatProjectionRunId } from "./tool-stream.ts";
48

59
describe("resolveChatProjectionRunId", () => {
@@ -33,3 +37,36 @@ describe("resolveChatProjectionRunId", () => {
3337
).toBe("run-local");
3438
});
3539
});
40+
41+
describe("transcript run identity", () => {
42+
it("does not project a session row's first active run without an explicit run id", () => {
43+
const build = vi.spyOn(chatThread, "buildCachedChatItems").mockReturnValue([]);
44+
45+
projectChatTranscript(
46+
{
47+
...threadProps("run-id-projection"),
48+
sessions: {
49+
ts: 0,
50+
path: "",
51+
count: 1,
52+
defaults: { modelProvider: "openai", model: "gpt-5", contextTokens: null },
53+
sessions: [
54+
{
55+
key: "agent:main:main",
56+
kind: "direct",
57+
updatedAt: 1,
58+
hasActiveRun: true,
59+
activeRunIds: ["arbitrary-first", "other-run"],
60+
},
61+
],
62+
},
63+
},
64+
{
65+
setContentReady: vi.fn(),
66+
syncMessageRows: vi.fn(),
67+
} as unknown as Parameters<typeof projectChatTranscript>[1],
68+
);
69+
70+
expect(build).toHaveBeenCalledWith(expect.objectContaining({ runId: null }));
71+
});
72+
});

‎ui/src/pages/chat/components/chat-transcript-projection.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ export function projectChatTranscript(
208208
const chatItems = buildCachedChatItems({
209209
paneId: props.paneId,
210210
sessionKey: props.sessionKey,
211-
runId: props.runId === undefined ? (activeSession?.activeRunIds?.[0] ?? null) : props.runId,
211+
runId: props.runId ?? null,
212212
locale,
213213
messages: props.messages,
214214
toolMessages: props.toolMessages,

0 commit comments

Comments
 (0)