Skip to content

Commit 5deb87a

Browse files
Merge branch 'main' into fix/issue-22946
Picks up the right panel tab swipe test fix that Test Web needs on Linux. Co-Authored-By: Claude Opus 5.5 <[email protected]>
2 parents b331df7 + a03d9bc commit 5deb87a

13 files changed

Lines changed: 603 additions & 39 deletions
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import type { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
2+
import type { ReactNode } from "react";
3+
import { act } from "react";
4+
import { createRoot } from "react-dom/client";
5+
import { expect, it, vi } from "vite-plus/test";
6+
7+
import type { PendingUserInput } from "../../lib/threadActivity";
8+
9+
const harness = vi.hoisted(() => ({
10+
navigate: [] as Array<[string, object | undefined]>,
11+
openedUrls: [] as string[],
12+
}));
13+
14+
type Children = { children?: ReactNode };
15+
16+
vi.mock("react-native", () => ({
17+
Platform: { OS: "ios" },
18+
View: ({ children }: Children) => <div>{children}</div>,
19+
ScrollView: ({ children }: Children) => <div>{children}</div>,
20+
Pressable: ({ children, onPress }: Children & { onPress?: () => void }) => (
21+
<div onClick={onPress}>{children}</div>
22+
),
23+
}));
24+
vi.mock("react-native-reanimated", () => {
25+
const animation = { duration: () => ({ easing: () => ({}) }) };
26+
return {
27+
default: { View: ({ children }: Children) => <div>{children}</div> },
28+
Easing: { out: () => () => 0, cubic: () => 0 },
29+
FadeInUp: animation,
30+
FadeOutDown: animation,
31+
useAnimatedStyle: () => ({}),
32+
useSharedValue: (value: number) => ({ value, set: () => {} }),
33+
};
34+
});
35+
vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
36+
vi.mock("../../components/ui/AppText", () => ({
37+
AppText: ({ children }: Children) => <span>{children}</span>,
38+
}));
39+
vi.mock("../../components/ui/ControlPill", () => ({ ControlPill: () => null }));
40+
vi.mock("../../components/ui/Button", () => ({ Button: () => null }));
41+
vi.mock("./QuestionAttachments", () => ({ QuestionAttachments: () => null }));
42+
vi.mock("../files/FileMarkdownPreview", () => ({
43+
useMarkdownPreviewStyles: () => ({ nativeTextStyle: {} }),
44+
}));
45+
vi.mock("../../native/SelectableMarkdownText", () => ({
46+
SelectableMarkdownText: (props: { markdown: string; onLinkPress?: (href: string) => void }) => (
47+
<p>
48+
{[...props.markdown.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g)].map(([, label, href]) => (
49+
<button key={href} type="button" onClick={() => props.onLinkPress?.(href!)}>
50+
{label}
51+
</button>
52+
))}
53+
</p>
54+
),
55+
}));
56+
vi.mock("../../state/entities", () => ({
57+
useLiveThreadLinkLabels: (markdown: string) => markdown,
58+
}));
59+
vi.mock("../../native/useOpenPullRequest", () => ({
60+
useOpenPullRequest: () => async (url: string) => {
61+
harness.openedUrls.push(url);
62+
return true;
63+
},
64+
}));
65+
vi.mock("@react-navigation/native", () => ({
66+
useNavigation: () => ({
67+
navigate: (name: string, params?: object) => harness.navigate.push([name, params]),
68+
}),
69+
}));
70+
71+
import { PendingUserInputCard } from "./PendingUserInputCard";
72+
73+
function setup(questionMarkdown: string) {
74+
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
75+
harness.navigate = [];
76+
harness.openedUrls = [];
77+
78+
const pendingUserInput = {
79+
requestId: "request-1" as RuntimeRequestId,
80+
responseCapability: "resumable",
81+
questions: [
82+
{
83+
id: "question-1",
84+
header: "Review",
85+
question: questionMarkdown,
86+
options: [],
87+
allowCustomAnswer: false,
88+
},
89+
],
90+
} as unknown as PendingUserInput;
91+
const container = document.createElement("div");
92+
const root = createRoot(container);
93+
act(() =>
94+
root.render(
95+
<PendingUserInputCard
96+
environmentId={"env-1" as EnvironmentId}
97+
threadId={"thread-1" as ThreadId}
98+
workspaceRoot="/repo"
99+
canOperateThread
100+
pendingUserInput={pendingUserInput}
101+
maxHeight={{ value: 600 } as never}
102+
cardProgress={{ value: 1, set: () => {} } as never}
103+
cardCoverage={{ value: 0, set: () => {} } as never}
104+
collapsed={false}
105+
onToggleCollapsed={() => {}}
106+
drafts={{}}
107+
answers={null}
108+
respondingUserInputId={null}
109+
onSelectOption={() => {}}
110+
onChangeCustomAnswer={() => {}}
111+
onSubmit={async () => {}}
112+
onDismiss={async () => {}}
113+
/>,
114+
),
115+
);
116+
return {
117+
async pressLink(label: string) {
118+
const link = [...container.querySelectorAll("button")].find(
119+
(button) => button.textContent === label,
120+
);
121+
if (!link) throw new Error(`No link labelled ${label}`);
122+
await act(async () => link.click());
123+
},
124+
[Symbol.dispose]() {
125+
act(() => root.unmount());
126+
},
127+
};
128+
}
129+
130+
it("opens a workspace file link in a question in the thread's file viewer", async () => {
131+
using screen = setup("Should I update [probe.md](docs/probe.md:12)?");
132+
133+
await screen.pressLink("probe.md");
134+
135+
expect(harness.openedUrls).toEqual([]);
136+
expect(harness.navigate).toEqual([
137+
[
138+
"ThreadFile",
139+
{ environmentId: "env-1", threadId: "thread-1", path: ["docs", "probe.md"], line: "12" },
140+
],
141+
]);
142+
});

