From 452cfb579c380cec7687127ca478405ff1833b03 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:34:16 -0600 Subject: [PATCH] fix(app): retry failed mark-viewed reports for every caller (#61809) --- .../src/shell/notifications/machine.test.ts | 297 +++++++++++++++++ .../app/src/shell/notifications/machine.ts | 313 ++++++++++++++++++ .../src/shell/notifications/notification.tsx | 249 ++++++++------ .../server-notification-state.test.ts | 17 +- 4 files changed, 765 insertions(+), 111 deletions(-) create mode 100644 packages/app/src/shell/notifications/machine.test.ts create mode 100644 packages/app/src/shell/notifications/machine.ts diff --git a/packages/app/src/shell/notifications/machine.test.ts b/packages/app/src/shell/notifications/machine.test.ts new file mode 100644 index 00000000000..a2105a2b789 --- /dev/null +++ b/packages/app/src/shell/notifications/machine.test.ts @@ -0,0 +1,297 @@ +import { describe, expect, test } from "bun:test" +import { + INITIAL_LEGACY_MIGRATION_STATE, + INITIAL_VIEW_REPORT_STATE, + selectLegacyHiddenReports, + selectSessionUnread, + transitionLegacyMigration, + transitionViewReport, + type LegacyMigrationEvent, + type LegacyMigrationState, + type LegacyMigrationTransition, + type ViewReportEvent, + type ViewReportState, + type ViewReportTransition, +} from "./machine" + +function replayView(events: ViewReportEvent[], from = INITIAL_VIEW_REPORT_STATE) { + return events.reduce((steps, event) => { + steps.push(transitionViewReport(steps.at(-1)?.state ?? from, event)) + + return steps + }, []) +} + +function replayLegacy(events: LegacyMigrationEvent[], from = INITIAL_LEGACY_MIGRATION_STATE) { + return events.reduce((steps, event) => { + steps.push(transitionLegacyMigration(steps.at(-1)?.state ?? from, event)) + + return steps + }, []) +} + +const failed = (attempt: number): ViewReportEvent => ({ type: "report.failed", attempt, notFound: false }) + +const reporting = (idle: number, attempt: number, failures = 0): ViewReportState => ({ + status: "reporting", + idle, + attempt, + failures, +}) + +describe("transitionViewReport", () => { + test("a one-shot view retries on its own until the report lands", () => { + // Menu and Inbox actions call markViewed once from an event handler; nothing re-runs them after a failure. + const steps = replayView([{ type: "view", idle: 2 }, failed(1), { type: "report.succeeded", attempt: 1 }]) + + expect(steps.map((step) => step.state)).toEqual([ + reporting(2, 1), + reporting(2, 1, 1), + { status: "reported", idle: 2, attempt: 1 }, + ]) + expect(steps.map((step) => step.effects)).toEqual([ + [{ type: "send", idle: 2, attempt: 1, delayMs: 0 }], + [{ type: "send", idle: 2, attempt: 1, delayMs: 250 }], + [], + ]) + }) + + test("backs off per root, gives up after the limit, and starts over on reconnect or a new view", () => { + const steps = replayView([{ type: "view", idle: 2 }, ...Array.from({ length: 7 }, () => failed(1))]) + + expect(steps.slice(1, 7).map((step) => step.effects[0])).toEqual( + [250, 500, 1000, 2000, 4000, 5000].map((delayMs) => ({ type: "send", idle: 2, attempt: 1, delayMs })), + ) + const gaveUp = steps.at(-1)! + expect(gaveUp).toEqual({ state: { status: "failed", idle: 2, attempt: 1 }, effects: [] }) + + expect(transitionViewReport(gaveUp.state, { type: "connected" })).toEqual({ + state: reporting(2, 2), + effects: [{ type: "send", idle: 2, attempt: 2, delayMs: 0 }], + }) + // A view of an older copy still reports the newest watermark the failed report held. + expect(transitionViewReport(gaveUp.state, { type: "view", idle: 1 })).toEqual({ + state: reporting(2, 2), + effects: [{ type: "send", idle: 2, attempt: 2, delayMs: 0 }], + }) + // The next failure after starting over waits the first delay again, not the cap. + expect(transitionViewReport(reporting(2, 2), failed(2)).effects).toEqual([ + { type: "send", idle: 2, attempt: 2, delayMs: 250 }, + ]) + }) + + test("a newer watermark replaces the report in flight and its late result is ignored", () => { + const steps = replayView([{ type: "view", idle: 2 }, failed(1), { type: "view", idle: 6 }]) + + expect(steps.at(-1)).toEqual({ + state: reporting(6, 2), + effects: [{ type: "send.cancel" }, { type: "send", idle: 6, attempt: 2, delayMs: 0 }], + }) + const current = steps.at(-1)!.state + expect(transitionViewReport(current, { type: "report.succeeded", attempt: 1 }).state).toBe(current) + expect(transitionViewReport(current, failed(1)).state).toBe(current) + }) + + test("re-running a view for a watermark already reported or in flight posts nothing", () => { + const inFlight = reporting(2, 1) + const reported: ViewReportState = { status: "reported", idle: 2, attempt: 1 } + + expect(transitionViewReport(inFlight, { type: "view", idle: 2 }).state).toBe(inFlight) + expect(transitionViewReport(reported, { type: "view", idle: 2 }).state).toBe(reported) + expect(transitionViewReport(reported, { type: "view", idle: 3 })).toEqual({ + state: reporting(3, 2), + effects: [{ type: "send", idle: 3, attempt: 2, delayMs: 0 }], + }) + expect(transitionViewReport(reported, { type: "connected" }).state).toBe(reported) + }) + + test("a deleted session is forgotten without a retry", () => { + expect(transitionViewReport(reporting(2, 3, 2), { type: "report.failed", attempt: 3, notFound: true })).toEqual({ + state: { status: "unreported", attempt: 3 }, + effects: [{ type: "forget" }], + }) + }) + + const afterDispose: ViewReportEvent[] = [ + { type: "view", idle: 9 }, + failed(1), + { type: "report.succeeded", attempt: 1 }, + { type: "connected" }, + ] + + test.each([ + [INITIAL_VIEW_REPORT_STATE, []], + [reporting(2, 1, 1), [{ type: "send.cancel" }]], + [{ status: "reported", idle: 2, attempt: 1 }, []], + [{ status: "failed", idle: 2, attempt: 1 }, []], + ] as const)("disposing from %o cancels pending work and ignores later results", (from, effects) => { + const disposed = transitionViewReport(from, { type: "disposed" }) + + expect(disposed).toEqual({ state: { status: "disposed" }, effects }) + afterDispose.forEach((event) => expect(transitionViewReport(disposed.state, event).state).toBe(disposed.state)) + }) +}) + +const list = [ + { session: "read-here", viewed: true }, + { session: "unread-here", viewed: false }, +] + +const hydrated = (connected: boolean, started?: number): LegacyMigrationEvent => ({ + type: "hydrated", + list, + started, + now: 10, + connected, +}) + +describe("transitionLegacyMigration", () => { + test("a transient failure while connected retries with backoff, then ends in done", () => { + const steps = replayLegacy([ + hydrated(true), + { type: "sessions.reported", reports: [{ sessionID: "s1", idle: 5 }] }, + { type: "run.failed", attempt: 1 }, + { type: "run.succeeded", attempt: 2 }, + ]) + + expect(steps[0]!.effects).toEqual([ + { type: "persist.started", started: 10 }, + { type: "run", attempt: 1, delayMs: 5000 }, + ]) + expect(steps[2]!.state).toMatchObject({ status: "migrating", attempt: 2, failures: 1 }) + expect(steps[2]!.effects).toEqual([{ type: "run", attempt: 2, delayMs: 5000 }]) + expect(steps[3]).toEqual({ + state: { status: "done", reported: new Map([["s1", 5]]) }, + effects: [{ type: "persist.remove" }], + }) + }) + + test("a disconnect cancels the run, ignores its late result, and the reconnect runs a new attempt", () => { + const steps = replayLegacy([hydrated(true), { type: "connection.changed", connected: false }]) + const idle = steps.at(-1)! + + expect(idle.state).toMatchObject({ status: "idle", attempt: 1 }) + expect(idle.effects).toEqual([{ type: "run.cancel" }]) + expect(transitionLegacyMigration(idle.state, { type: "run.succeeded", attempt: 1 }).state).toBe(idle.state) + expect(transitionLegacyMigration(idle.state, { type: "run.failed", attempt: 1 }).state).toBe(idle.state) + expect(transitionLegacyMigration(idle.state, { type: "connection.changed", connected: true })).toMatchObject({ + state: { status: "migrating", attempt: 2, failures: 0 }, + effects: [{ type: "run", attempt: 2, delayMs: 5000 }], + }) + }) + + test("after the last retry it keeps the list and waits for the next connection", () => { + const steps = replayLegacy([ + hydrated(true), + ...[1, 2, 3, 4].map((attempt): LegacyMigrationEvent => ({ type: "run.failed", attempt })), + ]) + + expect(steps.slice(1, 4).map((step) => step.effects)).toEqual( + [5000, 10000, 20000].map((delayMs, index) => [{ type: "run", attempt: index + 2, delayMs }]), + ) + expect(steps.at(-1)).toMatchObject({ state: { status: "idle", attempt: 4 }, effects: [] }) + }) + + test.each([ + ["no list", { ...hydrated(true), list: undefined }, { status: "done" }, []], + ["offline", hydrated(false), { status: "idle", attempt: 0 }, [{ type: "persist.started", started: 10 }]], + ["a cutoff from an earlier start", hydrated(false, 3), { status: "idle", carry: { started: 3 } }, []], + ] as const)("hydrating with %s", (_name, event, state, effects) => { + const result = transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, event) + + expect(result.state).toMatchObject(state) + expect(result.effects).toEqual(effects) + }) + + test("events that don't apply keep the same state", () => { + const idle = transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, hydrated(false)).state + + const reported = transitionLegacyMigration(idle, { + type: "sessions.reported", + reports: [{ sessionID: "s1", idle: 5 }], + }).state + + expect(transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, { type: "run.failed", attempt: 0 }).state).toBe( + INITIAL_LEGACY_MIGRATION_STATE, + ) + expect(transitionLegacyMigration(idle, hydrated(true)).state).toBe(idle) + expect(transitionLegacyMigration(idle, { type: "connection.changed", connected: false }).state).toBe(idle) + expect(transitionLegacyMigration(idle, { type: "sessions.reported", reports: [] }).state).toBe(idle) + expect( + transitionLegacyMigration(reported, { type: "sessions.reported", reports: [{ sessionID: "s1", idle: 4 }] }).state, + ).toBe(reported) + }) + + test("a page of reports is recorded in one state change", () => { + const idle = transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, hydrated(false)).state + + const reported = transitionLegacyMigration(idle, { + type: "sessions.reported", + reports: [ + { sessionID: "s1", idle: 5 }, + { sessionID: "s2", idle: 7 }, + ], + }).state + + expect(reported).toMatchObject({ + reported: new Map([ + ["s1", 5], + ["s2", 7], + ]), + }) + expect( + transitionLegacyMigration(reported, { + type: "sessions.reported", + reports: [ + { sessionID: "s1", idle: 4 }, + { sessionID: "s2", idle: 9 }, + ], + }).state, + ).toMatchObject({ + reported: new Map([ + ["s1", 5], + ["s2", 9], + ]), + }) + }) + + test("disposing cancels a pending run and ignores later results", () => { + const migrating = transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, hydrated(true)).state + const disposed = transitionLegacyMigration(migrating, { type: "disposed" }) + + expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "run.cancel" }] }) + expect(transitionLegacyMigration(disposed.state, { type: "run.succeeded", attempt: 1 }).state).toBe(disposed.state) + expect(transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, { type: "disposed" }).effects).toEqual([]) + }) +}) + +describe("selectSessionUnread", () => { + const sessions = [ + { id: "read-here", time: { idle: 5 } }, + { id: "unread-here", time: { idle: 6 } }, + { id: "viewed", time: { idle: 4, viewed: 4 } }, + { id: "untracked", time: { idle: 7, viewed: 3 } }, + { id: "new", time: { idle: 20 } }, + { id: "never-ran", time: {} }, + ] + + const carrying = transitionLegacyMigration(INITIAL_LEGACY_MIGRATION_STATE, hydrated(false)).state + const done: LegacyMigrationState = { status: "done", reported: new Map([["read-here", 5]]) } + + test.each([ + ["loading", INITIAL_LEGACY_MIGRATION_STATE, []], + ["carrying the old list", carrying, ["unread-here", "new"]], + ["done", done, ["unread-here", "untracked", "new"]], + ] as const)("while %s", (_name, state, unread) => { + expect(sessions.flatMap((session) => (selectSessionUnread(state, session) ? [session.id] : []))).toEqual([ + ...unread, + ]) + }) + + test("the carry-over reports the sessions the server has unread but this client shows read", () => { + expect(selectLegacyHiddenReports(carrying, sessions)).toEqual([ + { sessionID: "read-here", idle: 5 }, + { sessionID: "untracked", idle: 7 }, + ]) + }) +}) diff --git a/packages/app/src/shell/notifications/machine.ts b/packages/app/src/shell/notifications/machine.ts new file mode 100644 index 00000000000..a4c8a6c5a30 --- /dev/null +++ b/packages/app/src/shell/notifications/machine.ts @@ -0,0 +1,313 @@ +import type { SessionInfo } from "@opencode/client/promise" + +export const VIEW_RETRY_DELAY = 250 + +export const VIEW_RETRY_MAX_DELAY = 5_000 + +export const VIEW_RETRY_LIMIT = 6 + +// One root session's `session.view` report. `attempt` names one request, so a result for a watermark that a newer +// one replaced can never settle it. `reporting` covers both the request in flight and the backoff before a retry. +export type ViewReportState = + | { readonly status: "unreported"; readonly attempt: number } + | { readonly status: "reporting"; readonly idle: number; readonly attempt: number; readonly failures: number } + | { readonly status: "reported"; readonly idle: number; readonly attempt: number } + | { readonly status: "failed"; readonly idle: number; readonly attempt: number } + | { readonly status: "disposed" } + +export type ViewReportEvent = + | { readonly type: "view"; readonly idle: number } + | { readonly type: "report.succeeded"; readonly attempt: number } + | { readonly type: "report.failed"; readonly attempt: number; readonly notFound: boolean } + | { readonly type: "connected" } + | { readonly type: "disposed" } + +export type ViewReportEffect = + | { readonly type: "send"; readonly idle: number; readonly attempt: number; readonly delayMs: number } + | { readonly type: "send.cancel" } + | { readonly type: "forget" } + +export type ViewReportTransition = { + readonly state: ViewReportState + readonly effects: readonly ViewReportEffect[] +} + +export const INITIAL_VIEW_REPORT_STATE: ViewReportState = Object.freeze({ status: "unreported", attempt: 0 }) + +export function viewRetryDelay(failures: number) { + return Math.min(VIEW_RETRY_DELAY * 2 ** (failures - 1), VIEW_RETRY_MAX_DELAY) +} + +export function transitionViewReport(state: ViewReportState, event: ViewReportEvent): ViewReportTransition { + if (state.status === "disposed") return { state, effects: [] } + + if (event.type === "disposed") { + return { state: { status: "disposed" }, effects: state.status === "reporting" ? [{ type: "send.cancel" }] : [] } + } + + // Reactive callers view again whenever what they read changes; only a newer watermark starts a new report. A + // report that gave up starts over on any view, so clicking the session again retries it. + if (event.type === "view") { + if ((state.status === "reporting" || state.status === "reported") && event.idle <= state.idle) { + return { state, effects: [] } + } + + const idle = state.status === "failed" ? Math.max(state.idle, event.idle) : event.idle + + return report(state, idle) + } + + // A report that gave up while offline is retried once the connection is back. + if (event.type === "connected") { + if (state.status !== "failed") return { state, effects: [] } + + return report(state, state.idle) + } + + if (state.status !== "reporting" || state.attempt !== event.attempt) return { state, effects: [] } + + if (event.type === "report.succeeded") { + return { state: { status: "reported", idle: state.idle, attempt: state.attempt }, effects: [] } + } + + if (event.notFound) return { state: { status: "unreported", attempt: state.attempt }, effects: [{ type: "forget" }] } + + if (state.failures >= VIEW_RETRY_LIMIT) { + return { state: { status: "failed", idle: state.idle, attempt: state.attempt }, effects: [] } + } + + const failures = state.failures + 1 + + return { + state: { ...state, failures }, + effects: [{ type: "send", idle: state.idle, attempt: state.attempt, delayMs: viewRetryDelay(failures) }], + } +} + +function report(state: Exclude, idle: number): ViewReportTransition { + const attempt = state.attempt + 1 + const send: ViewReportEffect = { type: "send", idle, attempt, delayMs: 0 } + + return { + state: { status: "reporting", idle, attempt, failures: 0 }, + effects: state.status === "reporting" ? [{ type: "send.cancel" }, send] : [send], + } +} + +// The carry-over waits this long after connecting so it doesn't compete with startup requests. +export const LEGACY_MIGRATION_DELAY = 5_000 + +export const LEGACY_MIGRATION_RETRY_MAX_DELAY = 30_000 + +export const LEGACY_MIGRATION_RETRY_LIMIT = 3 + +export type LegacyListItem = { + readonly session?: string + readonly viewed: boolean +} + +export type LegacyCarry = { + // Sessions the old list still had unread. + readonly unseen: ReadonlySet + // When this client first found the list. Sessions that went idle later are new, whatever the list says. + readonly started: number +} + +export type LegacyViewReport = { + readonly sessionID: string + readonly idle: number +} + +// The background carry-over of the list Desktop kept before unread state moved to the server. `reported` keeps the +// watermarks it posted, so rows drawn from an older fetched copy of a session stay read after the list is deleted. +// `migrating` covers the delay before a run and the run itself. +export type LegacyMigrationState = + | { readonly status: "loading" } + | { + readonly status: "idle" + readonly carry: LegacyCarry + readonly reported: ReadonlyMap + readonly attempt: number + } + | { + readonly status: "migrating" + readonly carry: LegacyCarry + readonly reported: ReadonlyMap + readonly attempt: number + readonly failures: number + } + | { readonly status: "done"; readonly reported: ReadonlyMap } + | { readonly status: "disposed" } + +export type LegacyMigrationEvent = + | { + readonly type: "hydrated" + readonly list: readonly LegacyListItem[] | undefined + readonly started: number | undefined + readonly now: number + readonly connected: boolean + } + | { readonly type: "connection.changed"; readonly connected: boolean } + | { readonly type: "sessions.reported"; readonly reports: readonly LegacyViewReport[] } + | { readonly type: "run.succeeded"; readonly attempt: number } + | { readonly type: "run.failed"; readonly attempt: number } + | { readonly type: "disposed" } + +export type LegacyMigrationEffect = + | { readonly type: "persist.started"; readonly started: number } + | { readonly type: "persist.remove" } + | { readonly type: "run"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "run.cancel" } + +export type LegacyMigrationTransition = { + readonly state: LegacyMigrationState + readonly effects: readonly LegacyMigrationEffect[] +} + +export const INITIAL_LEGACY_MIGRATION_STATE: LegacyMigrationState = Object.freeze({ status: "loading" }) + +const EMPTY_REPORTED: ReadonlyMap = new Map() + +export function legacyRetryDelay(failures: number) { + return Math.min(LEGACY_MIGRATION_DELAY * 2 ** (failures - 1), LEGACY_MIGRATION_RETRY_MAX_DELAY) +} + +export function transitionLegacyMigration( + state: LegacyMigrationState, + event: LegacyMigrationEvent, +): LegacyMigrationTransition { + if (state.status === "disposed") return { state, effects: [] } + + if (event.type === "disposed") { + return { state: { status: "disposed" }, effects: state.status === "migrating" ? [{ type: "run.cancel" }] : [] } + } + + if (state.status === "loading") { + if (event.type !== "hydrated") return { state, effects: [] } + + return hydrate(event) + } + + if (event.type === "hydrated") return { state, effects: [] } + + // A report the server saved stays recorded even when the run that made it was cancelled or failed. A run records + // each page's reports in one event, so unread readers re-run once per page rather than once per session. + if (event.type === "sessions.reported") { + const updates = event.reports.filter((report) => report.idle > (state.reported.get(report.sessionID) ?? -Infinity)) + + if (updates.length === 0) return { state, effects: [] } + + const reported = new Map(state.reported) + + updates.forEach((report) => + reported.set(report.sessionID, Math.max(report.idle, reported.get(report.sessionID) ?? -Infinity)), + ) + + return { state: { ...state, reported }, effects: [] } + } + + if (state.status === "done") return { state, effects: [] } + + if (event.type === "connection.changed") { + if (event.connected && state.status === "idle") return migrate(state, state.attempt + 1, 0, LEGACY_MIGRATION_DELAY) + + if (!event.connected && state.status === "migrating") { + return { + state: { status: "idle", carry: state.carry, reported: state.reported, attempt: state.attempt }, + effects: [{ type: "run.cancel" }], + } + } + + return { state, effects: [] } + } + + if (state.status !== "migrating" || state.attempt !== event.attempt) return { state, effects: [] } + + if (event.type === "run.succeeded") { + return { state: { status: "done", reported: state.reported }, effects: [{ type: "persist.remove" }] } + } + + // After the last retry the list is kept, and the next connection tries again. + if (state.failures >= LEGACY_MIGRATION_RETRY_LIMIT) { + return { + state: { status: "idle", carry: state.carry, reported: state.reported, attempt: state.attempt }, + effects: [], + } + } + + const failures = state.failures + 1 + + return migrate(state, state.attempt + 1, failures, legacyRetryDelay(failures)) +} + +function hydrate(event: Extract): LegacyMigrationTransition { + if (!event.list) return { state: { status: "done", reported: EMPTY_REPORTED }, effects: [] } + + const started = event.started ?? event.now + + const state: LegacyMigrationState = { + status: "idle", + carry: { + unseen: new Set(event.list.flatMap((item) => (!item.viewed && item.session ? [item.session] : []))), + started, + }, + reported: EMPTY_REPORTED, + attempt: 0, + } + + const persist: LegacyMigrationEffect[] = event.started === undefined ? [{ type: "persist.started", started }] : [] + + if (!event.connected) return { state, effects: persist } + + const next = migrate(state, 1, 0, LEGACY_MIGRATION_DELAY) + + return { state: next.state, effects: [...persist, ...next.effects] } +} + +function migrate( + state: Extract, + attempt: number, + failures: number, + delayMs: number, +): LegacyMigrationTransition { + return { + state: { status: "migrating", carry: state.carry, reported: state.reported, attempt, failures }, + effects: [{ type: "run", attempt, delayMs }], + } +} + +type SessionTime = Pick + +type UnreadSession = { readonly id: string; readonly time: SessionTime } + +/** A session is unread on the server when its latest terminal execution is newer than the last one any client viewed. */ +export function isSessionUnread(session?: { readonly time: SessionTime }) { + const time = session?.time + + return time?.idle !== undefined && (time.viewed === undefined || time.idle > time.viewed) +} + +/** Whether the session shows unread here, honouring the old local list until its viewed state reaches the server. */ +export function selectSessionUnread(state: LegacyMigrationState, session?: UnreadSession) { + // Until the old list is read, a session it had read could flash unread. + if (state.status === "loading" || state.status === "disposed") return false + + const idle = session?.time.idle + + if (!session || idle === undefined || !isSessionUnread(session)) return false + + if (idle <= (state.reported.get(session.id) ?? -Infinity)) return false + + if (state.status === "done") return true + + return state.carry.unseen.has(session.id) || idle > state.carry.started +} + +/** Sessions on a fetched page that the server has unread but this client shows read: the carry-over reports these. */ +export function selectLegacyHiddenReports(state: LegacyMigrationState, sessions: readonly UnreadSession[]) { + return sessions.flatMap((session) => + session.time.idle !== undefined && isSessionUnread(session) && !selectSessionUnread(state, session) + ? [{ sessionID: session.id, idle: session.time.idle }] + : [], + ) +} diff --git a/packages/app/src/shell/notifications/notification.tsx b/packages/app/src/shell/notifications/notification.tsx index 7804b3ed9cf..004f950c272 100644 --- a/packages/app/src/shell/notifications/notification.tsx +++ b/packages/app/src/shell/notifications/notification.tsx @@ -1,5 +1,4 @@ -import { createEffect, createMemo, onCleanup, untrack } from "solid-js" -import { createStore } from "solid-js/store" +import { createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js" import { Schema } from "effect" import { isSessionNotFoundError, type SessionInfo } from "@opencode/client/promise" import type { ServerSDK } from "@/runtime/server/client" @@ -14,6 +13,19 @@ import type { createNotificationCoordinator } from "@/shell/notifications/coordi import { ServerConnection } from "@/runtime/server/registry" import { sessionIDHasOpenTab, useTabs } from "@/shell/tabs/tabs" import { useServer } from "@/runtime/server/current" +import { + INITIAL_LEGACY_MIGRATION_STATE, + INITIAL_VIEW_REPORT_STATE, + isSessionUnread, + selectLegacyHiddenReports, + selectSessionUnread, + transitionLegacyMigration, + transitionViewReport, + type LegacyMigrationEvent, + type LegacyViewReport, + type ViewReportEvent, + type ViewReportState, +} from "@/shell/notifications/machine" type NotificationTabs = Pick, "addSessionTab" | "rememberSessionRoute" | "select"> @@ -45,13 +57,6 @@ function hasRunningChild(data: Data, sessionID: string) { ) } -/** A session is unread when its latest terminal execution is newer than the last one any client viewed. */ -function isSessionUnread(session?: Pick) { - const time = session?.time - - return time?.idle !== undefined && (time.viewed === undefined || time.idle > time.viewed) -} - // The list Desktop kept before unread state moved to the server. Until its viewed state reaches the server, unread // state still honours it, so sessions read here don't light up while the server catches up. const LegacyNotificationStore = Persistence.struct({ @@ -62,17 +67,10 @@ const LegacyNotificationStore = Persistence.struct({ started: Schema.optional(Schema.Finite), }) -// The carry-over waits this long after connecting so it doesn't compete with startup requests. -const LEGACY_MIGRATION_DELAY = 5_000 - const LEGACY_MIGRATION_PAGE = 200 const LEGACY_MIGRATION_CONCURRENCY = 4 -const VIEW_RETRY_DELAY = 250 - -const VIEW_RETRY_MAX_DELAY = 5_000 - export function createServerNotificationState(input: { sdk: ServerSDK data: Data @@ -84,50 +82,100 @@ export function createServerNotificationState(input: { const language = useLanguage() const tabs = useTabs() const disposed = { value: false } - // Idle watermarks already reported per root session, so reactive re-runs don't re-post them. - const acknowledged = new Map() - // A failed view report re-runs the tracking caller with backoff, like the TUI. - const [state, setState] = createStore({ viewRetry: 0, legacyMigrated: false }) - let viewRetryTimer: ReturnType | undefined - let viewRetryAttempt = 0 - onCleanup(() => clearTimeout(viewRetryTimer)) + const connected = createMemo(() => input.sdk.connection.status() === "connected") + + // Per root session, so a failed report retries on its own whether or not a reactive caller is still viewing it. + const reports = new Map() + const reportTimers = new Map>() + + const dispatchView = (root: string, event: ViewReportEvent) => { + const result = transitionViewReport(reports.get(root) ?? INITIAL_VIEW_REPORT_STATE, event) + + reports.set(root, result.state) + result.effects.forEach((effect) => { + if (effect.type === "forget") { + input.data.session.forget(root) + + return + } + + clearTimeout(reportTimers.get(root)) + reportTimers.delete(root) + + if (effect.type === "send.cancel") return + + if (effect.delayMs === 0) { + sendView(root, effect) + + return + } + + reportTimers.set( + root, + setTimeout(() => { + reportTimers.delete(root) + sendView(root, effect) + }, effect.delayMs), + ) + }) + } + + const sendView = (root: string, effect: { idle: number; attempt: number }) => + void input.sdk.api.session.view({ sessionID: root, idle: effect.idle }).then( + () => dispatchView(root, { type: "report.succeeded", attempt: effect.attempt }), + (error) => + dispatchView(root, { type: "report.failed", attempt: effect.attempt, notFound: isSessionNotFoundError(error) }), + ) const legacyTarget = Persist.serverGlobal(input.sdk.scope, "notification") const [legacy, setLegacy, , legacyReady] = persisted(legacyTarget, LegacyNotificationStore, {}, platform) - const started = Date.now() - const legacyStarted = () => legacy.started ?? started + const [legacyState, setLegacyState] = createSignal(INITIAL_LEGACY_MIGRATION_STATE) + const discovered = Date.now() + let legacyRun: AbortController | undefined - // Sessions the old list still had unread, while its viewed state hasn't reached the server yet. - const legacyUnseen = createMemo(() => { - const list = legacy.list + const dispatchLegacy = (event: LegacyMigrationEvent) => { + const previous = untrack(legacyState) + const result = transitionLegacyMigration(previous, event) - if (!list || state.legacyMigrated) return + if (result.state !== previous) setLegacyState(result.state) + result.effects.forEach((effect) => { + if (effect.type === "persist.started") { + setLegacy("started", effect.started) - return new Set(list.flatMap((item) => (!item.viewed && item.session ? [item.session] : []))) - }) + return + } - // Idle watermarks the carry-over reported, so rows drawn from an older fetched copy of a session stay read. - const legacyReported = new Map() + if (effect.type === "persist.remove") { + removePersisted(legacyTarget, platform) - const unread = (session?: Pick) => { - const idle = session?.time.idle + return + } - // Until the old list is read, a session it had read could flash unread. - if (!legacyReady() || !session || idle === undefined || !isSessionUnread(session)) return false + legacyRun?.abort() + legacyRun = undefined - if (idle <= (legacyReported.get(session.id) ?? -Infinity)) return false - const unseen = legacyUnseen() + if (effect.type === "run.cancel") return - return !unseen || unseen.has(session.id) || idle > legacyStarted() + const controller = new AbortController() + + const timer = setTimeout( + () => + void migrateLegacy(controller.signal).then( + () => dispatchLegacy({ type: "run.succeeded", attempt: effect.attempt }), + () => dispatchLegacy({ type: "run.failed", attempt: effect.attempt }), + ), + effect.delayMs, + ) + + controller.signal.addEventListener("abort", () => clearTimeout(timer)) + legacyRun = controller + }) } // Carry the old list's viewed state to the server in the background: page through every root session and report - // the ones the server has unread but this client shows read. Then delete the list. A failure keeps it, and the - // next connection retries; reports already made are skipped because the server then has them read. - let legacyMigration: "idle" | "scheduled" | "running" = "idle" - - const migrateLegacy = async () => { - legacyMigration = "running" + // the ones the server has unread but this client shows read. Then delete the list. Reports already made are + // skipped on a retry because the server then has them read. + const migrateLegacy = async (signal: AbortSignal) => { let cursor: string | undefined for (;;) { @@ -138,54 +186,63 @@ export function createServerNotificationState(input: { cursor, }) - const hidden = page.data.flatMap((session) => - session.time.idle !== undefined && isSessionUnread(session) && !unread(session) - ? [{ sessionID: session.id, idle: session.time.idle }] - : [], - ) + const hidden = selectLegacyHiddenReports(untrack(legacyState), page.data) + const settled: PromiseSettledResult[] = [] for (let index = 0; index < hidden.length; index += LEGACY_MIGRATION_CONCURRENCY) { - if (disposed.value) return + if (signal.aborted || settled.some((result) => result.status === "rejected")) break - await Promise.all( - hidden.slice(index, index + LEGACY_MIGRATION_CONCURRENCY).map(async (report) => { - await input.sdk.api.session.view(report) - legacyReported.set(report.sessionID, report.idle) - }), + settled.push( + ...(await Promise.allSettled( + hidden + .slice(index, index + LEGACY_MIGRATION_CONCURRENCY) + .map((report) => input.sdk.api.session.view(report).then(() => report)), + )), ) } - if (page.data.length === 0 || !page.cursor.next) break + dispatchLegacy({ + type: "sessions.reported", + reports: settled.flatMap((result) => (result.status === "fulfilled" ? [result.value] : [])), + }) + + const failure = settled.find((result): result is PromiseRejectedResult => result.status === "rejected") + + if (failure) throw failure.reason + + if (signal.aborted || page.data.length === 0 || !page.cursor.next) return cursor = page.cursor.next } - - removePersisted(legacyTarget, platform) - setState("legacyMigrated", true) } - createEffect(() => { - if (!legacyReady() || !legacyUnseen()) return - - if (untrack(() => legacy.started) === undefined) setLegacy("started", started) - - if (input.sdk.connection.status() !== "connected" || legacyMigration !== "idle") return - legacyMigration = "scheduled" - - const timer = setTimeout( - () => - void migrateLegacy().catch(() => { - legacyMigration = "idle" - }), - LEGACY_MIGRATION_DELAY, + const hydrateLegacy = () => + untrack(() => + dispatchLegacy({ + type: "hydrated", + list: legacy.list, + started: legacy.started, + now: discovered, + connected: connected(), + }), ) - onCleanup(() => { - clearTimeout(timer) + // localStorage reads the old list at once; hydrate now so unread state is right before the first effect runs. + if (untrack(legacyReady)) hydrateLegacy() - if (legacyMigration === "scheduled") legacyMigration = "idle" - }) + createEffect(() => { + if (legacyReady()) hydrateLegacy() }) + createEffect(() => { + const online = connected() + + dispatchLegacy({ type: "connection.changed", connected: online }) + + if (online) reports.forEach((_, root) => dispatchView(root, { type: "connected" })) + }) + + const unread = (session?: Pick) => selectSessionUnread(legacyState(), session) + const roots = (directory: string) => input.data.session .list() @@ -195,40 +252,12 @@ export function createServerNotificationState(input: { ) const view = (sessionID: string) => { - void state.viewRetry const root = input.data.session.root(sessionID) const session = input.data.session.get(root) const idle = session?.time.idle - if (idle === undefined || !isSessionUnread(session) || acknowledged.get(root) === idle) return - acknowledged.set(root, idle) - void input.sdk.api.session.view({ sessionID: root, idle }).then( - () => { - clearTimeout(viewRetryTimer) - viewRetryTimer = undefined - viewRetryAttempt = 0 - }, - (error) => { - if (isSessionNotFoundError(error)) { - acknowledged.delete(root) - input.data.session.forget(root) - - return - } - - if (acknowledged.get(root) !== idle) return - acknowledged.delete(root) - - if (viewRetryTimer) return - - const delay = Math.min(VIEW_RETRY_DELAY * 2 ** viewRetryAttempt, VIEW_RETRY_MAX_DELAY) - viewRetryAttempt++ - viewRetryTimer = setTimeout(() => { - viewRetryTimer = undefined - setState("viewRetry", (value) => value + 1) - }, delay) - }, - ) + if (idle === undefined || !isSessionUnread(session)) return + dispatchView(root, { type: "view", idle }) } // Loading the session keeps a background completion visible in the server-derived unread state. @@ -367,6 +396,8 @@ export function createServerNotificationState(input: { onCleanup(() => { disposed.value = true unsub() + dispatchLegacy({ type: "disposed" }) + reports.forEach((_, root) => dispatchView(root, { type: "disposed" })) }) return { diff --git a/packages/app/test-browser/server-notification-state.test.ts b/packages/app/test-browser/server-notification-state.test.ts index 2ee7160996b..ed6f8e69e7a 100644 --- a/packages/app/test-browser/server-notification-state.test.ts +++ b/packages/app/test-browser/server-notification-state.test.ts @@ -166,6 +166,7 @@ test.each( createState({ sdk: { scope: ServerScope.local, + connection: { status: () => "connected" }, event: { listen: (listener: (event: OpenCodeEvent) => void) => { listeners.push(listener) @@ -264,6 +265,7 @@ test.each([ createState({ sdk: { scope: ServerScope.local, + connection: { status: () => "connected" }, event: { listen: (listener: (event: OpenCodeEvent) => void) => { listeners.push(listener) @@ -315,6 +317,7 @@ test("unread state and viewing follow the server's idle and viewed watermarks", const state = createState({ sdk: { scope: ServerScope.local, + connection: { status: () => "connected" }, event: { listen: () => () => {} }, api: { session: { @@ -368,11 +371,21 @@ test("unread state and viewing follow the server's idle and viewed watermarks", setStore("sessions", "root", "time", "idle", 6) expect(state.session.unread("root")).toBe(true) state.project.markViewed("/project") + expect(views.slice(2)).toEqual([{ sessionID: "root", idle: 6 }]) + + // Menu and Inbox actions mark sessions viewed from event handlers, with nothing to re-run them: a failed report + // still retries on its own, and a sibling's success does not cancel that retry. + setStore("viewing", undefined) + setStore("sessions", "root", "time", "idle", 8) + failures.remaining = 1 + state.project.markViewed("/project") state.project.markViewed("/other") - expect(views.slice(2)).toEqual([ - { sessionID: "root", idle: 6 }, + expect(views.slice(3)).toEqual([ + { sessionID: "root", idle: 8 }, { sessionID: "other", idle: 4 }, ]) + await new Promise((resolve) => setTimeout(resolve, 300)) + expect(views.slice(5)).toEqual([{ sessionID: "root", idle: 8 }]) dispose.dispose() })