The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { ThreadId, type ProjectId, type TerminalCwdNotFoundError } from "@t3tools/contracts"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import * as Layer from "effect/Layer"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Path from "effect/Path"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | |
| 10 | import * as ServerConfig from "../config.ts"; |
| 11 | import * as GitWorkflowService from "../git/GitWorkflowService.ts"; |
| 12 | import { scratchFolderRoot } from "../project/ManagedProjectFolders.ts"; |
| 13 | import * as ProjectService from "../project/ProjectService.ts"; |
| 14 | import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; |
| 15 | import { isWithinRoot } from "./KnownWorkspaces.ts"; |
| 16 | import { withWorkspaceLease } from "./workspaceLease.ts"; |
| 17 | import { TerminalCwdRecovery } from "../terminal/Manager.ts"; |
| 18 | |
| 19 | export class WorktreeRecreateError extends Schema.TaggedError<WorktreeRecreateError>()( |
| 20 | "WorktreeRecreateError", |
| 21 | { |
| 22 | worktreePath: Schema.String, |
| 23 | branch: Schema.String, |
| 24 | cause: Schema.Defect(), |
| 25 | }, |
| 26 | ) { |
| 27 | override get message(): string { |
| 28 | return `Could not recreate the worktree for branch '${this.branch}' at ${this.worktreePath}.`; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | class WorktreeRecreateNoBaseError extends Schema.TaggedError<WorktreeRecreateNoBaseError>()( |
| 33 | "WorktreeRecreateNoBaseError", |
| 34 | { worktreePath: Schema.String, branch: Schema.String }, |
| 35 | ) { |
| 36 | override get message(): string { |
| 37 | return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // `git worktree remove` skips pnpm junctions on Windows, leaving these behind without a checkout. |
| 42 | const LEFTOVER_WORKTREE_ENTRIES = new Set(["node_modules", ".next"]); |
| 43 | |
| 44 | interface WorktreeThread { |
| 45 | readonly id: ThreadId; |
| 46 | readonly projectId: ProjectId; |
| 47 | readonly worktreePath: string | null; |
| 48 | readonly branch: string | null; |
| 49 | } |
| 50 | |
| 51 | export const makeRestoreMissingWorktree = Effect.gen(function* () { |
| 52 | const fileSystem = yield* FileSystem.FileSystem; |
| 53 | const path = yield* Path.Path; |
| 54 | const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; |
| 55 | const projects = yield* ProjectService.ProjectService; |
| 56 | const isManagedWorktreePath = yield* makeIsManagedWorktreePath; |
| 57 | const serverConfig = yield* ServerConfig.ServerConfig; |
| 58 | |
| 59 | // Storage cleanup prunes idle No project folders, which have no branch to restore from. |
| 60 | // An empty folder, only directly inside the No project's own root, lets the thread run again. |
| 61 | const recreateScratchFolder = Effect.fn("restoreMissingWorktree.recreateScratchFolder")( |
| 62 | function* (thread: WorktreeThread, folder: string) { |
| 63 | if (path.resolve(folder) !== folder || (yield* fileSystem.exists(folder))) return; |
| 64 | const project = Option.getOrUndefined(yield* projects.getById(thread.projectId)); |
| 65 | if (project === undefined || path.dirname(folder) !== path.resolve(project.workspaceRoot)) |
| 66 | return; |
| 67 | const root = scratchFolderRoot(serverConfig.baseDir, path); |
| 68 | const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); |
| 69 | if (path.dirname(folder) !== root && path.dirname(folder) !== realRoot) return; |
| 70 | yield* Effect.logWarning("recreating missing scratch folder", { |
| 71 | threadId: thread.id, |
| 72 | folder, |
| 73 | }); |
| 74 | yield* fileSystem.makeDirectory(folder, { recursive: true }); |
| 75 | }, |
| 76 | // Turn start reports a folder that is still missing. |
| 77 | Effect.orElseSucceed(() => undefined), |
| 78 | ); |
| 79 | |
| 80 | // Only folders holding nothing but leftovers are cleared, never user files. |
| 81 | const isLeftoverFolder = (worktreePath: string) => |
| 82 | fileSystem.exists(path.join(worktreePath, ".git")).pipe( |
| 83 | Effect.flatMap((hasGit) => |
| 84 | hasGit |
| 85 | ? Effect.succeed(false) |
| 86 | : fileSystem.readDirectory(worktreePath).pipe( |
| 87 | Effect.flatMap((entries) => |
| 88 | Effect.forEach(entries, (entry) => |
| 89 | LEFTOVER_WORKTREE_ENTRIES.has(entry) |
| 90 | ? fileSystem |
| 91 | .stat(path.join(worktreePath, entry)) |
| 92 | .pipe(Effect.map((info) => info.type === "Directory")) |
| 93 | : Effect.succeed(false), |
| 94 | ), |
| 95 | ), |
| 96 | Effect.map((leftovers) => leftovers.every(Boolean)), |
| 97 | ), |
| 98 | ), |
| 99 | Effect.orElseSucceed(() => false), |
| 100 | ); |
| 101 | |
| 102 | const resolveRecreateBase = Effect.fn("restoreMissingWorktree.resolveRecreateBase")(function* ( |
| 103 | cwd: string, |
| 104 | remoteName: string | null, |
| 105 | ) { |
| 106 | // Recovery can follow an external checkout, before the status cache expires. |
| 107 | yield* gitWorkflow.invalidateLocalStatus(cwd); |
| 108 | const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd }); |
| 109 | if (currentBranch !== null) { |
| 110 | const refName = `refs/heads/${currentBranch}`; |
| 111 | return { refName, baseRefName: refName }; |
| 112 | } |
| 113 | const remoteHead = `refs/remotes/${remoteName}/HEAD`; |
| 114 | if (remoteName !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: remoteHead }))) { |
| 115 | const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({ |
| 116 | cwd, |
| 117 | refName: "HEAD", |
| 118 | fallbackRemoteName: remoteName, |
| 119 | }); |
| 120 | // Start from the commit so the thread branch does not track the default branch. |
| 121 | return { refName: commitSha, baseRefName: remoteHead }; |
| 122 | } |
| 123 | if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) { |
| 124 | return { refName: "HEAD", baseRefName: undefined }; |
| 125 | } |
| 126 | return null; |
| 127 | }); |
| 128 | |
| 129 | const recreateMissingWorktree = Effect.fn("restoreMissingWorktree.recreate")(function* (input: { |
| 130 | readonly cwd: string; |
| 131 | readonly worktreePath: string; |
| 132 | readonly branch: string; |
| 133 | }) { |
| 134 | const { cwd, worktreePath, branch } = input; |
| 135 | yield* gitWorkflow.pruneWorktrees({ cwd }); |
| 136 | const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd); |
| 137 | if (localBranchNames.includes(branch)) { |
| 138 | yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath }); |
| 139 | return; |
| 140 | } |
| 141 | const remoteName = yield* gitWorkflow |
| 142 | .resolvePrimaryRemoteName(cwd) |
| 143 | .pipe(Effect.orElseSucceed(() => null)); |
| 144 | // Push keeps the tracking ref current, so recovery reads it without fetching. |
| 145 | const pushedRef = remoteName === null ? null : `refs/remotes/${remoteName}/${branch}`; |
| 146 | if (pushedRef !== null && (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef }))) { |
| 147 | yield* gitWorkflow.createWorktree({ |
| 148 | cwd, |
| 149 | refName: pushedRef, |
| 150 | newRefName: branch, |
| 151 | path: worktreePath, |
| 152 | }); |
| 153 | return; |
| 154 | } |
| 155 | const base = yield* resolveRecreateBase(cwd, remoteName); |
| 156 | if (base === null) { |
| 157 | return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch }); |
| 158 | } |
| 159 | yield* gitWorkflow.createWorktree({ |
| 160 | cwd, |
| 161 | refName: base.refName, |
| 162 | newRefName: branch, |
| 163 | ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }), |
| 164 | path: worktreePath, |
| 165 | }); |
| 166 | }); |
| 167 | |
| 168 | return Effect.fn("restoreMissingWorktree")(function* (thread: WorktreeThread) { |
| 169 | const { worktreePath, branch } = thread; |
| 170 | if (worktreePath === null) return; |
| 171 | if (branch === null) return yield* recreateScratchFolder(thread, worktreePath); |
| 172 | const exists = yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true)); |
| 173 | const leftover = exists && (yield* isLeftoverFolder(worktreePath)); |
| 174 | if ((exists && !leftover) || !(yield* isManagedWorktreePath(worktreePath))) return; |
| 175 | const project = yield* projects.getById(thread.projectId).pipe( |
| 176 | Effect.map(Option.getOrUndefined), |
| 177 | Effect.orElseSucceed(() => undefined), |
| 178 | ); |
| 179 | if (project === undefined) return; |
| 180 | yield* Effect.logWarning("recreating missing worktree", { |
| 181 | threadId: thread.id, |
| 182 | worktreePath, |
| 183 | branch, |
| 184 | }); |
| 185 | // `git worktree add` refuses a non-empty target but accepts an empty one. Keep the folder |
| 186 | // itself: Windows cannot remove a folder that is still a terminal's or provider's cwd. |
| 187 | const clearLeftovers = Effect.suspend(() => fileSystem.readDirectory(worktreePath)).pipe( |
| 188 | Effect.flatMap((entries) => |
| 189 | Effect.forEach( |
| 190 | entries, |
| 191 | (entry) => fileSystem.remove(path.join(worktreePath, entry), { recursive: true }), |
| 192 | { discard: true }, |
| 193 | ), |
| 194 | ), |
| 195 | ); |
| 196 | yield* (leftover ? clearLeftovers : Effect.void).pipe( |
| 197 | Effect.andThen(recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch })), |
| 198 | Effect.mapError((cause) => |
| 199 | cause._tag === "WorktreeRecreateNoBaseError" |
| 200 | ? cause |
| 201 | : new WorktreeRecreateError({ worktreePath, branch, cause }), |
| 202 | ), |
| 203 | ); |
| 204 | }); |
| 205 | }); |
| 206 | |
| 207 | export class ThreadWorktreeRestore extends Context.Service< |
| 208 | ThreadWorktreeRestore, |
| 209 | { |
| 210 | readonly restore: ( |
| 211 | thread: WorktreeThread, |
| 212 | ) => Effect.Effect<void, WorktreeRecreateError | WorktreeRecreateNoBaseError>; |
| 213 | } |
| 214 | >()("t3/workspace/restoreMissingWorktree/ThreadWorktreeRestore") {} |
| 215 | |
| 216 | // Turn start restores under the same lease, so concurrent restores see each other's worktree. |
| 217 | export const layerThreadWorktreeRestore = Layer.effect( |
| 218 | ThreadWorktreeRestore, |
| 219 | Effect.gen(function* () { |
| 220 | const path = yield* Path.Path; |
| 221 | const restore = yield* makeRestoreMissingWorktree; |
| 222 | return { |
| 223 | restore: Effect.fn("ThreadWorktreeRestore.restore")(function* (thread: WorktreeThread) { |
| 224 | return yield* thread.worktreePath === null |
| 225 | ? restore(thread) |
| 226 | : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)); |
| 227 | }), |
| 228 | }; |
| 229 | }), |
| 230 | ); |
| 231 | |
| 232 | // Worktree setup uses terminals, so recovery must stay outside TerminalManager. |
| 233 | export const makePrepareTerminalLaunch = Effect.fn( |
| 234 | "restoreMissingWorktree.makePrepareTerminalLaunch", |
| 235 | )(function* <LookupError>( |
| 236 | getThreadShell: (threadId: ThreadId) => Effect.Effect<WorktreeThread | null, LookupError>, |
| 237 | ) { |
| 238 | const path = yield* Path.Path; |
| 239 | const restoreMissingWorktree = yield* makeRestoreMissingWorktree; |
| 240 | return Effect.fn("restoreMissingWorktree.prepareTerminalLaunch")(function* < |
| 241 | Input extends { |
| 242 | readonly threadId: string; |
| 243 | readonly cwd?: string | undefined; |
| 244 | readonly worktreePath?: string | null | undefined; |
| 245 | }, |
| 246 | >(input: Input) { |
| 247 | const thread = yield* getThreadShell(ThreadId.make(input.threadId)).pipe( |
| 248 | Effect.orElseSucceed(() => null), |
| 249 | ); |
| 250 | const worktreePath = thread?.worktreePath ?? null; |
| 251 | if ( |
| 252 | thread === null || |
| 253 | worktreePath === null || |
| 254 | !isWithinRoot(path, path.resolve(input.cwd ?? worktreePath), worktreePath) |
| 255 | ) { |
| 256 | return { input, recover: TerminalCwdRecovery.defaultValue() }; |
| 257 | } |
| 258 | const recover = (error: TerminalCwdNotFoundError) => |
| 259 | restoreMissingWorktree(thread).pipe( |
| 260 | Effect.catch((cause) => |
| 261 | Effect.logWarning("failed to recreate missing worktree", { |
| 262 | threadId: thread.id, |
| 263 | worktreePath, |
| 264 | cause, |
| 265 | }).pipe(Effect.andThen(Effect.fail(error))), |
| 266 | ), |
| 267 | ); |
| 268 | // The lease must cover the worktree root, even when the terminal opens in a subdirectory. |
| 269 | return { input: { ...input, worktreePath }, recover }; |
| 270 | }); |
| 271 | }); |