Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import {
3 followLinkedThread,
4 type LinkedThreadView as LinkedThreadState,
5} from "@t3tools/client-runtime/linked-thread";
6import {
7 EnvironmentId,
8 TurnItemId,
9 type OrchestrationV2ThreadHistoryPage,
10} from "@t3tools/contracts";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Queue from "effect/Queue";
14import * as Stream from "effect/Stream";
15import { act, type ReactNode } from "react";
16import { createRoot } from "react-dom/client";
17import { vi } from "vite-plus/test";
18
19import { v2Projection } from "../../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures";
20import { useLinkedThreadView } from "../../state/linkedThread";
21import { LinkedThreadView } from "./LinkedThreadSheet";
22
23vi.mock("@react-navigation/native", () => ({
24 StackActions: {},
25 useIsFocused: () => true,
26 useNavigation: () => ({}),
27}));
28vi.mock("react-native", () => {
29 const Container = ({ children }: { children: ReactNode }) => <div>{children}</div>;
30 return {
31 AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) },
32 Platform: { OS: "android" },
33 Pressable: ({ children, onPress }: { children: ReactNode; onPress?: () => void }) => (
34 <div data-pressable onClick={onPress}>
35 {children}
36 </div>
37 ),
38 ScrollView: Container,
39 Text: Container,
40 View: Container,
41 };
42});
43vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
44vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null }));
45vi.mock("../../components/ui/Button", () => ({
46 Button: (props: { label: string; disabled?: boolean; onPress: () => void }) => (
47 <button type="button" disabled={props.disabled} onClick={props.onPress}>
48 {props.label}
49 </button>
50 ),
51}));
52vi.mock("../../components/ui/ScreenContent", () => ({
53 ScreenContent: ({ children }: { children: ReactNode }) => children,
54}));
55vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null }));
56vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) }));
57vi.mock("../../state/linkedThread", () => ({
58 useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }),
59 useLinkedThreadView: vi.fn(),
60}));
61vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} }));
62vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) }));
63vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) }));
64vi.mock("./ReadOnlyComposerBar", () => ({
65 ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children,
66}));
67vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null }));
68vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined }));
69
70it.effect(
71 "shows a page error after Load earlier fails on an already disconnected linked chat",
72 () =>
73 Effect.gen(function* () {
74 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
75 const container = document.createElement("div");
76 const root = createRoot(container);
77 const target = {
78 viaEnvironmentId: EnvironmentId.make("via"),
79 environmentId: EnvironmentId.make("linked"),
80 threadId: v2Projection.thread.id,
81 label: "Linked test environment",
82 title: null,
83 };
84 const warning = "Linked test environment is not answering this environment";
85 const pageError = "Could not load earlier turns. Try again.";
86 const loadEarlier = () =>
87 [...container.querySelectorAll("button")].find(
88 (button) => button.textContent === "Load earlier",
89 )!;
90
91 try {
92 const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" };
93 const pages =
94 yield* Queue.unbounded<
95 Effect.Effect<OrchestrationV2ThreadHistoryPage, typeof unavailable>
96 >();
97 const views = yield* Queue.unbounded<LinkedThreadState>();
98 yield* followLinkedThread({
99 items: Stream.make({
100 kind: "snapshot",
101 snapshotSequence: 1,
102 projection: v2Projection,
103 historyCursor: "before-recent",
104 hasMoreHistory: true,
105 } as const).pipe(Stream.concat(Stream.fail(unavailable))),
106 historyPage: () => Queue.take(pages).pipe(Effect.flatten),
107 }).pipe(
108 Stream.runForEach((view) => Queue.offer(views, view)),
109 Effect.forkScoped,
110 );
111
112 const renderNext = Effect.gen(function* () {
113 const view = yield* Queue.take(views);
114 vi.mocked(useLinkedThreadView).mockReturnValue({
115 view,
116 error: view.error ?? null,
117 retry() {},
118 });
119 act(() => root.render(<LinkedThreadView target={target} />));
120 });
121
122 yield* renderNext; // Initial snapshot.
123 yield* renderNext; // Connection warning.
124 expect(container.textContent).toContain(warning);
125 expect(container.textContent).not.toContain(pageError);
126
127 act(() => loadEarlier().click());
128 yield* renderNext;
129 yield* Queue.offer(pages, Effect.fail(unavailable));
130 yield* renderNext;
131 expect(loadEarlier().parentElement?.textContent).toContain(pageError);
132 expect(container.textContent).toContain(warning);
133
134 act(() => loadEarlier().click());
135 yield* renderNext;
136 expect(container.textContent).not.toContain(pageError);
137 expect(loadEarlier().disabled).toBe(true);
138 } finally {
139 act(() => root.unmount());
140 vi.unstubAllGlobals();
141 }
142 }).pipe(Effect.scoped),
143);
144
145// Renders the linked thread with one read-only row, taps the row matching `label` and returns it.
146function openLinkedRow(
147 itemId: string,
148 fields: Record<string, unknown>,
149 label: string,
150 run: (row: HTMLElement) => void,
151) {
152 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
153 const container = document.createElement("div");
154 const root = createRoot(container);
155 const now = DateTime.makeUnsafe("2026-11-29T00:00:00Z");
156 const turnItemId = TurnItemId.make(itemId);
157 const threadId = v2Projection.thread.id;
158 const projection = {
159 ...v2Projection,
160 visibleTurnItems: [
161 {
162 position: 0,
163 visibility: "local",
164 sourceThreadId: threadId,
165 sourceItemId: turnItemId,
166 item: {
167 id: turnItemId,
168 threadId,
169 runId: null,
170 nodeId: null,
171 providerThreadId: null,
172 providerTurnId: null,
173 nativeItemRef: null,
174 parentItemId: null,
175 ordinal: 1,
176 status: "completed",
177 title: null,
178 startedAt: now,
179 completedAt: now,
180 updatedAt: now,
181 ...fields,
182 },
183 },
184 ],
185 } as unknown as typeof v2Projection;
186 vi.mocked(useLinkedThreadView).mockReturnValue({
187 view: {
188 thread: { projection, historyCursor: null },
189 error: null,
190 history: { loading: false, failed: false },
191 loadedHistory: null,
192 loadEarlier() {},
193 } as unknown as LinkedThreadState,
194 error: null,
195 retry() {},
196 });
197 try {
198 act(() =>
199 root.render(
200 <LinkedThreadView
201 target={{
202 viaEnvironmentId: EnvironmentId.make("via"),
203 environmentId: EnvironmentId.make("linked"),
204 threadId,
205 label: "Linked test environment",
206 title: null,
207 }}
208 />,
209 ),
210 );
211 const row = [...container.querySelectorAll<HTMLElement>("[data-pressable]")].find((element) =>
212 element.textContent?.includes(label),
213 )!;
214 act(() => row.click());
215 run(row);
216 } finally {
217 act(() => root.unmount());
218 vi.unstubAllGlobals();
219 }
220}
221
222it("shows a linked file search's pattern, not its raw item JSON, like the thread screen", () => {
223 openLinkedRow(
224 "linked-search",
225 {
226 type: "file_search",
227 pattern: "TODO",
228 results: [{ fileName: "src/app.ts", line: 3, preview: "// TODO tidy" }],
229 },
230 "TODO",
231 (row) => {
232 expect(row.textContent).toContain("pattern: TODO");
233 expect(row.textContent).toContain("3: // TODO tidy");
234 expect(row.textContent).not.toContain("sourceItemId");
235 },
236 );
237});
238
239it("shows a linked thread's reasoning text, not its raw item JSON, like the thread screen", () => {
240 openLinkedRow(
241 "linked-reasoning",
242 { type: "reasoning", text: "Check the config loader first.", streaming: false },
243 "Thinking",
244 (row) => {
245 expect(row.textContent).toContain("Check the config loader first.");
246 expect(row.textContent).not.toContain("sourceItemId");
247 },
248 );
249});