Skip to content

Commit 68e76d7

Browse files
author
Brain
committed
fix(desktop): preserve startup control readiness and mock replay
Signed-off-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
1 parent 8cb0881 commit 68e76d7

17 files changed

Lines changed: 374 additions & 66 deletions

‎desktop/src/features/agents/ui/ModelPicker.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ import type { AgentModelsResponse, ManagedAgent } from "@/shared/api/types";
99
import { getAgentModels, updateManagedAgent } from "@/shared/api/tauri";
1010
import { switchManagedAgentModel } from "@/shared/api/agentControl";
1111
import { awaitLiveSwitchOutcome } from "@/features/agents/lib/liveSwitchOutcome";
12-
import { subscribeControlResults } from "@/features/agents/observerRelayStore";
12+
import {
13+
ensureRelayObserverSubscription,
14+
subscribeControlResults,
15+
} from "@/features/agents/observerRelayStore";
1316
import { useActiveAgentTurns } from "@/features/agents/activeAgentTurnsStore";
1417
import {
1518
useAgentConfigSurface,
@@ -128,6 +131,7 @@ export function ModelPicker({
128131
subscribe: (listener) =>
129132
subscribeControlResults(agent.pubkey, listener),
130133
sendSwitches: async () => {
134+
await ensureRelayObserverSubscription();
131135
await Promise.all(
132136
channelIds.map((channelId) =>
133137
switchManagedAgentModel(

‎desktop/src/features/channels/observedUnreadNativeRig.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ export function makeStubRelayClient() {
374374
return {
375375
fetchEvents: async () => [],
376376
fetchFirstEvent: async () => null,
377-
subscribeLive: async () => async () => {},
377+
subscribeInteractive: async () => async () => {},
378378
subscribeToReconnects: () => () => {},
379379
publishEvent: async (event) => event,
380380
};

‎desktop/src/features/channels/readState/readStateManager.test.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ function makeFakeRelay() {
8181
return {
8282
fetchEvents: async () => [],
8383
publishEvent: async () => {},
84-
subscribeLive: () => () => {},
84+
subscribeInteractive: () => () => {},
8585
};
8686
}
8787

@@ -792,7 +792,7 @@ test("publishSplitSlots_noopSuppression_skipsWhenUnchanged", async () => {
792792
const fakeRelay = {
793793
fetchEvents: async () => [],
794794
publishEvent: async () => {},
795-
subscribeLive: () => () => {},
795+
subscribeInteractive: () => () => {},
796796
};
797797

798798
const pubkey = "b".repeat(64);

‎desktop/src/features/channels/readState/readStateManager.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,8 @@ export class ReadStateManager {
530530

531531
private async startLiveSubscription(): Promise<void> {
532532
try {
533-
const unsub = await this.relayClient.subscribeLive(
533+
// Unread UI readiness depends on this subscription, not the cold backlog.
534+
const unsub = await this.relayClient.subscribeInteractive(
534535
{
535536
kinds: [KIND_READ_STATE],
536537
authors: [this.pubkey],

‎desktop/src/features/channels/ui/AgentSessionThreadPanel.tsx‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@ import { useAnchoredScroll } from "@/features/messages/ui/useAnchoredScroll";
2525
import { useStableArrayShallow } from "@/shared/hooks/useStableReference";
2626
import { cancelManagedAgentTurn } from "@/shared/api/agentControl";
2727
import { awaitCancelTurnOutcome } from "@/features/agents/lib/cancelTurnOutcome";
28-
import { subscribeControlResults } from "@/features/agents/observerRelayStore";
28+
import {
29+
ensureRelayObserverSubscription,
30+
subscribeControlResults,
31+
} from "@/features/agents/observerRelayStore";
2932
import type { Channel } from "@/shared/api/types";
3033
import { useEscapeKey } from "@/shared/hooks/useEscapeKey";
3134
import { useIsThreadPanelOverlay } from "@/shared/hooks/use-mobile";
@@ -254,8 +257,14 @@ export function AgentSessionThreadPanel({
254257
channelId: sessionChannelId,
255258
subscribe: (listener) =>
256259
subscribeControlResults(agent.pubkey, listener),
257-
sendCancel: () =>
258-
cancelManagedAgentTurn(agent.pubkey, sessionChannelId, requestId),
260+
sendCancel: async () => {
261+
await ensureRelayObserverSubscription();
262+
await cancelManagedAgentTurn(
263+
agent.pubkey,
264+
sessionChannelId,
265+
requestId,
266+
);
267+
},
259268
scheduleTimeout: (onTimeout) => {
260269
const timeout = window.setTimeout(onTimeout, 8_000);
261270
return () => window.clearTimeout(timeout);

‎desktop/src/shared/api/observerRelay.test.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { subscribeToAgentObserverFrames } from "./observerRelay.ts";
1010
// network drop never re-delivers and the active-agents badge never appears.
1111
test("subscribeToAgentObserverFrames requests a replay-capable limit with a since window", () => {
1212
const calls = [];
13-
mock.method(relayClient, "subscribeLive", (filter) => {
13+
mock.method(relayClient, "subscribeInteractive", (filter) => {
1414
calls.push(filter);
1515
return () => {};
1616
});
@@ -44,7 +44,7 @@ test("subscribeToAgentObserverFrames since is at least 300s before now", () => {
4444
mock.method(Date, "now", () => FIXED_NOW_MS);
4545

4646
const calls = [];
47-
mock.method(relayClient, "subscribeLive", (filter) => {
47+
mock.method(relayClient, "subscribeInteractive", (filter) => {
4848
calls.push(filter);
4949
return () => {};
5050
});

‎desktop/src/shared/api/observerRelay.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ export function subscribeToAgentObserverFrames(
1515
ownerPubkey: string,
1616
onEvent: (event: RelayEvent) => void,
1717
) {
18-
return relayClient.subscribeLive(
18+
// Ephemeral control results must not wait behind cold channel history.
19+
return relayClient.subscribeInteractive(
1920
{
2021
kinds: [KIND_AGENT_OBSERVER_FRAME],
2122
"#p": [ownerPubkey],

‎desktop/src/shared/api/relayClientBurstDrain.test.mjs‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,119 @@ test("cold setup drains at most one live REQ per 250ms, prioritizes visible chan
149149
await Promise.all(entries.map((e) => e.promise));
150150
});
151151

152+
test("observer control-result subscription takes the next paced slot ahead of cold channels", async () => {
153+
const { relayClient: client } = await import("./relayClient.ts");
154+
const { subscribeToAgentObserverFrames } = await import("./observerRelay.ts");
155+
client.wsId = 7;
156+
clients.push(client);
157+
start(client, 296);
158+
await flush();
159+
const received = [];
160+
const pending = subscribeToAgentObserverFrames("owner", (event) =>
161+
received.push(event),
162+
);
163+
void pending.catch(() => {});
164+
await tickTo(249);
165+
assert.equal(frames("REQ").length, 1, "observer priority must retain pacing");
166+
await tickTo(250);
167+
const request = frames("REQ")[1].frame;
168+
assert.deepEqual(request[2], {
169+
kinds: [24200],
170+
"#p": ["owner"],
171+
limit: 1000,
172+
since: -300,
173+
});
174+
const result = { id: "result", kind: 24200, tags: [["p", "owner"]] };
175+
await deliver(client, ["EVENT", request[1], result]);
176+
await deliver(client, ["EOSE", request[1]]);
177+
const dispose = await pending;
178+
assert.deepEqual(
179+
received,
180+
[result],
181+
"ephemeral control results reach the admitted consumer",
182+
);
183+
await dispose();
184+
await tickTo(266); // Flush the session's existing event batch timer.
185+
});
186+
187+
test("read-state initialization takes the next paced slot ahead of cold channels", async () => {
188+
const { ReadStateManager } = await import(
189+
"../../features/channels/readState/readStateManager.ts"
190+
);
191+
const { KIND_READ_STATE } = await import("../constants/kinds.ts");
192+
const previousDocument = globalThis.document;
193+
const previousStorage = globalThis.localStorage;
194+
const store = new Map();
195+
const events = new EventTarget();
196+
Object.assign(window, {
197+
localStorage: {
198+
getItem: (key) => store.get(key) ?? null,
199+
setItem: (key, value) => store.set(key, value),
200+
removeItem: (key) => store.delete(key),
201+
},
202+
addEventListener: events.addEventListener.bind(events),
203+
removeEventListener: events.removeEventListener.bind(events),
204+
});
205+
globalThis.localStorage = window.localStorage;
206+
globalThis.document = new EventTarget();
207+
const client = session();
208+
const background = start(client, 296);
209+
await flush();
210+
onSend = async ({ frame }) => {
211+
if (frame[0] === "REQ") await deliver(client, ["EOSE", frame[1]]);
212+
};
213+
const pubkey = "a".repeat(64);
214+
const manager = new ReadStateManager(pubkey, client);
215+
let ready = false;
216+
const initialized = manager.initialize().then(() => {
217+
ready = true;
218+
});
219+
try {
220+
await tickTo(249);
221+
assert.equal(
222+
ready,
223+
false,
224+
"initialization must retain its live readiness gate",
225+
);
226+
assert.equal(
227+
frames("REQ").filter(({ frame }) => frame[1].startsWith("live-")).length,
228+
1,
229+
);
230+
await tickTo(250);
231+
assert.equal(
232+
ready,
233+
true,
234+
"unread UI must not wait behind 295 cold channels",
235+
);
236+
await initialized;
237+
const live = frames("REQ").filter(({ frame }) =>
238+
frame[1].startsWith("live-"),
239+
);
240+
assert.equal(live.length, 2);
241+
assert.equal(
242+
live[1].at,
243+
250,
244+
"read-state must retain ordinary request pacing",
245+
);
246+
assert.deepEqual(live[1].frame[2], {
247+
kinds: [KIND_READ_STATE],
248+
authors: [pubkey],
249+
"#t": ["read-state"],
250+
limit: 500,
251+
});
252+
} finally {
253+
manager.destroy();
254+
for (const entry of background) entry.controller.abort();
255+
client.disconnect();
256+
await initialized;
257+
globalThis.document = previousDocument;
258+
globalThis.localStorage = previousStorage;
259+
delete window.localStorage;
260+
delete window.addEventListener;
261+
delete window.removeEventListener;
262+
}
263+
});
264+
152265
test("125 refused live subscriptions cannot stampede beside a publish when cooldown releases", async () => {
153266
const client = session();
154267
const entries = start(client, 125);

‎desktop/src/testing/e2eBridge.ts‎

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
} from "@/features/agents/observerRelayStore";
3232
import { switchManagedAgentModel } from "@/shared/api/agentControl";
3333
import { mockSearchHitMatches } from "./e2eBridgeSearch.ts";
34+
import { selectMockHistory } from "./e2eBridgeHistory.ts";
3435
export { mockSearchHitMatches };
3536
import type { ConnectionState } from "@/shared/api/relayClientShared";
3637
import type {
@@ -4924,36 +4925,10 @@ function emitMockHistory(
49244925
channelIds: string[],
49254926
filter: MockFilter,
49264927
) {
4927-
const events = channelIds
4928-
.flatMap((channelId) => getMockMessageStore(channelId))
4929-
.filter((event) => {
4930-
if (filter.kinds && !filter.kinds.includes(event.kind)) {
4931-
return false;
4932-
}
4933-
if (filter.since !== undefined && event.created_at < filter.since) {
4934-
return false;
4935-
}
4936-
if (filter.until !== undefined && event.created_at > filter.until) {
4937-
return false;
4938-
}
4939-
return true;
4940-
})
4941-
// Relay order is `created_at DESC, id ASC` — match it (both the WS history
4942-
// page and the `get_channel_messages_before` keyset are backed by that one
4943-
// order in production, so the mock must be self-consistent too, else a
4944-
// same-second slice returned here won't line up with the keyset's tiebreak
4945-
// and the dense-second escape hatch can't prove completeness). Bare `until`
4946-
// still can't advance past a second denser than one page; the composite
4947-
// keyset is the escape hatch.
4948-
.sort(
4949-
(left, right) =>
4950-
right.created_at - left.created_at || left.id.localeCompare(right.id),
4951-
)
4952-
.slice(0, filter.limit ?? 50)
4953-
.sort(
4954-
(left, right) =>
4955-
left.created_at - right.created_at || left.id.localeCompare(right.id),
4956-
);
4928+
const events = selectMockHistory(
4929+
new Map(channelIds.map((id) => [id, getMockMessageStore(id)])),
4930+
[filter],
4931+
);
49574932

49584933
const emit = () => {
49594934
for (const event of events) {
@@ -10920,6 +10895,14 @@ function sendToMockSocket(args: {
1092010895
kinds: kinds.size > 0 ? [...kinds] : null,
1092110896
ownerPubkeys: [...ownerPubkeys],
1092210897
});
10898+
// Live requests still replay stored matches; pacing can admit them after
10899+
// a publish. Ephemeral/global fixtures are not channel history.
10900+
const history = new Map(
10901+
[...channelIds].map((id) => [id, getMockMessageStore(id)]),
10902+
);
10903+
for (const event of selectMockHistory(history, filters)) {
10904+
sendWsText(socket.handler, ["EVENT", subId, event]);
10905+
}
1092310906
sendWsText(socket.handler, ["EOSE", subId]);
1092410907
return;
1092510908
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
import { selectMockHistory } from "./e2eBridgeHistory.ts";
4+
5+
const event = (id, created_at, overrides = {}) => ({
6+
id,
7+
created_at,
8+
kind: 9,
9+
pubkey: "author",
10+
content: id,
11+
sig: "",
12+
tags: [
13+
["h", "channel"],
14+
["e", "root"],
15+
],
16+
...overrides,
17+
});
18+
const rows = [event("a", 10), event("b", 20), event("c", 20), event("d", 30)];
19+
const ids = (filters, events = rows) =>
20+
selectMockHistory(new Map([["channel", events]]), filters).map((e) => e.id);
21+
22+
test("replay includes admission-gap events with inclusive time bounds and relay ordering", () => {
23+
assert.deepEqual(
24+
ids([{ "#h": ["channel"], since: 10, until: 20, limit: 2 }]),
25+
["b", "c"],
26+
);
27+
assert.deepEqual(ids([{ since: 20, limit: 2 }]), ["b", "d"]);
28+
assert.deepEqual(ids([{ until: 0 }]), []);
29+
});
30+
test("live-only requests do not replay and old synthetic live events stay outside since", () => {
31+
assert.deepEqual(ids([{ limit: 0 }]), []);
32+
assert.deepEqual(ids([{ since: 31 }]), []);
33+
});
34+
test("filters retain author, kind, id and tag constraints", () => {
35+
for (const filter of [
36+
{ authors: ["other"] },
37+
{ kinds: [7] },
38+
{ ids: ["absent"] },
39+
{ "#h": ["other"] },
40+
{ "#e": ["other"] },
41+
]) {
42+
assert.deepEqual(ids([filter]), []);
43+
}
44+
assert.deepEqual(
45+
ids([{ authors: ["author"], kinds: [9], ids: ["b"], "#e": ["root"] }]),
46+
["b"],
47+
);
48+
});
49+
test("multiple filters apply independent limits and deduplicate their union", () => {
50+
assert.deepEqual(
51+
ids([
52+
{ until: 20, limit: 1 },
53+
{ since: 20, limit: 2 },
54+
]),
55+
["b", "d"],
56+
);
57+
assert.deepEqual(ids([{ limit: 10 }], [...rows, rows[0]]), [
58+
"a",
59+
"b",
60+
"c",
61+
"d",
62+
]);
63+
});
64+
65+
test("channel ownership scopes untagged auxiliary events without rewriting wire tags", () => {
66+
const reaction = event("reaction", 20, { kind: 7, tags: [["e", "root"]] });
67+
const foreign = event("foreign", 20, { tags: [["e", "root"]] });
68+
const conflicting = event("conflicting", 20, {
69+
kind: 7,
70+
tags: [
71+
["e", "root"],
72+
["h", "other"],
73+
],
74+
});
75+
const channels = new Map([
76+
["channel", [reaction, conflicting]],
77+
["other", [foreign]],
78+
]);
79+
assert.deepEqual(
80+
selectMockHistory(channels, [{ "#h": ["channel"], "#e": ["root"] }]),
81+
[reaction],
82+
);
83+
assert.deepEqual(reaction.tags, [["e", "root"]]);
84+
});

0 commit comments

Comments
 (0)