Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import {
3 AuthOrchestrationOperateScope,
4 AuthOrchestrationReadScope,
5 EnvironmentId,
6 ProjectId,
7 type AgentSessionProjectCandidate,
8 type AuthEnvironmentScope,
9 type AuthSessionState,
10} from "@t3tools/contracts";
11import { AsyncResult, Atom } from "effect/reactivity";
12import { expect, it, vi } from "vite-plus/test";
13
14import "~/index.css";
15import { act, render } from "../../../test/render";
16
17type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
18type Project = { id: ProjectId; environmentId: EnvironmentId; workspaceRoot: string };
19type CreateProjectInput = {
20 environmentId: EnvironmentId;
21 input: { projectId: ProjectId; workspaceRoot: string };
22};
23const state = vi.hoisted(() => ({
24 selectedEnvironment: "primary",
25 sessions: new Map<string, unknown>(),
26 projects: null as unknown,
27 providers: null as unknown,
28 config: null as unknown,
29 candidates: [] as AgentSessionProjectCandidate[],
30 createProject: vi.fn(),
31 importThreads: vi.fn(),
32 refreshProviders: vi.fn(),
33 connectPairing: vi.fn(),
34 completeOnboarding: vi.fn(),
35 onDone: vi.fn(),
36 scan: vi.fn(),
37 refreshScan: vi.fn(),
38}));
39
40// Session grants come from per-test atoms so a test can revoke or regrant mid-flow; the
41// real scope checks in ~/state/session read them through the app registry, which the
42// wizard is also rendered with.
43vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
44 const actual = await original();
45 return {
46 ...actual,
47 createEnvironmentSessionAtoms: ((runtime: never) => ({
48 ...actual.createEnvironmentSessionAtoms(runtime),
49 sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id),
50 })) as never,
51 };
52});
53vi.mock(import("../../cloud/publicConfig"), async (original) => ({
54 ...(await original()),
55 hasCloudPublicConfig: () => false,
56}));
57vi.mock(import("../../onboarding/firstRun"), async (original) => ({
58 ...(await original()),
59 completeOnboarding: state.completeOnboarding,
60}));
61vi.mock(import("../../state/environments"), async (original) => {
62 const environment = (environmentId: string) => ({
63 environmentId,
64 label: environmentId,
65 connection: { phase: "connected" },
66 entry: { enabled: true, target: { _tag: "DirectConnectionTarget" } },
67 });
68 const primary = environment("primary");
69 return {
70 ...(await original()),
71 usePrimaryEnvironment: (() => primary) as never,
72 useEnvironments: (() => ({ environments: [environment(state.selectedEnvironment)] })) as never,
73 };
74});
75vi.mock(import("../../state/server"), async (original) => {
76 const actual = await original();
77 return {
78 ...actual,
79 serverEnvironment: {
80 ...actual.serverEnvironment,
81 providersValueAtom: (() => state.providers) as never,
82 configValueAtom: (() => state.config) as never,
83 refreshProviders: "refreshProviders" as never,
84 },
85 };
86});
87vi.mock(import("../../state/entities"), async (original) => {
88 const { useAtomValue } = await import("@effect/atom-react");
89 return {
90 ...(await original()),
91 useProjects: (() => useAtomValue(state.projects as Atom.Atom<Project[]>)) as never,
92 readProjects: (() => appAtomRegistry.get(state.projects as Atom.Atom<Project[]>)) as never,
93 };
94});
95vi.mock(import("../../state/projects"), async (original) => ({
96 ...(await original()),
97 projectEnvironment: { create: "createProject" } as never,
98}));
99vi.mock(import("../../state/agentSessions"), async (original) => ({
100 ...(await original()),
101 agentSessionImport: "importThreads" as never,
102}));
103vi.mock(import("../../onboarding/useProjectScans"), async (original) => ({
104 ...(await original()),
105 useProjectScans: (ids: readonly EnvironmentId[]) =>
106 ids.map((environmentId) => {
107 state.scan({ environmentId });
108 return {
109 environmentId,
110 data: { candidates: state.candidates, truncated: false } as never,
111 isPending: false,
112 error: null,
113 refresh: state.refreshScan,
114 };
115 }),
116}));
117vi.mock(import("../../connection/onboarding"), async (original) => ({
118 ...(await original()),
119 connectPairing: "connectPairing" as never,
120}));
121vi.mock(import("../../state/use-atom-command"), async (original) => ({
122 ...(await original()),
123 useAtomCommand: ((
124 command: "createProject" | "importThreads" | "refreshProviders" | "connectPairing",
125 ) => state[command]) as never,
126}));
127vi.mock(import("../settings/ChatGptWelcomeCoordinator"), async (original) => ({
128 ...(await original()),
129 ChatGptWelcomeCoordinator: () => <></>,
130}));
131
132import { appAtomRegistry } from "../../rpc/atomRegistry";
133import { WelcomeWizard } from "./WelcomeWizard";
134
135const primaryId = EnvironmentId.make("primary");
136const remoteId = EnvironmentId.make("remote");
137const permissionMessage = "This connection cannot import projects or thread history.";
138
139function session(scopes: ReadonlyArray<AuthEnvironmentScope>): AuthSessionState {
140 return {
141 authenticated: true,
142 scopes: [AuthOrchestrationReadScope, ...scopes],
143 auth: {
144 policy: "remote-reachable",
145 bootstrapMethods: ["one-time-token"],
146 sessionMethods: ["bearer-access-token"],
147 sessionCookieName: "t3_session",
148 },
149 };
150}
151
152function sessionAtom(environmentId: EnvironmentId) {
153 return state.sessions.get(environmentId) as Atom.Writable<SessionResult>;
154}
155
156function projectsAtom() {
157 return state.projects as Atom.Writable<ReadonlyArray<Project>>;
158}
159
160function setGrant(environmentId: EnvironmentId, allowed: boolean) {
161 appAtomRegistry.set(
162 sessionAtom(environmentId),
163 AsyncResult.success(session(allowed ? [AuthOrchestrationOperateScope] : [])),
164 );
165}
166
167// Default selection only picks recently active projects, so pin "now".
168const NOW = Date.parse("2026-01-01T00:00:00.000Z");
169
170function candidate(path: string): AgentSessionProjectCandidate {
171 return {
172 path,
173 title: path.split("/").at(-1)!,
174 sources: ["codex"],
175 threadCount: 10,
176 lastActiveAt: new Date(NOW - 60_000).toISOString(),
177 alreadyImported: false,
178 };
179}
180
181function recordProject({ environmentId, input }: CreateProjectInput) {
182 appAtomRegistry.set(projectsAtom(), [
183 ...appAtomRegistry.get(projectsAtom()),
184 { id: input.projectId, environmentId, workspaceRoot: input.workspaceRoot },
185 ]);
186 return AsyncResult.success(undefined);
187}
188
189function deferred<T>() {
190 let resolve!: (value: T) => void;
191 const promise = new Promise<T>((complete) => {
192 resolve = complete;
193 });
194 return { promise, resolve };
195}
196
197function pageText() {
198 return document.body.textContent ?? "";
199}
200
201function button(label: string) {
202 const found = [...document.querySelectorAll("button")].find(
203 (element) => element.textContent?.trim() === label,
204 );
205 if (!found) throw new Error(`Missing button: ${label}`);
206 return found;
207}
208
209async function click(label: string) {
210 const target = button(label);
211 expect(target.disabled).toBe(false);
212 await act(async () => target.click());
213}
214
215async function mountImport(remote = false) {
216 state.selectedEnvironment = remote ? "remote" : "primary";
217 await using stack = new AsyncDisposableStack();
218 const screen = stack.use(
219 await render(
220 <RegistryContext.Provider value={appAtomRegistry}>
221 <WelcomeWizard localAvailable={!remote} onDone={state.onDone} />
222 </RegistryContext.Provider>,
223 ),
224 );
225 await click("Continue");
226 await click("Continue");
227 expect(pageText()).toContain("Import your projects");
228 stack.move();
229 return screen;
230}
231
232// The mocked modules read `state`, so every test starts by replacing all of it.
233// Returns the clock spy so each test can `using` it; the spy would otherwise outlive the test.
234function setup() {
235 const now = vi.spyOn(Date, "now").mockReturnValue(NOW);
236 state.sessions.clear();
237 for (const id of [primaryId, remoteId]) {
238 state.sessions.set(
239 id,
240 Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
241 Atom.keepAlive,
242 ),
243 );
244 }
245 state.projects = Atom.make<ReadonlyArray<Project>>([]).pipe(Atom.keepAlive);
246 state.providers = Atom.make<ReadonlyArray<never>>([]).pipe(Atom.keepAlive);
247 state.config = Atom.make(null).pipe(Atom.keepAlive);
248 state.candidates = [candidate("/projects/first"), candidate("/projects/second")];
249 state.createProject
250 .mockReset()
251 .mockImplementation(async (input: CreateProjectInput) => recordProject(input));
252 state.importThreads
253 .mockReset()
254 .mockResolvedValue(AsyncResult.success({ importedCount: 1, skippedCount: 0 }));
255 state.refreshProviders.mockReset().mockResolvedValue(AsyncResult.success(undefined));
256 state.connectPairing.mockReset().mockResolvedValue(AsyncResult.success(remoteId));
257 state.completeOnboarding.mockReset().mockResolvedValue(undefined);
258 state.onDone.mockReset();
259 state.scan.mockReset();
260 state.refreshScan.mockReset();
261 return now;
262}
263
264it("rechecks after project creation and can retry its history without recreating the project", async () => {
265 using _now = setup();
266 const creation = deferred<void>();
267 state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
268 await creation.promise;
269 return recordProject(input);
270 });
271 await using _screen = await mountImport();
272 await click("Import 2 projects");
273 expect(state.createProject).toHaveBeenCalledOnce();
274 await act(async () => {
275 setGrant(primaryId, false);
276 creation.resolve();
277 await creation.promise;
278 });
279 expect(state.importThreads).not.toHaveBeenCalled();
280 expect(state.createProject).toHaveBeenCalledOnce();
281 expect(state.onDone).not.toHaveBeenCalled();
282 expect(pageText()).toContain(permissionMessage);
283
284 await act(async () => setGrant(primaryId, true));
285 await click("Import 2 projects");
286 expect(state.createProject).toHaveBeenCalledTimes(2);
287 expect(state.importThreads).toHaveBeenCalledTimes(2);
288 expect(state.onDone).toHaveBeenCalledOnce();
289});
290
291it("completes accepted imports when permission is revoked after the final server write", async () => {
292 using _now = setup();
293 state.candidates = state.candidates.slice(0, 1);
294 const imported = deferred<{ importedCount: number; skippedCount: number }>();
295 state.importThreads.mockImplementationOnce(async () =>
296 AsyncResult.success(await imported.promise),
297 );
298 await using _screen = await mountImport();
299 await click("Import 1 project");
300 await act(async () => {
301 setGrant(primaryId, false);
302 imported.resolve({ importedCount: 1, skippedCount: 0 });
303 await imported.promise;
304 });
305 expect(state.createProject).toHaveBeenCalledOnce();
306 expect(state.importThreads).toHaveBeenCalledOnce();
307 expect(state.completeOnboarding).toHaveBeenCalledOnce();
308 expect(state.onDone).toHaveBeenCalledOnce();
309});