Add inline review comment selection to mobile diffs

- render comment rows and line selection state in the native diff view
- wire long-press/tap gestures to start and complete review comments
- tighten shared diff utilities and add coverage
This commit is contained in:
Julius Marminge committed 2026-05-20 10:55:55 +02:00
1 parent a49c2d1301
commit eba28035d2
15 files changed
+640 -37

No files matched your search

@@ -171,6 +171,7 @@ async function mountTerminalViewport(props: {
threadRef: ReturnType<typeof scopeThreadRef>;
drawerBackgroundColor?: string;
drawerTextColor?: string;
runtimeEnv?: Record<string, string>;
}) {
const drawer = document.createElement("div");
drawer.className = "thread-terminal-drawer";
@@ -194,6 +195,7 @@ async function mountTerminalViewport(props: {
terminalId="term-1"
terminalLabel="Terminal"
cwd="/repo/project"
{...(props.runtimeEnv ? { runtimeEnv: props.runtimeEnv } : {})}
onSessionExited={() => undefined}
onAddTerminalContext={() => undefined}
focusRequestId={0}
@@ -206,7 +208,10 @@ async function mountTerminalViewport(props: {
);
return {
rerender: async (nextProps: { threadRef: ReturnType<typeof scopeThreadRef> }) => {
rerender: async (nextProps: {
threadRef: ReturnType<typeof scopeThreadRef>;
runtimeEnv?: Record<string, string>;
}) => {
await screen.rerender(
<TerminalViewport
threadRef={nextProps.threadRef}
@@ -214,6 +219,7 @@ async function mountTerminalViewport(props: {
terminalId="term-1"
terminalLabel="Terminal"
cwd="/repo/project"
{...(nextProps.runtimeEnv ? { runtimeEnv: nextProps.runtimeEnv } : {})}
onSessionExited={() => undefined}
onAddTerminalContext={() => undefined}
focusRequestId={0}
@@ -259,6 +265,47 @@ describe("TerminalViewport", () => {
}
});
it("renders and attaches the terminal without the desktop local API", async () => {
const environment = createEnvironmentApi();
environmentApiById.set("environment-a", environment);
readLocalApiMock.mockReturnValueOnce(undefined);
const mounted = await mountTerminalViewport({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
});
try {
await vi.waitFor(() => {
expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
});
expect(terminalConstructorSpy).toHaveBeenCalledTimes(1);
} finally {
await mounted.cleanup();
}
});
it("keeps the terminal mounted when xterm fit runs before dimensions are ready", async () => {
const environment = createEnvironmentApi();
environmentApiById.set("environment-a", environment);
fitAddonFitSpy.mockImplementationOnce(() => {
throw new TypeError("Cannot read properties of undefined (reading 'dimensions')");
});
const mounted = await mountTerminalViewport({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
});
try {
await vi.waitFor(() => {
expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
});
expect(terminalConstructorSpy).toHaveBeenCalledTimes(1);
expect(fitAddonFitSpy).toHaveBeenCalled();
} finally {
await mounted.cleanup();
}
});
it("reattaches the terminal when the scoped thread reference changes", async () => {
const environmentA = createEnvironmentApi();
const environmentB = createEnvironmentApi();
@@ -313,6 +360,34 @@ describe("TerminalViewport", () => {
}
});
it("does not reattach when runtime env contents are unchanged but object identity changes", async () => {
const environment = createEnvironmentApi();
environmentApiById.set("environment-a", environment);
const mounted = await mountTerminalViewport({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
runtimeEnv: { PATH: "/usr/bin", T3: "1" },
});
try {
await vi.waitFor(() => {
expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
});
await mounted.rerender({
threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
runtimeEnv: { T3: "1", PATH: "/usr/bin" },
});
await vi.waitFor(() => {
expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
});
expect(terminalDisposeSpy).not.toHaveBeenCalled();
} finally {
await mounted.cleanup();
}
});
it("uses the drawer surface colors for the terminal theme", async () => {
const environment = createEnvironmentApi();
environmentApiById.set("environment-a", environment);
@@ -75,6 +75,24 @@ function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnap
}
}
function fitTerminalSafely(fitAddon: FitAddon): boolean {
try {
fitAddon.fit();
return true;
} catch {
return false;
}
}
function runtimeEnvSignature(runtimeEnv: Record<string, string> | undefined): string {
if (!runtimeEnv) return "";
return JSON.stringify(
Object.entries(runtimeEnv)
.filter(([key, value]) => key.length > 0 && typeof value === "string")
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
);
}
function normalizeComputedColor(value: string | null | undefined, fallback: string): string {
const normalizedValue = value?.trim().toLowerCase();
if (
@@ -283,6 +301,7 @@ export function TerminalViewport({
const selectionActionOpenRef = useRef(false);
const selectionActionTimerRef = useRef<number | null>(null);
const keybindingsRef = useRef(keybindings);
const runtimeEnvKey = useMemo(() => runtimeEnvSignature(runtimeEnv), [runtimeEnv]);
const handleSessionExited = useEffectEvent(() => {
onSessionExited();
});
@@ -302,7 +321,7 @@ export function TerminalViewport({
let disposed = false;
const api = readEnvironmentApi(environmentId);
const localApi = readLocalApi();
if (!api || !localApi) return;
if (!api) return;
const fitAddon = new FitAddon();
const terminal = new Terminal({
@@ -315,7 +334,7 @@ export function TerminalViewport({
});
terminal.loadAddon(fitAddon);
terminal.open(mount);
fitAddon.fit();
fitTerminalSafely(fitAddon);
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
@@ -369,6 +388,10 @@ export function TerminalViewport({
};
const showSelectionAction = async () => {
if (!localApi) {
clearSelectionAction();
return;
}
if (selectionActionOpenRef.current) {
return;
}
@@ -479,6 +502,10 @@ export function TerminalViewport({
const latestTerminal = terminalRef.current;
if (!latestTerminal) return;
if (!localApi) {
writeSystemMessage(latestTerminal, "Opening links is unavailable in this browser.");
return;
}
if (match.kind === "url") {
void localApi.shell.openExternal(match.text).catch((error: unknown) => {
@@ -630,7 +657,7 @@ export function TerminalViewport({
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
activeFitAddon.fit();
fitTerminalSafely(activeFitAddon);
unsubscribeAttach = attachTerminalSession({
environmentId,
client: api,
@@ -664,7 +691,7 @@ export function TerminalViewport({
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
fitTerminalSafely(activeFitAddon);
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
@@ -700,7 +727,7 @@ export function TerminalViewport({
// autoFocus is intentionally omitted;
// it is only read at mount time and must not trigger terminal teardown/recreation.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cwd, environmentId, runtimeEnv, terminalId, threadId, worktreePath]);
}, [cwd, environmentId, runtimeEnvKey, terminalId, threadId, worktreePath]);
useEffect(() => {
if (!autoFocus) return;
@@ -721,7 +748,7 @@ export function TerminalViewport({
if (!api || !terminal || !fitAddon) return;
const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
const frame = window.requestAnimationFrame(() => {
fitAddon.fit();
fitTerminalSafely(fitAddon);
if (wasAtBottom) {
terminal.scrollToBottom();
}
+17
View File
@@ -44,6 +44,23 @@ describe("contextWindow", () => {
expect(snapshot).toBeNull();
});
it("keeps valid zero-usage snapshots", () => {
const snapshot = deriveLatestContextWindowSnapshot([
makeActivity("activity-1", "context-window.updated", {
usedTokens: 0,
maxTokens: 100_000,
}),
]);
expect(snapshot).toMatchObject({
usedTokens: 0,
maxTokens: 100_000,
remainingTokens: 100_000,
usedPercentage: 0,
remainingPercentage: 100,
});
});
it("formats compact token counts", () => {
expect(formatContextWindowTokens(999)).toBe("999");
expect(formatContextWindowTokens(1400)).toBe("1.4k");
+1 -1
View File
@@ -36,7 +36,7 @@ export function deriveLatestContextWindowSnapshot(
const payload = asRecord(activity.payload);
const usedTokens = asFiniteNumber(payload?.usedTokens);
if (usedTokens === null || usedTokens <= 0) {
if (usedTokens === null || usedTokens < 0) {
continue;
}
+9
View File
@@ -40,4 +40,13 @@ describe("LRUCache", () => {
expect(cache.get("b")).toBe("B");
expect(cache.get("c")).toBe("C");
});
it("does not cache entries larger than the memory budget", () => {
const cache = new LRUCache<string>(2, 25);
cache.set("a", "A", 10);
cache.set("oversized", "X", 30);
expect(cache.get("a")).toBe("A");
expect(cache.get("oversized")).toBeNull();
});
});
+4
View File
@@ -29,6 +29,10 @@ export class LRUCache<T> {
this.cache.delete(key);
}
if (approximateSize > this.maxMemoryBytes) {
return;
}
this.evictIfNeeded(approximateSize);
this.cache.set(key, { value, approximateSize });
this.totalSize += approximateSize;
+48
View File
@@ -114,6 +114,31 @@ describe("sortThreads", () => {
]);
});
it("falls back to createdAt when updatedAt is invalid", () => {
const sorted = sortThreads(
[
makeThread({
id: ThreadId.make("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "invalid-date" as never,
messages: [],
}),
makeThread({
id: ThreadId.make("thread-2"),
createdAt: "2026-03-09T09:00:00.000Z",
updatedAt: "2026-03-09T09:30:00.000Z",
messages: [],
}),
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.make("thread-1"),
ThreadId.make("thread-2"),
]);
});
it("falls back to id ordering when threads have no sortable timestamps", () => {
const sorted = sortThreads(
[
@@ -162,6 +187,29 @@ describe("sortThreads", () => {
]);
});
it("uses updatedAt as a fallback for created_at sorting when createdAt is invalid", () => {
const sorted = sortThreads(
[
makeThread({
id: ThreadId.make("thread-1"),
createdAt: "invalid-date" as never,
updatedAt: "2026-03-09T10:05:00.000Z",
}),
makeThread({
id: ThreadId.make("thread-2"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
}),
],
"created_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.make("thread-1"),
ThreadId.make("thread-2"),
]);
});
it("returns the latest active thread for a project", () => {
const latestThread = getLatestThreadForProject(
[
+15 -2
View File
@@ -13,6 +13,17 @@ export function toSortableTimestamp(iso: string | undefined): number | null {
return Number.isFinite(ms) ? ms : null;
}
function getFirstSortableTimestamp(...values: Array<string | null | undefined>): number | null {
for (const value of values) {
const timestamp = toSortableTimestamp(value ?? undefined);
if (timestamp !== null) {
return timestamp;
}
}
return null;
}
function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
if (thread.latestUserMessageAt) {
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
@@ -34,7 +45,7 @@ function getLatestUserMessageTimestamp(thread: ThreadSortInput): number {
return latestUserMessageTimestamp;
}
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
return getFirstSortableTimestamp(thread.updatedAt, thread.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function getThreadSortTimestamp(
@@ -42,7 +53,9 @@ export function getThreadSortTimestamp(
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
): number {
if (sortOrder === "created_at") {
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
return (
getFirstSortableTimestamp(thread.createdAt, thread.updatedAt) ?? Number.NEGATIVE_INFINITY
);
}
return getLatestUserMessageTimestamp(thread);
}