From 3723150ad1e9d2d68099681aa38355bd03af6c10 Mon Sep 17 00:00:00 2001 From: lazyalex616 Date: Sun, 15 Nov 2026 21:47:39 +0800 Subject: [PATCH] fix: place synced sessions by project id when a repository lives at another path (#10) OpenCode 2 gives a repository the same project id on every machine. A session whose folder does not exist here now goes to this machine's project with that id, and a session parked in the home project moves into its repository's project once OpenCode has opened it here. Release 3.3.1. --- CHANGELOG.md | 9 ++++ CHANGELOG.zh-CN.md | 6 +++ README.md | 25 ++++++++-- README.zh-CN.md | 12 ++++- package-lock.json | 4 +- package.json | 2 +- src/core/projects.ts | 59 ++++++++++++++++++------ src/core/sessions.ts | 42 ++++++++++++++++- src/core/sync.ts | 3 ++ tests/sessions-v2.test.ts | 97 +++++++++++++++++++++++++++++++++++++++ 10 files changed, 237 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 129bc6c..8f8b9f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ [简体中文](./CHANGELOG.zh-CN.md) +## 3.3.1 + +### Fixed +- **A session from a repository checked out at a different path lands in that repository (#10).** OpenCode 2 lists only the current project's sessions, and 3.3.0 found a session's project by its folder alone. When the same repository lived at `~/code/app` on one machine and `D:/work/app` on another, the session was parked in the home folder's project and never showed up in `/session` inside the repository. OpenCode 2 gives a repository the same project id on every machine (from its remote URL, else `.git/opencode`, else its first commit), so an imported session now goes to this machine's project with that id, in the same subfolder when it exists here. +- **Parked sessions move into their repository later.** A session that arrived before the repository was cloned or opened on this machine was parked in the home folder's project and stayed there. The next pull after OpenCode has opened the repository here moves it into the repository's project. Only the session's location changes. + +### Contributors +- @spock64 — reported #10 + ## 3.3.0 OpenCode 2 support. Upgrade every machine before or together with OpenCode 2; diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 5ee8bcd..bdd2b42 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -2,6 +2,12 @@ [English](./CHANGELOG.md) +## 3.3.1 + +### 修复 +- **同一个仓库在两台电脑上路径不同时,会话也能进到这个仓库的项目里(#10)。** OpenCode 2 的 `/session` 只列出当前项目的会话,而 3.3.0 只按文件夹路径找会话所属的项目。同一个仓库在一台电脑上是 `~/code/app`、另一台是 `D:/work/app` 时,会话会被放进用户目录的项目里,在仓库里打开 `/session` 看不到。OpenCode 2 给同一个仓库在每台电脑上算出的项目 ID 都一样(先看远程地址,其次 `.git/opencode`,最后看第一个提交),所以现在导入的会话会放进本机同 ID 的项目里;原来的子文件夹本机也有时,放到那个子文件夹。 +- **先到的会话以后会自动挪回仓库。** 会话到达时本机还没克隆或打开过这个仓库,会被放进用户目录的项目里,以前就一直留在那里。现在 OpenCode 在本机打开过这个仓库后,下一次拉取会把它挪进仓库的项目。只改会话的位置,内容不动。 + ## 3.3.0 支持 OpenCode 2。请在升级 OpenCode 2 之前或同时,把每台电脑都升到这个版本;具体步骤见 README 的**升级到 OpenCode 2**。 diff --git a/README.md b/README.md index 8a61afa..27c3cd5 100644 --- a/README.md +++ b/README.md @@ -331,14 +331,31 @@ Instead each session is exported on its own as a small compressed file: its own. - **Lands in the right place.** On OpenCode 2 an imported session is placed in the project OpenCode 2 uses for its folder here. A folder under the other - machine's home is matched to the same folder under yours; a folder this - machine does not have puts the session in your home folder's project. + machine's home is matched to the same folder under yours, and a repository + checked out at a different path is matched by its project id. A session whose + folder or repository this machine does not have yet waits in your home + folder's project and moves into the repository's project on the first pull + after you open the repository here. - **Safe to import.** Each session is imported in one transaction, so a failure leaves your database as it was. Window, count and size limits are under **What to sync → Session settings**. Sessions need Node.js 22.5 or newer. +**How projects are handled (OpenCode 2).** Projects are not synced as such. +A project row records where a folder or repository lives on one machine, so +each machine keeps its own, and OpenCode creates them when it opens a folder. +What travels is the session, together with its project's id. OpenCode 2 gives +a repository the same id on every machine (from its remote URL, else +`.git/opencode`, else its first commit) and a plain folder an id from its +path, so on import the session is put into the matching project here: + +| On this machine | The session goes to | +|---|---| +| Same folder (or the same folder under your home) | That folder's project | +| Same repository, at another path | That repository's project, same subfolder if it exists | +| Neither yet | Your home folder's project; moved into the repository's project on the first pull after you open it here | + **Sessions missing from `/session` after upgrading to OpenCode 2?** OpenCode's own migration leaves some of them in a project `/session` never shows. Their content is intact: @@ -576,7 +593,9 @@ are still changing. **Diagnostics** in the menu shows whether the scheduled job is registered. **A synced session does not show up in `/session` (OpenCode 2).** Open -OpenCode in the session's folder; `/session` lists only that folder's project. +OpenCode in the session's folder or repository; `/session` lists only that +project. A session whose repository you have not opened on this machine yet is +in your home folder's project until the next pull after you open it. Sessions from before your upgrade to OpenCode 2: run `opencode-sync repair-sessions --apply`. diff --git a/README.zh-CN.md b/README.zh-CN.md index 5f93f45..9380624 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -270,11 +270,19 @@ opencode-sync sessions exclude ses_0ba19b4e7ffeMbSmWYi3Nj6xfZ # 这个会话永 - **体积小。** 只同步最近的会话(默认 7 天、最多 50 个),单个超过 5 MB 的会话直接跳过。 - **冲突少,而且有处理。** 两台电脑各自处理不同的会话,改的是不同的文件。同一个会话在两台电脑上都有改动时,保留较新的那份;在 OpenCode 2 上,如果本机那份有较新那份没有的消息,会先存进恢复目录再替换。 - **不打扰正在进行的对话。** 本机正在运行的会话不会被替换;运行中的状态(忙碌、压缩中、重试次数)也不会被带过去,所以接收方绝不会自己接着跑一段对话。 -- **放到对的地方。** 在 OpenCode 2 上,导入的会话会放进本机 OpenCode 2 为那个文件夹使用的项目里。另一台电脑用户目录下的文件夹,对应到你用户目录下的同名文件夹;本机没有的文件夹,会话放进用户目录的项目里。 +- **放到对的地方。** 在 OpenCode 2 上,导入的会话会放进本机 OpenCode 2 为那个文件夹使用的项目里。另一台电脑用户目录下的文件夹,对应到你用户目录下的同名文件夹;同一个仓库放在不同路径时,按项目 ID 对上。本机还没有那个文件夹或仓库时,会话先放在用户目录的项目里,等你在本机打开过这个仓库,下一次拉取就会挪进仓库的项目。 - **导入安全。** 每个会话在一个事务里导入,失败了数据库保持原样。 时间范围、数量和大小上限在**同步哪些内容 → 会话同步设置**里调。会话同步需要 Node.js 22.5 或更新版本。 +**项目是怎么处理的(OpenCode 2)。** 项目本身不同步。项目记录的是某个文件夹或仓库在一台电脑上的位置,所以每台电脑各有各的,由 OpenCode 打开文件夹时自己创建。同步的是会话,连同它所属项目的 ID。OpenCode 2 给同一个仓库在每台电脑上算出的 ID 都一样(先看远程地址,其次 `.git/opencode`,最后看第一个提交),普通文件夹的 ID 则由路径算出,所以导入时会话会放进本机对应的项目: + +| 本机情况 | 会话放到 | +|---|---| +| 有同一个文件夹(或用户目录下的同名文件夹) | 这个文件夹的项目 | +| 有同一个仓库,但路径不同 | 这个仓库的项目,子文件夹本机也有时放到子文件夹 | +| 都还没有 | 用户目录的项目;在本机打开这个仓库后,下一次拉取挪进仓库的项目 | + **升级到 OpenCode 2 后,`/session` 里少了会话?** OpenCode 自己迁移时,会把一部分会话留在 `/session` 永远不显示的项目里,内容其实都在: ```bash @@ -456,7 +464,7 @@ OpenCode 1 上,`auth.json` 作为文件同步。OpenCode 2 把登录存在数 **开了自动同步却没动静。** 运行 `opencode-sync autosync status`,看看是不是被暂停了、出错后在退避,还是因为文件还在变化而在等。菜单里的**诊断**可以看定时任务有没有注册上。 -**同步过来的会话在 `/session` 里看不到(OpenCode 2)。** 在那个会话所在的文件夹里打开 OpenCode;`/session` 只列出当前文件夹所属项目的会话。如果是升级到 OpenCode 2 之前的老会话,运行 `opencode-sync repair-sessions --apply`。 +**同步过来的会话在 `/session` 里看不到(OpenCode 2)。** 在那个会话所在的文件夹或仓库里打开 OpenCode;`/session` 只列出当前项目的会话。仓库还没在本机打开过时,会话先在用户目录的项目里,打开后下一次拉取就会挪过去。如果是升级到 OpenCode 2 之前的老会话,运行 `opencode-sync repair-sessions --apply`。 **会话完全没同步。** 看看 `opencode-sync status` 里会话同步是不是开着,以及 `node --version` 是不是 22.5 或更新。 diff --git a/package-lock.json b/package-lock.json index e83c6b1..e3ce673 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencode-github-sync", - "version": "3.3.0", + "version": "3.3.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencode-github-sync", - "version": "3.3.0", + "version": "3.3.1", "license": "MIT", "bin": { "opencode-sync": "dist/cli/index.js" diff --git a/package.json b/package.json index 3e7dbe6..25aef83 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-github-sync", - "version": "3.3.0", + "version": "3.3.1", "description": "Sync your OpenCode config, skills, and selected sessions across machines via a private GitHub repo — as a plugin or a CLI.", "type": "module", "license": "MIT", diff --git a/src/core/projects.ts b/src/core/projects.ts index 406818b..0dbe3db 100644 --- a/src/core/projects.ts +++ b/src/core/projects.ts @@ -16,14 +16,18 @@ import type { SqliteDatabase } from "./sqlite.js"; * * - the newest project whose worktree is the session directory, or the * deepest git worktree that contains it; + * - otherwise the project with the session's own id, when this machine has + * it: the same repository checked out at a different path; * - otherwise a project created with the id OpenCode 2 derives itself * (`sha1("directory:" + path)` for a plain directory); * - otherwise, for a directory this machine does not have, the home * directory's project, which is where `/session` is normally opened. * - * Project ids are deterministic in OpenCode 2 (git remote, root commit or - * directory path), so a project row from another machine is reused as is when - * its worktree also exists here. + * Project ids are deterministic in OpenCode 2 (git remote URL, then + * `.git/opencode`, then root commit; directory path outside a repository), so + * one repository has the same id on every machine wherever it is checked out, + * and a project row from another machine is reused as is when its worktree + * also exists here. */ export const GLOBAL_PROJECT_ID = "global"; @@ -184,6 +188,38 @@ export class ProjectResolver { return this.resolve(storedPath(path.resolve(home))) ?? this.createDirectoryProject(home); } + /** The project sessions are parked in, if this machine has one. */ + homeProjectId(): string | undefined { + return this.resolve(storedPath(path.resolve(this.options.home)))?.id; + } + + /** This machine's row for a project id, when its worktree exists here. */ + private byId(projectId: string): ProjectRow | undefined { + if (!projectId || projectId === GLOBAL_PROJECT_ID) return undefined; + const project = this.projects.find((p) => p.id === projectId); + return project?.worktree && this.exists(project.worktree) ? project : undefined; + } + + /** The session's subfolder inside this machine's checkout, or the checkout itself. */ + private within(project: ProjectRow, subpath: string | null): string { + const rel = (subpath ?? "").replace(/\\/g, "/"); + if (!rel || rel.startsWith("..") || path.isAbsolute(rel) || /^[A-Za-z]:/.test(rel)) { + return project.worktree; + } + const candidate = path.join(project.worktree, ...rel.split("/")); + return this.exists(candidate) ? storedPath(candidate) : project.worktree; + } + + private inside(target: ProjectRow, directory: string, fallback: string | null): Placement { + const exact = key(directory) === key(target.worktree); + return { + projectId: target.id, + directory: exact ? target.worktree : storedPath(directory), + path: relativePath(directory, target.worktree, fallback), + parked: false, + }; + } + /** Map a directory under the exporting machine's home onto this machine's home. */ private translate(directory: string, originHome: string | undefined): string { if (this.exists(directory) || !originHome) return directory; @@ -198,16 +234,13 @@ export class ProjectResolver { /** Where a session belongs on this machine. */ place(session: PlacementInput): Placement { const directory = this.translate(session.directory, session.originHome); - const target = this.resolve(directory) ?? this.createDirectoryProject(directory); - if (target) { - const exact = key(directory) === key(target.worktree); - return { - projectId: target.id, - directory: exact ? target.worktree : storedPath(directory), - path: relativePath(directory, target.worktree, session.path), - parked: false, - }; - } + const resolved = this.resolve(directory); + if (resolved) return this.inside(resolved, directory, session.path); + // The same repository checked out somewhere else on this machine. + const same = this.byId(session.projectId); + if (same) return this.inside(same, this.within(same, session.path), ""); + const created = this.createDirectoryProject(directory); + if (created) return this.inside(created, directory, session.path); const home = this.home(); if (!home) { return { diff --git a/src/core/sessions.ts b/src/core/sessions.ts index d650af9..d4e390e 100644 --- a/src/core/sessions.ts +++ b/src/core/sessions.ts @@ -151,6 +151,8 @@ export interface ExportResult { export interface ImportResult { imported: number; skippedOlder: number; + /** Sessions moved out of the home project into their own project here. */ + moved: number; /** Shards written by a machine on the other OpenCode major version. */ skippedOtherSchema: number; failed: { file: string; reason: string }[]; @@ -507,7 +509,13 @@ export async function importSessions( reporter: Reporter, options: ImportOptions = {}, ): Promise { - const result: ImportResult = { imported: 0, skippedOlder: 0, skippedOtherSchema: 0, failed: [] }; + const result: ImportResult = { + imported: 0, + skippedOlder: 0, + moved: 0, + skippedOtherSchema: 0, + failed: [], + }; const shardDir = path.join(repoRoot, SESSIONS_DIR); if (!fs.existsSync(shardDir)) return result; @@ -560,6 +568,9 @@ export async function importSessions( // locally — or running right now — is left completely alone, so an // in-progress conversation is never clobbered by a stale copy. if ((local !== undefined && local >= incoming) || localBusy.has(sessionId)) { + if (schema === "v2" && !localBusy.has(sessionId)) { + if (unpark(db, shard as SessionShardV2, resolver!)) result.moved++; + } result.skippedOlder++; continue; } @@ -711,6 +722,35 @@ function hasRow(db: SqliteDatabase, table: string, id: string): boolean { return readRows(db, `SELECT 1 AS x FROM "${table}" WHERE id = ?`, [id]).length > 0; } +/** + * Move a session that an earlier import parked in the home project into its + * own project, once this machine has one: the repository was cloned or opened + * here after the session arrived. Nothing but the session's location changes. + */ +function unpark(db: SqliteDatabase, shard: SessionShardV2, resolver: ProjectResolver): boolean { + const sessionId = String(shard.session.id); + const local = readRows(db, "SELECT project_id FROM session_v2 WHERE id = ?", [sessionId])[0]; + const home = resolver.homeProjectId(); + if (!local || !home || String(local.project_id) !== home) return false; + if (String(shard.session.project_id ?? "") === home) return false; + + const placement = resolver.place({ + directory: String(shard.session.directory ?? ""), + projectId: String(shard.session.project_id ?? ""), + path: shard.session.path == null ? null : String(shard.session.path), + originHome: shard.origin?.home, + }); + if (placement.parked || placement.projectId === home) return false; + if (!hasRow(db, "project", placement.projectId)) return false; + db.prepare("UPDATE session_v2 SET project_id = ?, directory = ?, path = ? WHERE id = ?").run( + placement.projectId, + placement.directory, + placement.path, + sessionId, + ); + return true; +} + /** List sessions available locally, newest first — powers `sessions list`. */ export async function listSessions(databaseFile: string, limit: number): Promise { if (!fs.existsSync(databaseFile)) return []; diff --git a/src/core/sync.ts b/src/core/sync.ts index a9b4e51..0821456 100644 --- a/src/core/sync.ts +++ b/src/core/sync.ts @@ -773,6 +773,9 @@ async function maybeImportSessions(ctx: Context): Promise 0) ctx.reporter.detail(`Imported ${result.imported} session(s)`); + if (result.moved > 0) { + ctx.reporter.detail(`Moved ${result.moved} session(s) from the home project into their own`); + } return { imported: result.imported, skipped: result.skippedOlder }; } diff --git a/tests/sessions-v2.test.ts b/tests/sessions-v2.test.ts index ffbe401..80c92fc 100644 --- a/tests/sessions-v2.test.ts +++ b/tests/sessions-v2.test.ts @@ -433,3 +433,100 @@ describe("OpenCode 2 sessions", () => { expect(Buffer.from(blob.data).equals(bytes)).toBe(true); }); }); + +describe("one repository at different paths (#10)", () => { + const REPO_ID = "c".repeat(40); + + function addRepo(db: SqliteDatabase, worktree: string): void { + db.prepare( + `INSERT INTO project (id, worktree, vcs, sandboxes, time_created, time_updated) + VALUES (?, ?, 'git', '[]', 1, 1)`, + ).run(REPO_ID, storedPath(worktree)); + } + + /** Machine A: a session in the `sub` folder of a checkout at `checkout`. */ + async function exportFromA(now: number, checkout: string, repo: string): Promise { + fs.mkdirSync(path.join(checkout, "sub"), { recursive: true }); + const source = path.join(root, "a.db"); + const db = await createDb(source); + addRepo(db, checkout); + addSession(db, { + id: "ses_repo", + project: REPO_ID, + directory: path.join(checkout, "sub"), + updated: now - DAY, + }); + db.prepare("UPDATE session_v2 SET path = 'sub' WHERE id = 'ses_repo'").run(); + db.close(); + await exportSessions(source, repo, { ...settings(), now }, silentReporter); + fs.rmSync(checkout, { recursive: true }); + } + + it("places a session in this machine's checkout of the same repository", async () => { + if (!available) return; + const now = Date.now(); + const repo = path.join(root, "repo"); + await exportFromA(now, path.join(root, "a-code", "app"), repo); + + const checkoutB = path.join(root, "b-work", "app"); + fs.mkdirSync(path.join(checkoutB, "sub"), { recursive: true }); + const home = path.join(root, "home-b"); + fs.mkdirSync(home); + const target = path.join(root, "b.db"); + const b = await createDb(target); + addRepo(b, checkoutB); + b.close(); + + const result = await importSessions(target, repo, silentReporter, { home, now }); + expect(result.failed).toEqual([]); + expect(result.imported).toBe(1); + + const db = await openDatabase(target, { readOnly: true }); + const session = rows(db, "SELECT project_id, directory, path FROM session_v2")[0]; + db.close(); + expect(session.project_id).toBe(REPO_ID); + expect(session.directory).toBe(storedPath(path.join(checkoutB, "sub"))); + expect(session.path).toBe("sub"); + }); + + it("moves a parked session into the repository once this machine has it", async () => { + if (!available) return; + const now = Date.now(); + const repo = path.join(root, "repo"); + await exportFromA(now, path.join(root, "a-code", "app"), repo); + + const home = path.join(root, "home-b"); + fs.mkdirSync(home); + const target = path.join(root, "b.db"); + (await createDb(target)).close(); + + await importSessions(target, repo, silentReporter, { home, now }); + let db = await openDatabase(target, { readOnly: true }); + expect(rows(db, "SELECT project_id FROM session_v2")[0].project_id).toBe( + directoryProjectId(home), + ); + db.close(); + + // The repository is cloned on B and opened in OpenCode, which creates its project. + const checkoutB = path.join(root, "b-work", "app"); + fs.mkdirSync(checkoutB, { recursive: true }); + const b = await openDatabase(target); + addRepo(b, checkoutB); + b.close(); + + const again = await importSessions(target, repo, silentReporter, { home, now }); + expect(again.imported).toBe(0); + expect(again.moved).toBe(1); + db = await openDatabase(target, { readOnly: true }); + const session = rows(db, "SELECT project_id, directory, path FROM session_v2")[0]; + expect(rows(db, "SELECT count(*) AS n FROM session_message")[0].n).toBe(2); + db.close(); + expect(session.project_id).toBe(REPO_ID); + // `sub` does not exist in this checkout, so the session opens at its root. + expect(session.directory).toBe(storedPath(checkoutB)); + expect(session.path).toBe(""); + + const third = await importSessions(target, repo, silentReporter, { home, now }); + expect(third.moved).toBe(0); + }); +});