/ utils / crossProjectResume.ts
crossProjectResume.ts
 1  import { sep } from 'path'
 2  import { getOriginalCwd } from '../bootstrap/state.js'
 3  import type { LogOption } from '../types/logs.js'
 4  import { quote } from './bash/shellQuote.js'
 5  import { getSessionIdFromLog } from './sessionStorage.js'
 6  
 7  export type CrossProjectResumeResult =
 8    | {
 9        isCrossProject: false
10      }
11    | {
12        isCrossProject: true
13        isSameRepoWorktree: true
14        projectPath: string
15      }
16    | {
17        isCrossProject: true
18        isSameRepoWorktree: false
19        command: string
20        projectPath: string
21      }
22  
23  /**
24   * Check if a log is from a different project directory and determine
25   * whether it's a related worktree or a completely different project.
26   *
27   * For same-repo worktrees, we can resume directly without requiring cd.
28   * For different projects, we generate the cd command.
29   */
30  export function checkCrossProjectResume(
31    log: LogOption,
32    showAllProjects: boolean,
33    worktreePaths: string[],
34  ): CrossProjectResumeResult {
35    const currentCwd = getOriginalCwd()
36  
37    if (!showAllProjects || !log.projectPath || log.projectPath === currentCwd) {
38      return { isCrossProject: false }
39    }
40  
41    // Gate worktree detection to ants only for staged rollout
42    if (process.env.USER_TYPE !== 'ant') {
43      const sessionId = getSessionIdFromLog(log)
44      const command = `cd ${quote([log.projectPath])} && claude --resume ${sessionId}`
45      return {
46        isCrossProject: true,
47        isSameRepoWorktree: false,
48        command,
49        projectPath: log.projectPath,
50      }
51    }
52  
53    // Check if log.projectPath is under a worktree of the same repo
54    const isSameRepo = worktreePaths.some(
55      wt => log.projectPath === wt || log.projectPath!.startsWith(wt + sep),
56    )
57  
58    if (isSameRepo) {
59      return {
60        isCrossProject: true,
61        isSameRepoWorktree: true,
62        projectPath: log.projectPath,
63      }
64    }
65  
66    // Different repo - generate cd command
67    const sessionId = getSessionIdFromLog(log)
68    const command = `cd ${quote([log.projectPath])} && claude --resume ${sessionId}`
69    return {
70      isCrossProject: true,
71      isSameRepoWorktree: false,
72      command,
73      projectPath: log.projectPath,
74    }
75  }