Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**。
Expand Down
25 changes: 22 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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`.

Expand Down
12 changes: 10 additions & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 或更新。

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
59 changes: 46 additions & 13 deletions src/core/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down
42 changes: 41 additions & 1 deletion src/core/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }[];
Expand Down Expand Up @@ -507,7 +509,13 @@ export async function importSessions(
reporter: Reporter,
options: ImportOptions = {},
): Promise<ImportResult> {
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;

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<SessionRecord[]> {
if (!fs.existsSync(databaseFile)) return [];
Expand Down
3 changes: 3 additions & 0 deletions src/core/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,9 @@ async function maybeImportSessions(ctx: Context): Promise<SyncResult["sessions"]
);
}
if (result.imported > 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 };
}

Expand Down
Loading
Loading