‎apps/mobile/src/features/threads/PendingUserInputCard.tsx‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import { Button } from "../../components/ui/Button";
22
import { QuestionAttachments } from "./QuestionAttachments";
3-
import type { EnvironmentId, RuntimeRequestId } from "@t3tools/contracts";
3+
import type { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
44
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
55
import {
66
markdownProseDirection,
77
textDirection,
88
type TextDirection,
99
} from "@t3tools/shared/textDirection";
10+
import { useNavigation } from "@react-navigation/native";
1011
import { useRef } from "react";
1112
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
1213
import Animated, {
@@ -20,9 +21,15 @@ import { SymbolView } from "../../components/ui/AppSymbol";
2021
import { AppText as Text } from "../../components/ui/AppText";
2122
import { ControlPill } from "../../components/ui/ControlPill";
2223
import { cn } from "../../lib/cn";
24+
import { resolveMarkdownLinkPresentation } from "../../lib/markdownLinks";
2325
import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
2426
import { useOpenPullRequest } from "../../native/useOpenPullRequest";
2527
import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
28+
import {
29+
fileRoutePathSegments,
30+
resolveFileLinkPath,
31+
resolveWorkspaceRelativeFilePath,
32+
} from "../files/filePath";
2633
import { useLiveThreadLinkLabels } from "../../state/entities";
2734
import {
2835
isPendingUserInputOptionSelected,
@@ -32,6 +39,8 @@ import type { PendingUserInput } from "../../lib/threadActivity";
3239

3340
export interface PendingUserInputCardProps {
3441
readonly environmentId: EnvironmentId;
42+
readonly threadId: ThreadId;
43+
readonly workspaceRoot: string | null;
3544
readonly canOperateThread: boolean;
3645
readonly pendingUserInput: PendingUserInput;
3746
readonly maxHeight: DerivedValue<number>;
@@ -69,11 +78,31 @@ function proseDirectionStyle(text: string, setDirection: TextDirection | undefin
6978
function QuestionText(props: {
7079
readonly markdown: string;
7180
readonly environmentId: EnvironmentId;
81+
readonly threadId: ThreadId;
82+
readonly workspaceRoot: string | null;
7283
readonly setDirection: TextDirection | undefined;
7384
}) {
7485
const styles = useMarkdownPreviewStyles();
7586
const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);
76-
const openLink = useOpenPullRequest();
87+
const navigation = useNavigation();
88+
const openPullRequest = useOpenPullRequest();
89+
const openLink = (href: string) => {
90+
const link = resolveMarkdownLinkPresentation(href);
91+
if (link.kind !== "file") {
92+
void openPullRequest(href);
93+
return;
94+
}
95+
const path = resolveFileLinkPath(props.workspaceRoot, link.path);
96+
if (path === null) return;
97+
navigation.navigate("ThreadFile", {
98+
environmentId: String(props.environmentId),
99+
threadId: String(props.threadId),
100+
path: fileRoutePathSegments(
101+
resolveWorkspaceRelativeFilePath(props.workspaceRoot, path) ?? path,
102+
),
103+
...(link.line ? { line: String(link.line) } : {}),
104+
});
105+
};
77106
return (
78107
<SelectableMarkdownText
79108
markdown={markdown}
@@ -83,7 +112,7 @@ function QuestionText(props: {
83112
textAlign={
84113
Platform.OS === "android" ? undefined : props.setDirection === "rtl" ? "right" : "left"
85114
}
86-
onLinkPress={(href) => void openLink(href)}
115+
onLinkPress={openLink}
87116
/>
88117
);
89118
}
@@ -239,6 +268,8 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
239268
<QuestionText
240269
markdown={question.question}
241270
environmentId={props.environmentId}
271+
threadId={props.threadId}
272+
workspaceRoot={props.workspaceRoot}
242273
setDirection={setDirection}
243274
/>
244275
<View className="gap-2">

‎apps/mobile/src/features/threads/ThreadDetailScreen.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1765,6 +1765,8 @@ function ThreadDetailBody(
17651765
{props.activePendingUserInput ? (
17661766
<PendingUserInputCard
17671767
environmentId={props.environmentId}
1768+
threadId={props.selectedThread.id}
1769+
workspaceRoot={props.threadCwd}
17681770
canOperateThread={props.canOperateThread}
17691771
pendingUserInput={props.activePendingUserInput}
17701772
maxHeight={pendingUserInputMaxHeight}

‎apps/mobile/vite.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const reactTests = [
3030
"src/features/threads/ThreadMarkdownImage.test.tsx",
3131
"src/components/ui/FilePreviewSession.test.tsx",
3232
"src/features/threads/UsageLimitRecoveryCard.test.tsx",
33+
"src/features/threads/PendingUserInputCard.test.tsx",
3334
"src/features/threads/NewTaskDraftRouteScreen.test.tsx",
3435
"src/native/NativeHeaderToolbar.test.tsx",
3536
"src/components/ComposerEditor.ios.test.tsx",

‎apps/server/src/serviceLauncher.test.ts‎

Lines changed: 121 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type * as NodeChildProcess from "node:child_process";
33
// @effect-diagnostics-next-line nodeBuiltinImport:off - the free-space probe is a plain Promise callback.
44
import * as NodeFS from "node:fs";
5+
import * as NodeSqlite from "node:sqlite";
56

67
import * as NodeServices from "@effect/platform-node/NodeServices";
78
import { assert, it } from "@effect/vitest";
@@ -464,6 +465,125 @@ if (context.update?.status === "pending") {
464465
}),
465466
);
466467

468+
it.effect.each(["wal", "delete"] as const)(
469+
"backs up a %s-mode database (online when WAL) and restores its final state",
470+
(journalMode) =>
471+
Effect.gen(function* () {
472+
const fs = yield* FileSystem.FileSystem;
473+
const path = yield* Path.Path;
474+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-online-" });
475+
const statePath = path.join(root, "runtime", "service-state.json");
476+
const databasePath = path.join(root, "userdata", "state.sqlite");
477+
const observationsPath = path.join(root, "observations.json");
478+
yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
479+
// SQLite keeps -wal beside the symlink's target, so the backup must restore it there.
480+
yield* fs.symlink("actual.sqlite", databasePath);
481+
const seed = new NodeSqlite.DatabaseSync(databasePath);
482+
seed.exec(`
483+
PRAGMA journal_mode = ${journalMode};
484+
CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
485+
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500)
486+
INSERT INTO events (payload) SELECT 'before the update ' || i FROM n;
487+
`);
488+
seed.close();
489+
490+
const encoded = JSON.stringify({ root, databasePath, observationsPath, journalMode });
491+
const childSource = `
492+
import { readdirSync, writeFileSync } from "node:fs";
493+
import { DatabaseSync } from "node:sqlite";
494+
const paths = ${encoded};
495+
const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT);
496+
if (context.update?.status === "pending") {
497+
writeFileSync(paths.observationsPath + ".trial", JSON.stringify(
498+
readdirSync(paths.root + "/runtime/db-backup/" + context.update.id).sort(),
499+
));
500+
const trial = new DatabaseSync(context.update.dbPath);
501+
trial.exec("PRAGMA journal_mode = " + paths.journalMode + "; INSERT INTO events (payload) VALUES ('trial');");
502+
trial.close();
503+
process.exit(1);
504+
} else if (context.update === undefined) {
505+
const db = new DatabaseSync(paths.databasePath);
506+
db.exec("PRAGMA busy_timeout = 5000;");
507+
db.exec("PRAGMA journal_mode = " + paths.journalMode + ";");
508+
const insert = db.prepare("INSERT INTO events (payload) VALUES (?)");
509+
const writer = setInterval(() => insert.run("written while serving"), 1);
510+
process.once("SIGTERM", () => {
511+
clearInterval(writer);
512+
insert.run("last write before stopping");
513+
const backupRoot = paths.root + "/runtime/db-backup";
514+
writeFileSync(paths.observationsPath, JSON.stringify({
515+
backupsAtStop: readdirSync(backupRoot).map((entry) => readdirSync(backupRoot + "/" + entry)),
516+
rows: db.prepare("SELECT count(*) AS n FROM events").get().n,
517+
}));
518+
db.close();
519+
process.exit(0);
520+
});
521+
process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
522+
} else {
523+
process.exit(0);
524+
}
525+
`;
526+
for (const version of ["1.0.0", "1.1.0"]) {
527+
yield* writeFakeRuntime(
528+
fs,
529+
path,
530+
path.join(root, "runtime", "versions", version),
531+
childSource,
532+
);
533+
}
534+
yield* Effect.promise(() =>
535+
writeServiceState(statePath, {
536+
protocol: SERVICE_LAUNCHER_PROTOCOL,
537+
activeVersion: "1.0.0",
538+
}),
539+
);
540+
541+
const launcher = new Launcher(
542+
root,
543+
yield* Effect.promise(() => readServiceState(statePath)),
544+
{
545+
backupSpaceProbe: { canClone: async () => false },
546+
},
547+
);
548+
yield* Effect.promise(() =>
549+
launcher.run().then(
550+
() => Promise.reject(new Error("launcher unexpectedly completed")),
551+
() => Promise.resolve(),
552+
),
553+
);
554+
555+
const state = yield* Effect.promise(() => readServiceState(statePath));
556+
assert.equal(state.update?.status, "rolled-back");
557+
const observed = JSON.parse(yield* fs.readFileString(observationsPath));
558+
// A WAL database's main file is copied before the server is asked to stop; others fall back offline.
559+
assert.deepEqual(observed.backupsAtStop, journalMode === "wal" ? [["database"]] : []);
560+
assert.isAbove(observed.rows, 501);
561+
// Only the online copy holds no -shm: the offline fallback copies the one the server left.
562+
assert.deepEqual(
563+
JSON.parse(yield* fs.readFileString(`${observationsPath}.trial`)),
564+
journalMode === "wal" ? ["database", "database-wal"] : ["database"],
565+
);
566+
const restored = new NodeSqlite.DatabaseSync(databasePath);
567+
try {
568+
assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok");
569+
assert.equal(
570+
restored.prepare("SELECT count(*) AS n FROM events").get()?.n,
571+
observed.rows,
572+
);
573+
assert.equal(
574+
restored
575+
.prepare(
576+
"SELECT count(*) AS n FROM events WHERE payload = 'last write before stopping'",
577+
)
578+
.get()?.n,
579+
1,
580+
);
581+
} finally {
582+
restored.close();
583+
}
584+
}),
585+
);
586+
467587
const requestRejectedUpdate = (backupSpaceProbe: Partial<BackupSpaceProbe>) =>
468588
Effect.gen(function* () {
469589
const fs = yield* FileSystem.FileSystem;
@@ -670,7 +790,7 @@ setInterval(() => {}, 1_000);
670790
assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free");
671791
const blocker = yield* check(8 * 1024 ** 3, false);
672792
assert.include(blocker ?? "", "Not enough free disk space");
673-
assert.include(blocker ?? "", "10.5 GB needed, 8.0 GB free");
793+
assert.include(blocker ?? "", "10.8 GB needed, 8.0 GB free");
674794
assert.include(blocker ?? "", "The server was not stopped");
675795
}),
676796
);

0 commit comments

Comments
 (0)