Skip to content

Commit 67fd397

Browse files
committed
fix: desktop app worktree collision - use separate ID per worktree (anomalyco#5638)
1 parent 3ac42e9 commit 67fd397

3 files changed

Lines changed: 143 additions & 25 deletions

File tree

‎packages/opencode/src/project/project.ts‎

Lines changed: 105 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -44,51 +44,102 @@ export namespace Project {
4444
export async function fromDirectory(directory: string) {
4545
log.info("fromDirectory", { directory })
4646

47-
const { id, worktree, vcs } = await iife(async () => {
47+
const { id, worktree, vcs, oldProjectID } = await iife(async () => {
4848
const matches = Filesystem.up({ targets: [".git"], start: directory })
4949
const git = await matches.next().then((x) => x.value)
5050
await matches.return()
5151
if (git) {
5252
let worktree = path.dirname(git)
53-
let id = await Bun.file(path.join(git, "opencode"))
53+
// First resolve the actual worktree path before generating ID
54+
worktree = await $`git rev-parse --show-toplevel`
55+
.quiet()
56+
.nothrow()
57+
.cwd(worktree)
58+
.text()
59+
.then((x) => path.resolve(worktree, x.trim()))
60+
61+
// Get the actual git directory (handles worktrees where .git is a file pointing elsewhere)
62+
const gitDir = await $`git rev-parse --git-dir`
63+
.quiet()
64+
.nothrow()
65+
.cwd(worktree)
66+
.text()
67+
.then((x) => path.resolve(worktree, x.trim()))
68+
69+
// Detect if this is a linked worktree (gitDir contains .git/worktrees/)
70+
const isLinkedWorktree = gitDir.includes(".git/worktrees/")
71+
72+
// Read cached root commit from .git/opencode (backwards compat with old opencode)
73+
const cachedRootCommit = await Bun.file(path.join(gitDir, "opencode"))
5474
.text()
5575
.then((x) => x.trim())
5676
.catch(() => {})
57-
if (!id) {
58-
const roots = await $`git rev-list --max-parents=0 --all`
59-
.quiet()
60-
.nothrow()
61-
.cwd(worktree)
62-
.text()
63-
.then((x) =>
64-
x
65-
.split("\n")
66-
.filter(Boolean)
67-
.map((x) => x.trim())
68-
.toSorted(),
69-
)
70-
id = roots[0]
71-
if (id) Bun.file(path.join(git, "opencode")).write(id)
77+
78+
// For linked worktrees, also check for cached worktree hash
79+
const cachedWorktreeHash = isLinkedWorktree
80+
? await Bun.file(path.join(gitDir, "opencode-worktree"))
81+
.text()
82+
.then((x) => x.trim())
83+
.catch(() => {})
84+
: undefined
85+
86+
// If we have cached values, construct the ID and return early
87+
if (cachedRootCommit) {
88+
if (isLinkedWorktree && cachedWorktreeHash) {
89+
const id = `${cachedRootCommit}|${cachedWorktreeHash}`
90+
return { id, worktree, vcs: "git", oldProjectID: undefined }
91+
}
92+
if (!isLinkedWorktree) {
93+
return { id: cachedRootCommit, worktree, vcs: "git", oldProjectID: undefined }
94+
}
7295
}
73-
if (!id)
96+
97+
const roots = await $`git rev-list --max-parents=0 --all`
98+
.quiet()
99+
.nothrow()
100+
.cwd(worktree)
101+
.text()
102+
.then((x) =>
103+
x
104+
.split("\n")
105+
.filter(Boolean)
106+
.map((x) => x.trim())
107+
.toSorted(),
108+
)
109+
const rootCommit = roots[0]
110+
if (!rootCommit)
74111
return {
75112
id: "global",
76113
worktree,
77114
vcs: "git",
115+
oldProjectID: undefined,
78116
}
79-
worktree = await $`git rev-parse --show-toplevel`
80-
.quiet()
81-
.nothrow()
82-
.cwd(worktree)
83-
.text()
84-
.then((x) => path.resolve(worktree, x.trim()))
85-
return { id, worktree, vcs: "git" }
117+
118+
// For main worktree: use root commit as ID (backwards compat)
119+
// For linked worktrees: use root commit + "|" + hash of worktree path
120+
let id: string
121+
if (isLinkedWorktree) {
122+
const worktreeHash = Bun.hash(worktree).toString(16)
123+
id = `${rootCommit}|${worktreeHash}`
124+
Bun.file(path.join(gitDir, "opencode-worktree")).write(worktreeHash)
125+
} else {
126+
id = rootCommit
127+
}
128+
129+
// Write root commit to .git/opencode
130+
if (!cachedRootCommit) {
131+
Bun.file(path.join(gitDir, "opencode")).write(rootCommit)
132+
}
133+
134+
// No migration needed - main worktree keeps same ID format
135+
return { id, worktree, vcs: "git", oldProjectID: undefined }
86136
}
87137

88138
return {
89139
id: "global",
90140
worktree: "/",
91141
vcs: Info.shape.vcs.parse(Flag.OPENCODE_FAKE_VCS),
142+
oldProjectID: undefined,
92143
}
93144
})
94145

@@ -105,6 +156,10 @@ export namespace Project {
105156
}
106157
if (id !== "global") {
107158
await migrateFromGlobal(id, worktree)
159+
// Migrate from old project ID format (root commit only) to new format (hash of root commit + worktree)
160+
if (oldProjectID) {
161+
await migrateSessions(oldProjectID, id, worktree)
162+
}
108163
}
109164
}
110165
if (Flag.OPENCODE_EXPERIMENTAL_ICON_DISCOVERY) discover(existing)
@@ -180,6 +235,31 @@ export namespace Project {
180235
})
181236
}
182237

238+
async function migrateSessions(oldProjectID: string, newProjectID: string, worktree: string) {
239+
const oldProject = await Storage.read<Info>(["project", oldProjectID]).catch(() => undefined)
240+
if (!oldProject) return
241+
// Only migrate if the old project's worktree matches this worktree
242+
if (oldProject.worktree !== worktree) return
243+
244+
const oldSessions = await Storage.list(["session", oldProjectID]).catch(() => [])
245+
if (oldSessions.length === 0) return
246+
247+
log.info("migrating sessions", { from: oldProjectID, to: newProjectID, worktree, count: oldSessions.length })
248+
249+
await work(10, oldSessions, async (key) => {
250+
const sessionID = key[key.length - 1]
251+
const session = await Storage.read<Session.Info>(key).catch(() => undefined)
252+
if (!session) return
253+
254+
session.projectID = newProjectID
255+
log.info("migrating session", { sessionID, from: oldProjectID, to: newProjectID })
256+
await Storage.write(["session", newProjectID, sessionID], session)
257+
await Storage.remove(key)
258+
}).catch((error) => {
259+
log.error("failed to migrate sessions", { error, from: oldProjectID, to: newProjectID })
260+
})
261+
}
262+
183263
export async function setInitialized(projectID: string) {
184264
await Storage.update<Info>(["project", projectID], (draft) => {
185265
draft.time.initialized = Date.now()

‎packages/opencode/src/snapshot/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ export namespace Snapshot {
2626
.nothrow()
2727
// Configure git to not convert line endings on Windows
2828
await $`git --git-dir ${git} config core.autocrlf false`.quiet().nothrow()
29+
// Disable fsmonitor to avoid hangs when worktree is a linked git worktree
30+
await $`git --git-dir ${git} config core.fsmonitor false`.quiet().nothrow()
2931
log.info("initialized")
3032
}
3133
await $`git --git-dir ${git} --work-tree ${Instance.worktree} add .`.quiet().cwd(Instance.directory).nothrow()

‎packages/opencode/test/project/project.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,48 @@ describe("Project.fromDirectory", () => {
3232

3333
expect(project).toBeDefined()
3434
expect(project.id).not.toBe("global")
35+
expect(project.id).not.toContain("|") // main worktree uses root commit only
3536
expect(project.vcs).toBe("git")
3637
expect(project.worktree).toBe(tmp.path)
3738

3839
const opencodeFile = path.join(tmp.path, ".git", "opencode")
3940
const fileExists = await Bun.file(opencodeFile).exists()
4041
expect(fileExists).toBe(true)
42+
43+
// Should not create opencode-worktree file for main worktree
44+
const worktreeFile = path.join(tmp.path, ".git", "opencode-worktree")
45+
const worktreeFileExists = await Bun.file(worktreeFile).exists()
46+
expect(worktreeFileExists).toBe(false)
47+
})
48+
49+
test("should use different ID format for linked worktrees", async () => {
50+
await using tmp = await tmpdir({ git: true })
51+
const worktreePath = `${tmp.path}-worktree`
52+
await $`git worktree add ${worktreePath} HEAD`.cwd(tmp.path).quiet()
53+
54+
try {
55+
const mainProject = await Project.fromDirectory(tmp.path)
56+
const linkedProject = await Project.fromDirectory(worktreePath)
57+
58+
// Main worktree uses root commit only
59+
expect(mainProject.id).not.toContain("|")
60+
61+
// Linked worktree uses root commit + "|" + hash
62+
expect(linkedProject.id).toContain("|")
63+
expect(linkedProject.id.startsWith(mainProject.id + "|")).toBe(true)
64+
65+
// Different IDs for different worktrees
66+
expect(linkedProject.id).not.toBe(mainProject.id)
67+
68+
// Linked worktree should have opencode-worktree file
69+
const gitDir = await $`git rev-parse --git-dir`.cwd(worktreePath).quiet().text()
70+
const worktreeFile = path.join(gitDir.trim(), "opencode-worktree")
71+
const worktreeFileExists = await Bun.file(worktreeFile).exists()
72+
expect(worktreeFileExists).toBe(true)
73+
} finally {
74+
await $`git worktree remove --force ${worktreePath}`.cwd(tmp.path).quiet().nothrow()
75+
await $`rm -rf ${worktreePath}`.quiet()
76+
}
4177
})
4278
})
4379

0 commit comments

Comments
 (0)