Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 4acbff7e3e test(e2e): settle Tailscale toggles and flush slowed socket queues
In pair-device-relay.spec.ts, slowConnectionToHost left delayed WebSocket frames in its queue after restoreSpeed() ran, and disableTailscale returned once the Tailscale listener closed before the browser received daemon.tailscale.set.response. Under CI load, enableTailscale could run while the prior change was still in flight.

Wait for the Tailscale switch to return to the enabled state in enableTailscale and disableTailscale, flush queued WebSocket frames when restoring speed, and verify slow-connection off-then-on toggling in pair-device-relay.spec.ts. (PR #10903 already disabled the Tailscale switch in app code while a toggle is pending.)
2026-11-26 09:39:32 +01:00
6 changed files with 53 additions and 147 deletions
-5
View File
@@ -61,11 +61,6 @@ the chat and its replica cache would keep only the end of the reply. A recovery
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
row by row and an older cursor repeats rows.
A live row whose epoch differs from the local cursor is a rewind or replacement this client never
saw as an invalidation, not a stale row. The app recovers like a gap: it asks `after` its own
cursor, and the daemon answers that stale epoch with a reset tail. Dropping the rows instead would
leave the chat on pre-rewind history while the new epoch streams.
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
Opening or resuming an agent fetches the latest available turns with a soft target of 40
@@ -97,6 +97,11 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
const restoreSpeed = await slowConnectionToHost(page, daemon.port, 300);
await expectTailscaleRowLoadsOn(page, address, () => openSetupMobileStep(page, daemon));
await expectTailscaleRowLoadsOn(page, address, () => preparePairingHost(page, daemon));
await test.step("Turning Tailscale off and back on settles over a slow connection", async () => {
await disableTailscale(page, address);
await enableTailscale(page);
await expectTailscaleAddress(page, address);
});
restoreSpeed();
});
+37 -18
View File
@@ -108,6 +108,7 @@ export async function enableTailscale(page: Page): Promise<void> {
await expect(toggle).not.toBeChecked();
await toggle.click();
await expect(toggle).toBeChecked();
await expect(toggle).toBeEnabled();
}
export async function expectTailscaleAddress(page: Page, address: string): Promise<void> {
@@ -142,6 +143,7 @@ export async function disableTailscale(page: Page, address: string): Promise<voi
await expect(toggle).toBeEnabled();
await toggle.click();
await expect(toggle).not.toBeChecked();
await expect(toggle).toBeEnabled();
await expect(tailscaleAddressRow(page, address)).toHaveCount(0);
await expectHostUnreachableAt(address);
}
@@ -307,7 +309,8 @@ export async function expectTailscaleRowLoadsOn(
/**
* Holds every message between the app and the host on `port` for `ms` in each direction, as on a
* slow network. The returned function brings the connection back to full speed.
* slow network. The returned function brings the connection back to full speed and flushes any
* queued messages.
*/
export async function slowConnectionToHost(
page: Page,
@@ -315,30 +318,29 @@ export async function slowConnectionToHost(
ms: number,
): Promise<() => void> {
let delay = ms;
const flushers = new Set<() => void>();
await page.routeWebSocket(wsRoutePatternForPort(String(port)), (app) => {
const host = app.connectToServer();
app.onMessage(
deliverInOrderAfter(
() => delay,
(message) => host.send(message),
),
const appToHost = deliverInOrderAfter(
() => delay,
(message) => host.send(message),
);
host.onMessage(
deliverInOrderAfter(
() => delay,
(message) => app.send(message),
),
const hostToApp = deliverInOrderAfter(
() => delay,
(message) => app.send(message),
);
flushers.add(appToHost.flushNow);
flushers.add(hostToApp.flushNow);
app.onMessage(appToHost.enqueue);
host.onMessage(hostToApp.enqueue);
});
return () => {
delay = 0;
for (const flushNow of flushers) flushNow();
};
}
function deliverInOrderAfter(
delay: () => number,
deliver: (message: string | Buffer) => void,
): (message: string | Buffer) => void {
function deliverInOrderAfter(delay: () => number, deliver: (message: string | Buffer) => void) {
const queue: { at: number; message: string | Buffer }[] = [];
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
@@ -346,9 +348,26 @@ function deliverInOrderAfter(
while (queue[0] && queue[0].at <= Date.now()) deliver(queue.shift()!.message);
if (queue[0]) timer = setTimeout(flush, queue[0].at - Date.now());
};
return (message) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
return {
enqueue: (message: string | Buffer) => {
queue.push({ at: Math.max(Date.now() + delay(), queue.at(-1)?.at ?? 0), message });
if (!timer) flush();
},
flushNow: () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
while (queue[0]) {
const next = queue.shift()!;
try {
deliver(next.message);
} catch {
queue.length = 0;
break;
}
}
},
};
}
-106
View File
@@ -204,112 +204,6 @@ describe("viewed timeline persistence", () => {
}
});
it("replaces pre-rewind history when a live row arrives in a new epoch", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
applySynced(AGENT_ID, 5);
const readTimelineState = () => {
const timeline = selectAgentTimelineState(
useSessionStore.getState().sessions[SERVER_ID],
AGENT_ID,
);
return {
status: timeline.status,
texts:
timeline.status === "cold"
? []
: timeline.items.flatMap((entry) =>
entry.kind === "assistant_message" ? [entry.text] : [],
),
};
};
const fetches: Array<{
direction: string;
cursor?: { epoch: string; seq: number };
}> = [];
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage: { readTimeline: async () => undefined, commitTimeline: () => undefined },
prepareAgent: async () => undefined,
});
const owner = createViewedTimelineOwner({
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => false,
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
readCursor: () => undefined,
fetchPage: async (_agentId, request) => {
fetches.push(request);
if (request.direction !== "after") return { hasNewer: false, endCursor: null };
// A cursor from the pre-rewind epoch makes the daemon reset to its current tail.
owner.applyTimelineResponse({
requestId: "rewind-reset",
agentId: AGENT_ID,
agent: null,
direction: "tail",
projection: "projected",
epoch: "epoch-2",
reset: true,
staleCursor: true,
gap: false,
window: { minSeq: 1, maxSeq: 2, nextSeq: 3 },
startCursor: { epoch: "epoch-2", seq: 1 },
endCursor: { epoch: "epoch-2", seq: 2 },
entries: [
{
provider: "codex",
item: { type: "assistant_message", text: "after rewind" },
timestamp: "2026-08-26T10:05:00.000Z",
seqStart: 1,
seqEnd: 2,
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
collapsed: [],
},
],
hasOlder: false,
hasNewer: false,
error: null,
});
return { hasNewer: false, endCursor: { epoch: "epoch-2", seq: 2 } };
},
fetchLatestTail: async () => ({ hasNewer: false, endCursor: null }),
reportError: () => undefined,
},
});
try {
owner.setConnected(true);
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
await expect.poll(() => fetches.length).toBe(1);
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "assistant_message", text: "new prompt reply" },
} as AgentStreamEventPayload,
seq: 6,
epoch: "epoch-2",
timestamp: new Date("2026-08-26T10:06:00.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
await expect.poll(() => fetches.length).toBe(2);
expect(fetches[1]).toMatchObject({
direction: "after",
cursor: { epoch: "epoch-1", seq: 5 },
});
await expect.poll(readTimelineState).toEqual({
status: "synced",
texts: ["after rewind"],
});
} finally {
owner.dispose();
}
});
it("shares an in-flight cache preparation with the viewed owner", async () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
let release!: (value: CachedTimeline) => void;
@@ -3834,7 +3834,7 @@ describe("processAgentStreamEvent", () => {
expect(result.sideEffects).toEqual([]);
});
it("requests authoritative recovery when a live row has a different epoch", () => {
it("drops timeline event with epoch mismatch", () => {
const existingCursor: TimelineCursor = {
epoch: "epoch-1",
startSeq: 1,
@@ -3852,9 +3852,7 @@ describe("processAgentStreamEvent", () => {
expect(result.cursorChanged).toBe(false);
expect(result.changedTail).toBe(false);
expect(result.changedHead).toBe(false);
expect(result.sideEffects).toEqual([
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 5 } },
]);
expect(result.sideEffects).toEqual([]);
});
it("resets visible timeline when a new epoch starts at seq 1", () => {
@@ -1545,20 +1545,7 @@ function processTimelineSequencingGate(input: {
cursorChanged: true,
};
}
if (decision === "drop_epoch" && seq === 1) {
return {
...base,
nextTimelineCursor: { epoch, startSeq: seq, endSeq: seq },
cursorChanged: true,
resetLiveTimeline: true,
};
}
// A gap and an epoch change both mean the local cursor cannot certify the next row.
// The epoch case is a rewind or replacement this client did not observe as an
// invalidation; the daemon answers an `after` request carrying the stale epoch with a
// reset tail, which installs current history. Dropping those rows would leave the chat
// on pre-rewind history while the new epoch streams.
if (decision === "gap" || decision === "drop_epoch") {
if (decision === "gap") {
return {
...base,
shouldApplyStreamEvent: false,
@@ -1572,6 +1559,14 @@ function processTimelineSequencingGate(input: {
],
};
}
if (decision === "drop_epoch" && seq === 1) {
return {
...base,
nextTimelineCursor: { epoch, startSeq: seq, endSeq: seq },
cursorChanged: true,
resetLiveTimeline: true,
};
}
return {
...base,
shouldApplyStreamEvent: false,