Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(web): release ended Runs from the live Room Run set

jeffrey3d7683b10bed
diff --git a/apps/web/src/features/rooms/runtime-status/runtime-presentation-events-sync.ts b/apps/web/src/features/rooms/runtime-status/runtime-presentation-events-sync.ts
index 4b5a373f..563f1c9e 100644
--- a/apps/web/src/features/rooms/runtime-status/runtime-presentation-events-sync.ts
+++ b/apps/web/src/features/rooms/runtime-status/runtime-presentation-events-sync.ts
@@ -39,7 +39,8 @@ interface RunStatusSyncState {
runStatusId: string;
job?: LimitedSyncJob;
key: string;
- owners: Set<symbol>;
+ /** Each owning sync and its revision-complete listener. */
+ owners: Map<symbol, (runStatusId: string) => void>;
queryClient: QueryClient;
queryKey: ReturnType<typeof roomRuntimePresentationEventsQueryKey>;
registry: RuntimePresentationSyncRegistry;
@@ -55,11 +56,17 @@ const registries = new WeakMap<QueryClient, RuntimePresentationSyncRegistry>();
export function createRuntimePresentationEventsSync({
client,
+ onRevisionComplete = () => undefined,
queryClient,
roomId,
tenantId,
}: {
client: RuntimePresentationSyncClient;
+ /**
+ * Called after a sync completes the revisions requested so far, or stops
+ * for good on an error that a retry cannot fix.
+ */
+ onRevisionComplete?: (runStatusId: string) => void;
queryClient: QueryClient;
roomId: string;
tenantId: string;
@@ -87,7 +94,11 @@ export function createRuntimePresentationEventsSync({
roomRuntimePresentationEventsQueryKey(tenantId, roomId, runStatusId),
);
const state = ownedStates.get(key);
- return state !== undefined && state.completedRevision >= revision;
+ // A blocked read never completes; its caller can let the Run go.
+ return (
+ state !== undefined &&
+ (state.blocked || state.completedRevision >= revision)
+ );
},
request(runStatusId: string, revision: number) {
if (disposed) return;
@@ -106,7 +117,7 @@ export function createRuntimePresentationEventsSync({
completedRevision: -1,
runStatusId,
key,
- owners: new Set(),
+ owners: new Map(),
queryClient,
queryKey,
registry,
@@ -124,7 +135,7 @@ export function createRuntimePresentationEventsSync({
}
}
if (!state.owners.has(owner)) {
- state.owners.add(owner);
+ state.owners.set(owner, onRevisionComplete);
ownedStates.set(key, state);
}
if (state.requestedRevision > state.completedRevision) schedule(state);
@@ -213,7 +224,13 @@ function start(state: RunStatusSyncState): Promise<void> {
state.completedRevision,
targetRevision,
);
- if (state.requestedRevision > state.completedRevision) schedule(state);
+ if (state.requestedRevision > state.completedRevision) {
+ schedule(state);
+ return;
+ }
+ for (const notify of [...state.owners.values()]) {
+ notify(state.runStatusId);
+ }
},
(error: unknown) => {
if (state.running !== running) return;
@@ -238,6 +255,9 @@ function start(state: RunStatusSyncState): Promise<void> {
);
} else {
state.blocked = true;
+ for (const notify of [...state.owners.values()]) {
+ notify(state.runStatusId);
+ }
}
},
);
diff --git a/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.test.tsx b/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.test.tsx
index ddc0401a..e859c42b 100644
--- a/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.test.tsx
+++ b/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.test.tsx
@@ -637,6 +637,127 @@ describe("Room Runtime presentations", () => {
});
});
+ it("stops observing a terminal Run after its final sync once it left the timeline", async () => {
+ const finalCatchUp = deferred<TeamHubRuntimePresentationEventPage>();
+ const runtime = createTestTeamHubRuntime();
+ const listRoomRuntimePresentationEvents = vi
+ .fn<TestRouteHandler>()
+ .mockReturnValueOnce(eventPage(["1"], "1"))
+ .mockReturnValueOnce(finalCatchUp.promise);
+ runtime.server.on("GET", EVENTS_PATH, listRoomRuntimePresentationEvents);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const initialProps: { runStatus?: TeamHubRunStatus } = {
+ runStatus: testRunStatus(1),
+ };
+ const { rerender } = renderHook(
+ ({ runStatus }: { runStatus?: TeamHubRunStatus }) =>
+ useRoomRuntimePresentations({
+ activeRunStatuses: runStatus?.status === "active" ? [runStatus] : [],
+ runStatuses: runStatus ? [runStatus] : [],
+ roomId: "room-1",
+ tenantId: "tenant-1",
+ }),
+ {
+ initialProps,
+ wrapper: queryWrapper(queryClient, runtime),
+ },
+ );
+ await waitFor(() =>
+ expect(listRoomRuntimePresentationEvents).toHaveBeenCalledOnce(),
+ );
+ rerender({ runStatus: { ...testRunStatus(2), status: "completed" } });
+ await waitFor(() =>
+ expect(listRoomRuntimePresentationEvents).toHaveBeenCalledTimes(2),
+ );
+ // The live set drops the ended Run before its tail arrives.
+ rerender({ runStatus: undefined });
+ expect(observerCount(queryClient)).toBe(1);
+
+ await act(async () => {
+ finalCatchUp.resolve(eventPage(["2"], "2"));
+ await finalCatchUp.promise;
+ });
+ await waitFor(() => expect(observerCount(queryClient)).toBe(0));
+ expect(cachedEvents(queryClient)?.published_through_ordinal).toBe("2");
+ });
+
+ it("reads once more and releases a Run that left before its end arrived", async () => {
+ const runtime = createTestTeamHubRuntime();
+ const listRoomRuntimePresentationEvents = vi
+ .fn<TestRouteHandler>()
+ .mockReturnValueOnce(eventPage(["1"], "1"))
+ .mockReturnValueOnce(eventPage(["2", "3"], "3"));
+ runtime.server.on("GET", EVENTS_PATH, listRoomRuntimePresentationEvents);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const { rerender } = renderHook(
+ ({ visible }: { visible: boolean }) =>
+ useRoomRuntimePresentations({
+ activeRunStatuses: visible ? [testRunStatus(1)] : [],
+ runStatuses: visible ? [testRunStatus(1)] : [],
+ roomId: "room-1",
+ tenantId: "tenant-1",
+ }),
+ {
+ initialProps: { visible: true },
+ wrapper: queryWrapper(queryClient, runtime),
+ },
+ );
+ await waitFor(() =>
+ expect(cachedEvents(queryClient)?.published_through_ordinal).toBe("1"),
+ );
+ // A reconnect snapshot omits the succeeded Run, so no end is ever seen.
+ rerender({ visible: false });
+
+ await waitFor(() => expect(observerCount(queryClient)).toBe(0));
+ expect(eventRead(listRoomRuntimePresentationEvents.mock.calls[1]!)).toEqual(
+ ["room-1", "run-status-1", "1", 200],
+ );
+ expect(cachedEvents(queryClient)?.published_through_ordinal).toBe("3");
+ });
+
+ it("releases an ended Run whose final read stops on a protocol violation", async () => {
+ const runtime = createTestTeamHubRuntime();
+ const listRoomRuntimePresentationEvents = vi
+ .fn<TestRouteHandler>()
+ .mockReturnValueOnce(eventPage(["1"], "1"))
+ // A page that skips ordinals is a protocol violation, not retried.
+ .mockReturnValue(eventPage(["5"], "5"));
+ runtime.server.on("GET", EVENTS_PATH, listRoomRuntimePresentationEvents);
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const initialProps: { runStatus?: TeamHubRunStatus } = {
+ runStatus: testRunStatus(1),
+ };
+ const { rerender } = renderHook(
+ ({ runStatus }: { runStatus?: TeamHubRunStatus }) =>
+ useRoomRuntimePresentations({
+ runStatuses: runStatus ? [runStatus] : [],
+ roomId: "room-1",
+ tenantId: "tenant-1",
+ }),
+ {
+ initialProps,
+ wrapper: queryWrapper(queryClient, runtime),
+ },
+ );
+ await waitFor(() =>
+ expect(cachedEvents(queryClient)?.published_through_ordinal).toBe("1"),
+ );
+ rerender({ runStatus: { ...testRunStatus(2), status: "completed" } });
+ await waitFor(() =>
+ expect(listRoomRuntimePresentationEvents).toHaveBeenCalledTimes(2),
+ );
+ rerender({ runStatus: undefined });
+
+ await waitFor(() => expect(observerCount(queryClient)).toBe(0));
+ expect(listRoomRuntimePresentationEvents).toHaveBeenCalledTimes(2);
+ });
+
it("retries a failed synchronization with backoff instead of waiting for a rerender", async () => {
const runtime = createTestTeamHubRuntime();
const listRoomRuntimePresentationEvents = vi
@@ -866,3 +987,41 @@ function testRunStatus(
updated_at: `2026-08-25T00:00:0${revision}Z`,
};
}
+
+function queryWrapper(
+ queryClient: QueryClient,
+ runtime: ReturnType<typeof createTestTeamHubRuntime>,
+) {
+ return function QueryWrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <TeamHubRuntimeProvider runtime={runtime}>
+ {children}
+ </TeamHubRuntimeProvider>
+ </QueryClientProvider>
+ );
+ };
+}
+
+function eventsQueryKey() {
+ return roomRuntimePresentationEventsQueryKey(
+ "tenant-1",
+ "room-1",
+ "run-status-1",
+ );
+}
+
+function observerCount(queryClient: QueryClient) {
+ return (
+ queryClient
+ .getQueryCache()
+ .find({ exact: true, queryKey: eventsQueryKey() })
+ ?.getObserversCount() ?? 0
+ );
+}
+
+function cachedEvents(queryClient: QueryClient) {
+ return queryClient.getQueryData<TeamHubRuntimePresentationEventPage>(
+ eventsQueryKey(),
+ );
+}
diff --git a/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.ts b/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.ts
index 33c08a7b..7c5dd347 100644
--- a/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.ts
+++ b/apps/web/src/features/rooms/runtime-status/use-room-runtime-presentations.ts
@@ -1,5 +1,5 @@
import { useQueries, useQueryClient } from "@tanstack/react-query";
-import { useEffect, useMemo, useRef } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
import type {
@@ -32,15 +32,19 @@ export function useRoomRuntimePresentations({
// eslint-disable-next-line react-hooks/exhaustive-deps -- scope identities are intentional reset keys
[client, queryClient, roomId, tenantId],
);
+ // Counts eager syncs finished after their Run ended, so the observed set
+ // drops them and React Query can collect their events.
+ const [releasedSyncs, setReleasedSyncs] = useState(0);
const runStatusesToSync = activeRunStatuses ?? runStatuses;
const observedRunStatusIds = useMemo(() => {
+ void releasedSyncs;
const runStatusIds = runStatuses.map((runStatus) => runStatus.id);
const visibleRunStatusIds = new Set(runStatusIds);
for (const runStatusId of eagerlySyncedRunStatuses.keys()) {
if (!visibleRunStatusIds.has(runStatusId)) runStatusIds.push(runStatusId);
}
return runStatusIds;
- }, [runStatuses, eagerlySyncedRunStatuses]);
+ }, [runStatuses, eagerlySyncedRunStatuses, releasedSyncs]);
const queries = useQueries({
queries: observedRunStatusIds.map((runStatusId) => ({
...roomRuntimePresentationEventsQueryOptions(
@@ -56,6 +60,17 @@ export function useRoomRuntimePresentations({
useEffect(() => {
const sync = createRuntimePresentationEventsSync({
client,
+ onRevisionComplete: (runStatusId) => {
+ const target = eagerlySyncedRunStatuses.get(runStatusId);
+ if (
+ !target?.terminal ||
+ !sync.isRevisionComplete(runStatusId, target.revision)
+ ) {
+ return;
+ }
+ eagerlySyncedRunStatuses.delete(runStatusId);
+ setReleasedSyncs((count) => count + 1);
+ },
queryClient,
roomId,
tenantId,
@@ -65,7 +80,7 @@ export function useRoomRuntimePresentations({
sync.dispose();
syncRef.current = null;
};
- }, [client, queryClient, roomId, tenantId]);
+ }, [client, queryClient, roomId, tenantId, eagerlySyncedRunStatuses]);
useEffect(() => {
const sync = syncRef.current;
if (!sync) return;
@@ -86,6 +101,18 @@ export function useRoomRuntimePresentations({
eagerlySyncedRunStatuses.set(runStatus.id, target);
sync.request(runStatus.id, target.revision);
}
+ const shownRunStatusIds = new Set(
+ [...runStatuses, ...runStatusesToSync].map((runStatus) => runStatus.id),
+ );
+ for (const [runStatusId, target] of eagerlySyncedRunStatuses) {
+ if (target.terminal || shownRunStatusIds.has(runStatusId)) continue;
+ // The Run left before its end reached this hook (a reconnect snapshot
+ // omits succeeded Runs, or updates were batched): read once more now
+ // that it has ended, then release it.
+ const ended = { revision: target.revision + 1, terminal: true };
+ eagerlySyncedRunStatuses.set(runStatusId, ended);
+ sync.request(runStatusId, ended.revision);
+ }
for (const [runStatusId, target] of eagerlySyncedRunStatuses) {
if (
target.terminal &&
@@ -101,7 +128,7 @@ export function useRoomRuntimePresentations({
retainedRunStatusIds.add(runStatusId);
}
sync.retain(retainedRunStatusIds);
- }, [runStatuses, runStatusesToSync, eagerlySyncedRunStatuses]);
+ }, [runStatuses, runStatusesToSync, eagerlySyncedRunStatuses, releasedSyncs]);
return useMemo(() => {
const eventsByRunStatusId: Record<
diff --git a/apps/web/src/features/teamhub/run-status-transport.test.ts b/apps/web/src/features/teamhub/run-status-transport.test.ts
index 7ee6a27c..f7c80808 100644
--- a/apps/web/src/features/teamhub/run-status-transport.test.ts
+++ b/apps/web/src/features/teamhub/run-status-transport.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { createRunStatusTransport } from "./run-status-transport";
+import {
+ createRunStatusTransport,
+ endedRunRereadMs,
+} from "./run-status-transport";
import { TeamHubError } from "./teamhub-error";
import type { TeamHubEventSignal } from "./event-transport";
import type {
@@ -10,6 +13,48 @@ import type {
} from "./teamhub-types";
describe("Run status transport", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("rereads the snapshot once after a burst of ends, which settles the set", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const harness = createHarness([run("run-1", 1), run("run-2", 1)]);
+ const collections = harness.subscribe();
+ await vi.waitFor(() => expect(collections).toHaveLength(1));
+ await harness.announce(published("run-1", 4, "completed"));
+ await harness.announce(published("run-2", 3, "aborted"));
+ expect(collections.at(-1)!.map(({ status }) => status)).toEqual([
+ "completed",
+ "aborted",
+ ]);
+
+ // The server keeps the failed Run and omits the succeeded one.
+ harness.items = [{ ...run("run-2", 3), status: "aborted" }];
+ vi.advanceTimersByTime(endedRunRereadMs);
+ await vi.waitFor(() => expect(harness.list).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() =>
+ expect(collections.at(-1)!.map(({ id }) => id)).toEqual(["run-2"]),
+ );
+ vi.advanceTimersByTime(endedRunRereadMs);
+ expect(harness.list).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not reread after it is unsubscribed", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const harness = createHarness([run("run-1", 1)]);
+ const collections: TeamHubRunStatus[][] = [];
+ const unsubscribe = harness.transport.subscribe({
+ onCollection: (items) => collections.push(items),
+ onSessionExpired: vi.fn(),
+ roomId: "room-1",
+ });
+ await vi.waitFor(() => expect(collections).toHaveLength(1));
+ await harness.announce(published("run-1", 4, "completed"));
+ unsubscribe();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it("publishes the Room snapshot, then each newer announcement", async () => {
const harness = createHarness([run("run-1", 1)]);
const collections = harness.subscribe();
@@ -267,5 +312,5 @@ function createHarness(
},
},
});
- return harness;
+ return Object.assign(harness, { transport });
}
diff --git a/apps/web/src/features/teamhub/run-status-transport.ts b/apps/web/src/features/teamhub/run-status-transport.ts
index 7c8124f3..a1471c4f 100644
--- a/apps/web/src/features/teamhub/run-status-transport.ts
+++ b/apps/web/src/features/teamhub/run-status-transport.ts
@@ -19,6 +19,8 @@ export interface RunStatusTransport {
const snapshotRetryBaseMs = 1_000;
const snapshotRetryMaxMs = 30_000;
+// How long after a Run ends the snapshot is read again to settle the set.
+export const endedRunRereadMs = 60_000;
/**
* Follows the Run statuses a Room shows: the list endpoint is the snapshot,
@@ -28,6 +30,11 @@ const snapshotRetryMaxMs = 30_000;
* were lost, so both reread the snapshot. A failed snapshot read is retried
* with backoff until one succeeds, because nothing else repairs a Run that
* ended while the stream was down.
+ *
+ * The server decides which Runs the set keeps. An announced end shows at
+ * once, and endedRunRereadMs later one snapshot read replaces the set, so
+ * the Runs that read omits leave it. Ends announced close together share
+ * that read.
*/
export function createRunStatusTransport({
client,
@@ -43,6 +50,7 @@ export function createRunStatusTransport({
let loads = 0;
let failedLoads = 0;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
+ let rereadTimer: ReturnType<typeof setTimeout> | undefined;
const publish = () => input.onCollection([...runs.values()]);
const apply = (run: TeamHubRunStatus) => {
const current = runs.get(run.id);
@@ -119,11 +127,18 @@ export function createRunStatusTransport({
if (!apply(run)) return;
recordTerminalReceipt(run);
publish();
+ if (run.status !== "active" && rereadTimer === undefined) {
+ rereadTimer = setTimeout(() => {
+ rereadTimer = undefined;
+ void load();
+ }, endedRunRereadMs);
+ }
});
void load();
return () => {
disposed = true;
clearTimeout(retryTimer);
+ clearTimeout(rereadTimer);
unsubscribe();
};
},