Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
c6f382a
test(server): pin a re-cleared file to the head's current revision
only21mil Oct 22, 2026
8ca2b70
fix(server): refresh file revisions before recording viewed marks
only21mil Oct 22, 2026
2d6909a
fix: record the file version a viewed press was shown
only21mil Oct 23, 2026
f1e6b70
fix(web): a viewed tick in one commit's diff records the head's version
only21mil Oct 23, 2026
6b1388e
Merge remote-tracking branch 'upstream/main' into babysit-24151
only21mil Oct 24, 2026
da14baf
fix(pull-request): merge main into viewed revision fix
maria-rcks Oct 26, 2026
94fcb56
refactor(pull-request): simplify viewed revision regression coverage
maria-rcks Oct 26, 2026
079989b
fix(pull-request): refresh comparisons after displayed revision marks
maria-rcks Oct 26, 2026
63749ff
fix: let bitbucket revision comparisons read fresh pushes
maria-rcks Oct 26, 2026
14c7b19
fix(pull-request): merge main and preserve viewed revisions
maria-rcks Oct 27, 2026
5f60c38
fix(web): settle viewed presses after completed reads
maria-rcks Oct 27, 2026
37ce86b
fix(pull-request): merge main and preserve viewed range revisions
maria-rcks Oct 30, 2026
e322095
fix(web): settle viewed marks only from server answers
maria-rcks Oct 30, 2026
1095cd7
Merge branch 'main' into r13/n012-refresh-file-revisions-before-recor…
only21mil Nov 12, 2026
4a6c69a
Merge branch 'main' into r13/n012-refresh-file-revisions-before-recor…
only21mil Nov 12, 2026
ba76528
chore(server): keep main's held head read for presses without a revision
only21mil Nov 12, 2026
390dfa3
chore(bitbucket): keep main's revision-patch cache
only21mil Nov 12, 2026
78c31db
Merge remote-tracking branch 'origin/main' into r13/n012-refresh-file…
juliusmarminge Nov 14, 2026
917fd01
fix(mobile): settle viewed presses on completed reads
juliusmarminge Nov 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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({});
});
});
12 changes: 4 additions & 8 deletions apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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<Record<string, ViewedPress>>,
read: FilesViewedRead,
reads: number,
): Record<string, boolean> {
const overlay: Record<string, boolean> = {};
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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<ViewedState>({ 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 }),
Expand All @@ -48,19 +53,16 @@ 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")
return {
...current,
presses: {
...current.presses,
[path]: { viewed, version, awaitingReadAfter: { read: readAtWrite } },
[path]: { viewed, version, awaitingReadAfter: readsAtWrite },
},
};
const rest = { ...current.presses };
Expand Down
16 changes: 15 additions & 1 deletion apps/mobile/src/state/pull-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) =>
Expand Down Expand Up @@ -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);
Expand Down
37 changes: 37 additions & 0 deletions apps/server/src/pullRequest/PullRequestService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReadonlyArray<string>> = [];
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(), []);
Expand Down
13 changes: 11 additions & 2 deletions apps/server/src/pullRequest/PullRequestService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}),
),
),
),
);
Expand Down Expand Up @@ -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<string, number>();
let everyFileRevisionEpoch = 0;
const viewedFiles = ViewedFiles.make({
filesViewedStore,
Expand All @@ -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 = (
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/pullRequest/pullRequestViewedFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const MAX_FILE_REVISION_PATHS = 1_000;
interface FileRevisionsDependencies {
readonly runFork: (effect: Effect.Effect<void>) => unknown;
readonly refEpoch: (ref: PullRequestRef) => number;
readonly fileRevisionsEpoch: () => number;
readonly fileRevisionsEpoch: (ref: PullRequestRef) => string;
readonly toPullRequestError: (
operation: string,
) => (error: PullRequestProviderError) => PullRequestError;
Expand All @@ -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,
Expand Down
11 changes: 3 additions & 8 deletions apps/web/src/components/pullRequest/filesViewedStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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();
});
Expand Down Expand Up @@ -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();
Expand Down
41 changes: 15 additions & 26 deletions apps/web/src/components/pullRequest/filesViewedStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -68,13 +70,8 @@ interface FilesViewedScope {
readonly sentBy: Map<string, number>;
requests: number;
timer: ReturnType<typeof setTimeout> | 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<string, PullRequestFilesViewedResult | null>;
// Completed reads retire acknowledged presses even when equal data is structurally shared.
readonly answeredFrom: Set<string>;
}

/**
Expand All @@ -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<string>();
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);
}
Expand Down Expand Up @@ -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);
});
};
Expand All @@ -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,
Expand All @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading