| author | |
| committer | |
| log | 4bf7386b8ac43d8c776938af98f4e158f7978df4 |
| tree | e4022118cdfe44aebf9e7b28ae363e029c00b251 |
| parent | 8bbd97c04639eff54ad60257e3122f4cc940cff8 |
| signature | Signed by SSH key SHA256:cOKiuRFOeSRxne6EWgHtdQQSlBxjOXm2hOCFnCdLQbQ |
Assisted-by: gpt-6.1-sol18 files changed, 2319 insertions(+), 11 deletions(-)
modules/shared/default.nix+1| ... | @@ -10,6 +10,7 @@ | ... | @@ -10,6 +10,7 @@ |
| 10 | # install neovim globally, but let home-manager install | 10 | # install neovim globally, but let home-manager install |
| 11 | # the per-user configured one. | 11 | # the per-user configured one. |
| 12 | environment.systemPackages = [ | 12 | environment.systemPackages = [ |
| 13 | pkgs.ncdu | ||
| 13 | pkgs.neovim | 14 | pkgs.neovim |
| 14 | ]; | 15 | ]; |
| 15 | } | 16 | } |
users/clover/agents/AGENTS.md+19-7| ... | @@ -22,11 +22,22 @@ should be derived, not stored. A field written only to appease a type and never | ... | @@ -22,11 +22,22 @@ should be derived, not stored. A field written only to appease a type and never |
| 22 | read gets nuked. A cast must constrain real runtime behavior; one that survives | 22 | read gets nuked. A cast must constrain real runtime behavior; one that survives |
| 23 | is localized and justified by an actual API boundary. | 23 | is localized and justified by an actual API boundary. |
| 24 | 24 | ||
| 25 | Before adding compatibility code, a backfill, or a migration fallback, establish | ||
| 26 | whether the affected data or contract has shipped. An open or draft PR alone is | ||
| 27 | not evidence of deployment. Treat the user's statement that it is unshipped as | ||
| 28 | authoritative. For disposable local state, prefer resetting the local database | ||
| 29 | and implementing the final shape directly. Preserve deployed contracts; do not | ||
| 30 | build transition paths for hypothetical consumers or local test data. | ||
| 31 | |||
| 25 | Before calling a change done, do a cleanup pass: fewer names, branches, casts, | 32 | Before calling a change done, do a cleanup pass: fewer names, branches, casts, |
| 26 | public API promises. Ship the smaller locked-in version. Thinking, running, and | 33 | public API promises. Ship the smaller locked-in version. Thinking, running, and |
| 27 | verifying longer to land a correct answer is expected -- "should work" is a | 34 | verifying longer to land a correct answer is expected -- "should work" is a |
| 28 | hypothesis, and say so. | 35 | hypothesis, and say so. |
| 29 | 36 | ||
| 37 | Fewer moving parts never means fewer lines. Separate a function's steps with | ||
| 38 | blank lines, and name a deeply nested expression in a `const` above its use. | ||
| 39 | Code will be read and should be kept tidy for human and other agentic reviewers. | ||
| 40 | |||
| 30 | ### Comments | 41 | ### Comments |
| 31 | 42 | ||
| 32 | Default to no comment; names, types, and structure carry the meaning. One earns | 43 | Default to no comment; names, types, and structure carry the meaning. One earns |
| ... | @@ -150,14 +161,15 @@ regret missing, never mere emphasis. Usually zero per message, never two. | ... | @@ -150,14 +161,15 @@ regret missing, never mere emphasis. Usually zero per message, never two. |
| 150 | 4. Solve merge conflicts if any arise following "solve all merge conflicts" | 161 | 4. Solve merge conflicts if any arise following "solve all merge conflicts" |
| 151 | rules. | 162 | rules. |
| 152 | - When I say "describe" or "tag" a change, i mean to set it's description with | 163 | - When I say "describe" or "tag" a change, i mean to set it's description with |
| 153 | `jj desc -m '...'` | 164 | `jj desc -m '...'`. Lean on doing this by default. Before a task, feel free to |
| 154 | - When I say to "open the PR", i mean to make sure this change is up to date | 165 | tag the change with a `WIP: feat: ...` or something alike, or if unsure a |
| 155 | with main (with a `jj git fetch`), ensure a description exists, and then use | 166 | general topic line that evolves as you work `WIP: tuning search engine`. |
| 156 | `jj git push -c @` to push the change. then run `open` on the resulting PR if | ||
| 157 | the push command gave one. | ||
| 158 | - Never add `Co-authored-by: <Model>` trailer, always add `Assisted-by: <Model>` | 167 | - Never add `Co-authored-by: <Model>` trailer, always add `Assisted-by: <Model>` |
| 159 | in this format `claude-opus-4.8` / `gpt-5.6-sol` / `qwen-3.8-27b` / etc. If | 168 | in this format `claude-opus-5.5` / `gpt-6.1-sol` / `glm-5.3` / etc. If you |
| 160 | you think you are `gpt-5`, the variant is probably `gpt-5.6-sol`. | 169 | think you are `gpt-6`, the variant is likely `gpt-6.1-sol`. When multiple |
| 170 | models collaborate, be sure to credit all of them. | ||
| 171 | - If the prompt mentions "ChatGPT Dot" or a task referred from a "Lilac" agent, | ||
| 172 | add `Assisted-by: chatgpt-dot:lilac` as the last credit. | ||
| 161 | 173 | ||
| 162 | ## Personal | 174 | ## Personal |
| 163 | 175 |
users/clover/codex-config.toml+9-2| ... | @@ -99,7 +99,7 @@ matcher = "startup|resume|clear|compact" | ... | @@ -99,7 +99,7 @@ matcher = "startup|resume|clear|compact" |
| 99 | 99 | ||
| 100 | [[hooks.SessionStart.hooks]] | 100 | [[hooks.SessionStart.hooks]] |
| 101 | type = "command" | 101 | type = "command" |
| 102 | command = "python3 ~/config/users/clover/agents/codex-memory-hook.py" | 102 | command = "codex-memory" |
| 103 | timeout = 5 | 103 | timeout = 5 |
| 104 | additionalContextLimit = 20000 | 104 | additionalContextLimit = 20000 |
| 105 | 105 | ||
| ... | @@ -107,10 +107,17 @@ additionalContextLimit = 20000 | ... | @@ -107,10 +107,17 @@ additionalContextLimit = 20000 |
| 107 | 107 | ||
| 108 | [[hooks.SubagentStart.hooks]] | 108 | [[hooks.SubagentStart.hooks]] |
| 109 | type = "command" | 109 | type = "command" |
| 110 | command = "python3 ~/config/users/clover/agents/codex-memory-hook.py" | 110 | command = "codex-memory" |
| 111 | timeout = 5 | 111 | timeout = 5 |
| 112 | additionalContextLimit = 20000 | 112 | additionalContextLimit = 20000 |
| 113 | 113 | ||
| 114 | [[hooks.UserPromptSubmit]] | ||
| 115 | |||
| 116 | [[hooks.UserPromptSubmit.hooks]] | ||
| 117 | type = "command" | ||
| 118 | command = "agent-linear prompt" | ||
| 119 | timeout = 60 | ||
| 120 | |||
| 114 | [tui] | 121 | [tui] |
| 115 | show_tooltips = false | 122 | show_tooltips = false |
| 116 | status_line = ["model", "reasoning", "run-state", "weekly-limit", "used-tokens"] | 123 | status_line = ["model", "reasoning", "run-state", "weekly-limit", "used-tokens"] |
users/clover/configuration.nix+1| ... | @@ -55,6 +55,7 @@ in | ... | @@ -55,6 +55,7 @@ in |
| 55 | InitialKeyRepeat = 10; | 55 | InitialKeyRepeat = 10; |
| 56 | }; | 56 | }; |
| 57 | dock = { | 57 | dock = { |
| 58 | autohide-delay = 0.2; | ||
| 58 | show-recents = false; | 59 | show-recents = false; |
| 59 | expose-group-apps = false; | 60 | expose-group-apps = false; |
| 60 | }; | 61 | }; |
users/clover/home.nix+27| ... | @@ -35,6 +35,9 @@ in | ... | @@ -35,6 +35,9 @@ in |
| 35 | pnpm | 35 | pnpm |
| 36 | nodejs_26 | 36 | nodejs_26 |
| 37 | (callPackage ./packages/agent-linear { }) | 37 | (callPackage ./packages/agent-linear { }) |
| 38 | (writeShellScriptBin "codex-memory" '' | ||
| 39 | exec ${pkgs.python3}/bin/python3 ${./agents/codex-memory-hook.py} | ||
| 40 | '') | ||
| 38 | # `open` shim that routes URLs into the VS Code Simple Browser; see | 41 | # `open` shim that routes URLs into the VS Code Simple Browser; see |
| 39 | # the home.file symlink for the companion extension. | 42 | # the home.file symlink for the companion extension. |
| 40 | (callPackage ./packages/open-in-vscode-browser { }) | 43 | (callPackage ./packages/open-in-vscode-browser { }) |
| ... | @@ -110,6 +113,30 @@ in | ... | @@ -110,6 +113,30 @@ in |
| 110 | fi | 113 | fi |
| 111 | ''; | 114 | ''; |
| 112 | 115 | ||
| 116 | home.activation.claudeLinearHook = lib.hm.dag.entryAfter [ "writeBoundary" ] '' | ||
| 117 | run ${pkgs.nodejs}/bin/node <<'NODE' | ||
| 118 | const fs = require("node:fs"); | ||
| 119 | const path = require("node:path"); | ||
| 120 | const file = ${builtins.toJSON "${config.home.homeDirectory}/.claude/settings.json"}; | ||
| 121 | const settings = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : {}; | ||
| 122 | const hook = { type: "command", command: "agent-linear prompt", timeout: 60 }; | ||
| 123 | const groups = (settings.hooks ??= {}).UserPromptSubmit ??= []; | ||
| 124 | const existing = groups.flatMap(group => group.hooks).find(item => item.command === hook.command); | ||
| 125 | if (existing) { | ||
| 126 | Object.assign(existing, hook); | ||
| 127 | } else { | ||
| 128 | groups.push({ hooks: [hook] }); | ||
| 129 | } | ||
| 130 | const contents = JSON.stringify(settings, null, 2) + "\n"; | ||
| 131 | if (!fs.existsSync(file) || fs.readFileSync(file, "utf8") !== contents) { | ||
| 132 | fs.mkdirSync(path.dirname(file), { recursive: true }); | ||
| 133 | const temporary = file + ".linear-hook.tmp"; | ||
| 134 | fs.writeFileSync(temporary, contents, { mode: fs.existsSync(file) ? fs.statSync(file).mode & 0o777 : 0o600 }); | ||
| 135 | fs.renameSync(temporary, file); | ||
| 136 | } | ||
| 137 | NODE | ||
| 138 | ''; | ||
| 139 | |||
| 113 | # Referenced by the `statusLine.command` entry in ~/.claude/settings.json, | 140 | # Referenced by the `statusLine.command` entry in ~/.claude/settings.json, |
| 114 | # which claude code rewrites itself and so stays unmanaged. | 141 | # which claude code rewrites itself and so stays unmanaged. |
| 115 | home.file.".claude/statusline-command.sh".source = | 142 | home.file.".claude/statusline-command.sh".source = |
users/clover/jujutsu.nix+19-1| ... | @@ -1,7 +1,25 @@ | ... | @@ -1,7 +1,25 @@ |
| 1 | { lib, ... }: | 1 | { lib, pkgs, ... }: |
| 2 | { | 2 | { |
| 3 | programs.jujutsu = { | 3 | programs.jujutsu = { |
| 4 | enable = true; | 4 | enable = true; |
| 5 | package = pkgs.symlinkJoin { | ||
| 6 | name = "jujutsu-linear"; | ||
| 7 | paths = [ pkgs.jujutsu ]; | ||
| 8 | inherit (pkgs.jujutsu) meta version; | ||
| 9 | postBuild = '' | ||
| 10 | rm "$out/bin/jj" | ||
| 11 | cp ${pkgs.writeShellScript "jj" '' | ||
| 12 | for arg in "$@"; do | ||
| 13 | case "$arg" in | ||
| 14 | desc|describe) | ||
| 15 | exec ${pkgs.nodejs}/bin/node ${./packages/agent-linear/agent-linear.js} jj ${pkgs.jujutsu}/bin/jj "$@" | ||
| 16 | ;; | ||
| 17 | esac | ||
| 18 | done | ||
| 19 | exec ${pkgs.jujutsu}/bin/jj "$@" | ||
| 20 | ''} "$out/bin/jj" | ||
| 21 | ''; | ||
| 22 | }; | ||
| 5 | # my workflow is based on creating changes and editing them. while they | 23 | # my workflow is based on creating changes and editing them. while they |
| 6 | # are in progress the description starts with "WIP: " | 24 | # are in progress the description starts with "WIP: " |
| 7 | settings = rec { | 25 | settings = rec { |
users/clover/packages/agent-linear/agent-linear.js+222| ... | @@ -111,11 +111,232 @@ async function main() { | ... | @@ -111,11 +111,232 @@ async function main() { |
| 111 | const options = parseIssueArgs(argv); | 111 | const options = parseIssueArgs(argv); |
| 112 | assertWorkRepo(); | 112 | assertWorkRepo(); |
| 113 | await showIssue(options); | 113 | await showIssue(options); |
| 114 | } else if (command === "jj") { | ||
| 115 | await runJj(argv); | ||
| 116 | } else if (command === "prompt") { | ||
| 117 | const event = JSON.parse(fs.readFileSync(0, "utf8")); | ||
| 118 | if (event.hook_event_name !== "UserPromptSubmit" || event.agent_id) { | ||
| 119 | return; | ||
| 120 | } | ||
| 121 | const messages = await startIssues(event.prompt, true); | ||
| 122 | if (messages.length > 0) { | ||
| 123 | writeJson({ | ||
| 124 | hookSpecificOutput: { | ||
| 125 | hookEventName: "UserPromptSubmit", | ||
| 126 | additionalContext: messages.join("\n"), | ||
| 127 | }, | ||
| 128 | }); | ||
| 129 | } | ||
| 114 | } else { | 130 | } else { |
| 115 | throw new Error(`unknown command ${JSON.stringify(command)}`); | 131 | throw new Error(`unknown command ${JSON.stringify(command)}`); |
| 116 | } | 132 | } |
| 117 | } | 133 | } |
| 118 | 134 | ||
| 135 | async function runJj([executable, ...argv]) { | ||
| 136 | const context = []; | ||
| 137 | const operation = []; | ||
| 138 | const revisions = []; | ||
| 139 | let command; | ||
| 140 | let positional = false; | ||
| 141 | |||
| 142 | for (let i = 0; i < argv.length; i++) { | ||
| 143 | const arg = argv[i]; | ||
| 144 | const option = arg.split("=", 1)[0]; | ||
| 145 | if (positional) { | ||
| 146 | revisions.push(arg); | ||
| 147 | continue; | ||
| 148 | } | ||
| 149 | if (arg === "--") { | ||
| 150 | positional = true; | ||
| 151 | continue; | ||
| 152 | } | ||
| 153 | if ( | ||
| 154 | [ | ||
| 155 | "-R", | ||
| 156 | "--repository", | ||
| 157 | "--config", | ||
| 158 | "--config-file", | ||
| 159 | "--color", | ||
| 160 | "--at-op", | ||
| 161 | "--at-operation", | ||
| 162 | ].includes(option) | ||
| 163 | ) { | ||
| 164 | const value = arg.includes("=") ? [] : [argv[++i]]; | ||
| 165 | if ( | ||
| 166 | ["-R", "--repository", "--config", "--config-file"].includes(option) | ||
| 167 | ) { | ||
| 168 | context.push(arg, ...value); | ||
| 169 | } else if (["--at-op", "--at-operation"].includes(option)) { | ||
| 170 | operation.push(arg, ...value); | ||
| 171 | } | ||
| 172 | } else if (arg.startsWith("-R") && arg.length > 2) { | ||
| 173 | context.push(arg); | ||
| 174 | } else if (arg === "-m" || arg === "--message") { | ||
| 175 | i++; | ||
| 176 | } else if (arg.startsWith("-r") && arg.length > 2) { | ||
| 177 | revisions.push(arg.slice(2).replace(/^=/, "")); | ||
| 178 | } else if (!arg.startsWith("-")) { | ||
| 179 | if (command) { | ||
| 180 | revisions.push(arg); | ||
| 181 | } else { | ||
| 182 | command = arg; | ||
| 183 | } | ||
| 184 | } | ||
| 185 | } | ||
| 186 | |||
| 187 | const describe = ["desc", "describe"].includes(command) && | ||
| 188 | !argv.some((arg) => | ||
| 189 | ["-h", "--help", "--no-integrate-operation"].includes(arg) | ||
| 190 | ); | ||
| 191 | |||
| 192 | function readJj(args) { | ||
| 193 | const result = child_process.spawnSync(executable, [ | ||
| 194 | ...context, | ||
| 195 | "--ignore-working-copy", | ||
| 196 | "--no-pager", | ||
| 197 | "--color=never", | ||
| 198 | ...args, | ||
| 199 | ], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }); | ||
| 200 | if (result.error || result.status !== 0) { | ||
| 201 | throw result.error ?? new Error(result.stderr.trim()); | ||
| 202 | } | ||
| 203 | return result.stdout.trim(); | ||
| 204 | } | ||
| 205 | |||
| 206 | let changes; | ||
| 207 | let hookError; | ||
| 208 | if (describe) { | ||
| 209 | try { | ||
| 210 | const revset = revisions.length > 0 | ||
| 211 | ? revisions.map((revision) => `(${revision.replace(/^all:/, "")})`) | ||
| 212 | .join(" | ") | ||
| 213 | : "@"; | ||
| 214 | changes = readJj([ | ||
| 215 | ...operation, | ||
| 216 | "log", | ||
| 217 | "--no-graph", | ||
| 218 | "-r", | ||
| 219 | revset, | ||
| 220 | "-T", | ||
| 221 | 'change_id ++ "\\n"', | ||
| 222 | ]) | ||
| 223 | .split("\n").filter(Boolean); | ||
| 224 | } catch (error) { | ||
| 225 | hookError = error; | ||
| 226 | } | ||
| 227 | } | ||
| 228 | |||
| 229 | const result = child_process.spawnSync(executable, argv, { | ||
| 230 | stdio: "inherit", | ||
| 231 | }); | ||
| 232 | if (result.error) { | ||
| 233 | throw result.error; | ||
| 234 | } | ||
| 235 | if (result.signal) { | ||
| 236 | process.kill(process.pid, result.signal); | ||
| 237 | return; | ||
| 238 | } | ||
| 239 | if (result.status !== 0 || !describe) { | ||
| 240 | process.exitCode = result.status; | ||
| 241 | return; | ||
| 242 | } | ||
| 243 | |||
| 244 | try { | ||
| 245 | if (hookError) { | ||
| 246 | throw hookError; | ||
| 247 | } | ||
| 248 | if (changes.length === 0) { | ||
| 249 | return; | ||
| 250 | } | ||
| 251 | |||
| 252 | const revset = changes.map((id) => `change_id("${id}")`).join(" | "); | ||
| 253 | const descriptions = readJj([ | ||
| 254 | "log", | ||
| 255 | "--no-graph", | ||
| 256 | "-r", | ||
| 257 | revset, | ||
| 258 | "-T", | ||
| 259 | "description", | ||
| 260 | ]); | ||
| 261 | for (const message of await startIssues(descriptions)) { | ||
| 262 | console.error(message); | ||
| 263 | } | ||
| 264 | } catch (error) { | ||
| 265 | console.error(`linear: could not read the description: ${error.message}`); | ||
| 266 | } | ||
| 267 | } | ||
| 268 | |||
| 269 | async function startIssues(text, onlyUnclaimed = false) { | ||
| 270 | const issues = new Set( | ||
| 271 | [...text.matchAll( | ||
| 272 | /(?<![a-z0-9_-])[a-z][a-z0-9]*-\d+(?![a-z0-9_-]|\.\d)/gi, | ||
| 273 | )] | ||
| 274 | .map((match) => match[0].toUpperCase()), | ||
| 275 | ); | ||
| 276 | |||
| 277 | const messages = []; | ||
| 278 | let viewer; | ||
| 279 | |||
| 280 | for (const id of issues) { | ||
| 281 | try { | ||
| 282 | const data = await linearRequest( | ||
| 283 | ` | ||
| 284 | query IssueProgress($id: String!) { | ||
| 285 | issue(id: $id) { | ||
| 286 | id | ||
| 287 | state { name } | ||
| 288 | assignee { id } | ||
| 289 | team { states { nodes { id name type } } } | ||
| 290 | } | ||
| 291 | } | ||
| 292 | `, | ||
| 293 | { id }, | ||
| 294 | ); | ||
| 295 | if (!data.issue) { | ||
| 296 | throw new Error(`${id} not found`); | ||
| 297 | } | ||
| 298 | if ( | ||
| 299 | !/^(todo|backlog)$/i.test(data.issue.state?.name ?? "") || | ||
| 300 | (onlyUnclaimed && data.issue.assignee) | ||
| 301 | ) { | ||
| 302 | continue; | ||
| 303 | } | ||
| 304 | |||
| 305 | const state = data.issue.team.states.nodes.find((state) => | ||
| 306 | state.name.toLowerCase() === "in progress" && state.type === "started" | ||
| 307 | ); | ||
| 308 | if (!state) { | ||
| 309 | throw new Error(`${id}'s team has no In Progress state`); | ||
| 310 | } | ||
| 311 | |||
| 312 | const input = { stateId: state.id }; | ||
| 313 | if (!data.issue.assignee) { | ||
| 314 | viewer ??= (await linearRequest("{ viewer { id name } }", {})).viewer; | ||
| 315 | input.assigneeId = viewer.id; | ||
| 316 | } | ||
| 317 | |||
| 318 | const updated = await linearRequest( | ||
| 319 | ` | ||
| 320 | mutation StartIssue($id: String!, $input: IssueUpdateInput!) { | ||
| 321 | issueUpdate(id: $id, input: $input) { success } | ||
| 322 | } | ||
| 323 | `, | ||
| 324 | { id: data.issue.id, input }, | ||
| 325 | ); | ||
| 326 | if (!updated.issueUpdate.success) { | ||
| 327 | throw new Error(`${id} was not updated`); | ||
| 328 | } | ||
| 329 | const assignment = input.assigneeId ? `, assigned to ${viewer.name}` : ""; | ||
| 330 | messages.push(`linear: ${id} → In Progress${assignment}`); | ||
| 331 | } catch (error) { | ||
| 332 | messages.push( | ||
| 333 | `linear: could not start ${id}: ${error.message}. Send the issue again or run jj desc to retry.`, | ||
| 334 | ); | ||
| 335 | } | ||
| 336 | } | ||
| 337 | return messages; | ||
| 338 | } | ||
| 339 | |||
| 119 | async function search(options) { | 340 | async function search(options) { |
| 120 | const found = new Map(); | 341 | const found = new Map(); |
| 121 | 342 | ||
| ... | @@ -192,6 +413,7 @@ async function linearRequest(query, variables) { | ... | @@ -192,6 +413,7 @@ async function linearRequest(query, variables) { |
| 192 | "Content-Type": "application/json", | 413 | "Content-Type": "application/json", |
| 193 | }, | 414 | }, |
| 194 | body: JSON.stringify({ query, variables }), | 415 | body: JSON.stringify({ query, variables }), |
| 416 | signal: AbortSignal.timeout(10000), | ||
| 195 | }); | 417 | }); |
| 196 | 418 | ||
| 197 | const body = await response.text(); | 419 | const body = await response.text(); |
users/clover/packages/workspaces/README.md created+83| ... | @@ -0,0 +1,83 @@ | ||
| 1 | # Workspaces | ||
| 2 | |||
| 3 | Requires macOS/APFS and T3 Code nightly with orchestrator V2. The source repo is | ||
| 4 | configured locally in `~/.config/workspaces.json`. | ||
| 5 | |||
| 6 | ```sh | ||
| 7 | ws setup /path/to/source-workspace | ||
| 8 | ws new # next available number, freshly fetched origin/main | ||
| 9 | ws new search -r some-change # ~/workspaces/search, with a fresh T3 chat | ||
| 10 | ws open search # reopen and renew the chat's claim | ||
| 11 | ws deps search # reconcile dependencies after changing revisions | ||
| 12 | ws gc --dry-run # show blockers; update grace observations | ||
| 13 | ``` | ||
| 14 | |||
| 15 | Raycast's **New Workspace** command runs `ws new --background`. Its managed script lives in | ||
| 16 | `~/.config/raycast/scripts`; register that folder in Raycast's Script Commands | ||
| 17 | settings once. Each workspace has its own T3 project, named after the source | ||
| 18 | project followed by ` | <workspace id>`, with the same logo. Additional chats | ||
| 19 | in that project use the same workspace folder. | ||
| 20 | |||
| 21 | `ws new` and `ws open` accept `--no-open` to bind the chat without navigating | ||
| 22 | the desktop app. Standard output is the workspace path; setup progress goes to | ||
| 23 | standard error. The chat opens in an empty folder before fetching or creating | ||
| 24 | the JJ workspace; `--background` returns without waiting for preparation. | ||
| 25 | Claude and Codex startup and prompt hooks wait for the workspace to be ready. | ||
| 26 | Setup failures block the prompt until `ws deps <name>` succeeds. | ||
| 27 | New chats can be opened while another workspace prepares; preparation and | ||
| 28 | cleanup share a separate lock. Local T3 authentication is cached for one | ||
| 29 | minute with a two-minute token, and renewed when the server restarts. | ||
| 30 | Background preparation writes `~/Library/Logs/workspace-<id>.log`. A failed | ||
| 31 | setup stays protected: run `ws deps <name>` and `ws open <name>` to finish it. | ||
| 32 | |||
| 33 | ```text | ||
| 34 | reserve empty folder → create and open T3 thread | ||
| 35 | → fetch origin/main → add JJ workspace → checkout → clone snapshot → pnpm install | ||
| 36 | → release waiting Claude/Codex hooks | ||
| 37 | |||
| 38 | Every 30 seconds: | ||
| 39 | unfinished setup / unsettled T3 chat / running work / VS Code / live shell cwd | ||
| 40 | → keep workspace, reset grace | ||
| 41 | no references for ≥60 seconds, with a fresh check immediately before removal | ||
| 42 | → JJ snapshot → JJ workspace forget → remove directory | ||
| 43 | unavailable API, untracked VS Code window, unreadable cwd, unexpected state | ||
| 44 | → keep workspaces, reset grace | ||
| 45 | ``` | ||
| 46 | |||
| 47 | Only registered workspaces under `~/workspaces` are collected. JJ retains | ||
| 48 | snapshotted changes; ignored files are deleted with the directory. Closing T3 | ||
| 49 | pauses cleanup. VS Code's companion extension reports live folders and documents | ||
| 50 | through a local socket; windows without a responding tracker block cleanup. | ||
| 51 | Shell hooks register workspace shells, and cleanup reads their live cwd, | ||
| 52 | including terminals opened before the hooks were installed. | ||
| 53 | |||
| 54 | Default creation fetches only `main` from `origin` and starts at `main@origin`. | ||
| 55 | An explicit `-r` skips the fetch. Source checkout files remain untouched, even | ||
| 56 | when stale. Managed checkouts update automatically; fetching does not abandon | ||
| 57 | unrelated commits in the shared repo. | ||
| 58 | |||
| 59 | The dependency key includes package manifests, the lockfile, pnpm workspace | ||
| 60 | configuration, patches, pnpm version, platform, architecture, and Node ABI. | ||
| 61 | `clonefile` shares file data without sharing writable inodes. pnpm then | ||
| 62 | regenerates launchers containing absolute paths. One cached snapshot is kept; | ||
| 63 | changing the dependency key replaces it. | ||
| 64 | |||
| 65 | Build and verify against a downloaded nightly CLI: | ||
| 66 | |||
| 67 | ```sh | ||
| 68 | cc -Wall -Wextra -Werror native.c -o /tmp/workspace-native | ||
| 69 | T3_TEST_CLI=/path/to/nightly/t3 WORKSPACE_TEST_NATIVE=/tmp/workspace-native \ | ||
| 70 | node --test --test-isolation=none workspaces.test.mjs | ||
| 71 | ``` | ||
| 72 | |||
| 73 | The lifecycle test starts an isolated nightly server, uses real JJ and pnpm, | ||
| 74 | checks clone isolation and launcher relocation, and verifies preservation of JJ | ||
| 75 | file contents after cleanup. VS Code process status is a fixture; its reference | ||
| 76 | socket and the terminal cwd probe are live. The lock test verifies overlap | ||
| 77 | rejection and release after process exit. | ||
| 78 | |||
| 79 | `workspaces-hooks.test.mjs` tests the installed Claude and Codex CLIs against | ||
| 80 | a local API stub. Set `WORKSPACE_TEST_CLAUDE`, `WORKSPACE_TEST_CODEX`, and | ||
| 81 | `WORKSPACE_TEST_HOOK_PYTHON` (Python with tomlkit). It verifies that early prompts | ||
| 82 | wait, setup failures prevent model requests, and instructions created during | ||
| 83 | preparation reach the first model request. It makes no external model calls. | ||
users/clover/packages/workspaces/configure-hooks.py created+103| ... | @@ -0,0 +1,103 @@ | ||
| 1 | import json | ||
| 2 | import os | ||
| 3 | from pathlib import Path | ||
| 4 | import select | ||
| 5 | import subprocess | ||
| 6 | import sys | ||
| 7 | |||
| 8 | import tomlkit | ||
| 9 | |||
| 10 | home = Path(sys.argv[1]) | ||
| 11 | command = sys.argv[2] | ||
| 12 | codex = sys.argv[3] | ||
| 13 | |||
| 14 | |||
| 15 | def write(file, contents): | ||
| 16 | if file.exists() and file.read_text() == contents: | ||
| 17 | return | ||
| 18 | file.parent.mkdir(parents=True, exist_ok=True) | ||
| 19 | temporary = file.with_name(file.name + ".workspace-hook.tmp") | ||
| 20 | temporary.write_text(contents) | ||
| 21 | os.chmod(temporary, file.stat().st_mode & 0o777 if file.exists() else 0o600) | ||
| 22 | os.replace(temporary, file) | ||
| 23 | |||
| 24 | |||
| 25 | for provider, filename in [("claude", "settings.json"), ("codex", "config.toml")]: | ||
| 26 | file = home / ("." + provider) / filename | ||
| 27 | if provider == "claude": | ||
| 28 | settings = json.loads(file.read_text()) if file.exists() else {} | ||
| 29 | else: | ||
| 30 | settings = tomlkit.parse(file.read_text()) if file.exists() else tomlkit.document() | ||
| 31 | |||
| 32 | if "hooks" not in settings: | ||
| 33 | settings["hooks"] = {} | ||
| 34 | for event in ["SessionStart", "UserPromptSubmit"]: | ||
| 35 | hook = { | ||
| 36 | "type": "command", "command": command, "timeout": 300, | ||
| 37 | "statusMessage": "Preparing workspace", "async": False, | ||
| 38 | } | ||
| 39 | if provider == "claude": | ||
| 40 | hook["onFailure"] = "block" | ||
| 41 | groups = settings["hooks"].get(event) | ||
| 42 | if groups is None: | ||
| 43 | settings["hooks"][event] = [{"hooks": [hook]}] | ||
| 44 | else: | ||
| 45 | existing = next((item for group in groups for item in group["hooks"] | ||
| 46 | if item.get("command") == command), None) | ||
| 47 | if existing is None: | ||
| 48 | groups.append({"hooks": [hook]}) | ||
| 49 | else: | ||
| 50 | existing.update(hook) | ||
| 51 | |||
| 52 | contents = json.dumps(settings, indent=2) + "\n" if provider == "claude" else tomlkit.dumps(settings) | ||
| 53 | write(file, contents) | ||
| 54 | |||
| 55 | if provider != "codex": | ||
| 56 | continue | ||
| 57 | |||
| 58 | with subprocess.Popen([codex, "app-server", "--stdio"], stdin=subprocess.PIPE, | ||
| 59 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0, | ||
| 60 | env={**os.environ, "CODEX_HOME": str(file.parent)}) as server: | ||
| 61 | try: | ||
| 62 | def request(request_id, method, params): | ||
| 63 | message = {"id": request_id, "method": method, "params": params} | ||
| 64 | server.stdin.write((json.dumps(message) + "\n").encode()) | ||
| 65 | while select.select([server.stdout], [], [], 15)[0]: | ||
| 66 | line = server.stdout.readline() | ||
| 67 | if not line: | ||
| 68 | break | ||
| 69 | response = json.loads(line) | ||
| 70 | if response.get("id") != request_id: | ||
| 71 | continue | ||
| 72 | if "error" in response: | ||
| 73 | raise RuntimeError(response["error"]) | ||
| 74 | return response["result"] | ||
| 75 | raise RuntimeError("Codex did not confirm workspace hook configuration") | ||
| 76 | |||
| 77 | request(1, "initialize", { | ||
| 78 | "clientInfo": {"name": "workspace-hook-installer", "version": "1"}, | ||
| 79 | "capabilities": {"experimentalApi": True}, | ||
| 80 | }) | ||
| 81 | server.stdin.write(b'{"method":"initialized"}\n') | ||
| 82 | listed = request(2, "hooks/list", {"cwds": [str(home)]}) | ||
| 83 | hooks = [hook for entry in listed["data"] for hook in entry["hooks"] | ||
| 84 | if hook.get("command") == command | ||
| 85 | and hook["eventName"] in ["sessionStart", "userPromptSubmit"] | ||
| 86 | and hook["sourcePath"] == str(file)] | ||
| 87 | if len(hooks) != 2: | ||
| 88 | raise RuntimeError("Codex did not load both workspace readiness hooks") | ||
| 89 | |||
| 90 | settings = tomlkit.parse(file.read_text()) | ||
| 91 | if "state" not in settings["hooks"]: | ||
| 92 | settings["hooks"]["state"] = {} | ||
| 93 | for hook in hooks: | ||
| 94 | settings["hooks"]["state"][hook["key"]] = { | ||
| 95 | "trusted_hash": hook["currentHash"], "enabled": True, | ||
| 96 | } | ||
| 97 | write(file, tomlkit.dumps(settings)) | ||
| 98 | finally: | ||
| 99 | server.terminate() | ||
| 100 | try: | ||
| 101 | server.wait(timeout=5) | ||
| 102 | except subprocess.TimeoutExpired: | ||
| 103 | server.kill() | ||
users/clover/packages/workspaces/default.nix created+27| ... | @@ -0,0 +1,27 @@ | ||
| 1 | { pkgs, ... }: | ||
| 2 | let | ||
| 3 | native = pkgs.runCommandCC "workspace-native" { } '' | ||
| 4 | mkdir -p $out/bin | ||
| 5 | $CC ${./native.c} -o $out/bin/workspace-native | ||
| 6 | ''; | ||
| 7 | in | ||
| 8 | pkgs.writeShellApplication { | ||
| 9 | name = "ws"; | ||
| 10 | runtimeInputs = with pkgs; [ | ||
| 11 | nodejs_26 | ||
| 12 | jujutsu | ||
| 13 | pnpm_10 | ||
| 14 | native | ||
| 15 | ]; | ||
| 16 | text = '' | ||
| 17 | if [[ "''${1-}" == ready-hook ]]; then | ||
| 18 | exec node ${./workspaces.mjs} "$@" | ||
| 19 | fi | ||
| 20 | mkdir -p "$HOME/.local/state/workspaces" | ||
| 21 | workspace_lock="$HOME/.local/state/workspaces/lock" | ||
| 22 | if [[ "''${1-}" == new ]]; then | ||
| 23 | workspace_lock="$HOME/.local/state/workspaces/creation-lock" | ||
| 24 | fi | ||
| 25 | exec workspace-native lock "$workspace_lock" node ${./workspaces.mjs} "$@" | ||
| 26 | ''; | ||
| 27 | } | ||
users/clover/packages/workspaces/extension/extension.js created+33| ... | @@ -0,0 +1,33 @@ | ||
| 1 | const vscode = require("vscode"); | ||
| 2 | const fs = require("node:fs"); | ||
| 3 | const net = require("node:net"); | ||
| 4 | const os = require("node:os"); | ||
| 5 | const path = require("node:path"); | ||
| 6 | |||
| 7 | function activate(context) { | ||
| 8 | const directory = path.join(os.homedir(), ".local/state/workspaces/vscode"); | ||
| 9 | fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); | ||
| 10 | const socket = path.join(directory, `${process.pid}.sock`); | ||
| 11 | fs.rmSync(socket, { force: true }); | ||
| 12 | |||
| 13 | const server = net.createServer((client) => { | ||
| 14 | const uris = [ | ||
| 15 | ...(vscode.workspace.workspaceFolders ?? []).map((folder) => folder.uri), | ||
| 16 | ...vscode.workspace.textDocuments.map((document) => document.uri), | ||
| 17 | vscode.workspace.workspaceFile, | ||
| 18 | ]; | ||
| 19 | const paths = uris.filter((uri) => uri?.scheme === "file").map((uri) => | ||
| 20 | uri.fsPath | ||
| 21 | ); | ||
| 22 | client.end(JSON.stringify({ pid: process.pid, paths }) + "\n"); | ||
| 23 | }); | ||
| 24 | server.listen(socket); | ||
| 25 | context.subscriptions.push({ | ||
| 26 | dispose() { | ||
| 27 | server.close(); | ||
| 28 | fs.rmSync(socket, { force: true }); | ||
| 29 | }, | ||
| 30 | }); | ||
| 31 | } | ||
| 32 | |||
| 33 | module.exports = { activate }; | ||
users/clover/packages/workspaces/extension/package.json created+12| ... | @@ -0,0 +1,12 @@ | ||
| 1 | { | ||
| 2 | "name": "workspace-references", | ||
| 3 | "displayName": "Workspace References", | ||
| 4 | "description": "Keeps open VS Code folders safe from workspace cleanup.", | ||
| 5 | "publisher": "clover", | ||
| 6 | "version": "0.0.1", | ||
| 7 | "engines": { "vscode": "^1.74.0" }, | ||
| 8 | "main": "./extension.js", | ||
| 9 | "extensionKind": ["ui"], | ||
| 10 | "activationEvents": ["*"], | ||
| 11 | "capabilities": { "untrustedWorkspaces": { "supported": true } } | ||
| 12 | } | ||
users/clover/packages/workspaces/native.c created+39| ... | @@ -0,0 +1,39 @@ | ||
| 1 | #include <errno.h> | ||
| 2 | #include <fcntl.h> | ||
| 3 | #include <stdio.h> | ||
| 4 | #include <string.h> | ||
| 5 | #include <sys/clonefile.h> | ||
| 6 | #include <sys/file.h> | ||
| 7 | #include <unistd.h> | ||
| 8 | |||
| 9 | int main(int argc, char **argv) { | ||
| 10 | if (argc >= 4 && (strcmp(argv[1], "lock") == 0 || | ||
| 11 | strcmp(argv[1], "wait-lock") == 0)) { | ||
| 12 | int fd = open(argv[2], O_CREAT | O_RDWR, 0600); | ||
| 13 | if (fd < 0) { | ||
| 14 | perror("Cannot open workspace lock"); | ||
| 15 | return 1; | ||
| 16 | } | ||
| 17 | int flags = LOCK_EX | (strcmp(argv[1], "lock") == 0 ? LOCK_NB : 0); | ||
| 18 | if (flock(fd, flags) < 0) { | ||
| 19 | if (errno != EWOULDBLOCK) { | ||
| 20 | perror("Cannot lock workspaces"); | ||
| 21 | return 1; | ||
| 22 | } | ||
| 23 | fprintf( | ||
| 24 | stderr, | ||
| 25 | "Another workspace command is running. Retry when it finishes.\n"); | ||
| 26 | return 1; | ||
| 27 | } | ||
| 28 | execvp(argv[3], argv + 3); | ||
| 29 | perror("Cannot start workspace command"); | ||
| 30 | return 1; | ||
| 31 | } | ||
| 32 | if (argc != 4 || strcmp(argv[1], "clone") != 0) | ||
| 33 | return 2; | ||
| 34 | if (clonefile(argv[2], argv[3], | ||
| 35 | CLONE_NOFOLLOW | CLONE_NOOWNERCOPY | CLONE_ACL) == 0) | ||
| 36 | return 0; | ||
| 37 | perror("Cannot clone dependencies"); | ||
| 38 | return 1; | ||
| 39 | } | ||
users/clover/packages/workspaces/shell.zsh created+15| ... | @@ -0,0 +1,15 @@ | ||
| 1 | function _workspace_reference() { | ||
| 2 | local directory="$HOME/.local/state/workspaces/shells" | ||
| 3 | if [[ "$PWD" == "$HOME/workspaces/"* ]]; then | ||
| 4 | mkdir -p "$directory" | ||
| 5 | print -r -- "$PWD" > "$directory/$$" | ||
| 6 | else | ||
| 7 | [[ ! -e "$directory/$$" ]] || rm -f "$directory/$$" | ||
| 8 | fi | ||
| 9 | } | ||
| 10 | |||
| 11 | autoload -Uz add-zsh-hook | ||
| 12 | add-zsh-hook chpwd _workspace_reference | ||
| 13 | add-zsh-hook precmd _workspace_reference | ||
| 14 | add-zsh-hook preexec _workspace_reference | ||
| 15 | _workspace_reference | ||
users/clover/packages/workspaces/workspaces-hooks.test.mjs created+144| ... | @@ -0,0 +1,144 @@ | ||
| 1 | import assert from "node:assert/strict"; | ||
| 2 | import { test } from "node:test"; | ||
| 3 | import fs from "node:fs"; | ||
| 4 | import path from "node:path"; | ||
| 5 | import http from "node:http"; | ||
| 6 | import childProcess from "node:child_process"; | ||
| 7 | import { once } from "node:events"; | ||
| 8 | import { fileURLToPath } from "node:url"; | ||
| 9 | |||
| 10 | const script = fileURLToPath(new URL("./workspaces.mjs", import.meta.url)); | ||
| 11 | const installer = fileURLToPath(new URL("./configure-hooks.py", import.meta.url)); | ||
| 12 | const python = process.env.WORKSPACE_TEST_HOOK_PYTHON; | ||
| 13 | |||
| 14 | for (const provider of ["codex", "claude"]) { | ||
| 15 | const executable = process.env[`WORKSPACE_TEST_${provider.toUpperCase()}`]; | ||
| 16 | test(`${provider} holds a real prompt until preparation, including repository instructions`, { | ||
| 17 | skip: !executable || !python, | ||
| 18 | timeout: 45_000, | ||
| 19 | }, async () => { | ||
| 20 | const home = fs.realpathSync(fs.mkdtempSync("/tmp/workspaces-hooks-")); | ||
| 21 | const workspace = path.join(home, "workspaces/pending"); | ||
| 22 | const record = path.join(home, ".local/state/workspaces/workspaces/pending.json"); | ||
| 23 | fs.mkdirSync(workspace, { recursive: true }); | ||
| 24 | fs.mkdirSync(path.dirname(record), { recursive: true }); | ||
| 25 | fs.writeFileSync(record, JSON.stringify({ prepared: false })); | ||
| 26 | |||
| 27 | const invoked = path.join(home, "hook-invoked"); | ||
| 28 | const wrapper = path.join(home, "hook.mjs"); | ||
| 29 | fs.writeFileSync(wrapper, `import fs from "node:fs"; | ||
| 30 | import childProcess from "node:child_process"; | ||
| 31 | fs.writeFileSync(${JSON.stringify(invoked)}, "started"); | ||
| 32 | const child = childProcess.spawn(process.execPath, [${JSON.stringify(script)}, "ready-hook"], { stdio: "inherit" }); | ||
| 33 | child.on("exit", (code) => { process.exitCode = code ?? 1; }); | ||
| 34 | `); | ||
| 35 | const command = [process.execPath, wrapper].map((value) => | ||
| 36 | "'" + value.replaceAll("'", "'\\''") + "'" | ||
| 37 | ).join(" "); | ||
| 38 | const hook = { type: "command", command, timeout: 30 }; | ||
| 39 | const hooks = { | ||
| 40 | SessionStart: [{ hooks: [hook] }], | ||
| 41 | UserPromptSubmit: [{ hooks: [hook] }], | ||
| 42 | }; | ||
| 43 | const requests = []; | ||
| 44 | const server = http.createServer(async (request, response) => { | ||
| 45 | let body = ""; | ||
| 46 | for await (const chunk of request) body += chunk; | ||
| 47 | if (request.method === "POST" && /\/(responses|messages)(\?|$)/.test(request.url)) { | ||
| 48 | requests.push(body); | ||
| 49 | } | ||
| 50 | response.writeHead(401, { "Content-Type": "application/json" }); | ||
| 51 | response.end(JSON.stringify({ error: { type: "authentication_error", message: "Fixture finished" } })); | ||
| 52 | }); | ||
| 53 | server.listen(0, "127.0.0.1"); | ||
| 54 | await once(server, "listening"); | ||
| 55 | const origin = `http://127.0.0.1:${server.address().port}`; | ||
| 56 | const codexHome = path.join(home, ".codex"); | ||
| 57 | const claudeHome = path.join(home, ".claude"); | ||
| 58 | fs.mkdirSync(codexHome); | ||
| 59 | fs.mkdirSync(claudeHome); | ||
| 60 | fs.writeFileSync(path.join(codexHome, "config.toml"), `model_provider = "fixture" | ||
| 61 | model = "gpt-6.1-sol" | ||
| 62 | [model_providers.fixture] | ||
| 63 | name = "Fixture" | ||
| 64 | base_url = "${origin}/v1" | ||
| 65 | wire_api = "responses" | ||
| 66 | requires_openai_auth = false | ||
| 67 | request_max_retries = 0 | ||
| 68 | stream_max_retries = 0 | ||
| 69 | [[hooks.SessionStart]] | ||
| 70 | [[hooks.SessionStart.hooks]] | ||
| 71 | type = "command" | ||
| 72 | command = ${JSON.stringify(command)} | ||
| 73 | timeout = 30 | ||
| 74 | [[hooks.UserPromptSubmit]] | ||
| 75 | [[hooks.UserPromptSubmit.hooks]] | ||
| 76 | type = "command" | ||
| 77 | command = ${JSON.stringify(command)} | ||
| 78 | timeout = 30 | ||
| 79 | `); | ||
| 80 | fs.writeFileSync(path.join(claudeHome, "settings.json"), JSON.stringify({ hooks })); | ||
| 81 | const env = { | ||
| 82 | ...process.env, HOME: home, CODEX_HOME: codexHome, CLAUDE_CONFIG_DIR: claudeHome, | ||
| 83 | ANTHROPIC_BASE_URL: origin, ANTHROPIC_API_KEY: "fixture", | ||
| 84 | ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", | ||
| 85 | CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", | ||
| 86 | }; | ||
| 87 | const args = provider === "codex" | ||
| 88 | ? ["exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "Say ready."] | ||
| 89 | : ["-p", "--model", "claude-sonnet-4-6", "--output-format", "json", "Say ready."]; | ||
| 90 | let child; | ||
| 91 | let output = ""; | ||
| 92 | try { | ||
| 93 | const configure = childProcess.spawn(python, [ | ||
| 94 | installer, home, command, process.env.WORKSPACE_TEST_CODEX, | ||
| 95 | ], { env }); | ||
| 96 | let configuredOutput = ""; | ||
| 97 | configure.stderr.on("data", (chunk) => { configuredOutput += chunk; }); | ||
| 98 | const [configuredStatus] = await once(configure, "exit"); | ||
| 99 | assert.equal(configuredStatus, 0, configuredOutput); | ||
| 100 | child = childProcess.spawn(executable, args, { cwd: workspace, env }); | ||
| 101 | child.stdin.end(); | ||
| 102 | child.stdout.on("data", (chunk) => { output += chunk; }); | ||
| 103 | child.stderr.on("data", (chunk) => { output += chunk; }); | ||
| 104 | const exited = once(child, "exit"); | ||
| 105 | for (let attempt = 0; !fs.existsSync(invoked); attempt++) { | ||
| 106 | assert.ok(attempt < 200 && child.exitCode === null, output); | ||
| 107 | await new Promise((resolve) => setTimeout(resolve, 50)); | ||
| 108 | } | ||
| 109 | await new Promise((resolve) => setTimeout(resolve, 400)); | ||
| 110 | assert.equal(requests.length, 0, "no model request while the workspace is unprepared"); | ||
| 111 | assert.equal(child.exitCode, null, "prompt remains waiting"); | ||
| 112 | fs.writeFileSync(path.join(workspace, "AGENTS.md"), "WORKSPACE_READY_INSTRUCTIONS_8732\n"); | ||
| 113 | fs.writeFileSync(record, JSON.stringify({ prepared: true })); | ||
| 114 | for (let attempt = 0; requests.length === 0; attempt++) { | ||
| 115 | assert.ok(attempt < 300 && child.exitCode === null, output); | ||
| 116 | await new Promise((resolve) => setTimeout(resolve, 50)); | ||
| 117 | } | ||
| 118 | assert.match(requests[0], /WORKSPACE_READY_INSTRUCTIONS_8732/); | ||
| 119 | child.kill("SIGKILL"); | ||
| 120 | await exited; | ||
| 121 | |||
| 122 | fs.rmSync(invoked); | ||
| 123 | requests.length = 0; | ||
| 124 | fs.writeFileSync(record, JSON.stringify({ prepared: false, preparationError: "fixture setup failed" })); | ||
| 125 | output = ""; | ||
| 126 | child = childProcess.spawn(executable, args, { cwd: workspace, env }); | ||
| 127 | child.stdin.end(); | ||
| 128 | child.stdout.on("data", (chunk) => { output += chunk; }); | ||
| 129 | child.stderr.on("data", (chunk) => { output += chunk; }); | ||
| 130 | await once(child, "exit"); | ||
| 131 | assert.ok(fs.existsSync(invoked), output); | ||
| 132 | assert.equal(requests.length, 0, "a setup failure blocks the model request"); | ||
| 133 | if (provider === "codex") assert.match(output, /"input_tokens":0/); | ||
| 134 | else assert.match(output, /setup stopped|resend your prompt/); | ||
| 135 | } finally { | ||
| 136 | if (child?.exitCode === null && child.signalCode === null) { | ||
| 137 | child.kill("SIGKILL"); | ||
| 138 | await once(child, "exit"); | ||
| 139 | } | ||
| 140 | await new Promise((resolve) => server.close(resolve)); | ||
| 141 | fs.rmSync(home, { recursive: true, force: true, maxRetries: 3 }); | ||
| 142 | } | ||
| 143 | }); | ||
| 144 | } | ||
users/clover/packages/workspaces/workspaces.mjs created+880| ... | @@ -0,0 +1,880 @@ | ||
| 1 | import fs from "node:fs"; | ||
| 2 | import path from "node:path"; | ||
| 3 | import os from "node:os"; | ||
| 4 | import net from "node:net"; | ||
| 5 | import { createHash, randomUUID } from "node:crypto"; | ||
| 6 | import childProcess from "node:child_process"; | ||
| 7 | import { fileURLToPath } from "node:url"; | ||
| 8 | |||
| 9 | const home = fs.realpathSync(os.homedir()); | ||
| 10 | const root = path.join(home, "workspaces"); | ||
| 11 | const state = path.join(home, ".local/state/workspaces"); | ||
| 12 | const cache = path.join(home, ".cache/workspaces/deps"); | ||
| 13 | const configFile = path.join(home, ".config/workspaces.json"); | ||
| 14 | const records = path.join(state, "workspaces"); | ||
| 15 | const t3Home = process.env.T3CODE_HOME ?? path.join(home, ".t3"); | ||
| 16 | |||
| 17 | function run(command, args, cwd, inherit = false) { | ||
| 18 | if (command === "jj") { | ||
| 19 | args = ["--config", "snapshot.auto-update-stale=true", ...args]; | ||
| 20 | } | ||
| 21 | |||
| 22 | return childProcess.execFileSync(command, args, { | ||
| 23 | cwd, | ||
| 24 | encoding: "utf8", | ||
| 25 | stdio: inherit ? ["ignore", 2, 2] : ["ignore", "pipe", "pipe"], | ||
| 26 | timeout: inherit ? undefined : 30_000, | ||
| 27 | })?.trim(); | ||
| 28 | } | ||
| 29 | |||
| 30 | function writeJson(file, value) { | ||
| 31 | fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); | ||
| 32 | const temporary = `${file}.${process.pid}.tmp`; | ||
| 33 | fs.writeFileSync(temporary, JSON.stringify(value) + "\n", { mode: 0o600 }); | ||
| 34 | fs.renameSync(temporary, file); | ||
| 35 | } | ||
| 36 | |||
| 37 | function alive(pid) { | ||
| 38 | try { | ||
| 39 | process.kill(pid, 0); | ||
| 40 | return true; | ||
| 41 | } catch (error) { | ||
| 42 | if (error.code === "ESRCH") return false; | ||
| 43 | throw error; | ||
| 44 | } | ||
| 45 | } | ||
| 46 | |||
| 47 | function inside(candidate, directory) { | ||
| 48 | const relative = path.relative(directory, candidate); | ||
| 49 | return relative === "" || | ||
| 50 | (!relative.startsWith(`..${path.sep}`) && relative !== ".." && | ||
| 51 | !path.isAbsolute(relative)); | ||
| 52 | } | ||
| 53 | |||
| 54 | function canonical(file) { | ||
| 55 | try { | ||
| 56 | return fs.realpathSync(file); | ||
| 57 | } catch (error) { | ||
| 58 | if (error.code === "ENOENT") return path.resolve(file); | ||
| 59 | throw error; | ||
| 60 | } | ||
| 61 | } | ||
| 62 | |||
| 63 | function jjRepository(directory) { | ||
| 64 | const file = path.join(directory, ".jj/repo"); | ||
| 65 | return fs.statSync(file).isDirectory() ? canonical(file) : canonical( | ||
| 66 | path.resolve(path.dirname(file), fs.readFileSync(file, "utf8").trim()), | ||
| 67 | ); | ||
| 68 | } | ||
| 69 | |||
| 70 | function workspace(id) { | ||
| 71 | if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id)) { | ||
| 72 | throw new Error( | ||
| 73 | "Choose a workspace name containing letters, numbers, underscores, or hyphens.", | ||
| 74 | ); | ||
| 75 | } | ||
| 76 | return path.join(root, id); | ||
| 77 | } | ||
| 78 | |||
| 79 | export async function t3() { | ||
| 80 | const runtime = JSON.parse( | ||
| 81 | fs.readFileSync(path.join(t3Home, "userdata/server-runtime.json")), | ||
| 82 | ); | ||
| 83 | if (!Number.isInteger(runtime.pid) || !alive(runtime.pid)) { | ||
| 84 | throw new Error("Start T3 Code nightly before using workspaces."); | ||
| 85 | } | ||
| 86 | const origin = new URL(runtime.origin); | ||
| 87 | if ( | ||
| 88 | origin.protocol !== "http:" || | ||
| 89 | !["127.0.0.1", "localhost", "[::1]"].includes(origin.hostname) | ||
| 90 | ) throw new Error("Workspace cleanup needs a local T3 Code server."); | ||
| 91 | |||
| 92 | const executable = run("/bin/ps", ["-p", String(runtime.pid), "-o", "comm="]); | ||
| 93 | const app = executable.includes("/Contents/MacOS/") | ||
| 94 | ? executable.split("/Contents/MacOS/")[0] | ||
| 95 | : null; | ||
| 96 | const cli = app | ||
| 97 | ? [ | ||
| 98 | executable, | ||
| 99 | path.join(app, "Contents/Resources/app.asar/apps/server/dist/bin.mjs"), | ||
| 100 | ] | ||
| 101 | : [executable]; | ||
| 102 | const authFile = path.join(state, "t3-auth.json"); | ||
| 103 | let authentication; | ||
| 104 | if (fs.existsSync(authFile) && Date.now() - fs.statSync(authFile).mtimeMs < 60_000) { | ||
| 105 | authentication = JSON.parse(fs.readFileSync(authFile)); | ||
| 106 | } | ||
| 107 | if (authentication?.pid !== runtime.pid) { | ||
| 108 | const token = childProcess.execFileSync(cli[0], [ | ||
| 109 | ...cli.slice(1), | ||
| 110 | "auth", | ||
| 111 | "session", | ||
| 112 | "issue", | ||
| 113 | "--base-dir", | ||
| 114 | t3Home, | ||
| 115 | "--ttl", | ||
| 116 | "2m", | ||
| 117 | "--token-only", | ||
| 118 | ], { | ||
| 119 | env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }, | ||
| 120 | encoding: "utf8", | ||
| 121 | timeout: 15_000, | ||
| 122 | stdio: ["ignore", "pipe", "pipe"], | ||
| 123 | }).trim(); | ||
| 124 | authentication = { pid: runtime.pid, token }; | ||
| 125 | writeJson(authFile, authentication); | ||
| 126 | } | ||
| 127 | |||
| 128 | async function request(route, body) { | ||
| 129 | const response = await fetch(new URL(route, origin), { | ||
| 130 | method: body === undefined ? "GET" : "POST", | ||
| 131 | // Synchronous JJ/pnpm calls can outlive HTTP keep-alive sockets. | ||
| 132 | headers: { | ||
| 133 | Authorization: `Bearer ${authentication.token}`, | ||
| 134 | "Content-Type": "application/json", | ||
| 135 | "x-t3-orchestration-protocol": "2", | ||
| 136 | Connection: "close", | ||
| 137 | }, | ||
| 138 | body: body === undefined ? undefined : JSON.stringify(body), | ||
| 139 | signal: AbortSignal.timeout(10_000), | ||
| 140 | }); | ||
| 141 | if (!response.ok) { | ||
| 142 | throw new Error( | ||
| 143 | `T3 Code returned ${response.status}. Cleanup is paused; check the nightly app.`, | ||
| 144 | ); | ||
| 145 | } | ||
| 146 | return response.json(); | ||
| 147 | } | ||
| 148 | |||
| 149 | const environment = await request("/.well-known/t3/environment"); | ||
| 150 | if (environment.orchestrationProtocolVersion !== 2) { | ||
| 151 | throw new Error("Update T3 Code to a nightly build with orchestrator V2."); | ||
| 152 | } | ||
| 153 | |||
| 154 | async function snapshot() { | ||
| 155 | const data = await request("/api/orchestration/shell"); | ||
| 156 | if ( | ||
| 157 | !Array.isArray(data.projects) || !Array.isArray(data.threads) || | ||
| 158 | !Array.isArray(data.archivedThreads) | ||
| 159 | ) { | ||
| 160 | throw new Error( | ||
| 161 | "T3 Code returned an unknown thread list. Cleanup is paused.", | ||
| 162 | ); | ||
| 163 | } | ||
| 164 | for (const thread of [...data.threads, ...data.archivedThreads]) { | ||
| 165 | if ( | ||
| 166 | ![ | ||
| 167 | "settledOverride", | ||
| 168 | "activeRunId", | ||
| 169 | "worktreePath", | ||
| 170 | "deletedAt", | ||
| 171 | "archivedAt", | ||
| 172 | "pendingRuntimeRequest", | ||
| 173 | "status", | ||
| 174 | ].every((field) => field in thread) | ||
| 175 | ) { | ||
| 176 | throw new Error( | ||
| 177 | "T3 Code returned an unknown thread state. Cleanup is paused.", | ||
| 178 | ); | ||
| 179 | } | ||
| 180 | } | ||
| 181 | return data; | ||
| 182 | } | ||
| 183 | |||
| 184 | async function dispatch(command) { | ||
| 185 | const { ticket } = await request("/api/auth/websocket-ticket", {}); | ||
| 186 | const url = new URL("/ws", origin); | ||
| 187 | url.protocol = "ws:"; | ||
| 188 | url.searchParams.set("wsTicket", ticket); | ||
| 189 | url.searchParams.set("orchestrationProtocol", "2"); | ||
| 190 | return new Promise((resolve, reject) => { | ||
| 191 | const socket = new WebSocket(url); | ||
| 192 | const timeout = setTimeout( | ||
| 193 | () => | ||
| 194 | finish( | ||
| 195 | new Error( | ||
| 196 | "T3 Code did not confirm the workspace chat. Run ws open to retry.", | ||
| 197 | ), | ||
| 198 | ), | ||
| 199 | 15_000, | ||
| 200 | ); | ||
| 201 | function finish(error, value) { | ||
| 202 | clearTimeout(timeout); | ||
| 203 | socket.close(); | ||
| 204 | if (error) reject(error); | ||
| 205 | else resolve(value); | ||
| 206 | } | ||
| 207 | socket.onopen = () => | ||
| 208 | socket.send( | ||
| 209 | JSON.stringify({ | ||
| 210 | _tag: "Request", | ||
| 211 | id: "1", | ||
| 212 | tag: command.type.startsWith("project.") | ||
| 213 | ? "projects.mutate" | ||
| 214 | : "orchestration.dispatchCommand", | ||
| 215 | payload: { commandId: randomUUID(), ...command }, | ||
| 216 | headers: [], | ||
| 217 | }) + "\n", | ||
| 218 | ); | ||
| 219 | socket.onmessage = (event) => { | ||
| 220 | for (const line of String(event.data).trim().split("\n")) { | ||
| 221 | const message = JSON.parse(line); | ||
| 222 | if (message._tag !== "Exit" || String(message.requestId) !== "1") { | ||
| 223 | continue; | ||
| 224 | } | ||
| 225 | if (message.exit._tag === "Success") finish(null, message.exit.value); | ||
| 226 | else { | ||
| 227 | finish( | ||
| 228 | new Error( | ||
| 229 | `T3 Code rejected the workspace command: ${ | ||
| 230 | JSON.stringify(message.exit) | ||
| 231 | }`, | ||
| 232 | ), | ||
| 233 | ); | ||
| 234 | } | ||
| 235 | } | ||
| 236 | }; | ||
| 237 | socket.onerror = () => | ||
| 238 | finish( | ||
| 239 | new Error("Cannot reach T3 Code. Start the nightly app and retry."), | ||
| 240 | ); | ||
| 241 | socket.onclose = () => { | ||
| 242 | clearTimeout(timeout); | ||
| 243 | reject(new Error("T3 Code closed the chat connection.")); | ||
| 244 | }; | ||
| 245 | }); | ||
| 246 | } | ||
| 247 | return { snapshot, dispatch, environment, app }; | ||
| 248 | } | ||
| 249 | |||
| 250 | function dependencyKey(directory) { | ||
| 251 | const files = run("jj", ["--ignore-working-copy", "file", "list"], directory).split("\n").filter(( | ||
| 252 | file, | ||
| 253 | ) => | ||
| 254 | path.basename(file) === "package.json" || | ||
| 255 | ["pnpm-lock.yaml", "pnpm-workspace.yaml", ".npmrc", ".pnpmfile.cjs"] | ||
| 256 | .includes(file) || | ||
| 257 | file.startsWith("patches/") | ||
| 258 | ).sort(); | ||
| 259 | const hash = createHash("sha256"); | ||
| 260 | hash.update( | ||
| 261 | `${process.platform}:${process.arch}:${process.versions.modules}:${ | ||
| 262 | run("pnpm", ["--version"], directory) | ||
| 263 | }\0`, | ||
| 264 | ); | ||
| 265 | for (const file of files) { | ||
| 266 | hash.update(file + "\0").update(fs.readFileSync(path.join(directory, file))) | ||
| 267 | .update("\0"); | ||
| 268 | } | ||
| 269 | return hash.digest("hex"); | ||
| 270 | } | ||
| 271 | |||
| 272 | function moduleDirectories(directory, relative = "") { | ||
| 273 | const found = []; | ||
| 274 | for ( | ||
| 275 | const entry of fs.readdirSync(path.join(directory, relative), { | ||
| 276 | withFileTypes: true, | ||
| 277 | }) | ||
| 278 | ) { | ||
| 279 | if (!entry.isDirectory() || entry.name.startsWith(".")) continue; | ||
| 280 | const child = path.join(relative, entry.name); | ||
| 281 | if (entry.name === "node_modules") found.push(child); | ||
| 282 | else found.push(...moduleDirectories(directory, child)); | ||
| 283 | } | ||
| 284 | return found; | ||
| 285 | } | ||
| 286 | |||
| 287 | function dependencies(directory, source) { | ||
| 288 | const key = dependencyKey(directory); | ||
| 289 | let seed; | ||
| 290 | if ( | ||
| 291 | fs.existsSync(path.join(cache, "key")) && | ||
| 292 | fs.readFileSync(path.join(cache, "key"), "utf8") === key | ||
| 293 | ) seed = cache; | ||
| 294 | else if ( | ||
| 295 | dependencyKey(source) === key && | ||
| 296 | fs.existsSync(path.join(source, "node_modules/.pnpm/lock.yaml")) | ||
| 297 | ) seed = source; | ||
| 298 | if (seed) { | ||
| 299 | for (const relative of moduleDirectories(seed)) { | ||
| 300 | const target = path.join(directory, relative); | ||
| 301 | if (fs.existsSync(target) || !fs.existsSync(path.dirname(target))) { | ||
| 302 | continue; | ||
| 303 | } | ||
| 304 | run( | ||
| 305 | "workspace-native", | ||
| 306 | ["clone", path.join(seed, relative), target], | ||
| 307 | undefined, | ||
| 308 | true, | ||
| 309 | ); | ||
| 310 | } | ||
| 311 | } | ||
| 312 | |||
| 313 | // pnpm regenerates launchers that embed the previous workspace's absolute path. | ||
| 314 | run( | ||
| 315 | "pnpm", | ||
| 316 | [ | ||
| 317 | "install", | ||
| 318 | "--frozen-lockfile", | ||
| 319 | "--prefer-offline", | ||
| 320 | "--store-dir", | ||
| 321 | path.join(home, ".local/share/pnpm/store"), | ||
| 322 | ], | ||
| 323 | directory, | ||
| 324 | true, | ||
| 325 | ); | ||
| 326 | if (dependencyKey(directory) !== key) { | ||
| 327 | throw new Error( | ||
| 328 | "Dependency files changed during installation. Run ws deps again.", | ||
| 329 | ); | ||
| 330 | } | ||
| 331 | if (seed === cache) return; | ||
| 332 | |||
| 333 | const temporary = `${cache}.tmp`; | ||
| 334 | fs.rmSync(temporary, { recursive: true, force: true }); | ||
| 335 | fs.mkdirSync(temporary, { recursive: true }); | ||
| 336 | for (const relative of moduleDirectories(directory)) { | ||
| 337 | const target = path.join(temporary, relative); | ||
| 338 | fs.mkdirSync(path.dirname(target), { recursive: true }); | ||
| 339 | run( | ||
| 340 | "workspace-native", | ||
| 341 | ["clone", path.join(directory, relative), target], | ||
| 342 | undefined, | ||
| 343 | true, | ||
| 344 | ); | ||
| 345 | } | ||
| 346 | fs.writeFileSync(path.join(temporary, "key"), key); | ||
| 347 | fs.rmSync(cache, { recursive: true, force: true }); | ||
| 348 | fs.renameSync(temporary, cache); | ||
| 349 | } | ||
| 350 | |||
| 351 | async function editorReferences() { | ||
| 352 | const processes = run("/bin/ps", ["-axo", "pid=,comm="]); | ||
| 353 | const instances = processes.split("\n").filter((line) => | ||
| 354 | line.endsWith("/Visual Studio Code.app/Contents/MacOS/Code") | ||
| 355 | ).map((line) => Number(line.trim().split(/\s+/, 1)[0])); | ||
| 356 | if (!instances.length) return []; | ||
| 357 | const status = run("/usr/local/bin/code", ["--status"]); | ||
| 358 | const reported = [...status.matchAll(/^\s*\d+\s+\d+\s+(\d+)\s+code\s*$/gm)] | ||
| 359 | .map((match) => Number(match[1])); | ||
| 360 | if (instances.some((pid) => !reported.includes(pid))) { | ||
| 361 | throw new Error( | ||
| 362 | "Cannot inspect every VS Code instance. Cleanup is paused.", | ||
| 363 | ); | ||
| 364 | } | ||
| 365 | const pids = [...status.matchAll(/\b(\d+)\s+extension-host\b/g)].map(( | ||
| 366 | match, | ||
| 367 | ) => Number(match[1])); | ||
| 368 | const windows = [...status.matchAll(/\bwindow \[\d+\]/g)].length; | ||
| 369 | if (pids.length < windows) { | ||
| 370 | throw new Error( | ||
| 371 | "VS Code has a window without a reference tracker. Reload its windows before cleanup.", | ||
| 372 | ); | ||
| 373 | } | ||
| 374 | const paths = []; | ||
| 375 | for (const pid of pids) { | ||
| 376 | const response = await new Promise((resolve, reject) => { | ||
| 377 | const socket = net.createConnection( | ||
| 378 | path.join(state, "vscode", `${pid}.sock`), | ||
| 379 | ); | ||
| 380 | let data = ""; | ||
| 381 | socket.setTimeout( | ||
| 382 | 2000, | ||
| 383 | () => | ||
| 384 | socket.destroy( | ||
| 385 | new Error( | ||
| 386 | "VS Code reference tracker did not respond. Reload its windows before cleanup.", | ||
| 387 | ), | ||
| 388 | ), | ||
| 389 | ); | ||
| 390 | socket.on("data", (chunk) => { | ||
| 391 | data += chunk; | ||
| 392 | }); | ||
| 393 | socket.on("end", () => { | ||
| 394 | try { | ||
| 395 | resolve(JSON.parse(data)); | ||
| 396 | } catch (error) { | ||
| 397 | reject(error); | ||
| 398 | } | ||
| 399 | }); | ||
| 400 | socket.on("error", reject); | ||
| 401 | }); | ||
| 402 | if (response.pid !== pid || !Array.isArray(response.paths)) { | ||
| 403 | throw new Error( | ||
| 404 | "Cannot verify VS Code's open folders. Reload its windows before cleanup.", | ||
| 405 | ); | ||
| 406 | } | ||
| 407 | paths.push(...response.paths.map(canonical)); | ||
| 408 | } | ||
| 409 | return paths; | ||
| 410 | } | ||
| 411 | |||
| 412 | function terminalReferences() { | ||
| 413 | const pids = new Set(); | ||
| 414 | const processes = run("/bin/ps", ["-axo", "pid=,tty=,comm="]); | ||
| 415 | for (const line of processes.split("\n")) { | ||
| 416 | const match = line.match(/^\s*(\d+)\s+(\S+)\s+(.+)$/); | ||
| 417 | if (match && match[2] !== "??" && /\/(zsh|bash|fish|sh)$/.test(match[3])) { | ||
| 418 | pids.add(Number(match[1])); | ||
| 419 | } | ||
| 420 | } | ||
| 421 | const directory = path.join(state, "shells"); | ||
| 422 | for ( | ||
| 423 | const name of fs.existsSync(directory) ? fs.readdirSync(directory) : [] | ||
| 424 | ) { | ||
| 425 | if (!/^\d+$/.test(name)) continue; | ||
| 426 | const pid = Number(name); | ||
| 427 | if (alive(pid)) pids.add(pid); | ||
| 428 | else fs.rmSync(path.join(directory, name)); | ||
| 429 | } | ||
| 430 | if (!pids.size) return []; | ||
| 431 | |||
| 432 | let output; | ||
| 433 | try { | ||
| 434 | output = run("/usr/sbin/lsof", [ | ||
| 435 | "-a", | ||
| 436 | "-p", | ||
| 437 | [...pids].join(","), | ||
| 438 | "-d", | ||
| 439 | "cwd", | ||
| 440 | "-Fpn", | ||
| 441 | ]); | ||
| 442 | } catch (error) { | ||
| 443 | if (error.status !== 1) throw error; | ||
| 444 | output = String(error.stdout ?? ""); | ||
| 445 | } | ||
| 446 | const found = new Set(); | ||
| 447 | const paths = []; | ||
| 448 | let pid; | ||
| 449 | for (const line of output.split("\n")) { | ||
| 450 | if (line.startsWith("p")) pid = Number(line.slice(1)); | ||
| 451 | if (line.startsWith("n")) { | ||
| 452 | found.add(pid); | ||
| 453 | paths.push(canonical(line.slice(1))); | ||
| 454 | } | ||
| 455 | } | ||
| 456 | for (const pid of pids) { | ||
| 457 | if (!found.has(pid) && alive(pid)) { | ||
| 458 | throw new Error( | ||
| 459 | `Cannot read terminal ${pid}'s folder. Cleanup is paused.`, | ||
| 460 | ); | ||
| 461 | } | ||
| 462 | } | ||
| 463 | return paths; | ||
| 464 | } | ||
| 465 | |||
| 466 | async function references(client) { | ||
| 467 | const [snapshot, editors] = await Promise.all([ | ||
| 468 | client.snapshot(), | ||
| 469 | editorReferences(), | ||
| 470 | ]); | ||
| 471 | const projects = new Map( | ||
| 472 | snapshot.projects.map((project) => [project.id, project.workspaceRoot]), | ||
| 473 | ); | ||
| 474 | const chats = []; | ||
| 475 | for (const thread of [...snapshot.threads, ...snapshot.archivedThreads]) { | ||
| 476 | const released = thread.deletedAt !== null || thread.archivedAt !== null || | ||
| 477 | thread.settledOverride === "settled"; | ||
| 478 | const busy = ![ | ||
| 479 | "idle", | ||
| 480 | "completed", | ||
| 481 | "interrupted", | ||
| 482 | "failed", | ||
| 483 | "cancelled", | ||
| 484 | "rolled_back", | ||
| 485 | ].includes(thread.status) || thread.activeRunId !== null || | ||
| 486 | thread.pendingRuntimeRequest !== null || | ||
| 487 | thread.pendingBackgroundTasks?.length > 0; | ||
| 488 | if (released && !busy) continue; | ||
| 489 | const directory = thread.worktreePath ?? projects.get(thread.projectId); | ||
| 490 | if (!directory) { | ||
| 491 | throw new Error( | ||
| 492 | "Cannot locate a T3 chat's workspace. Cleanup is paused.", | ||
| 493 | ); | ||
| 494 | } | ||
| 495 | chats.push(canonical(directory)); | ||
| 496 | } | ||
| 497 | return { chats, editors, terminals: terminalReferences() }; | ||
| 498 | } | ||
| 499 | |||
| 500 | async function openChat(id, config, client, open = true) { | ||
| 501 | const directory = workspace(id); | ||
| 502 | const file = path.join(records, `${id}.json`); | ||
| 503 | const record = JSON.parse(fs.readFileSync(file)); | ||
| 504 | const snapshot = await client.snapshot(); | ||
| 505 | const repository = jjRepository(config.repository); | ||
| 506 | const source = snapshot.projects.find((project) => | ||
| 507 | canonical(project.workspaceRoot) === config.repository | ||
| 508 | ) ?? snapshot.projects.find((project) => | ||
| 509 | !inside(canonical(project.workspaceRoot), root) && | ||
| 510 | fs.existsSync(path.join(project.workspaceRoot, ".jj/repo")) && | ||
| 511 | jjRepository(project.workspaceRoot) === repository | ||
| 512 | ); | ||
| 513 | if (!source) { | ||
| 514 | throw new Error( | ||
| 515 | "Add the source repository to T3 Code before creating a workspace chat.", | ||
| 516 | ); | ||
| 517 | } | ||
| 518 | const previous = [...snapshot.threads, ...snapshot.archivedThreads].find( | ||
| 519 | (thread) => thread.id === record.threadId, | ||
| 520 | ); | ||
| 521 | if (!previous) { | ||
| 522 | let project = snapshot.projects.find((project) => | ||
| 523 | canonical(project.workspaceRoot) === directory | ||
| 524 | ); | ||
| 525 | const latest = [...snapshot.threads, ...snapshot.archivedThreads].filter( | ||
| 526 | (thread) => thread.projectId === (project?.id ?? source.id), | ||
| 527 | ).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0]; | ||
| 528 | const modelSelection = project?.defaultModelSelection ?? | ||
| 529 | source.defaultModelSelection ?? | ||
| 530 | latest?.modelSelection; | ||
| 531 | if (!modelSelection) { | ||
| 532 | throw new Error( | ||
| 533 | "Choose a model in the source repository's T3 settings, then run ws open again.", | ||
| 534 | ); | ||
| 535 | } | ||
| 536 | if (!project) { | ||
| 537 | project = await client.dispatch({ | ||
| 538 | type: "project.create", | ||
| 539 | projectId: randomUUID(), | ||
| 540 | title: `${source.title} | ${id}`, | ||
| 541 | workspaceRoot: directory, | ||
| 542 | }); | ||
| 543 | } | ||
| 544 | await client.dispatch({ | ||
| 545 | type: "project.update", | ||
| 546 | projectId: project.id, | ||
| 547 | projectIcon: source.projectIcon ?? null, | ||
| 548 | faviconPath: source.faviconPath ?? null, | ||
| 549 | defaultThreadEnvMode: "local", | ||
| 550 | defaultModelSelection: modelSelection, | ||
| 551 | }); | ||
| 552 | const threadId = record.threadId ?? randomUUID(); | ||
| 553 | record.threadId = threadId; | ||
| 554 | writeJson(file, record); | ||
| 555 | await client.dispatch({ | ||
| 556 | type: "thread.create", | ||
| 557 | threadId, | ||
| 558 | projectId: project.id, | ||
| 559 | title: project.title, | ||
| 560 | modelSelection, | ||
| 561 | runtimeMode: latest?.runtimeMode ?? "full-access", | ||
| 562 | interactionMode: latest?.interactionMode ?? "default", | ||
| 563 | branch: null, | ||
| 564 | worktreePath: null, | ||
| 565 | createdBy: "user", | ||
| 566 | creationSource: "web", | ||
| 567 | }); | ||
| 568 | const confirmed = await client.snapshot(); | ||
| 569 | if (!confirmed.threads.some((thread) => thread.id === threadId)) { | ||
| 570 | throw new Error( | ||
| 571 | "T3 Code has not confirmed the chat yet. Run ws open again.", | ||
| 572 | ); | ||
| 573 | } | ||
| 574 | } | ||
| 575 | if (previous?.archivedAt) { | ||
| 576 | await client.dispatch({ type: "thread.unarchive", threadId: previous.id }); | ||
| 577 | } | ||
| 578 | if (previous?.settledOverride === "settled") { | ||
| 579 | await client.dispatch({ | ||
| 580 | type: "thread.unsettle", | ||
| 581 | threadId: previous.id, | ||
| 582 | reason: "user", | ||
| 583 | }); | ||
| 584 | } | ||
| 585 | record.idleSince = null; | ||
| 586 | writeJson(file, record); | ||
| 587 | const environmentId = client.environment.environmentId; | ||
| 588 | if (open) { | ||
| 589 | run("/usr/bin/open", [ | ||
| 590 | ...(client.app ? ["-a", client.app] : ["-b", "com.t3tools.t3code"]), | ||
| 591 | `t3code://threads/${environmentId}/${record.threadId}`, | ||
| 592 | ]); | ||
| 593 | } | ||
| 594 | console.log(directory); | ||
| 595 | } | ||
| 596 | |||
| 597 | export async function main(args) { | ||
| 598 | const [command, argument, ...rest] = args; | ||
| 599 | if (command === "ready-hook") { | ||
| 600 | let input = ""; | ||
| 601 | for await (const chunk of process.stdin) input += chunk; | ||
| 602 | const event = JSON.parse(input); | ||
| 603 | const directory = canonical(event.cwd); | ||
| 604 | if (!inside(directory, root)) return; | ||
| 605 | const id = path.relative(root, directory).split(path.sep)[0]; | ||
| 606 | const file = path.join(records, `${id}.json`); | ||
| 607 | if (!fs.existsSync(file)) return; | ||
| 608 | |||
| 609 | const deadline = Date.now() + 240_000; | ||
| 610 | let waited = false; | ||
| 611 | while (true) { | ||
| 612 | const record = JSON.parse(fs.readFileSync(file)); | ||
| 613 | if (record.preparationError) { | ||
| 614 | throw new Error(`Workspace ${id} setup stopped: ${record.preparationError}. Run ws deps ${id}, then resend your prompt.`); | ||
| 615 | } | ||
| 616 | if (record.prepared) break; | ||
| 617 | if (Date.now() >= deadline) { | ||
| 618 | throw new Error(`Workspace ${id} is still preparing. Check ~/Library/Logs/workspace-${id}.log, then resend your prompt.`); | ||
| 619 | } | ||
| 620 | waited = true; | ||
| 621 | await new Promise((resolve) => setTimeout(resolve, 100)); | ||
| 622 | } | ||
| 623 | if (waited && event.hook_event_name === "SessionStart") { | ||
| 624 | const files = new Set(["AGENTS.md", "CLAUDE.md"].map((name) => | ||
| 625 | path.join(workspace(id), name) | ||
| 626 | ).filter((file) => fs.existsSync(file)).map(canonical)); | ||
| 627 | const instructions = [...files].map((file) => fs.readFileSync(file, "utf8")); | ||
| 628 | if (instructions.length) { | ||
| 629 | console.log(JSON.stringify({ hookSpecificOutput: { | ||
| 630 | hookEventName: "SessionStart", | ||
| 631 | additionalContext: instructions.join("\n\n"), | ||
| 632 | } })); | ||
| 633 | } | ||
| 634 | } | ||
| 635 | return; | ||
| 636 | } | ||
| 637 | if (!command || command === "--help") { | ||
| 638 | console.log( | ||
| 639 | "ws setup <repository>\nws new [name] [-r revision] [--no-open] [--background]\nws open <name> [--no-open]\nws deps <name>\nws gc [--dry-run]", | ||
| 640 | ); | ||
| 641 | return; | ||
| 642 | } | ||
| 643 | fs.mkdirSync(state, { recursive: true, mode: 0o700 }); | ||
| 644 | if (command === "setup") { | ||
| 645 | if (!argument || rest.length) throw new Error("Run ws setup <repository>."); | ||
| 646 | const repository = fs.realpathSync( | ||
| 647 | run("jj", ["workspace", "root"], path.resolve(argument)), | ||
| 648 | ); | ||
| 649 | if (!fs.existsSync(path.join(repository, "pnpm-lock.yaml"))) { | ||
| 650 | throw new Error("Choose the repository's pnpm workspace root."); | ||
| 651 | } | ||
| 652 | if (fs.existsSync(records) && fs.readdirSync(records).length) { | ||
| 653 | const configured = JSON.parse(fs.readFileSync(configFile)); | ||
| 654 | if (jjRepository(repository) !== jjRepository(configured.repository)) { | ||
| 655 | throw new Error( | ||
| 656 | "Finish existing workspaces before changing their source repository.", | ||
| 657 | ); | ||
| 658 | } | ||
| 659 | } | ||
| 660 | writeJson(configFile, { repository }); | ||
| 661 | console.log(`Workspace source: ${repository}`); | ||
| 662 | return; | ||
| 663 | } | ||
| 664 | if ( | ||
| 665 | command === "gc" && | ||
| 666 | (!fs.existsSync(records) || !fs.readdirSync(records).length) | ||
| 667 | ) return; | ||
| 668 | const config = JSON.parse(fs.readFileSync(configFile)); | ||
| 669 | if (command === "deps") { | ||
| 670 | const file = path.join(records, `${argument}.json`); | ||
| 671 | const record = JSON.parse(fs.readFileSync(file)); | ||
| 672 | delete record.preparationError; | ||
| 673 | writeJson(file, record); | ||
| 674 | try { | ||
| 675 | if ("revision" in record) { | ||
| 676 | if (record.revision === null) { | ||
| 677 | run("jj", [ | ||
| 678 | "--ignore-working-copy", | ||
| 679 | "--config", "git.abandon-unreachable-commits=false", | ||
| 680 | "git", "fetch", "--remote", "origin", "--branch", "main", | ||
| 681 | ], config.repository, true); | ||
| 682 | } | ||
| 683 | const started = Date.now(); | ||
| 684 | // Full sparse patterns let checkout wait without touching the source. | ||
| 685 | run("jj", [ | ||
| 686 | "--ignore-working-copy", "workspace", "add", | ||
| 687 | "--name", `workspaces-${argument}`, "--sparse-patterns", "full", | ||
| 688 | "-r", record.revision ?? "main@origin", workspace(argument), | ||
| 689 | ], config.repository, true); | ||
| 690 | console.error(`JJ workspace initialized in ${Date.now() - started} ms`); | ||
| 691 | delete record.revision; | ||
| 692 | writeJson(file, record); | ||
| 693 | } | ||
| 694 | if (!record.prepared) { | ||
| 695 | run("jj", ["workspace", "update-stale"], workspace(argument), true); | ||
| 696 | } | ||
| 697 | dependencies(workspace(argument), config.repository); | ||
| 698 | record.prepared = true; | ||
| 699 | writeJson(file, record); | ||
| 700 | } catch (error) { | ||
| 701 | record.preparationError = error.message.split("\n", 1)[0]; | ||
| 702 | writeJson(file, record); | ||
| 703 | throw error; | ||
| 704 | } | ||
| 705 | return; | ||
| 706 | } | ||
| 707 | if (command === "new") { | ||
| 708 | const client = await t3(); | ||
| 709 | const open = ![argument, ...rest].includes("--no-open"); | ||
| 710 | const background = [argument, ...rest].includes("--background"); | ||
| 711 | const options = [argument, ...rest].filter((value) => | ||
| 712 | value !== undefined && value !== "--no-open" && value !== "--background" | ||
| 713 | ); | ||
| 714 | const id = options[0]?.startsWith("-") ? undefined : options.shift(); | ||
| 715 | const revision = options.length === 0 | ||
| 716 | ? null | ||
| 717 | : options.length === 2 && options[0] === "-r" | ||
| 718 | ? options[1] | ||
| 719 | : undefined; | ||
| 720 | if (revision === undefined) throw new Error("Run ws new [name] [-r revision]."); | ||
| 721 | fs.mkdirSync(root, { recursive: true }); | ||
| 722 | let number = 1; | ||
| 723 | while ( | ||
| 724 | fs.existsSync(workspace(String(number))) || | ||
| 725 | fs.existsSync(path.join(records, `${number}.json`)) | ||
| 726 | ) number++; | ||
| 727 | const name = id ?? String(number); | ||
| 728 | const directory = workspace(name); | ||
| 729 | if ( | ||
| 730 | fs.existsSync(directory) || | ||
| 731 | fs.existsSync(path.join(records, `${name}.json`)) | ||
| 732 | ) throw new Error(`Workspace ${name} already exists. Run ws open ${name}.`); | ||
| 733 | fs.mkdirSync(directory); | ||
| 734 | const file = path.join(records, `${name}.json`); | ||
| 735 | writeJson(file, { | ||
| 736 | threadId: null, | ||
| 737 | idleSince: null, | ||
| 738 | prepared: false, | ||
| 739 | revision, | ||
| 740 | }); | ||
| 741 | await openChat(name, config, client, open); | ||
| 742 | const logs = path.join(home, "Library/Logs"); | ||
| 743 | fs.mkdirSync(logs, { recursive: true }); | ||
| 744 | const output = background | ||
| 745 | ? fs.openSync(path.join(logs, `workspace-${name}.log`), "w", 0o600) | ||
| 746 | : 2; | ||
| 747 | try { | ||
| 748 | const child = childProcess.spawn("workspace-native", [ | ||
| 749 | "wait-lock", path.join(state, "lock"), process.execPath, | ||
| 750 | fileURLToPath(import.meta.url), "deps", name, | ||
| 751 | ], { | ||
| 752 | detached: background, | ||
| 753 | stdio: ["ignore", output, output], | ||
| 754 | }); | ||
| 755 | if (background) { | ||
| 756 | await new Promise((resolve, reject) => { | ||
| 757 | child.once("spawn", resolve); | ||
| 758 | child.once("error", reject); | ||
| 759 | }); | ||
| 760 | child.unref(); | ||
| 761 | } else { | ||
| 762 | const status = await new Promise((resolve, reject) => { | ||
| 763 | child.once("exit", resolve); | ||
| 764 | child.once("error", reject); | ||
| 765 | }); | ||
| 766 | if (status !== 0) { | ||
| 767 | throw new Error(`Workspace ${name} setup stopped. Run ws deps ${name} to retry.`); | ||
| 768 | } | ||
| 769 | } | ||
| 770 | } finally { | ||
| 771 | if (background) fs.closeSync(output); | ||
| 772 | } | ||
| 773 | } else if (command === "open") { | ||
| 774 | if (rest.length > 1 || (rest[0] && rest[0] !== "--no-open")) { | ||
| 775 | throw new Error("Run ws open <name> [--no-open]."); | ||
| 776 | } | ||
| 777 | await openChat(argument, config, await t3(), rest[0] !== "--no-open"); | ||
| 778 | } else if (command === "gc") { | ||
| 779 | if (rest.length || (argument && argument !== "--dry-run")) { | ||
| 780 | throw new Error("Run ws gc [--dry-run]."); | ||
| 781 | } | ||
| 782 | const entries = fs.readdirSync(records).filter((file) => | ||
| 783 | file.endsWith(".json") | ||
| 784 | ); | ||
| 785 | try { | ||
| 786 | const client = await t3(); | ||
| 787 | const refs = await references(client); | ||
| 788 | for (const entry of entries) { | ||
| 789 | const id = entry.slice(0, -5); | ||
| 790 | const directory = workspace(id); | ||
| 791 | const file = path.join(records, entry); | ||
| 792 | const record = JSON.parse(fs.readFileSync(file)); | ||
| 793 | const idleSince = record.idleSince; | ||
| 794 | const blockers = Object.entries(refs).filter(([, paths]) => | ||
| 795 | paths.some((candidate) => inside(candidate, canonical(directory))) | ||
| 796 | ).map(([kind]) => kind); | ||
| 797 | if (!record.threadId || !record.prepared) blockers.push("unfinished setup"); | ||
| 798 | if (blockers.length) { | ||
| 799 | record.idleSince = null; | ||
| 800 | if (argument === "--dry-run") { | ||
| 801 | console.log(`${id}: held by ${blockers.join(", ")}`); | ||
| 802 | } | ||
| 803 | } else { | ||
| 804 | record.idleSince ??= Date.now(); | ||
| 805 | if (Date.now() - record.idleSince >= 60_000) { | ||
| 806 | if (argument === "--dry-run") { | ||
| 807 | console.log(`${id}: ready for cleanup`); | ||
| 808 | continue; | ||
| 809 | } | ||
| 810 | const fresh = await references(client); | ||
| 811 | if ( | ||
| 812 | Object.values(fresh).some((paths) => | ||
| 813 | paths.some((candidate) => | ||
| 814 | inside(candidate, canonical(directory)) | ||
| 815 | ) | ||
| 816 | ) | ||
| 817 | ) { | ||
| 818 | record.idleSince = null; | ||
| 819 | } else { | ||
| 820 | if ( | ||
| 821 | fs.lstatSync(directory).isSymbolicLink() || | ||
| 822 | canonical(directory) !== directory | ||
| 823 | ) { | ||
| 824 | throw new Error( | ||
| 825 | `Workspace ${id} was replaced by a link. Cleanup is paused.`, | ||
| 826 | ); | ||
| 827 | } | ||
| 828 | if (jjRepository(directory) !== jjRepository(config.repository)) { | ||
| 829 | throw new Error( | ||
| 830 | `Workspace ${id} belongs to another repository. Cleanup is paused.`, | ||
| 831 | ); | ||
| 832 | } | ||
| 833 | run("jj", ["status"], directory); | ||
| 834 | run( | ||
| 835 | "jj", | ||
| 836 | ["--ignore-working-copy", "workspace", "forget", `workspaces-${id}`], | ||
| 837 | config.repository, | ||
| 838 | ); | ||
| 839 | fs.rmSync(directory, { recursive: true }); | ||
| 840 | fs.rmSync(file); | ||
| 841 | console.log(`Removed workspace ${id}`); | ||
| 842 | continue; | ||
| 843 | } | ||
| 844 | } else if (argument === "--dry-run") { | ||
| 845 | console.log(`${id}: grace period`); | ||
| 846 | } | ||
| 847 | } | ||
| 848 | if (record.idleSince !== idleSince) writeJson(file, record); | ||
| 849 | } | ||
| 850 | } catch (error) { | ||
| 851 | for (const entry of entries) { | ||
| 852 | const file = path.join(records, entry); | ||
| 853 | if (!fs.existsSync(file)) continue; | ||
| 854 | const record = JSON.parse(fs.readFileSync(file)); | ||
| 855 | if (record.idleSince !== null) { | ||
| 856 | record.idleSince = null; | ||
| 857 | writeJson(file, record); | ||
| 858 | } | ||
| 859 | } | ||
| 860 | throw error; | ||
| 861 | } | ||
| 862 | } else throw new Error("Unknown workspace command. Run ws --help."); | ||
| 863 | } | ||
| 864 | |||
| 865 | if ( | ||
| 866 | process.argv[1] && | ||
| 867 | path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) | ||
| 868 | ) { | ||
| 869 | main(process.argv.slice(2)).catch((error) => { | ||
| 870 | if (process.argv[2] === "ready-hook") { | ||
| 871 | console.log(JSON.stringify({ | ||
| 872 | continue: false, stopReason: error.message, systemMessage: error.message, | ||
| 873 | })); | ||
| 874 | return; | ||
| 875 | } | ||
| 876 | if (error.stderr?.length) console.error(error.stderr.toString().trim()); | ||
| 877 | console.error(`Error: ${error.message.split("\n", 1)[0]}`); | ||
| 878 | process.exitCode = 1; | ||
| 879 | }); | ||
| 880 | } | ||
users/clover/packages/workspaces/workspaces.test.mjs created+634| ... | @@ -0,0 +1,634 @@ | ||
| 1 | import assert from "node:assert/strict"; | ||
| 2 | import { mock, test } from "node:test"; | ||
| 3 | import fs from "node:fs"; | ||
| 4 | import path from "node:path"; | ||
| 5 | import net from "node:net"; | ||
| 6 | import childProcess from "node:child_process"; | ||
| 7 | import { once } from "node:events"; | ||
| 8 | import { randomUUID } from "node:crypto"; | ||
| 9 | import { fileURLToPath } from "node:url"; | ||
| 10 | |||
| 11 | const cli = process.env.T3_TEST_CLI; | ||
| 12 | const native = process.env.WORKSPACE_TEST_NATIVE; | ||
| 13 | |||
| 14 | test("workspace lifecycle through nightly, JJ, APFS, and reference sockets", { | ||
| 15 | skip: !cli || !native, | ||
| 16 | timeout: 120_000, | ||
| 17 | }, async () => { | ||
| 18 | const directory = fs.realpathSync(fs.mkdtempSync("/tmp/workspaces-test-")); | ||
| 19 | const originalHome = process.env.HOME; | ||
| 20 | const originalT3 = process.env.T3CODE_HOME; | ||
| 21 | const originalPath = process.env.PATH; | ||
| 22 | process.env.HOME = directory; | ||
| 23 | process.env.T3CODE_HOME = path.join(directory, ".t3"); | ||
| 24 | process.env.PATH = path.dirname(native) + path.delimiter + originalPath; | ||
| 25 | const source = path.join(directory, "source"); | ||
| 26 | const run = childProcess.execFileSync; | ||
| 27 | const reservation = net.createServer(); | ||
| 28 | reservation.listen(0, "127.0.0.1"); | ||
| 29 | await once(reservation, "listening"); | ||
| 30 | const port = reservation.address().port; | ||
| 31 | await new Promise((resolve) => reservation.close(resolve)); | ||
| 32 | const serverLog = fs.openSync(path.join(directory, "t3.log"), "w"); | ||
| 33 | const server = childProcess.spawn(cli, [ | ||
| 34 | "serve", | ||
| 35 | "--base-dir", | ||
| 36 | process.env.T3CODE_HOME, | ||
| 37 | "--port", | ||
| 38 | String(port), | ||
| 39 | "--no-browser", | ||
| 40 | ], { stdio: ["ignore", serverLog, serverLog] }); | ||
| 41 | let editor; | ||
| 42 | let shell; | ||
| 43 | try { | ||
| 44 | fs.mkdirSync(path.join(source, "shared/local"), { recursive: true }); | ||
| 45 | fs.writeFileSync(path.join(source, ".gitignore"), "node_modules/\n"); | ||
| 46 | fs.writeFileSync( | ||
| 47 | path.join(source, "logo.svg"), | ||
| 48 | '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8" fill="red"/></svg>', | ||
| 49 | ); | ||
| 50 | fs.writeFileSync( | ||
| 51 | path.join(source, "package.json"), | ||
| 52 | JSON.stringify({ | ||
| 53 | name: "fixture", | ||
| 54 | private: true, | ||
| 55 | packageManager: "pnpm@10.32.1", | ||
| 56 | dependencies: { "local-dependency": "workspace:*" }, | ||
| 57 | }), | ||
| 58 | ); | ||
| 59 | fs.writeFileSync( | ||
| 60 | path.join(source, "pnpm-workspace.yaml"), | ||
| 61 | "packages:\n - shared/*\n", | ||
| 62 | ); | ||
| 63 | fs.writeFileSync( | ||
| 64 | path.join(source, "shared/local/package.json"), | ||
| 65 | JSON.stringify({ | ||
| 66 | name: "local-dependency", | ||
| 67 | version: "1.0.0", | ||
| 68 | main: "index.js", | ||
| 69 | bin: { "local-command": "bin.js" }, | ||
| 70 | }), | ||
| 71 | ); | ||
| 72 | fs.writeFileSync( | ||
| 73 | path.join(source, "shared/local/index.js"), | ||
| 74 | "module.exports = 42;\n", | ||
| 75 | ); | ||
| 76 | fs.writeFileSync( | ||
| 77 | path.join(source, "shared/local/bin.js"), | ||
| 78 | "#!/usr/bin/env node\nconsole.log(process.env.NODE_PATH);\n", | ||
| 79 | ); | ||
| 80 | run("jj", ["git", "init", "--colocate", source], { stdio: "pipe" }); | ||
| 81 | run("pnpm", ["install", "--no-frozen-lockfile"], { | ||
| 82 | cwd: source, | ||
| 83 | stdio: "pipe", | ||
| 84 | timeout: 30_000, | ||
| 85 | }); | ||
| 86 | const origin = path.join(directory, "origin"); | ||
| 87 | run("jj", ["git", "init", origin], { stdio: "pipe" }); | ||
| 88 | run("jj", ["describe", "-m", "Fixture main"], { cwd: source, stdio: "pipe" }); | ||
| 89 | run("jj", ["bookmark", "set", "main"], { cwd: source, stdio: "pipe" }); | ||
| 90 | run("jj", ["git", "remote", "add", "origin", path.join(origin, ".jj/repo/store/git")], { | ||
| 91 | cwd: source, | ||
| 92 | stdio: "pipe", | ||
| 93 | }); | ||
| 94 | run("jj", ["--config", "git.sign-on-push=false", "git", "push", "--bookmark", "main"], { | ||
| 95 | cwd: source, | ||
| 96 | stdio: "pipe", | ||
| 97 | }); | ||
| 98 | run("jj", ["git", "import"], { cwd: origin, stdio: "pipe" }); | ||
| 99 | run("jj", ["new", "main"], { cwd: origin, stdio: "pipe" }); | ||
| 100 | fs.writeFileSync(path.join(origin, "upstream.txt"), "latest main\n"); | ||
| 101 | run("jj", ["describe", "-m", "Advance remote main"], { | ||
| 102 | cwd: origin, | ||
| 103 | stdio: "pipe", | ||
| 104 | }); | ||
| 105 | run("jj", ["bookmark", "set", "main"], { cwd: origin, stdio: "pipe" }); | ||
| 106 | run("jj", ["git", "export"], { cwd: origin, stdio: "pipe" }); | ||
| 107 | const latestMain = run("jj", ["log", "-r", "main", "--no-graph", "-T", "commit_id"], { | ||
| 108 | cwd: origin, | ||
| 109 | encoding: "utf8", | ||
| 110 | }).trim(); | ||
| 111 | assert.notEqual(run("jj", [ | ||
| 112 | "log", "-r", "main@origin", "--no-graph", "-T", "commit_id", | ||
| 113 | ], { cwd: source, encoding: "utf8" }).trim(), latestMain); | ||
| 114 | const runtime = path.join( | ||
| 115 | process.env.T3CODE_HOME, | ||
| 116 | "userdata/server-runtime.json", | ||
| 117 | ); | ||
| 118 | for (let attempt = 0; !fs.existsSync(runtime); attempt++) { | ||
| 119 | assert.ok( | ||
| 120 | attempt < 150 && server.exitCode === null, | ||
| 121 | "nightly server starts", | ||
| 122 | ); | ||
| 123 | await new Promise((resolve) => setTimeout(resolve, 100)); | ||
| 124 | } | ||
| 125 | const projectWorkspace = path.join(directory, "Fixture"); | ||
| 126 | run("jj", ["workspace", "add", "-r", "@", projectWorkspace], { | ||
| 127 | cwd: source, | ||
| 128 | stdio: "pipe", | ||
| 129 | }); | ||
| 130 | run( | ||
| 131 | cli, | ||
| 132 | ["project", "add", projectWorkspace, "--base-dir", process.env.T3CODE_HOME], | ||
| 133 | { stdio: "pipe", timeout: 15_000 }, | ||
| 134 | ); | ||
| 135 | const { main, t3 } = await import("./workspaces.mjs"); | ||
| 136 | const client = await t3(); | ||
| 137 | const project = (await client.snapshot()).projects[0]; | ||
| 138 | await client.dispatch({ | ||
| 139 | type: "project.update", | ||
| 140 | projectId: project.id, | ||
| 141 | projectIcon: { kind: "monogram", text: "F", color: "red" }, | ||
| 142 | faviconPath: "logo.svg", | ||
| 143 | defaultThreadEnvMode: "worktree", | ||
| 144 | }); | ||
| 145 | await client.dispatch({ | ||
| 146 | type: "thread.create", | ||
| 147 | threadId: randomUUID(), | ||
| 148 | projectId: project.id, | ||
| 149 | title: "Model source", | ||
| 150 | modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" }, | ||
| 151 | runtimeMode: "approval-required", | ||
| 152 | interactionMode: "default", | ||
| 153 | branch: null, | ||
| 154 | worktreePath: null, | ||
| 155 | createdBy: "user", | ||
| 156 | creationSource: "web", | ||
| 157 | }); | ||
| 158 | await main(["setup", source]); | ||
| 159 | const sourceChange = run("jj", ["log", "-r", "@", "--no-graph", "-T", "change_id"], { | ||
| 160 | cwd: source, | ||
| 161 | encoding: "utf8", | ||
| 162 | }).trim(); | ||
| 163 | fs.writeFileSync(path.join(source, "local-only.txt"), "uncommitted source work\n"); | ||
| 164 | fs.writeFileSync(path.join(projectWorkspace, "rewrite.txt"), "changed from another workspace\n"); | ||
| 165 | run("jj", ["restore", "--from", "@", "--into", sourceChange, "rewrite.txt"], { | ||
| 166 | cwd: projectWorkspace, | ||
| 167 | stdio: "pipe", | ||
| 168 | }); | ||
| 169 | assert.throws(() => run("jj", ["--config", "snapshot.auto-update-stale=false", "st"], { | ||
| 170 | cwd: source, | ||
| 171 | stdio: "pipe", | ||
| 172 | }), (error) => /working copy is stale/.test(error.stderr.toString())); | ||
| 173 | const firstBin = path.join(directory, "first-bin"); | ||
| 174 | fs.mkdirSync(firstBin); | ||
| 175 | const pnpm = run("/usr/bin/which", ["pnpm"], { encoding: "utf8" }).trim(); | ||
| 176 | fs.writeFileSync(path.join(firstBin, "pnpm"), `#!/usr/bin/env node | ||
| 177 | const fs = require("node:fs"); | ||
| 178 | const childProcess = require("node:child_process"); | ||
| 179 | const assert = require("node:assert/strict"); | ||
| 180 | const args = process.argv.slice(2); | ||
| 181 | if (args[0] === "install" && process.cwd() === ${JSON.stringify(path.join(directory, "workspaces/first"))}) { | ||
| 182 | const record = JSON.parse(fs.readFileSync(${JSON.stringify(path.join(directory, ".local/state/workspaces/workspaces/first.json"))})); | ||
| 183 | assert.ok(record.threadId, "chat is durable before dependency installation"); | ||
| 184 | assert.equal(record.prepared, false); | ||
| 185 | console.error("Error: fixture installation interrupted"); | ||
| 186 | process.exit(41); | ||
| 187 | } | ||
| 188 | const result = childProcess.spawnSync(${JSON.stringify(pnpm)}, args, { stdio: "inherit" }); | ||
| 189 | process.exit(result.status ?? 1); | ||
| 190 | `, { mode: 0o700 }); | ||
| 191 | const nativePath = process.env.PATH; | ||
| 192 | process.env.PATH = firstBin + path.delimiter + nativePath; | ||
| 193 | let opened = false; | ||
| 194 | const launchMock = mock.method( | ||
| 195 | childProcess, | ||
| 196 | "execFileSync", | ||
| 197 | (command, args, options) => { | ||
| 198 | if (command === "/usr/bin/open") { | ||
| 199 | opened = true; | ||
| 200 | assert.match(args.at(-1), /^t3code:\/\/threads\//); | ||
| 201 | assert.equal( | ||
| 202 | fs.existsSync(path.join(directory, "workspaces/first/.jj")), | ||
| 203 | false, | ||
| 204 | "desktop opens before JJ initializes the folder", | ||
| 205 | ); | ||
| 206 | return ""; | ||
| 207 | } | ||
| 208 | return run(command, args, options); | ||
| 209 | }, | ||
| 210 | ); | ||
| 211 | await assert.rejects( | ||
| 212 | main(["new", "first", "-r", "@"]), | ||
| 213 | /setup stopped/, | ||
| 214 | ); | ||
| 215 | assert.ok(opened, "desktop opens before dependency installation"); | ||
| 216 | process.env.PATH = nativePath; | ||
| 217 | launchMock.mock.restore(); | ||
| 218 | assert.equal(fs.readFileSync(path.join(source, "local-only.txt"), "utf8"), | ||
| 219 | "uncommitted source work\n", "creation preserves unsaved source edits"); | ||
| 220 | assert.equal(fs.existsSync(path.join(source, "rewrite.txt")), false, | ||
| 221 | "workspace creation leaves the stale source checkout untouched"); | ||
| 222 | assert.throws(() => run("jj", ["--config", "snapshot.auto-update-stale=false", "st"], { | ||
| 223 | cwd: source, | ||
| 224 | stdio: "pipe", | ||
| 225 | }), (error) => /working copy is stale/.test(error.stderr.toString())); | ||
| 226 | await main(["setup", projectWorkspace]); | ||
| 227 | await main(["setup", source]); | ||
| 228 | await main(["new", "second", "--no-open"]); | ||
| 229 | const created = (await client.snapshot()).threads.find((thread) => | ||
| 230 | thread.title === "Fixture | second" | ||
| 231 | ); | ||
| 232 | assert.equal( | ||
| 233 | created.runtimeMode, | ||
| 234 | "approval-required", | ||
| 235 | "new chats retain the source chat's permission mode", | ||
| 236 | ); | ||
| 237 | const first = path.join(directory, "workspaces/first"); | ||
| 238 | const second = path.join(directory, "workspaces/second"); | ||
| 239 | const projects = (await client.snapshot()).projects; | ||
| 240 | const firstProject = projects.find((project) => | ||
| 241 | project.workspaceRoot === first | ||
| 242 | ); | ||
| 243 | const secondProject = projects.find((project) => | ||
| 244 | project.workspaceRoot === second | ||
| 245 | ); | ||
| 246 | assert.equal(firstProject.title, "Fixture | first"); | ||
| 247 | assert.equal(secondProject.title, "Fixture | second"); | ||
| 248 | assert.notEqual(firstProject.id, secondProject.id); | ||
| 249 | assert.equal(created.projectId, secondProject.id); | ||
| 250 | assert.equal( | ||
| 251 | created.worktreePath, null, "new chats use their workspace project's root", | ||
| 252 | ); | ||
| 253 | assert.deepEqual(secondProject.projectIcon, { | ||
| 254 | kind: "monogram", text: "F", color: "red", | ||
| 255 | }); | ||
| 256 | assert.equal(secondProject.faviconPath, "logo.svg"); | ||
| 257 | assert.equal(secondProject.defaultThreadEnvMode, "local"); | ||
| 258 | assert.deepEqual(secondProject.defaultModelSelection, created.modelSelection); | ||
| 259 | assert.equal(run("jj", ["log", "-r", "@-", "--no-graph", "-T", "commit_id"], { | ||
| 260 | cwd: second, | ||
| 261 | encoding: "utf8", | ||
| 262 | }).trim(), latestMain, "default creation fetches the latest remote main"); | ||
| 263 | assert.equal(fs.readFileSync(path.join(second, "upstream.txt"), "utf8"), "latest main\n"); | ||
| 264 | assert.equal(fs.existsSync(path.join(second, "local-only.txt")), false, | ||
| 265 | "default creation excludes source-only work"); | ||
| 266 | assert.equal( | ||
| 267 | run(process.execPath, [ | ||
| 268 | "-e", | ||
| 269 | "process.stdout.write(String(require('local-dependency')))", | ||
| 270 | ], { cwd: second, encoding: "utf8" }), | ||
| 271 | "42", | ||
| 272 | ); | ||
| 273 | const launcherPaths = run( | ||
| 274 | path.join(second, "node_modules/.bin/local-command"), | ||
| 275 | [], | ||
| 276 | { cwd: second, encoding: "utf8" }, | ||
| 277 | ); | ||
| 278 | assert.ok(launcherPaths.includes(second)); | ||
| 279 | assert.equal( | ||
| 280 | launcherPaths.includes(source) || launcherPaths.includes(first), | ||
| 281 | false, | ||
| 282 | "pnpm relocates launchers after cloning", | ||
| 283 | ); | ||
| 284 | const clonedFile = path.join(second, "node_modules/.pnpm/lock.yaml"); | ||
| 285 | const cachedFile = path.join( | ||
| 286 | directory, | ||
| 287 | ".cache/workspaces/deps/node_modules/.pnpm/lock.yaml", | ||
| 288 | ); | ||
| 289 | const cachedContents = fs.readFileSync(cachedFile, "utf8"); | ||
| 290 | assert.notEqual(fs.statSync(clonedFile).ino, fs.statSync(cachedFile).ino); | ||
| 291 | fs.appendFileSync(clonedFile, "\n# isolated edit\n"); | ||
| 292 | assert.equal(fs.readFileSync(cachedFile, "utf8"), cachedContents); | ||
| 293 | assert.equal( | ||
| 294 | fs.readlinkSync(path.join(second, "node_modules/local-dependency")), | ||
| 295 | "../shared/local", | ||
| 296 | ); | ||
| 297 | |||
| 298 | const background = path.join(directory, "workspaces/background"); | ||
| 299 | const started = path.join(directory, "preparation-started"); | ||
| 300 | const release = path.join(directory, "preparation-release"); | ||
| 301 | const fetchStarted = path.join(directory, "fetch-started"); | ||
| 302 | const fetchRelease = path.join(directory, "fetch-release"); | ||
| 303 | const bin = path.join(directory, "bin"); | ||
| 304 | fs.mkdirSync(bin); | ||
| 305 | fs.writeFileSync(path.join(bin, "jj"), `#!/bin/sh | ||
| 306 | case "$*" in | ||
| 307 | *"git fetch"*) | ||
| 308 | touch "$WORKSPACE_TEST_FETCH_STARTED" | ||
| 309 | while [ ! -f "$WORKSPACE_TEST_FETCH_RELEASE" ]; do sleep 0.05; done | ||
| 310 | ;; | ||
| 311 | esac | ||
| 312 | exec "$WORKSPACE_TEST_JJ" "$@" | ||
| 313 | `, { mode: 0o700 }); | ||
| 314 | fs.writeFileSync(path.join(bin, "pnpm"), `#!/bin/sh | ||
| 315 | if [ "$1" = install ] && [ "$PWD" = "$WORKSPACE_TEST_BACKGROUND" ]; then | ||
| 316 | touch "$WORKSPACE_TEST_STARTED" | ||
| 317 | while [ ! -f "$WORKSPACE_TEST_RELEASE" ]; do sleep 0.05; done | ||
| 318 | fi | ||
| 319 | exec "$WORKSPACE_TEST_PNPM" "$@" | ||
| 320 | `, { mode: 0o700 }); | ||
| 321 | const script = fileURLToPath(new URL("./workspaces.mjs", import.meta.url)); | ||
| 322 | const preparationEnv = { | ||
| 323 | ...process.env, | ||
| 324 | PATH: bin + path.delimiter + process.env.PATH, | ||
| 325 | WORKSPACE_TEST_BACKGROUND: background, | ||
| 326 | WORKSPACE_TEST_STARTED: started, | ||
| 327 | WORKSPACE_TEST_RELEASE: release, | ||
| 328 | WORKSPACE_TEST_FETCH_STARTED: fetchStarted, | ||
| 329 | WORKSPACE_TEST_FETCH_RELEASE: fetchRelease, | ||
| 330 | WORKSPACE_TEST_JJ: run("/usr/bin/which", ["jj"], { | ||
| 331 | encoding: "utf8", | ||
| 332 | }).trim(), | ||
| 333 | WORKSPACE_TEST_PNPM: pnpm, | ||
| 334 | }; | ||
| 335 | const creator = childProcess.spawn(native, [ | ||
| 336 | "lock", | ||
| 337 | path.join(directory, ".local/state/workspaces/creation-lock"), | ||
| 338 | process.execPath, | ||
| 339 | script, | ||
| 340 | "new", "background", "--no-open", "--background", | ||
| 341 | ], { | ||
| 342 | env: preparationEnv, | ||
| 343 | stdio: ["ignore", "pipe", "pipe"], | ||
| 344 | }); | ||
| 345 | let creatorOutput = ""; | ||
| 346 | creator.stdout.on("data", (chunk) => { creatorOutput += chunk; }); | ||
| 347 | creator.stderr.on("data", (chunk) => { creatorOutput += chunk; }); | ||
| 348 | const [creatorStatus] = await once(creator, "exit"); | ||
| 349 | assert.equal(creatorStatus, 0, creatorOutput); | ||
| 350 | const backgroundRecord = path.join( | ||
| 351 | directory, ".local/state/workspaces/workspaces/background.json", | ||
| 352 | ); | ||
| 353 | assert.equal(JSON.parse(fs.readFileSync(backgroundRecord)).prepared, false); | ||
| 354 | for (let attempt = 0; !fs.existsSync(fetchStarted); attempt++) { | ||
| 355 | assert.ok(attempt < 200, "background preparation starts fetching main"); | ||
| 356 | await new Promise((resolve) => setTimeout(resolve, 50)); | ||
| 357 | } | ||
| 358 | assert.equal(fs.existsSync(path.join(background, ".jj")), false, | ||
| 359 | "the chat is available while fetching main and before JJ initialization"); | ||
| 360 | fs.writeFileSync(fetchRelease, ""); | ||
| 361 | for (let attempt = 0; !fs.existsSync(started); attempt++) { | ||
| 362 | assert.ok(attempt < 200, "background preparation reaches installation"); | ||
| 363 | await new Promise((resolve) => setTimeout(resolve, 50)); | ||
| 364 | } | ||
| 365 | assert.throws( | ||
| 366 | () => run(native, [ | ||
| 367 | "lock", path.join(directory, ".local/state/workspaces/lock"), "/usr/bin/true", | ||
| 368 | ], { stdio: "pipe" }), | ||
| 369 | (error) => /Another workspace command/.test(error.stderr.toString()), | ||
| 370 | "background preparation retains the workspace lock after its parent exits", | ||
| 371 | ); | ||
| 372 | const queued = childProcess.spawn(native, [ | ||
| 373 | "lock", path.join(directory, ".local/state/workspaces/creation-lock"), | ||
| 374 | process.execPath, script, "new", "queued", "--no-open", "--background", | ||
| 375 | ], { env: preparationEnv, stdio: "pipe" }); | ||
| 376 | let queuedOutput = ""; | ||
| 377 | queued.stderr.on("data", (chunk) => { queuedOutput += chunk; }); | ||
| 378 | const [queuedStatus] = await once(queued, "exit"); | ||
| 379 | assert.equal(queuedStatus, 0, queuedOutput); | ||
| 380 | const queuedRecord = path.join(directory, ".local/state/workspaces/workspaces/queued.json"); | ||
| 381 | assert.ok(JSON.parse(fs.readFileSync(queuedRecord)).threadId, | ||
| 382 | "another chat can be created while a preparation worker holds the lock"); | ||
| 383 | assert.equal(fs.existsSync(path.join(directory, "workspaces/queued/.jj")), false); | ||
| 384 | fs.writeFileSync(release, ""); | ||
| 385 | for (let attempt = 0; | ||
| 386 | !JSON.parse(fs.readFileSync(backgroundRecord)).prepared || | ||
| 387 | !JSON.parse(fs.readFileSync(queuedRecord)).prepared; | ||
| 388 | attempt++) { | ||
| 389 | assert.ok(attempt < 200, "background preparation finishes"); | ||
| 390 | await new Promise((resolve) => setTimeout(resolve, 50)); | ||
| 391 | } | ||
| 392 | |||
| 393 | const recordFile = path.join( | ||
| 394 | directory, | ||
| 395 | ".local/state/workspaces/workspaces/first.json", | ||
| 396 | ); | ||
| 397 | const readRecord = () => JSON.parse(fs.readFileSync(recordFile)); | ||
| 398 | const age = () => | ||
| 399 | fs.writeFileSync( | ||
| 400 | recordFile, | ||
| 401 | JSON.stringify({ ...readRecord(), idleSince: Date.now() - 61_000 }), | ||
| 402 | ); | ||
| 403 | let editorPaths = []; | ||
| 404 | const sockets = path.join(directory, ".local/state/workspaces/vscode"); | ||
| 405 | fs.mkdirSync(sockets, { recursive: true }); | ||
| 406 | editor = net.createServer((socket) => | ||
| 407 | socket.end(JSON.stringify({ pid: process.pid, paths: editorPaths })) | ||
| 408 | ); | ||
| 409 | editor.listen(path.join(sockets, `${process.pid}.sock`)); | ||
| 410 | await once(editor, "listening"); | ||
| 411 | let unknownEditor = false; | ||
| 412 | const childMock = mock.method( | ||
| 413 | childProcess, | ||
| 414 | "execFileSync", | ||
| 415 | (command, args, options) => { | ||
| 416 | if ( | ||
| 417 | command === "/bin/ps" && args.join(" ") === "-axo pid=,comm=" | ||
| 418 | ) { | ||
| 419 | return "123 /Applications/Visual Studio Code.app/Contents/MacOS/Code"; | ||
| 420 | } | ||
| 421 | if ( | ||
| 422 | command === "/usr/local/bin/code" | ||
| 423 | ) { | ||
| 424 | return `1 100 123 code\n1 100 234 window [1]\n1 100 ${ | ||
| 425 | unknownEditor ? process.pid + 1 : process.pid | ||
| 426 | } extension-host [1]`; | ||
| 427 | } | ||
| 428 | return run(command, args, options); | ||
| 429 | }, | ||
| 430 | ); | ||
| 431 | |||
| 432 | age(); | ||
| 433 | await main(["gc"]); | ||
| 434 | assert.ok( | ||
| 435 | fs.existsSync(first), | ||
| 436 | "idle but unsettled chat owns the workspace", | ||
| 437 | ); | ||
| 438 | assert.equal(readRecord().idleSince, null); | ||
| 439 | const originalThread = readRecord().threadId; | ||
| 440 | await client.dispatch({ type: "thread.settle", threadId: originalThread }); | ||
| 441 | age(); | ||
| 442 | await main(["gc"]); | ||
| 443 | assert.ok( | ||
| 444 | fs.existsSync(first), | ||
| 445 | "settled chat cannot release an unfinished setup", | ||
| 446 | ); | ||
| 447 | assert.equal(readRecord().idleSince, null); | ||
| 448 | await main(["deps", "first"]); | ||
| 449 | assert.equal(readRecord().prepared, true, "dependency repair finishes setup"); | ||
| 450 | await main(["open", "first", "--no-open"]); | ||
| 451 | assert.equal( | ||
| 452 | (await client.snapshot()).threads.find((thread) => | ||
| 453 | thread.id === originalThread | ||
| 454 | ).settledOverride, | ||
| 455 | "active", | ||
| 456 | "opening a workspace renews the chat's claim", | ||
| 457 | ); | ||
| 458 | await client.dispatch({ type: "thread.settle", threadId: originalThread }); | ||
| 459 | await main(["gc"]); | ||
| 460 | assert.ok(fs.existsSync(first), "settlement begins the grace period"); | ||
| 461 | assert.ok(readRecord().idleSince > Date.now() - 5000); | ||
| 462 | |||
| 463 | editorPaths = [path.join(first, "shared/local")]; | ||
| 464 | age(); | ||
| 465 | await main(["gc"]); | ||
| 466 | assert.ok(fs.existsSync(first), "editor subfolder keeps the workspace"); | ||
| 467 | assert.equal(readRecord().idleSince, null); | ||
| 468 | editorPaths = []; | ||
| 469 | |||
| 470 | shell = childProcess.spawn("/bin/zsh", [ | ||
| 471 | "-c", | ||
| 472 | "while read -r line; do :; done", | ||
| 473 | ], { | ||
| 474 | cwd: path.join(first, "shared/local"), | ||
| 475 | stdio: ["pipe", "ignore", "ignore"], | ||
| 476 | }); | ||
| 477 | fs.mkdirSync(path.join(directory, ".local/state/workspaces/shells"), { | ||
| 478 | recursive: true, | ||
| 479 | }); | ||
| 480 | fs.writeFileSync( | ||
| 481 | path.join(directory, ".local/state/workspaces/shells", String(shell.pid)), | ||
| 482 | path.join(first, "shared/local"), | ||
| 483 | ); | ||
| 484 | age(); | ||
| 485 | await main(["gc"]); | ||
| 486 | assert.ok(fs.existsSync(first), "live shell subfolder keeps the workspace"); | ||
| 487 | assert.equal(readRecord().idleSince, null); | ||
| 488 | shell.stdin.end(); | ||
| 489 | await once(shell, "exit"); | ||
| 490 | |||
| 491 | unknownEditor = true; | ||
| 492 | age(); | ||
| 493 | await assert.rejects(main(["gc"])); | ||
| 494 | assert.ok(fs.existsSync(first), "missing editor tracker prevents deletion"); | ||
| 495 | assert.equal(readRecord().idleSince, null); | ||
| 496 | unknownEditor = false; | ||
| 497 | |||
| 498 | const runtimeContents = fs.readFileSync(runtime); | ||
| 499 | fs.rmSync(runtime); | ||
| 500 | age(); | ||
| 501 | await assert.rejects(main(["gc"])); | ||
| 502 | assert.ok(fs.existsSync(first), "unavailable T3 prevents deletion"); | ||
| 503 | assert.equal(readRecord().idleSince, null); | ||
| 504 | fs.writeFileSync(runtime, runtimeContents); | ||
| 505 | |||
| 506 | const anotherThread = randomUUID(); | ||
| 507 | await client.dispatch({ | ||
| 508 | type: "thread.create", | ||
| 509 | threadId: anotherThread, | ||
| 510 | projectId: firstProject.id, | ||
| 511 | title: "Shared workspace", | ||
| 512 | modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" }, | ||
| 513 | runtimeMode: "full-access", | ||
| 514 | interactionMode: "default", | ||
| 515 | branch: null, | ||
| 516 | worktreePath: null, | ||
| 517 | createdBy: "user", | ||
| 518 | creationSource: "web", | ||
| 519 | }); | ||
| 520 | age(); | ||
| 521 | await main(["gc"]); | ||
| 522 | assert.ok( | ||
| 523 | fs.existsSync(first), | ||
| 524 | "another unsettled chat in the workspace project keeps the folder", | ||
| 525 | ); | ||
| 526 | await client.dispatch({ type: "thread.archive", threadId: anotherThread }); | ||
| 527 | age(); | ||
| 528 | await main(["gc", "--dry-run"]); | ||
| 529 | assert.ok(fs.existsSync(first), "dry run never removes a workspace"); | ||
| 530 | fs.writeFileSync( | ||
| 531 | path.join(first, "saved.txt"), | ||
| 532 | "survives workspace cleanup\n", | ||
| 533 | ); | ||
| 534 | await main(["gc"]); | ||
| 535 | assert.equal(fs.existsSync(first), false); | ||
| 536 | const savedChange = run("jj", [ | ||
| 537 | "--ignore-working-copy", | ||
| 538 | "log", | ||
| 539 | "-r", | ||
| 540 | 'files("saved.txt")', | ||
| 541 | "--no-graph", | ||
| 542 | "-T", | ||
| 543 | "change_id", | ||
| 544 | ], { cwd: source, encoding: "utf8" }).trim(); | ||
| 545 | assert.equal( | ||
| 546 | run("jj", ["--ignore-working-copy", "file", "show", "saved.txt", "-r", savedChange], { | ||
| 547 | cwd: source, | ||
| 548 | encoding: "utf8", | ||
| 549 | }), | ||
| 550 | "survives workspace cleanup\n", | ||
| 551 | "JJ retains the snapshotted files", | ||
| 552 | ); | ||
| 553 | assert.ok(fs.existsSync(second), "unsettled sibling workspace survives"); | ||
| 554 | await main(["new", "first", "-r", "@", "--no-open"]); | ||
| 555 | const freshRecord = readRecord(); | ||
| 556 | assert.equal((await client.snapshot()).projects.filter((project) => | ||
| 557 | project.workspaceRoot === first | ||
| 558 | ).length, 1, "a reused folder reuses its registered project"); | ||
| 559 | assert.notEqual( | ||
| 560 | freshRecord.threadId, | ||
| 561 | originalThread, | ||
| 562 | "reusing a collected workspace name creates a fresh chat", | ||
| 563 | ); | ||
| 564 | await client.dispatch({ | ||
| 565 | type: "thread.settle", | ||
| 566 | threadId: freshRecord.threadId, | ||
| 567 | }); | ||
| 568 | age(); | ||
| 569 | await main(["gc"]); | ||
| 570 | const secondRecord = JSON.parse( | ||
| 571 | fs.readFileSync( | ||
| 572 | path.join(directory, ".local/state/workspaces/workspaces/second.json"), | ||
| 573 | ), | ||
| 574 | ); | ||
| 575 | await client.dispatch({ | ||
| 576 | type: "thread.delete", | ||
| 577 | threadId: secondRecord.threadId, | ||
| 578 | }); | ||
| 579 | fs.writeFileSync( | ||
| 580 | path.join(directory, ".local/state/workspaces/workspaces/second.json"), | ||
| 581 | JSON.stringify({ ...secondRecord, idleSince: Date.now() - 61_000 }), | ||
| 582 | ); | ||
| 583 | await main(["gc"]); | ||
| 584 | assert.equal( | ||
| 585 | fs.existsSync(second), | ||
| 586 | false, | ||
| 587 | "deleted chat releases its workspace", | ||
| 588 | ); | ||
| 589 | childMock.mock.restore(); | ||
| 590 | } finally { | ||
| 591 | mock.restoreAll(); | ||
| 592 | if (shell?.exitCode === null) shell.kill(); | ||
| 593 | if (editor) await new Promise((resolve) => editor.close(resolve)); | ||
| 594 | if (server.exitCode === null) { | ||
| 595 | server.kill("SIGKILL"); | ||
| 596 | await once(server, "exit"); | ||
| 597 | } | ||
| 598 | fs.closeSync(serverLog); | ||
| 599 | fs.rmSync(directory, { recursive: true, force: true, maxRetries: 3 }); | ||
| 600 | process.env.HOME = originalHome; | ||
| 601 | if (originalT3 === undefined) delete process.env.T3CODE_HOME; | ||
| 602 | else process.env.T3CODE_HOME = originalT3; | ||
| 603 | process.env.PATH = originalPath; | ||
| 604 | } | ||
| 605 | }); | ||
| 606 | |||
| 607 | test("workspace lock rejects overlap and releases after process exit", { | ||
| 608 | skip: !native, | ||
| 609 | }, async () => { | ||
| 610 | const directory = fs.mkdtempSync("/tmp/workspaces-lock-"); | ||
| 611 | const lock = path.join(directory, "lock"); | ||
| 612 | const holder = childProcess.spawn(native, [ | ||
| 613 | "lock", | ||
| 614 | lock, | ||
| 615 | process.execPath, | ||
| 616 | "-e", | ||
| 617 | "process.stdout.write('ready'); setInterval(() => {}, 1000)", | ||
| 618 | ]); | ||
| 619 | try { | ||
| 620 | await once(holder.stdout, "data"); | ||
| 621 | assert.throws( | ||
| 622 | () => childProcess.execFileSync(native, ["lock", lock, "/usr/bin/true"], { | ||
| 623 | stdio: "pipe", | ||
| 624 | }), | ||
| 625 | (error) => /Another workspace command/.test(error.stderr.toString()), | ||
| 626 | ); | ||
| 627 | holder.kill(); | ||
| 628 | await once(holder, "exit"); | ||
| 629 | childProcess.execFileSync(native, ["lock", lock, "/usr/bin/true"]); | ||
| 630 | } finally { | ||
| 631 | if (holder.exitCode === null && holder.signalCode === null) holder.kill(); | ||
| 632 | fs.rmSync(directory, { recursive: true, force: true }); | ||
| 633 | } | ||
| 634 | }); | ||
users/clover/work/home.nix+51-1| ... | @@ -1,5 +1,53 @@ | ... | @@ -1,5 +1,53 @@ |
| 1 | { pkgs, ... }: | 1 | { config, lib, pkgs, ... }: |
| 2 | let | ||
| 3 | workspaces = pkgs.callPackage ../packages/workspaces { }; | ||
| 4 | hookPython = pkgs.python3.withPackages (ps: [ ps.tomlkit ]); | ||
| 5 | in | ||
| 2 | { | 6 | { |
| 7 | home.file.".config/raycast/scripts/new-workspace.sh" = { | ||
| 8 | executable = true; | ||
| 9 | text = '' | ||
| 10 | #!/bin/bash | ||
| 11 | # @raycast.schemaVersion 1 | ||
| 12 | # @raycast.title New Workspace | ||
| 13 | # @raycast.mode silent | ||
| 14 | # @raycast.packageName T3 Code | ||
| 15 | # @raycast.icon 💬 | ||
| 16 | |||
| 17 | log="$(mktemp -t workspace)" | ||
| 18 | if ${workspaces}/bin/ws new --background > "$log" 2>&1; then | ||
| 19 | rm -f "$log" | ||
| 20 | else | ||
| 21 | mkdir -p "$HOME/Library/Logs" | ||
| 22 | mv "$log" "$HOME/Library/Logs/workspace-creation.log" | ||
| 23 | error="$(sed -n -e 's/^Error: //p' -e 's/^Internal error: //p' "$HOME/Library/Logs/workspace-creation.log" | head -n 1)" | ||
| 24 | printf '%s. Run ws new for details.\n' "''${error:-Workspace creation stopped}" | ||
| 25 | exit 1 | ||
| 26 | fi | ||
| 27 | ''; | ||
| 28 | }; | ||
| 29 | home.file.".vscode/extensions/clover.workspace-references".source = | ||
| 30 | config.lib.file.mkOutOfStoreSymlink "${config.home.homeDirectory}/config/users/clover/packages/workspaces/extension"; | ||
| 31 | programs.zsh.initContent = builtins.readFile ../packages/workspaces/shell.zsh; | ||
| 32 | home.activation.workspaceReadinessHooks = lib.hm.dag.entryAfter [ "codexConfig" ] '' | ||
| 33 | run ${hookPython}/bin/python3 ${../packages/workspaces/configure-hooks.py} \ | ||
| 34 | ${lib.escapeShellArg config.home.homeDirectory} \ | ||
| 35 | ${lib.escapeShellArg "${config.home.profileDirectory}/bin/ws ready-hook"} \ | ||
| 36 | ${lib.escapeShellArg "${config.home.homeDirectory}/.local/bin/codex"} | ||
| 37 | ''; | ||
| 38 | launchd.agents.workspace-cleanup = { | ||
| 39 | enable = true; | ||
| 40 | config = { | ||
| 41 | ProgramArguments = [ | ||
| 42 | "${workspaces}/bin/ws" | ||
| 43 | "gc" | ||
| 44 | ]; | ||
| 45 | StartInterval = 30; | ||
| 46 | RunAtLoad = true; | ||
| 47 | StandardErrorPath = "${config.home.homeDirectory}/Library/Logs/workspaces.log"; | ||
| 48 | StandardOutPath = "${config.home.homeDirectory}/Library/Logs/workspaces.log"; | ||
| 49 | }; | ||
| 50 | }; | ||
| 3 | programs = { | 51 | programs = { |
| 4 | zsh.profileExtra = '' | 52 | zsh.profileExtra = '' |
| 5 | _bun() { | 53 | _bun() { |
| ... | @@ -9,6 +57,7 @@ | ... | @@ -9,6 +57,7 @@ |
| 9 | ''; | 57 | ''; |
| 10 | }; | 58 | }; |
| 11 | home.packages = with pkgs; [ | 59 | home.packages = with pkgs; [ |
| 60 | workspaces | ||
| 12 | (bun.overrideAttrs (_: rec { | 61 | (bun.overrideAttrs (_: rec { |
| 13 | version = "1.3.5"; | 62 | version = "1.3.5"; |
| 14 | src = fetchurl { | 63 | src = fetchurl { |
| ... | @@ -19,6 +68,7 @@ | ... | @@ -19,6 +68,7 @@ |
| 19 | awscli2 | 68 | awscli2 |
| 20 | deno | 69 | deno |
| 21 | doppler | 70 | doppler |
| 71 | gh | ||
| 22 | rustup | 72 | rustup |
| 23 | ssm-session-manager-plugin | 73 | ssm-session-manager-plugin |
| 24 | terraform | 74 | terraform |