|
| 1 | +import { RegistryContext, useAtomValue } from "@effect/atom-react"; |
| 2 | +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; |
| 3 | +import { EnvironmentRegistry } from "@t3tools/client-runtime/connection"; |
| 4 | +import { createEnvironmentSubscriptionAtomFamily } from "@t3tools/client-runtime/state/runtime"; |
| 5 | +import { |
| 6 | + AuthFilesystemReadScope, |
| 7 | + EnvironmentId, |
| 8 | + ProjectId, |
| 9 | + type VcsListRefsResult, |
| 10 | +} from "@t3tools/contracts"; |
| 11 | +import * as Effect from "effect/Effect"; |
| 12 | +import * as Layer from "effect/Layer"; |
| 13 | +import * as Queue from "effect/Queue"; |
| 14 | +import * as Stream from "effect/Stream"; |
| 15 | +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 16 | +import { act, useLayoutEffect } from "react"; |
| 17 | +import { createRoot } from "react-dom/client"; |
| 18 | +import { expect, it, vi } from "vite-plus/test"; |
| 19 | +import type { ComposerDraft } from "../../state/use-composer-drafts"; |
| 20 | + |
| 21 | +const mocks = vi.hoisted(() => ({ |
| 22 | + projects: vi.fn(), |
| 23 | + status: vi.fn(), |
| 24 | + refs: vi.fn(), |
| 25 | + readFile: vi.fn(), |
| 26 | + session: vi.fn(), |
| 27 | + presentation: vi.fn(), |
| 28 | + registry: vi.fn(), |
| 29 | + drafts: vi.fn(), |
| 30 | + snapshot: vi.fn(), |
| 31 | + createDraft: vi.fn(), |
| 32 | + retargetDraft: vi.fn(), |
| 33 | + writeSettings: vi.fn(), |
| 34 | + writeText: vi.fn(), |
| 35 | +})); |
| 36 | +vi.mock("../../state/atom-registry", () => ({ |
| 37 | + appAtomRegistry: { |
| 38 | + get: (atom: Atom.Atom<unknown>) => mocks.registry().get(atom), |
| 39 | + set: (atom: Atom.Writable<unknown, unknown>, value: unknown) => |
| 40 | + mocks.registry().set(atom, value), |
| 41 | + }, |
| 42 | +})); |
| 43 | +vi.mock("../../state/entities", () => ({ |
| 44 | + useProjects: mocks.projects, |
| 45 | + useThreadShells: () => [], |
| 46 | + useEnvironmentServerConfig: () => null, |
| 47 | + useServerConfigs: () => new Map(), |
| 48 | +})); |
| 49 | +vi.mock("../../state/vcs", () => ({ |
| 50 | + vcsEnvironment: { status: mocks.status, listRefs: mocks.refs }, |
| 51 | +})); |
| 52 | +vi.mock("../../state/projects", () => ({ |
| 53 | + projectEnvironment: { readFile: mocks.readFile, openScratch: {} }, |
| 54 | +})); |
| 55 | +vi.mock("../../state/session", () => ({ |
| 56 | + environmentSession: { sessionStateAtom: mocks.session }, |
| 57 | +})); |
| 58 | +vi.mock("../../state/presentation", () => ({ |
| 59 | + useEnvironmentPresentation: mocks.presentation, |
| 60 | +})); |
| 61 | +vi.mock("../../state/orchestration", () => ({ orchestrationEnvironment: {} })); |
| 62 | +vi.mock("../../state/threads", () => ({ olderSettledThreads: {}, threadFamilies: {} })); |
| 63 | +vi.mock("../../state/pull-requests", () => ({ composerPullRequests: {} })); |
| 64 | +vi.mock("../../state/olderSettledShelf", () => ({ useOlderSettledCount: () => 0 })); |
| 65 | +vi.mock("../../state/project-grouping", () => ({ |
| 66 | + useMobileProjectGroupingSettings: () => ({ sidebarProjectGroupingMode: "none" }), |
| 67 | +})); |
| 68 | +vi.mock("./use-legacy-plan-mode-enabled", () => ({ |
| 69 | + useLegacyPlanModeState: () => ({ enabled: false, loaded: true }), |
| 70 | +})); |
| 71 | +vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); |
| 72 | +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() })); |
| 73 | +vi.mock("../../state/use-remote-environment-registry", () => ({ |
| 74 | + useSavedRemoteConnections: () => ({ savedConnectionsById: {} }), |
| 75 | + useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }), |
| 76 | + setPendingConnectionError: vi.fn(), |
| 77 | +})); |
| 78 | +vi.mock("../../state/use-model-option-memory", () => ({ |
| 79 | + rememberModelOptions: vi.fn(), |
| 80 | + withRememberedModelOptions: (value: unknown) => value, |
| 81 | +})); |
| 82 | +vi.mock("../../state/use-composer-drafts", () => ({ |
| 83 | + composerDraftsLoadedAtom: Atom.make(true), |
| 84 | + useComposerDraft: mocks.drafts, |
| 85 | + getComposerDraftSnapshot: mocks.snapshot, |
| 86 | + createNewTaskDraft: mocks.createDraft, |
| 87 | + retargetNewTaskDraft: mocks.retargetDraft, |
| 88 | + updateComposerDraftSettings: mocks.writeSettings, |
| 89 | + setComposerDraftText: mocks.writeText, |
| 90 | + useStickyComposerModelSelection: () => null, |
| 91 | + isNewTaskDraftKey: (key: string) => key.startsWith("new-task:"), |
| 92 | + clearComposerDraft: vi.fn(), |
| 93 | + appendComposerDraftAttachments: vi.fn(), |
| 94 | + removeComposerDraftAttachment: vi.fn(), |
| 95 | + replaceComposerDraftAttachments: vi.fn(), |
| 96 | + setStickyComposerModelSelection: vi.fn(), |
| 97 | + setComposerDraftContext: vi.fn(), |
| 98 | + scheduleUnusedComposerAttachmentCleanup: vi.fn(), |
| 99 | + isComposerDraftEmpty: (draft: ComposerDraft) => |
| 100 | + draft.text === "" && draft.attachments.length === 0, |
| 101 | +})); |
| 102 | + |
| 103 | +vi.mock("../../state/peerLinks", () => ({ useLinkedEnvironments: () => new Map() })); |
| 104 | +vi.mock("../../state/project-has-threads", () => ({ useProjectHasThreads: () => false })); |
| 105 | +vi.mock("../../state/workspace", () => ({ |
| 106 | + useConnectionsReady: () => true, |
| 107 | + useWorkspaceEnvironments: () => [], |
| 108 | +})); |
| 109 | +vi.mock("../../state/shell", () => ({ useEnvironmentShellReadiness: () => ({}) })); |
| 110 | +vi.mock("../../lib/clock", () => ({ useNowMinuteMs: () => 0 })); |
| 111 | + |
| 112 | +import { NewTaskFlowProvider, useNewTaskFlow } from "./new-task-flow-provider"; |
| 113 | + |
| 114 | +function project(environment: string, id: string): EnvironmentProject { |
| 115 | + return { |
| 116 | + environmentId: EnvironmentId.make(environment), |
| 117 | + id: ProjectId.make(id), |
| 118 | + title: id, |
| 119 | + workspaceRoot: `/${id}`, |
| 120 | + repositoryIdentity: null, |
| 121 | + defaultModelSelection: null, |
| 122 | + defaultThreadEnvMode: "worktree", |
| 123 | + scripts: [], |
| 124 | + createdAt: "2026-10-26T00:00:00Z", |
| 125 | + updatedAt: "2026-10-26T00:00:00Z", |
| 126 | + }; |
| 127 | +} |
| 128 | + |
| 129 | +function setup() { |
| 130 | + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; |
| 131 | + vi.useFakeTimers(); |
| 132 | + vi.clearAllMocks(); |
| 133 | + const registry = AtomRegistry.make(); |
| 134 | + mocks.registry.mockReturnValue(registry); |
| 135 | + const projects = [project("one", "a"), project("one", "b"), project("two", "b")]; |
| 136 | + mocks.projects.mockReturnValue(projects); |
| 137 | + mocks.presentation.mockReturnValue({ |
| 138 | + isReady: true, |
| 139 | + presentation: { connection: { phase: "connected", error: null } }, |
| 140 | + }); |
| 141 | + const events: string[] = []; |
| 142 | + let checkout = "main"; |
| 143 | + let checkoutIsRepo = true; |
| 144 | + let holdStatus = false; |
| 145 | + const emitters = new Map<string, (branch: string, isRepo?: boolean) => void>(); |
| 146 | + const runtime = Atom.runtime( |
| 147 | + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, { |
| 148 | + followStream: (_environmentId, source) => source, |
| 149 | + } as EnvironmentRegistry.EnvironmentRegistry["Service"]), |
| 150 | + ); |
| 151 | + const status = createEnvironmentSubscriptionAtomFamily(runtime, { |
| 152 | + label: "test:new-task-status", |
| 153 | + idleTtlMs: 10_000, |
| 154 | + subscribe: ({ cwd }: { cwd: string }) => |
| 155 | + Stream.callback<{ refName: string; isRepo: boolean }>((queue) => |
| 156 | + Effect.acquireRelease( |
| 157 | + Effect.sync(() => { |
| 158 | + events.push(`start:${cwd}`); |
| 159 | + const emit = (refName: string, isRepo = true) => |
| 160 | + void Queue.offerUnsafe(queue, { refName, isRepo }); |
| 161 | + emitters.set(cwd, emit); |
| 162 | + if (!holdStatus) emit(checkout, checkoutIsRepo); |
| 163 | + }), |
| 164 | + () => Effect.sync(() => void events.push(`stop:${cwd}`)), |
| 165 | + ), |
| 166 | + ), |
| 167 | + }); |
| 168 | + mocks.status.mockImplementation(status); |
| 169 | + const refs = Atom.family((key: string) => |
| 170 | + Atom.make(() => { |
| 171 | + const [, cwd] = JSON.parse(key) as [string, string]; |
| 172 | + const result: VcsListRefsResult = { |
| 173 | + refs: [{ name: "main", current: true, isDefault: true, worktreePath: cwd }], |
| 174 | + isRepo: true, |
| 175 | + hasPrimaryRemote: true, |
| 176 | + nextCursor: null, |
| 177 | + totalCount: 1, |
| 178 | + }; |
| 179 | + return AsyncResult.success(result); |
| 180 | + }).pipe(Atom.keepAlive), |
| 181 | + ); |
| 182 | + mocks.refs.mockImplementation(({ environmentId, input }) => |
| 183 | + refs(JSON.stringify([environmentId, input.cwd])), |
| 184 | + ); |
| 185 | + const session = Atom.make( |
| 186 | + AsyncResult.success({ authenticated: true, scopes: [AuthFilesystemReadScope] }), |
| 187 | + ); |
| 188 | + mocks.session.mockReturnValue(session); |
| 189 | + const file = Atom.make(AsyncResult.success({ exists: true, contents: "{}" })); |
| 190 | + mocks.readFile.mockReturnValue(file); |
| 191 | + |
| 192 | + const empty: ComposerDraft = { text: "", attachments: [] }; |
| 193 | + const drafts = Atom.make<Record<string, ComposerDraft>>({}).pipe(Atom.keepAlive); |
| 194 | + const snapshot = (key: string | null): ComposerDraft => |
| 195 | + (key === null ? undefined : registry.get(drafts)[key]) ?? empty; |
| 196 | + const write = (key: string, patch: Partial<ComposerDraft>) => |
| 197 | + registry.set(drafts, { ...registry.get(drafts), [key]: { ...snapshot(key), ...patch } }); |
| 198 | + mocks.drafts.mockImplementation((key: string | null) => { |
| 199 | + const all = useAtomValue(drafts); |
| 200 | + return (key === null ? undefined : all[key]) ?? empty; |
| 201 | + }); |
| 202 | + mocks.snapshot.mockImplementation(snapshot); |
| 203 | + mocks.createDraft.mockImplementation((target) => { |
| 204 | + const key = `new-task:${Object.keys(registry.get(drafts)).length}`; |
| 205 | + write(key, { project: target }); |
| 206 | + return key; |
| 207 | + }); |
| 208 | + mocks.retargetDraft.mockImplementation((key, target) => |
| 209 | + write(key, { project: target, workspaceSelection: undefined }), |
| 210 | + ); |
| 211 | + mocks.writeSettings.mockImplementation(write); |
| 212 | + mocks.writeText.mockImplementation((key, text) => write(key, { text })); |
| 213 | + let current: ReturnType<typeof useNewTaskFlow>; |
| 214 | + function Probe() { |
| 215 | + const value = useNewTaskFlow(); |
| 216 | + useLayoutEffect(() => { |
| 217 | + current = value; |
| 218 | + }); |
| 219 | + return null; |
| 220 | + } |
| 221 | + const root = createRoot(document.createElement("div")); |
| 222 | + return { |
| 223 | + projects, |
| 224 | + events, |
| 225 | + checkout(branch: string, isRepo = true) { |
| 226 | + checkout = branch; |
| 227 | + checkoutIsRepo = isRepo; |
| 228 | + }, |
| 229 | + holdStatus() { |
| 230 | + holdStatus = true; |
| 231 | + }, |
| 232 | + offline() { |
| 233 | + mocks.presentation.mockReturnValue({ |
| 234 | + isReady: true, |
| 235 | + presentation: { connection: { phase: "offline", error: null } }, |
| 236 | + }); |
| 237 | + holdStatus = true; |
| 238 | + }, |
| 239 | + snapshot, |
| 240 | + clearWorkspace(key: string) { |
| 241 | + act(() => write(key, { workspaceSelection: undefined })); |
| 242 | + }, |
| 243 | + get current() { |
| 244 | + return current; |
| 245 | + }, |
| 246 | + async render(active: boolean) { |
| 247 | + await act(async () => |
| 248 | + root.render( |
| 249 | + <RegistryContext.Provider value={registry}> |
| 250 | + <NewTaskFlowProvider active={active} flowKey="test-flow"> |
| 251 | + <Probe /> |
| 252 | + </NewTaskFlowProvider> |
| 253 | + </RegistryContext.Provider>, |
| 254 | + ), |
| 255 | + ); |
| 256 | + }, |
| 257 | + async emit(cwd: string, branch: string, isRepo = true) { |
| 258 | + await act(async () => emitters.get(cwd)!(branch, isRepo)); |
| 259 | + }, |
| 260 | + async expireIdle() { |
| 261 | + await act(async () => vi.advanceTimersByTime(11_000)); |
| 262 | + }, |
| 263 | + [Symbol.dispose]() { |
| 264 | + act(() => root.unmount()); |
| 265 | + registry.dispose(); |
| 266 | + vi.useRealTimers(); |
| 267 | + }, |
| 268 | + }; |
| 269 | +} |
| 270 | + |
| 271 | +it("owns a status stream only while the draft is active, retaining draft choices on reopen", async () => { |
| 272 | + using screen = setup(); |
| 273 | + await screen.render(false); |
| 274 | + expect(screen.current.selectedProject).toEqual(screen.projects[0]); |
| 275 | + expect.soft([...screen.events]).toEqual([]); |
| 276 | + expect(mocks.createDraft).not.toHaveBeenCalled(); |
| 277 | + |
| 278 | + await screen.render(true); |
| 279 | + expect(screen.events).toEqual(["start:/a"]); |
| 280 | + const draftKey = screen.current.draftKey!; |
| 281 | + act(() => screen.current.setPrompt("keep this draft")); |
| 282 | + |
| 283 | + await act(async () => screen.current.setProject(screen.projects[1]!)); |
| 284 | + expect(screen.current.prompt).toBe("keep this draft"); |
| 285 | + expect(screen.current.draftKey).toBe(draftKey); |
| 286 | + expect(screen.events).toEqual(["start:/a", "start:/b"]); |
| 287 | + await act(async () => screen.current.selectEnvironment(EnvironmentId.make("two"))); |
| 288 | + expect(screen.current.selectedProject).toEqual(screen.projects[2]); |
| 289 | + expect(screen.snapshot(draftKey).project).toEqual({ |
| 290 | + environmentId: "two", |
| 291 | + projectId: "b", |
| 292 | + }); |
| 293 | + expect(screen.events).toEqual(["start:/a", "start:/b", "start:/b"]); |
| 294 | + // A late old-project result cannot replace the current environment's checkout. |
| 295 | + await screen.emit("/a", "stale-branch"); |
| 296 | + expect(screen.current.currentCheckoutBranchName).toBe("main"); |
| 297 | + expect(screen.snapshot(draftKey).workspaceSelection).toBeUndefined(); |
| 298 | + act(() => screen.current.setWorkspaceMode("worktree")); |
| 299 | + act(() => |
| 300 | + screen.current.selectBranch({ |
| 301 | + name: "feature", |
| 302 | + current: false, |
| 303 | + isDefault: false, |
| 304 | + worktreePath: null, |
| 305 | + }), |
| 306 | + ); |
| 307 | + act(() => screen.current.setStartFromOrigin(true)); |
| 308 | + const chosenWorkspace = screen.snapshot(draftKey).workspaceSelection; |
| 309 | + expect(chosenWorkspace).toEqual({ |
| 310 | + mode: "worktree", |
| 311 | + branch: "feature", |
| 312 | + worktreePath: null, |
| 313 | + startFromOrigin: true, |
| 314 | + }); |
| 315 | + |
| 316 | + await screen.render(false); |
| 317 | + const settingsWrites = mocks.writeSettings.mock.calls.length; |
| 318 | + await screen.expireIdle(); |
| 319 | + expect.soft(screen.events.filter((event) => event.startsWith("stop:"))).toHaveLength(3); |
| 320 | + expect(mocks.writeSettings).toHaveBeenCalledTimes(settingsWrites); |
| 321 | + expect(screen.snapshot(draftKey).workspaceSelection).toEqual(chosenWorkspace); |
| 322 | + expect(screen.current.prompt).toBe("keep this draft"); |
| 323 | + |
| 324 | + screen.checkout("updated-checkout"); |
| 325 | + await screen.render(true); |
| 326 | + expect.soft(screen.events.filter((event) => event.startsWith("start:"))).toHaveLength(4); |
| 327 | + expect.soft(screen.current.currentCheckoutBranchName).toBe("updated-checkout"); |
| 328 | + expect(screen.current.prompt).toBe("keep this draft"); |
| 329 | + expect(screen.snapshot(draftKey).workspaceSelection).toEqual(chosenWorkspace); |
| 330 | +}); |
| 331 | + |
| 332 | +it("does not persist a provisional workspace default after releasing inactive status", async () => { |
| 333 | + using screen = setup(); |
| 334 | + await screen.render(true); |
| 335 | + await screen.emit("/a", "main", false); |
| 336 | + const draftKey = screen.current.draftKey!; |
| 337 | + screen.clearWorkspace(draftKey); |
| 338 | + mocks.writeSettings.mockClear(); |
| 339 | + expect(screen.snapshot(draftKey).workspaceSelection).toBeUndefined(); |
| 340 | + await screen.render(false); |
| 341 | + expect(screen.snapshot(draftKey).workspaceSelection).toBeUndefined(); |
| 342 | + expect(mocks.writeSettings).not.toHaveBeenCalled(); |
| 343 | + await screen.expireIdle(); |
| 344 | + screen.holdStatus(); |
| 345 | + await screen.render(true); |
| 346 | + expect(screen.snapshot(draftKey).workspaceSelection).toBeUndefined(); |
| 347 | + await screen.emit("/a", "main", false); |
| 348 | + expect(screen.snapshot(draftKey).workspaceSelection).toBeUndefined(); |
| 349 | + expect(mocks.writeSettings).not.toHaveBeenCalled(); |
| 350 | +}); |
| 351 | + |
| 352 | +it("uses cached repository capability and branch defaults while offline", async () => { |
| 353 | + using screen = setup(); |
| 354 | + screen.offline(); |
| 355 | + await screen.render(true); |
| 356 | + expect(screen.current.currentCheckoutBranchName).toBeNull(); |
| 357 | + expect(screen.current.isGitRepoKnown).toBe(true); |
| 358 | + expect(screen.current.workspaceMode).toBe("worktree"); |
| 359 | + expect(screen.current.selectedBranchName).toBe("main"); |
| 360 | + const draftKey = screen.current.draftKey!; |
| 361 | + expect(screen.snapshot(draftKey).workspaceSelection).toBeUndefined(); |
| 362 | + await screen.render(false); |
| 363 | + await screen.expireIdle(); |
| 364 | + await screen.render(true); |
| 365 | + expect(screen.current.draftKey).toBe(draftKey); |
| 366 | + expect(screen.current.selectedBranchName).toBe("main"); |
| 367 | +}); |
0 commit comments