diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts index ee438e618721..aca2a28ae8a2 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts @@ -1,24 +1,16 @@ -import type { PullRequestFilesViewedResult } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { viewedOverlay } from "./pullRequestFilesViewed"; -// The overlay compares reads by identity, so each call is a distinct read. -const read = (): PullRequestFilesViewedResult => ({ files: [], truncated: false }); - describe("viewedOverlay", () => { it("keeps a press while its write is in flight", () => { - const before = read(); expect( - viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, before), + viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, 3), ).toEqual({ "a.ts": true }); }); - it("keeps a landed press until a read newer than the one current at the write", () => { - const before = read(); - const presses = { - "a.ts": { viewed: true, version: 1, awaitingReadAfter: { read: before } }, - }; - expect(viewedOverlay(presses, before)).toEqual({ "a.ts": true }); - expect(viewedOverlay(presses, read())).toEqual({}); + it("yields a landed press to the next completed read, even one with unchanged data", () => { + const presses = { "a.ts": { viewed: true, version: 1, awaitingReadAfter: 3 } }; + expect(viewedOverlay(presses, 3)).toEqual({ "a.ts": true }); + expect(viewedOverlay(presses, 4)).toEqual({}); }); }); diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts index b76d3193c9c8..6cbfe3795b5e 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts @@ -1,12 +1,8 @@ -import type { PullRequestFilesViewedResult } from "@t3tools/contracts"; - -export type FilesViewedRead = PullRequestFilesViewedResult | null; - export interface ViewedPress { readonly viewed: boolean; readonly version: number; - /** Set once the write lands: the press yields to the server once a read newer than this lands. */ - readonly awaitingReadAfter: { readonly read: FilesViewedRead } | undefined; + /** Completed reads when the write landed: the press yields once a later read completes. */ + readonly awaitingReadAfter: number | undefined; } export interface ViewedState { @@ -18,11 +14,11 @@ export interface ViewedState { /** The pressed states the server's read has not caught up with yet. */ export function viewedOverlay( presses: Readonly>, - read: FilesViewedRead, + reads: number, ): Record { const overlay: Record = {}; for (const [path, press] of Object.entries(presses)) - if (press.awaitingReadAfter === undefined || press.awaitingReadAfter.read === read) + if (press.awaitingReadAfter === undefined || press.awaitingReadAfter === reads) overlay[path] = press.viewed; return overlay; } diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts index 7467c73fbe40..c973c81dac39 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts @@ -2,9 +2,12 @@ import { usePullRequestConnected } from "./usePullRequestConnected"; import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { AsyncResult } from "effect/reactivity"; import { use, useState } from "react"; -import { composerPullRequests } from "../../state/pull-requests"; +import { + composerPullRequests, + filesViewedReadsFamily, + filesViewedReadsKey, +} from "../../state/pull-requests"; import { useEnvironmentQuery } from "../../state/query"; import { useAtomCommand } from "../../state/use-atom-command"; import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"; @@ -23,11 +26,13 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq const allowed = connected && permission; const query = useEnvironmentQuery(supported ? composerPullRequests.filesViewed(target) : null); const refresh = useAtomRefresh(composerPullRequests.filesViewed(target)); + const readsAtom = filesViewedReadsFamily(filesViewedReadsKey(target)); + const reads = useAtomValue(readsAtom); const write = useAtomCommand(composerPullRequests.setFilesViewed, { reportFailure: false }); const [state, setState] = useState({ key: scopeKey, presses: {}, error: null }); const presses = state.key === scopeKey ? state.presses : {}; const error = state.key === scopeKey ? state.error : null; - const overlay = viewedOverlay(presses, query.data); + const overlay = viewedOverlay(presses, reads); const update = (change: (current: ViewedState) => ViewedState) => setState((current) => change(current.key === scopeKey ? current : { key: scopeKey, presses: {}, error: null }), @@ -48,11 +53,8 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq ...target, input: { ...target.input, files: [{ path, viewed }] }, }); - // The read that is current once the write lands still predates it; a newer one carries it. - const readAtWrite = AsyncResult.getOrElse( - registry.get(composerPullRequests.filesViewed(target)), - () => null, - ); + // A read completed by the time the write lands may predate it; the next one carries it. + const readsAtWrite = registry.get(readsAtom); setState((current) => { if (current.key !== scopeKey || current.presses[path]?.version !== version) return current; if (response._tag === "Success") @@ -60,7 +62,7 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq ...current, presses: { ...current.presses, - [path]: { viewed, version, awaitingReadAfter: { read: readAtWrite } }, + [path]: { viewed, version, awaitingReadAfter: readsAtWrite }, }, }; const rest = { ...current.presses }; diff --git a/apps/mobile/src/state/pull-requests.ts b/apps/mobile/src/state/pull-requests.ts index 6d7872fa5600..8ca65760e591 100644 --- a/apps/mobile/src/state/pull-requests.ts +++ b/apps/mobile/src/state/pull-requests.ts @@ -3,7 +3,7 @@ import { createPullRequestStackAtomFamily, patchPullRequestListEntries, } from "@t3tools/client-runtime/state/pull-requests"; -import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts"; +import type { EnvironmentId, PullRequestListInput, PullRequestRef } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -41,6 +41,16 @@ export const pullRequestListStatsFamily = Atom.family((_environmentId: string) = ), ); +export const filesViewedReadsKey = (target: { + readonly environmentId: EnvironmentId; + readonly input: PullRequestRef; +}) => JSON.stringify([target.environmentId, target.input]); + +/** Completed server reads of each viewed-files query; unchanged answers are structurally shared. */ +export const filesViewedReadsFamily = Atom.family((_key: string) => + Atom.make(0).pipe(Atom.setIdleTTL(5 * 60_000)), +); + export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, { // Rows on pages past each listing's head; the head itself is patched where it is cached. actionReply: (target, reply, registry) => @@ -69,6 +79,10 @@ export const composerPullRequests = createPullRequestEnvironmentAtoms(connection if (Option.isSome(previous) && previous.value.headSha !== value.headSha) registry.refresh(composerPullRequests.filesViewed(target)); }), + filesViewed: (target, _value, registry) => + Effect.sync(() => + registry.update(filesViewedReadsFamily(filesViewedReadsKey(target)), (reads) => reads + 1), + ), list: (target, value, registry) => Effect.sync(() => { const statsAtom = pullRequestListStatsFamily(target.environmentId); diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index ad3a29ac398c..c233ab46dced 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -4419,6 +4419,43 @@ it.effect("keeps viewed files itself for a host that keeps none of its own", () }), ); +it.effect("records shown revisions until the reader ticks the pushed version", () => + Effect.gen(function* () { + const asked: Array> = []; + const revisions = new Map([ + ["src/a.ts", "pushed-a"], + ["src/b.ts", "current-b"], + ]); + const service = yield* environmentViewedService(revisions, asked); + + yield* service.setFilesViewed({ + ...GITLAB_REFERENCE, + files: [ + { path: "src/a.ts", viewed: true, revision: "shown-a" }, + { path: "src/b.ts", viewed: true }, + ], + }); + assert.deepStrictEqual(asked, [["src/b.ts"]]); + yield* service.invalidate({ reference: GITLAB_REFERENCE }); + assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ + { path: "src/a.ts", state: "dismissed" }, + { path: "src/b.ts", state: "viewed" }, + ]); + + const reads = asked.length; + revisions.set("src/a.ts", "pushed-a-again"); + yield* service.setFilesViewed({ + ...GITLAB_REFERENCE, + files: [{ path: "src/a.ts", viewed: true, revision: "pushed-a-again" }], + }); + assert.strictEqual(asked.length, reads); + assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ + { path: "src/a.ts", state: "viewed" }, + { path: "src/b.ts", state: "viewed" }, + ]); + }), +); + it.effect("keeps a deleted file cleared, which the head has no version of at all", () => Effect.gen(function* () { const service = yield* environmentViewedService(new Map(), []); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 2b8859304c5b..b83d20895589 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -2085,7 +2085,14 @@ export const make = Effect.gen(function* () { // Deliberately not `invalidatedByMutation`: ticking a file off says nothing about the // change request, and dropping a 300-file diff on every checkbox is the whole cost of // the feature. - Effect.ensuring(Effect.sync(() => bumpFilesViewedEpoch(ref))), + Effect.ensuring( + Effect.sync(() => { + bumpFilesViewedEpoch(ref); + if (input.files.some((file) => file.viewed && file.revision !== undefined)) { + bumpEpoch(fileRevisionEpochs, ref); + } + }), + ), ), ), ); @@ -3001,6 +3008,7 @@ export const make = Effect.gen(function* () { const filesViewedEpoch = (ref: PullRequestRef) => filesViewedEpochs.get(refScope(ref)) ?? 0; const bumpFilesViewedEpoch = (ref: PullRequestRef) => bumpEpoch(filesViewedEpochs, ref); + const fileRevisionEpochs = new Map(); let everyFileRevisionEpoch = 0; const viewedFiles = ViewedFiles.make({ filesViewedStore, @@ -3009,7 +3017,8 @@ export const make = Effect.gen(function* () { toPullRequestError, runFork, refEpoch, - fileRevisionsEpoch: () => everyFileRevisionEpoch, + fileRevisionsEpoch: (ref) => + `${everyFileRevisionEpoch}:${fileRevisionEpochs.get(refScope(ref)) ?? 0}`, }); const filtersOfKey = ( diff --git a/apps/server/src/pullRequest/pullRequestViewedFiles.ts b/apps/server/src/pullRequest/pullRequestViewedFiles.ts index ee956dfa0fe9..7558e8b6a166 100644 --- a/apps/server/src/pullRequest/pullRequestViewedFiles.ts +++ b/apps/server/src/pullRequest/pullRequestViewedFiles.ts @@ -30,7 +30,7 @@ const MAX_FILE_REVISION_PATHS = 1_000; interface FileRevisionsDependencies { readonly runFork: (effect: Effect.Effect) => unknown; readonly refEpoch: (ref: PullRequestRef) => number; - readonly fileRevisionsEpoch: () => number; + readonly fileRevisionsEpoch: (ref: PullRequestRef) => string; readonly toPullRequestError: ( operation: string, ) => (error: PullRequestProviderError) => PullRequestError; @@ -50,7 +50,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { const fileRevisionsKey = (project: SupportedProject, ref: PullRequestRef) => [ refEpoch({ ...ref, host: project.host, repository: project.repository }), - fileRevisionsEpoch(), + fileRevisionsEpoch({ ...ref, host: project.host, repository: project.repository }), ref.projectId, project.repository.trim().toLowerCase(), ref.number, diff --git a/apps/web/src/components/pullRequest/filesViewedStore.test.ts b/apps/web/src/components/pullRequest/filesViewedStore.test.ts index 3caef2d75410..b4de9e867b7a 100644 --- a/apps/web/src/components/pullRequest/filesViewedStore.test.ts +++ b/apps/web/src/components/pullRequest/filesViewedStore.test.ts @@ -71,7 +71,8 @@ function setup(initial: PullRequestFilesViewedResult | null = answer(false)) { describe("createFilesViewedStore", () => { it("batches presses and holds them until a read that could have seen them", async () => { - using t = setup(); + const unchanged = { files: [{ path: "a.ts", state: "dismissed" as const }], truncated: false }; + using t = setup(unchanged); const scope = t.store.scope(first); const release = scope.subscribe(() => {}); scope.setViewed("a.ts", true, "shown-a"); @@ -88,10 +89,7 @@ describe("createFilesViewedStore", () => { expect(scope.getSnapshot().get("a.ts")).toBe(true); // A push landed between the write and the next read: the host's answer wins. - t.answerFor(first, { - files: [{ path: "a.ts", state: "dismissed" }], - truncated: false, - }); + t.answerFor(first, unchanged); expect(scope.getSnapshot().size).toBe(0); release(); }); @@ -205,9 +203,6 @@ describe("createFilesViewedStore", () => { await vi.advanceTimersByTimeAsync(400); t.settles[0]?.(AsyncResult.success(undefined)); await vi.advanceTimersByTimeAsync(0); - // The same answer published again is not a new read. - t.answerFor(first, agreeing); - expect(scope.getSnapshot().get("a.ts")).toBe(true); t.answerFor(first, answer(false)); expect(scope.getSnapshot().size).toBe(0); release(); diff --git a/apps/web/src/components/pullRequest/filesViewedStore.ts b/apps/web/src/components/pullRequest/filesViewedStore.ts index 6ebafcd929b9..656459d1c2d9 100644 --- a/apps/web/src/components/pullRequest/filesViewedStore.ts +++ b/apps/web/src/components/pullRequest/filesViewedStore.ts @@ -8,10 +8,12 @@ import type { PullRequestFilesViewedResult, PullRequestRef, } from "@t3tools/contracts"; -import { AsyncResult } from "effect/reactivity"; import { appAtomRegistry } from "~/rpc/atomRegistry"; -import { pullRequestEnvironment } from "~/state/pullRequests"; +import { + pullRequestEnvironment, + subscribePullRequestFilesViewedAnswers, +} from "~/state/pullRequests"; import { toastManager } from "../ui/toast"; import { @@ -36,7 +38,7 @@ type FilesViewedBatch = ReadonlyArray<{ export interface FilesViewedStoreDeps { readonly flushDelayMs: number; - /** Calls `onAnswer` with the host's current answer at once, then with every later one. */ + /** Calls `onAnswer` only after completed server reads, excluding persisted values. */ readonly subscribeAnswers: ( target: FilesViewedTarget, onAnswer: (answer: PullRequestFilesViewedResult | null) => void, @@ -68,13 +70,8 @@ interface FilesViewedScope { readonly sentBy: Map; requests: number; timer: ReturnType | null; - answer: PullRequestFilesViewedResult | null; - /** - * The host's answer as it stood when a completed write was acknowledged, per path. The first - * answer that differs from it is the first read that could have seen the write, which is what - * retires the press rather than the host happening to agree with it. - */ - readonly answeredFrom: Map; + // Completed reads retire acknowledged presses even when equal data is structurally shared. + readonly answeredFrom: Set; } /** @@ -95,12 +92,11 @@ export function createFilesViewedStore(deps: FilesViewedStoreDeps) { const isLive = (key: string, scope: FilesViewedScope) => scopes.get(key) === scope; const settle = (scope: FilesViewedScope, answer: PullRequestFilesViewedResult | null) => { - if (answer === scope.answer) return; - scope.answer = answer; + if (answer === null) return; const pending = new Set([...scope.queued.keys(), ...scope.sentBy.keys()]); const answered = new Set(); - for (const [path, from] of scope.answeredFrom) { - if (pending.has(path) || from === answer) continue; + for (const path of scope.answeredFrom) { + if (pending.has(path)) continue; answered.add(path); scope.answeredFrom.delete(path); } @@ -141,7 +137,7 @@ export function createFilesViewedStore(deps: FilesViewedStoreDeps) { } // Answered for from the next read on, whatever it says. A push landing between the write // and that read comes back as `dismissed`, and the press must not stand over it. - for (const path of mine) scope.answeredFrom.set(path, scope.answer); + for (const path of mine) scope.answeredFrom.add(path); deps.refresh(scope.target); }); }; @@ -160,10 +156,8 @@ export function createFilesViewedStore(deps: FilesViewedStoreDeps) { if (scope === undefined) { const listeners = new Set<() => void>(); let created: FilesViewedScope | undefined; - let initial: PullRequestFilesViewedResult | null = null; const unsubscribeAnswers = deps.subscribeAnswers(target, (answer) => { - if (created === undefined) initial = answer; - else settle(created, answer); + if (created !== undefined) settle(created, answer); }); created = { target, @@ -174,8 +168,7 @@ export function createFilesViewedStore(deps: FilesViewedStoreDeps) { sentBy: new Map(), requests: 0, timer: null, - answer: initial, - answeredFrom: new Map(), + answeredFrom: new Set(), }; scope = created; scopes.set(key, scope); @@ -240,12 +233,8 @@ const filesViewedAtom = ({ environmentId, reference }: FilesViewedTarget) => const filesViewedStore = createFilesViewedStore({ flushDelayMs: 400, - subscribeAnswers: (target, onAnswer) => - appAtomRegistry.subscribe( - filesViewedAtom(target), - (result) => onAnswer(AsyncResult.getOrElse(result, () => null)), - { immediate: true }, - ), + subscribeAnswers: ({ environmentId, reference }, onAnswer) => + subscribePullRequestFilesViewedAnswers({ environmentId, input: reference }, onAnswer), send: ({ environmentId, reference }, files) => runAtomCommand( appAtomRegistry, diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts index bb8961328f1a..5e75d32cad75 100644 --- a/apps/web/src/state/pullRequests.ts +++ b/apps/web/src/state/pullRequests.ts @@ -12,6 +12,7 @@ import { type EnvironmentId, type ProjectId, type PullRequestChecksState, + type PullRequestFilesViewedResult, type PullRequestListInput, type PullRequestFilterOptionsInput, type PullRequestListStatsInput, @@ -369,8 +370,44 @@ export function restoredPullRequestList( return restorePullRequestList(snapshotStorage(), targets); } +const filesViewedAnswerListeners = new Map< + string, + Set<(answer: PullRequestFilesViewedResult) => void> +>(); + +function filesViewedAnswerKey({ environmentId, input }: EnvironmentQueryTarget) { + return JSON.stringify([ + environmentId, + input.projectId, + input.host, + input.expectedAccountId, + input.allowStale, + input.repository, + input.number, + ]); +} + +export function subscribePullRequestFilesViewedAnswers( + target: EnvironmentQueryTarget, + onAnswer: (answer: PullRequestFilesViewedResult) => void, +) { + const key = filesViewedAnswerKey(target); + let listeners = filesViewedAnswerListeners.get(key); + if (listeners === undefined) filesViewedAnswerListeners.set(key, (listeners = new Set())); + listeners.add(onAnswer); + return () => { + listeners.delete(onAnswer); + if (listeners.size === 0) filesViewedAnswerListeners.delete(key); + }; +} + // Answers are stamped on arrival: older servers leave no other ordering for same-dated reads. export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, { + filesViewed: (target, answer) => + Effect.sync(() => { + for (const listener of filesViewedAnswerListeners.get(filesViewedAnswerKey(target)) ?? []) + listener(answer); + }), list: ({ environmentId, input }, answer, registry) => Effect.map(Clock.currentTimeMillis, (observedAt) => { rememberPullRequestListAnswer(snapshotStorage(), { environmentId, input }, answer); diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index 9605acf7a19f..e930bd2c17b3 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -390,6 +390,7 @@ export interface PullRequestAnswerHandlers { readonly list?: QueryAnswerHandler; readonly listStats?: QueryAnswerHandler; readonly detail?: QueryAnswerHandler; + readonly filesViewed?: QueryAnswerHandler; readonly checks?: QueryAnswerHandler; readonly reviewGuide?: QueryAnswerHandler; /** Once per action reply, after the loaded readers show it; unscoped references only. */ @@ -839,6 +840,7 @@ export function createPullRequestEnvironmentAtoms( }), filesViewed: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:pull-requests:files-viewed", + ...(onAnswer.filesViewed === undefined ? {} : { onAnswer: onAnswer.filesViewed }), persistence: persistQuery(PullRequestFilesViewedResult), tag: WS_METHODS.pullRequestsFilesViewed, execute: (input) => routedRequest(WS_METHODS.pullRequestsFilesViewed, input),