Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(portability): restore archives across environments (#53)
Leo2ddeeb1a88d6
diff --git a/apps/server/src/portability.test.ts b/apps/server/src/portability.test.tsindex 9abddfab2..910093e0a 100644--- a/apps/server/src/portability.test.ts+++ b/apps/server/src/portability.test.ts@@ -26,6 +26,7 @@ import {commandsForPortabilityImport,createPortabilityArchive,isPortabilityPreviewCurrent,+ normalizePortabilityProjectFolders,parsePortabilityArchive,portabilityChecksum,portableRecords,@@ -497,7 +498,7 @@ describe("portability archive", () => {});describe("portability import", () => {- it("previews additions, conflicts, missing providers, skipped secrets, and unsupported state", () => {+ it("previews additions, conflicts, missing providers, and excluded data", () => {const source = makeSnapshot({bots: [{@@ -538,15 +539,7 @@ describe("portability import", () => {expect(preview.conflicts.map((entry) => entry.recordType)).toEqual(["bot", "group", "thread"]);expect(preview.missingProviders).toEqual(["missing-instance", "missing-provider"]);expect(preview.skippedSecrets).toHaveLength(3);- expect(preview.unsupported).toEqual(- expect.arrayContaining([- expect.objectContaining({ kind: "jobs", count: 0 }),- expect.objectContaining({ kind: "memory", count: 0 }),- expect.objectContaining({ kind: "routines", count: 0 }),- expect.objectContaining({ kind: "skill-assignments", count: 0 }),- expect.objectContaining({ kind: "usage-history", count: 0 }),- ]),- );+ expect(preview.unsupported).toEqual([]);});it("uses live provider availability instead of static settings keys", () => {@@ -839,32 +832,292 @@ describe("portability import", () => {expect(plan.commands.some((command) => command.type.startsWith("thread."))).toBe(false);});- it("reports missing project matches as unsupported", () => {+ it("skips unmapped project records while applying independent records", () => {const archive = createPortabilityArchive(makeSnapshot(), makeSettings(), NOW);+ const target = makeSnapshot({+ projects: [],+ bots: [],+ groups: [],+ mcpServers: [],+ threads: [],+ });+ const preview = previewPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ );+ const plan = commandsForPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ );+ expect(+ preview.unsupported.some((item) => item.kind === "project" || item.kind === "thread"),+ ).toBe(false);+ expect(preview.projectFolders).toEqual([+ {+ projectId: PROJECT_ID,+ title: "Portable project",+ workspaceName: "portable-project",+ destination: null,+ },+ ]);+ expect(plan.commands.map((command) => command.type)).toEqual(+ expect.arrayContaining(["mcp-server.create", "bot.create", "group.create"]),+ );+ expect(plan.commands.some((command) => command.type.startsWith("project."))).toBe(false);+ expect(plan.commands.some((command) => command.type.startsWith("thread."))).toBe(false);+ expect(plan.skipped).toBe(2);+ });++ it("creates projects and restores their threads into reviewed folders", () => {+ const source = makeSnapshot({+ projects: [{ ...makeSnapshot().projects[0]!, defaultThreadEnvMode: "worktree" }],+ });+ const archive = createPortabilityArchive(source, makeSettings(), NOW);+ const target = makeSnapshot({ projects: [], threads: [] });+ const projectFolders = { [PROJECT_ID]: "/tmp/restored-portable-project" };+ const preview = previewPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ projectFolders,+ );+ const plan = commandsForPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ projectFolders,+ );++ expect(preview.projectFolders).toEqual([+ expect.objectContaining({+ projectId: PROJECT_ID,+ destination: "/tmp/restored-portable-project",+ }),+ ]);+ expect(preview.additions).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ recordType: "project", id: PROJECT_ID }),+ expect.objectContaining({ recordType: "thread", id: THREAD_ID }),+ ]),+ );+ expect(plan.commands).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: "project.create",+ projectId: PROJECT_ID,+ workspaceRoot: "/tmp/restored-portable-project",+ }),+ expect.objectContaining({+ type: "thread.create",+ threadId: THREAD_ID,+ projectId: PROJECT_ID,+ }),+ expect.objectContaining({+ type: "project.meta.update",+ projectId: PROJECT_ID,+ defaultThreadEnvMode: "worktree",+ }),+ ]),+ );+ expect(plan.commands.findIndex((command) => command.type === "project.create")).toBeLessThan(+ plan.commands.findIndex((command) => command.type === "thread.create"),+ );+ expect(+ isPortabilityPreviewCurrent(+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ preview,+ projectFolders,+ ),+ ).toBe(true);+ expect(+ isPortabilityPreviewCurrent(target, makeSettings(), AVAILABLE_PROVIDER_IDS, preview, {+ [PROJECT_ID]: "/tmp/other-folder",+ }),+ ).toBe(false);+ });++ it("skips threads when a mapped project needs a missing provider", () => {+ const sourceProject = makeSnapshot().projects[0]!;+ const source = makeSnapshot({+ projects: [+ {+ ...sourceProject,+ defaultModelSelection: {+ instanceId: ProviderInstanceId.make("missing-project-provider"),+ model: "missing-model",+ },+ },+ ],+ });+ const archive = createPortabilityArchive(source, makeSettings(), NOW);const target = makeSnapshot({ projects: [], threads: [] });+ const projectFolders = { [PROJECT_ID]: "/tmp/restored-portable-project" };const preview = previewPortabilityImport(archive,target,makeSettings(),AVAILABLE_PROVIDER_IDS,+ projectFolders,);const plan = commandsForPortabilityImport(archive,target,makeSettings(),AVAILABLE_PROVIDER_IDS,+ projectFolders,);- expect(preview.unsupported).toEqual(+ expect(preview.conflicts).toEqual(expect.arrayContaining([- expect.objectContaining({ kind: "project", count: 1 }),- expect.objectContaining({ kind: "thread", count: 1 }),+ expect.objectContaining({ recordType: "project", id: PROJECT_ID }),+ expect.objectContaining({ recordType: "thread", id: THREAD_ID }),]),);expect(plan.commands.some((command) => command.type.startsWith("project."))).toBe(false);expect(plan.commands.some((command) => command.type.startsWith("thread."))).toBe(false);});+ it("matches an already restored project by its imported ID", () => {+ const source = makeSnapshot();+ const archive = createPortabilityArchive(source, makeSettings(), NOW);+ const target = makeSnapshot({+ projects: [+ {+ ...source.projects[0]!,+ workspaceRoot: "/tmp/restored-under-a-new-name",+ repositoryIdentity: null,+ },+ ],+ threads: [],+ });+ const preview = previewPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ );+ const plan = commandsForPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ );++ expect(preview.projectFolders).toEqual([]);+ expect(plan.commands).not.toContainEqual(expect.objectContaining({ type: "project.create" }));+ expect(plan.commands).toContainEqual(+ expect.objectContaining({ type: "thread.create", projectId: PROJECT_ID }),+ );+ });++ it("restores a deleted same-ID project under a fresh ID", () => {+ const source = makeSnapshot();+ const archive = createPortabilityArchive(source, makeSettings(), NOW);+ const deletedProject = { ...source.projects[0]!, deletedAt: NOW };+ const target = makeSnapshot({ projects: [deletedProject], threads: [] });+ const projectFolders = { [PROJECT_ID]: "/tmp/restored-after-delete" };+ const preview = previewPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ projectFolders,+ );+ const plan = commandsForPortabilityImport(+ archive,+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ projectFolders,+ );+ const createProject = plan.commands.find((command) => command.type === "project.create");++ expect(preview.additions).toContainEqual(+ expect.objectContaining({ recordType: "project", id: PROJECT_ID }),+ );+ expect(createProject).toEqual(+ expect.objectContaining({+ type: "project.create",+ workspaceRoot: "/tmp/restored-after-delete",+ }),+ );+ expect(createProject?.projectId).not.toBe(PROJECT_ID);+ expect(plan.commands).toContainEqual(+ expect.objectContaining({ type: "thread.create", projectId: createProject?.projectId }),+ );+ });++ effectIt.effect("preflights new project restores through the decider", () => {+ const source = makeSnapshot();+ const target = makeSnapshot({+ projects: [],+ bots: [],+ groups: [],+ mcpServers: [],+ threads: [],+ });+ const commands = commandsForPortabilityImport(+ createPortabilityArchive(source, makeSettings(), NOW),+ target,+ makeSettings(),+ AVAILABLE_PROVIDER_IDS,+ { [PROJECT_ID]: "/tmp/restored-portable-project" },+ ).commands;++ return decideCommandSequence({ commands, readModel: target }).pipe(+ Effect.tap((events) =>+ Effect.sync(() => {+ expect(events).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ type: "project.created" }),+ expect.objectContaining({ type: "thread.created" }),+ ]),+ );+ }),+ ),+ Effect.provide(NodeServices.layer),+ );+ });++ it("rejects unsafe project folder maps", () => {+ const firstProject = makeSnapshot().projects[0]!;+ const secondProjectId = ProjectId.make("project-second");+ const source = makeSnapshot({+ projects: [+ firstProject,+ {+ ...firstProject,+ id: secondProjectId,+ title: "Second project",+ workspaceRoot: "/source/second-project",+ repositoryIdentity: null,+ },+ ],+ });+ const archive = createPortabilityArchive(source, makeSettings(), NOW);+ const target = makeSnapshot({ projects: [], threads: [] });++ expect(() =>+ normalizePortabilityProjectFolders(archive, target, {+ [PROJECT_ID]: "relative/project",+ }),+ ).toThrow("absolute path");+ expect(() =>+ normalizePortabilityProjectFolders(archive, target, {+ [PROJECT_ID]: "/tmp/restored",+ [secondProjectId]: "/tmp/restored/",+ }),+ ).toThrow("same destination");+ });+it("rejects a stale preview token when projection state changes", () => {const snapshot = makeSnapshot();const settings = makeSettings();diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.tsindex bfc7460df..e3e1236d8 100644--- a/apps/server/src/portability.ts+++ b/apps/server/src/portability.ts@@ -15,6 +15,7 @@ import {type PortabilityArchiveRecord,type PortabilityImportItem,type PortabilityImportPreview,+ type PortabilityProjectFolderMap,type PortabilityProjectData,type PortabilitySafeServerSettings,type OrchestrationCommand,@@ -22,6 +23,11 @@ import {type ServerSettings,type ServerSettingsPatch,} from "@t3tools/contracts";+import {+ isWindowsAbsolutePath,+ normalizeProjectPathForComparison,+ normalizeProjectPathForDispatch,+} from "@t3tools/shared/path";import * as Duration from "effect/Duration";import * as Schema from "effect/Schema";@@ -800,6 +806,7 @@ function item(record: PortabilityArchiveRecord): PortabilityImportItem {type ProjectRestoreMatch =| { readonly kind: "matched"; readonly targetId: ProjectId }+ | { readonly kind: "created"; readonly targetId: ProjectId; readonly workspaceRoot: string }| { readonly kind: "conflict" }| { readonly kind: "unsupported"; readonly reason: string };@@ -827,7 +834,7 @@ function repositoriesMatch(return sourceDisplayName !== undefined && sourceDisplayName === targetDisplayName;}-function resolveProjectRestoreMatches(+function resolveExistingProjectRestoreMatches(archive: PortabilityArchive,snapshot: OrchestrationReadModel,): Map<string, ProjectRestoreMatch> {@@ -838,6 +845,11 @@ function resolveProjectRestoreMatches(const matches = new Map<string, ProjectRestoreMatch>();for (const source of sourceProjects) {+ const sameIdTarget = targets.find((target) => target.project.id === source.id);+ if (sameIdTarget) {+ matches.set(source.id, { kind: "matched", targetId: sameIdTarget.project.id });+ continue;+ }const repositoryCandidates = source.data.repository? targets.filter((target) =>repositoriesMatch(source.data.repository, target.data.repository),@@ -910,6 +922,83 @@ function resolveProjectRestoreMatches(return matches;}+export function normalizePortabilityProjectFolders(+ archive: PortabilityArchive,+ snapshot: OrchestrationReadModel,+ projectFolders: PortabilityProjectFolderMap = {},+): PortabilityProjectFolderMap {+ const sourceProjects = new Map(+ archive.records.flatMap((record) =>+ record.type === "project" ? [[record.id, record] as const] : [],+ ),+ );+ const existingMatches = resolveExistingProjectRestoreMatches(archive, snapshot);+ const activeWorkspaceRoots = new Set(+ snapshot.projects+ .filter((project) => project.deletedAt === null)+ .map((project) => normalizeProjectPathForComparison(project.workspaceRoot)),+ );+ const targetWorkspaceRoots = new Map<string, string>();+ const normalized: Record<string, string> = {};++ for (const [projectId, destination] of Object.entries(projectFolders)) {+ if (!sourceProjects.has(projectId)) {+ throw new Error(`Project folder map references unknown project '${projectId}'.`);+ }+ if (existingMatches.get(projectId)?.kind !== "unsupported") {+ throw new Error(`Project '${projectId}' already has a target project.`);+ }+ if (!destination.startsWith("/") && !isWindowsAbsolutePath(destination)) {+ throw new Error(`Project '${projectId}' destination must be an absolute path.`);+ }+ const workspaceRoot = normalizeProjectPathForDispatch(destination);+ if (workspaceRoot === "/" || /^[A-Za-z]:[\\/]$/.test(workspaceRoot)) {+ throw new Error(`Project '${projectId}' destination cannot be a filesystem root.`);+ }+ const comparisonRoot = normalizeProjectPathForComparison(workspaceRoot);+ if (activeWorkspaceRoots.has(comparisonRoot)) {+ throw new Error(`Project '${projectId}' destination already belongs to an active project.`);+ }+ const otherProjectId = targetWorkspaceRoots.get(comparisonRoot);+ if (otherProjectId) {+ throw new Error(+ `Projects '${otherProjectId}' and '${projectId}' cannot use the same destination.`,+ );+ }+ targetWorkspaceRoots.set(comparisonRoot, projectId);+ normalized[projectId] = workspaceRoot;+ }++ return normalized as PortabilityProjectFolderMap;+}++function resolveProjectRestoreMatches(+ archive: PortabilityArchive,+ snapshot: OrchestrationReadModel,+ projectFolders: PortabilityProjectFolderMap = {},+): Map<string, ProjectRestoreMatch> {+ const matches = resolveExistingProjectRestoreMatches(archive, snapshot);+ const normalizedProjectFolders = normalizePortabilityProjectFolders(+ archive,+ snapshot,+ projectFolders,+ );+ for (const [sourceId, workspaceRoot] of Object.entries(normalizedProjectFolders)) {+ let targetId = ProjectId.make(sourceId);+ let collision = 0;+ while (snapshot.projects.some((project) => project.id === targetId)) {+ targetId = ProjectId.make(portableId("project", { sourceId, workspaceRoot, collision }));+ collision += 1;+ }+ matches.set(sourceId, {+ kind: "created",+ targetId,+ workspaceRoot,+ });+ }+ return matches;+}+function mutableProjectData(data: PortabilityProjectData) {return {title: data.title,@@ -935,10 +1024,21 @@ export function isPortabilityPreviewCurrent(settings: ServerSettings,availableProviderIds: ReadonlySet<string>,preview: Pick<PortabilityImportPreview, "snapshotSequence" | "stateChecksum">,+ projectFolders: PortabilityProjectFolderMap = {},): boolean {return (snapshot.snapshotSequence === preview.snapshotSequence &&- portabilityStateChecksum(snapshot, settings, availableProviderIds) === preview.stateChecksum+ portabilityChecksum({+ state: portabilityStateChecksum(snapshot, settings, availableProviderIds),+ projectFolders: Object.fromEntries(+ Object.entries(projectFolders)+ .sort(([left], [right]) => left.localeCompare(right))+ .map(([projectId, destination]) => [+ projectId,+ normalizeProjectPathForDispatch(destination),+ ]),+ ),+ }) === preview.stateChecksum);}@@ -947,11 +1047,18 @@ export function previewPortabilityImport(snapshot: OrchestrationReadModel,settings: ServerSettings,availableProviderIds: ReadonlySet<string>,+ projectFolders: PortabilityProjectFolderMap = {},): PortabilityImportPreview {const current = new Map(portableRecords(snapshot, settings).map((record) => [`${record.type}:${record.id}`, record]),);- const projectMatches = resolveProjectRestoreMatches(archive, snapshot);+ const normalizedProjectFolders = normalizePortabilityProjectFolders(+ archive,+ snapshot,+ projectFolders,+ );+ const existingProjectMatches = resolveExistingProjectRestoreMatches(archive, snapshot);+ const projectMatches = resolveProjectRestoreMatches(archive, snapshot, normalizedProjectFolders);const additions: PortabilityImportItem[] = [];const changes: PortabilityImportItem[] = [];const conflicts: PortabilityImportItem[] = [];@@ -984,6 +1091,15 @@ export function previewPortabilityImport(),].sort();const missingProviderIds = new Set(missingProviders);+ const uncreatableProjectIds = new Set(+ archive.records.flatMap((record) =>+ record.type === "project" &&+ record.data.defaultModelSelection !== null &&+ missingProviderIds.has(record.data.defaultModelSelection.instanceId)+ ? [record.id]+ : [],+ ),+ );const unavailableBotIds = new Set(archive.records.flatMap((record) =>record.type === "bot" &&@@ -1008,15 +1124,6 @@ export function previewPortabilityImport(: [];}),);- const unsupportedCounts = new Map<- string,- { kind: "project" | "thread"; count: number; reason: string }- >();- const addUnsupported = (kind: "project" | "thread", reason: string) => {- const key = `${kind}:${reason}`;- const existing = unsupportedCounts.get(key);- unsupportedCounts.set(key, { kind, count: (existing?.count ?? 0) + 1, reason });- };for (const record of archive.records) {const projectMatch =record.type === "project"@@ -1025,7 +1132,6 @@ export function previewPortabilityImport(? projectMatches.get(record.data.projectId): undefined;if (projectMatch?.kind === "unsupported") {- addUnsupported(record.type as "project" | "thread", projectMatch.reason);continue;}if (projectMatch?.kind === "conflict") {@@ -1044,6 +1150,7 @@ export function previewPortabilityImport((record.type === "group" && unavailableGroupIds.has(record.id)) ||(record.type === "thread" &&(deletedThreadIds.has(record.id) ||+ (projectMatch?.kind === "created" && uncreatableProjectIds.has(record.data.projectId)) ||missingProviderIds.has(record.data.modelSelection.instanceId) ||(record.data.botId !== undefined &&record.data.botId !== null &&@@ -1056,12 +1163,14 @@ export function previewPortabilityImport(continue;}const existingKey =- record.type === "project" && projectMatch?.kind === "matched"+ record.type === "project" &&+ (projectMatch?.kind === "matched" || projectMatch?.kind === "created")? `project:${projectMatch.targetId}`: `${record.type}:${record.id}`;const existing = current.get(existingKey);const importedData =- record.type === "thread" && projectMatch?.kind === "matched"+ record.type === "thread" &&+ (projectMatch?.kind === "matched" || projectMatch?.kind === "created")? { ...record.data, projectId: projectMatch.targetId }: record.data;if (!existing) additions.push(item(record));@@ -1081,7 +1190,9 @@ export function previewPortabilityImport(record.type === "thread" &&existing.type === "thread" &&(existing.data.projectId !==- (projectMatch?.kind === "matched" ? projectMatch.targetId : record.data.projectId) ||+ (projectMatch?.kind === "matched" || projectMatch?.kind === "created"+ ? projectMatch.targetId+ : record.data.projectId) ||existing.data.botId !== record.data.botId ||existing.data.groupId !== record.data.groupId ||((existing.data.messages.length > 0 ||@@ -1105,45 +1216,32 @@ export function previewPortabilityImport(}return {snapshotSequence: snapshot.snapshotSequence,- stateChecksum: portabilityStateChecksum(snapshot, settings, availableProviderIds),+ stateChecksum: portabilityChecksum({+ state: portabilityStateChecksum(snapshot, settings, availableProviderIds),+ projectFolders: normalizedProjectFolders,+ }),additions,changes,conflicts,missingProviders,skippedSecrets: [- "Provider credentials and opaque provider configuration",- "MCP credentials and environment variables",- "Local paths, image avatar files, Git state, and event identifiers",- ],- unsupported: [- ...unsupportedCounts.values(),- {- kind: "jobs" as const,- count: 0,- reason: "The Akeru read model has no jobs collection or repository.",- },- {- kind: "memory" as const,- count: 0,- reason: "The Akeru read model has no durable memory collection or repository.",- },- {- kind: "routines" as const,- count: 0,- reason: "The Akeru read model has no routines collection or repository.",- },- {- kind: "skill-assignments" as const,- count: 0,- reason: "Provider skill discovery exists, but Akeru has no persisted skill assignments.",- },- {- kind: "usage-history" as const,- count: 0,- reason:- "Usage is read from provider-owned transcripts. Akeru has no usage import repository.",- },+ "Provider sign-ins and private provider settings",+ "MCP server credentials and environment variables",+ "Device-specific paths, image files, Git state, and internal event identifiers",],+ projectFolders: archive.records.flatMap((record) =>+ record.type === "project" && existingProjectMatches.get(record.id)?.kind === "unsupported"+ ? [+ {+ projectId: ProjectId.make(record.id),+ title: record.data.title,+ workspaceName: record.data.workspaceName,+ destination: normalizedProjectFolders[ProjectId.make(record.id)] ?? null,+ },+ ]+ : [],+ ),+ unsupported: [],};}@@ -1245,6 +1343,7 @@ export function commandsForPortabilityImport(snapshot: OrchestrationReadModel,settings: ServerSettings,availableProviderIds: ReadonlySet<string>,+ projectFolders: PortabilityProjectFolderMap = {},): {commands: OrchestrationCommand[];commandItems: PortabilityImportItem[];@@ -1253,11 +1352,19 @@ export function commandsForPortabilityImport(applied: number;skipped: number;} {- const preview = previewPortabilityImport(archive, snapshot, settings, availableProviderIds);- const projectMatches = resolveProjectRestoreMatches(archive, snapshot);+ const preview = previewPortabilityImport(+ archive,+ snapshot,+ settings,+ availableProviderIds,+ projectFolders,+ );+ const projectMatches = resolveProjectRestoreMatches(archive, snapshot, projectFolders);const projectSourceIdByTarget = new Map([...projectMatches.entries()].flatMap(([sourceId, match]) =>- match.kind === "matched" ? [[match.targetId, sourceId] as const] : [],+ match.kind === "matched" || match.kind === "created"+ ? [[match.targetId, sourceId] as const]+ : [],),);const conflictKeys = new Set(preview.conflicts.map((entry) => `${entry.recordType}:${entry.id}`));@@ -1282,8 +1389,19 @@ export function commandsForPortabilityImport(const deferredBotArchiveCommands: OrchestrationCommand[] = [];let settingsPatch: ServerSettingsPatch | undefined;let applied = 0;+ const unmappedProjectRecordCount = archive.records.filter((record) => {+ const match =+ record.type === "project"+ ? projectMatches.get(record.id)+ : record.type === "thread"+ ? projectMatches.get(record.data.projectId)+ : undefined;+ return match?.kind === "unsupported";+ }).length;let skipped =- preview.conflicts.length + preview.unsupported.reduce((total, entry) => total + entry.count, 0);+ preview.conflicts.length ++ preview.unsupported.reduce((total, entry) => total + entry.count, 0) ++ unmappedProjectRecordCount;for (const record of archive.records) {if (conflictKeys.has(`${record.type}:${record.id}`)) continue;@@ -1318,6 +1436,27 @@ export function commandsForPortabilityImport(for (const record of archive.records) {if (record.type !== "project" || conflictKeys.has(`project:${record.id}`)) continue;const match = projectMatches.get(record.id);+ if (match?.kind === "created") {+ commands.push({+ type: "project.create",+ commandId: nextCommandId(),+ projectId: match.targetId,+ title: record.data.title,+ workspaceRoot: match.workspaceRoot,+ defaultModelSelection: record.data.defaultModelSelection,+ createdAt: record.updatedAt,+ });+ if (record.data.defaultThreadEnvMode) {+ commands.push({+ type: "project.meta.update",+ commandId: nextCommandId(),+ projectId: match.targetId,+ defaultThreadEnvMode: record.data.defaultThreadEnvMode,+ });+ }+ applied += 1;+ continue;+ }if (match?.kind !== "matched") continue;const existing = projectsById.get(match.targetId);if (!existing) continue;@@ -1471,7 +1610,7 @@ export function commandsForPortabilityImport(if (record.type !== "thread" ||conflictKeys.has(`thread:${record.id}`) ||- projectMatch?.kind !== "matched"+ (projectMatch?.kind !== "matched" && projectMatch?.kind !== "created")) {continue;}diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex e93657595..3e184525b 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -5,6 +5,7 @@ import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";+import * as Path from "effect/Path";import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";@@ -29,6 +30,7 @@ import {type FileManagerRevealKind,type OrchestrationClientOrigin,type OrchestrationCommand,+ type OrchestrationReadModel,type GitActionProgressEvent,type GitManagerServiceError,OrchestrationDispatchCommandError,@@ -41,6 +43,8 @@ import {OrchestrationSearchThreadsError,OrchestrationGetTurnDiffError,PortabilityArchiveError,+ type PortabilityArchive,+ type PortabilityProjectFolderMap,ORCHESTRATION_WS_METHODS,type ProjectId,type ProjectEntriesFailure,@@ -183,6 +187,36 @@ const availablePortabilityProviderIds = (providers: ReadonlyArray<ServerProvider.map((provider) => provider.instanceId),);+const validatePortabilityProjectFolders = Effect.fn("validatePortabilityProjectFolders")(function* (+ archive: PortabilityArchive,+ snapshot: OrchestrationReadModel,+ projectFolders: PortabilityProjectFolderMap,+ operation: "preview" | "apply",+) {+ const workspacePaths = yield* WorkspacePaths.WorkspacePaths;+ const path = yield* Path.Path;+ for (const [projectId, destination] of Object.entries(projectFolders)) {+ if (!path.isAbsolute(destination) || path.dirname(destination) === destination) {+ return yield* portabilityError(+ operation,+ new Error(`Project '${projectId}' destination must be an absolute non-root path.`),+ );+ }+ }+ const normalized = Portability.normalizePortabilityProjectFolders(+ archive,+ snapshot,+ projectFolders,+ );+ return Object.fromEntries(+ yield* Effect.forEach(Object.entries(normalized), ([projectId, workspaceRoot]) =>+ workspacePaths+ .normalizeWorkspaceRoot(workspaceRoot)+ .pipe(Effect.map((normalizedRoot) => [projectId, normalizedRoot] as const)),+ ),+ ) as PortabilityProjectFolderMap;+});+const resolveDiscoveryForConfig = <A, E, R>(discovery: Effect.Effect<A, E, R>,onTimeout: () => A,@@ -1979,7 +2013,7 @@ const makeWsRpcLayer = (}).pipe(Effect.mapError((cause) => portabilityError("export", cause))),{ "rpc.aggregate": "portability" },),- [WS_METHODS.portabilityPreviewImport]: ({ contents }) =>+ [WS_METHODS.portabilityPreviewImport]: ({ contents, projectFolders = {} }) =>observeRpcEffect(WS_METHODS.portabilityPreviewImport,Effect.gen(function* () {@@ -1992,17 +2026,25 @@ const makeWsRpcLayer = (serverSettings.getSettings,providerRegistry.getProviders,]);+ const validatedProjectFolders = yield* validatePortabilityProjectFolders(+ archive,+ snapshot,+ projectFolders,+ "preview",+ );return Portability.previewPortabilityImport(archive,snapshot,settings,availablePortabilityProviderIds(providers),+ validatedProjectFolders,);}).pipe(Effect.mapError((cause) => portabilityError("preview", cause))),{ "rpc.aggregate": "portability" },),[WS_METHODS.portabilityApplyImport]: ({contents,+ projectFolders = {},expectedSnapshotSequence,expectedStateChecksum,}) =>@@ -2019,11 +2061,23 @@ const makeWsRpcLayer = (providerRegistry.getProviders,]);const availableProviderIds = availablePortabilityProviderIds(providers);+ const validatedProjectFolders = yield* validatePortabilityProjectFolders(+ archive,+ snapshot,+ projectFolders,+ "apply",+ );if (- !Portability.isPortabilityPreviewCurrent(snapshot, settings, availableProviderIds, {- snapshotSequence: expectedSnapshotSequence,- stateChecksum: expectedStateChecksum,- })+ !Portability.isPortabilityPreviewCurrent(+ snapshot,+ settings,+ availableProviderIds,+ {+ snapshotSequence: expectedSnapshotSequence,+ stateChecksum: expectedStateChecksum,+ },+ validatedProjectFolders,+ )) {return yield* portabilityError("apply",@@ -2035,6 +2089,7 @@ const makeWsRpcLayer = (snapshot,settings,availableProviderIds,+ validatedProjectFolders,);yield* decideCommandSequence({ commands: plan.commands, readModel: snapshot }).pipe(Effect.provideService(Crypto.Crypto, crypto),diff --git a/apps/web/src/components/settings/PortabilitySettings.logic.test.ts b/apps/web/src/components/settings/PortabilitySettings.logic.test.tsindex 5c2a20bd5..078b03cee 100644--- a/apps/web/src/components/settings/PortabilitySettings.logic.test.ts+++ b/apps/web/src/components/settings/PortabilitySettings.logic.test.ts@@ -1,4 +1,9 @@-import type { PortabilityImportPreview } from "@t3tools/contracts";+import {+ BearerConnectionTarget,+ PrimaryConnectionTarget,+ RelayConnectionTarget,+} from "@t3tools/client-runtime/connection";+import { EnvironmentId, ProjectId, type PortabilityImportPreview } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import { PORTABILITY_ARCHIVE_MAX_CHARS } from "@t3tools/contracts";@@ -6,8 +11,41 @@ import { PORTABILITY_ARCHIVE_MAX_CHARS } from "@t3tools/contracts";import {canApplyPortabilityPreview,portabilityArchiveFileError,+ portabilityProjectPickerTarget,+ updatePortabilityProjectFolderMap,} from "./PortabilitySettings.logic";+const ENVIRONMENT_ID = EnvironmentId.make("environment-1");++describe("portabilityProjectPickerTarget", () => {+ it("uses only native or desktop-local folder pickers", () => {+ expect(+ portabilityProjectPickerTarget(+ new PrimaryConnectionTarget({+ environmentId: ENVIRONMENT_ID,+ httpBaseUrl: "http://127.0.0.1:3773",+ label: "This device",+ wsBaseUrl: "ws://127.0.0.1:3773",+ }),+ ),+ ).toBeNull();+ expect(+ portabilityProjectPickerTarget(+ new BearerConnectionTarget({+ connectionId: "local:wsl:Ubuntu",+ environmentId: ENVIRONMENT_ID,+ label: "WSL",+ }),+ ),+ ).toBe("wsl:Ubuntu");+ expect(+ portabilityProjectPickerTarget(+ new RelayConnectionTarget({ environmentId: ENVIRONMENT_ID, label: "Remote" }),+ ),+ ).toBeUndefined();+ });+});+const preview: PortabilityImportPreview = {snapshotSequence: 1,stateChecksum: "0".repeat(64),@@ -16,6 +54,7 @@ const preview: PortabilityImportPreview = {conflicts: [],missingProviders: [],skippedSecrets: [],+ projectFolders: [],unsupported: [],};@@ -34,6 +73,33 @@ describe("canApplyPortabilityPreview", () => {changes: [{ recordType: "mcp-server", id: "mcp-1", title: "MCP server" }],}),).toBe(true);+ const partial = {+ ...preview,+ changes: [{ recordType: "mcp-server" as const, id: "mcp-1", title: "MCP server" }],+ projectFolders: [+ {+ projectId: ProjectId.make("project-1"),+ title: "Project",+ workspaceName: "project",+ destination: null,+ },+ ],+ };+ expect(canApplyPortabilityPreview(partial)).toBe(true);+ expect(+ canApplyPortabilityPreview({+ ...preview,+ additions: [{ recordType: "project", id: "project-1", title: "Project" }],+ projectFolders: [+ {+ projectId: ProjectId.make("project-1"),+ title: "Project",+ workspaceName: "project",+ destination: null,+ },+ ],+ }),+ ).toBe(true);});});@@ -45,3 +111,23 @@ describe("portabilityArchiveFileError", () => {);});});++describe("updatePortabilityProjectFolderMap", () => {+ it("keeps prior folder picks and can clear one mapping", () => {+ const first = ProjectId.make("project-1");+ const second = ProjectId.make("project-2");+ const withBoth = updatePortabilityProjectFolderMap(+ updatePortabilityProjectFolderMap({}, first, " /tmp/first "),+ second,+ "/tmp/second",+ );++ expect(withBoth).toEqual({+ [first]: "/tmp/first",+ [second]: "/tmp/second",+ });+ expect(updatePortabilityProjectFolderMap(withBoth, first, "")).toEqual({+ [second]: "/tmp/second",+ });+ });+});diff --git a/apps/web/src/components/settings/PortabilitySettings.logic.ts b/apps/web/src/components/settings/PortabilitySettings.logic.tsindex d54d4d817..38179fe52 100644--- a/apps/web/src/components/settings/PortabilitySettings.logic.ts+++ b/apps/web/src/components/settings/PortabilitySettings.logic.ts@@ -1,4 +1,32 @@-import { PORTABILITY_ARCHIVE_MAX_CHARS, type PortabilityImportPreview } from "@t3tools/contracts";+import type { ConnectionTarget } from "@t3tools/client-runtime/connection";+import {+ PORTABILITY_ARCHIVE_MAX_CHARS,+ type PortabilityImportPreview,+ type PortabilityProjectFolderMap,+ type ProjectId,+} from "@t3tools/contracts";++import { desktopLocalBackendId } from "../../connection/desktopLocal";++export function portabilityProjectPickerTarget(+ target: ConnectionTarget | null,+): string | null | undefined {+ if (target === null) return undefined;+ if (target._tag === "PrimaryConnectionTarget") return null;+ return desktopLocalBackendId(target) ?? undefined;+}++export function updatePortabilityProjectFolderMap(+ current: PortabilityProjectFolderMap,+ projectId: ProjectId,+ destination: string,+): PortabilityProjectFolderMap {+ const next = Object.fromEntries(+ Object.entries(current).filter(([candidateId]) => candidateId !== projectId),+ ) as PortabilityProjectFolderMap;+ const normalizedDestination = destination.trim();+ return normalizedDestination ? { ...next, [projectId]: normalizedDestination } : next;+}export function portabilityArchiveFileError(size: number): string | null {return size > PORTABILITY_ARCHIVE_MAX_CHARS ? "Archives must be 20 MB or smaller." : null;diff --git a/apps/web/src/components/settings/PortabilitySettings.tsx b/apps/web/src/components/settings/PortabilitySettings.tsxindex 4d5921a74..bf87afb01 100644--- a/apps/web/src/components/settings/PortabilitySettings.tsx+++ b/apps/web/src/components/settings/PortabilitySettings.tsx@@ -7,13 +7,18 @@ import type {PortabilityApplyImportResult,PortabilityImportItem,PortabilityImportPreview,+ PortabilityProjectFolderMap,+ ProjectId,} from "@t3tools/contracts";import { useRef, useState } from "react";-import { usePrimaryEnvironmentId } from "../../state/environments";+import { usePrimaryEnvironment, usePrimaryEnvironmentId } from "../../state/environments";+import { readLocalApi } from "../../localApi";import { portabilityEnvironment } from "../../state/portability";import { useAtomCommand } from "../../state/use-atom-command";+import { resolveProjectPickerTarget } from "../../wslPaths";import { Button } from "../ui/button";+import { DraftInput } from "../ui/draft-input";import {Dialog,DialogDescription,@@ -27,6 +32,8 @@ import { toastManager } from "../ui/toast";import {canApplyPortabilityPreview,portabilityArchiveFileError,+ portabilityProjectPickerTarget,+ updatePortabilityProjectFolderMap,} from "./PortabilitySettings.logic";import { SettingsRow } from "./settingsLayout";import { searchableSetting } from "./settingsSearch";@@ -35,6 +42,7 @@ interface ImportPreviewState {readonly contents: string;readonly filename: string;readonly preview: PortabilityImportPreview;+ readonly projectFolders: PortabilityProjectFolderMap;}function downloadArchive(filename: string, contents: string): void {@@ -82,9 +90,61 @@ function ImportItems({);}-function ImportPreview({ preview }: { readonly preview: PortabilityImportPreview }) {+function ImportPreview({+ preview,+ projectFolders,+ canPickProjectFolders,+ pending,+ onProjectFolderChange,+ onProjectFolderPick,+}: {+ readonly preview: PortabilityImportPreview;+ readonly projectFolders: PortabilityProjectFolderMap;+ readonly canPickProjectFolders: boolean;+ readonly pending: boolean;+ readonly onProjectFolderChange: (projectId: ProjectId, destination: string) => void;+ readonly onProjectFolderPick: (projectId: ProjectId, destination: string | null) => void;+}) {+ const unsupported = preview.unsupported.filter((item) => item.count > 0);return (<div className="space-y-5">+ {preview.projectFolders.length > 0 ? (+ <section className="space-y-2">+ <h3 className="text-xs font-semibold text-foreground">Project locations</h3>+ <p className="text-xs text-muted-foreground">+ Choose an existing folder for each project. Akeru Bot links the project to the folder+ without copying its files.+ </p>+ {preview.projectFolders.map((project) => (+ <div key={project.projectId} className="space-y-1">+ <label className="text-xs text-foreground/80" htmlFor={`folder-${project.projectId}`}>+ {project.title}+ </label>+ <div className="flex gap-1.5">+ <DraftInput+ id={`folder-${project.projectId}`}+ size="compact"+ disabled={pending}+ value={projectFolders[project.projectId] ?? project.destination ?? ""}+ placeholder={project.workspaceName}+ onCommit={(destination) => onProjectFolderChange(project.projectId, destination)}+ />+ {canPickProjectFolders ? (+ <Button+ size="xs"+ variant="outline"+ disabled={pending}+ onClick={() => onProjectFolderPick(project.projectId, project.destination)}+ >+ Choose+ </Button>+ ) : null}+ </div>+ </div>+ ))}+ </section>+ ) : null}+<div className="grid grid-cols-1 gap-4 sm:grid-cols-3"><ImportItems title="Additions" items={preview.additions} /><ImportItems title="Changes" items={preview.changes} />@@ -102,37 +162,42 @@ function ImportPreview({ preview }: { readonly preview: PortabilityImportPreview</section><section className="space-y-1.5">- <h3 className="text-xs font-semibold text-foreground">Secrets not included</h3>+ <h3 className="text-xs font-semibold text-foreground">Not transferred</h3><ul className="space-y-1 text-xs text-muted-foreground">{preview.skippedSecrets.map((item) => (<li key={item}>{item}</li>))}</ul>+ <p className="text-xs text-muted-foreground">+ After restore, sign in to providers and reconnect imported MCP servers on this device.+ </p></section>- <section className="space-y-1.5">- <h3 className="text-xs font-semibold text-foreground">Unsupported</h3>- <ul className="space-y-2 text-xs text-muted-foreground">- {preview.unsupported.map((item) => (- <li key={item.kind}>- <span className="font-medium text-foreground/80">- {item.kind} ({item.count})- </span>- <span className="block">{item.reason}</span>- </li>- ))}- </ul>- </section>+ {unsupported.length > 0 ? (+ <section className="space-y-1.5">+ <h3 className="text-xs font-semibold text-foreground">Not restored</h3>+ <ul className="space-y-2 text-xs text-muted-foreground">+ {unsupported.map((item) => (+ <li key={item.kind}>+ <span className="font-medium text-foreground/80">+ {item.kind} ({item.count})+ </span>+ <span className="block">{item.reason}</span>+ </li>+ ))}+ </ul>+ </section>+ ) : null}</div>);}function importResultDescription(result: PortabilityApplyImportResult): string {const counts = [- `${result.applied} applied`,+ `${result.applied} restored`,...(result.skipped > 0 ? [`${result.skipped} skipped`] : []),...(result.failed > 0 ? [`${result.failed} failed`] : []),- ...(result.partial > 0 ? [`${result.partial} partly applied`] : []),+ ...(result.partial > 0 ? [`${result.partial} partly restored`] : []),];const firstFailure = result.failures[0];return `${counts.join(". ")}.${firstFailure ? ` ${firstFailure.title}: ${firstFailure.message}` : ""}`;@@ -140,7 +205,14 @@ function importResultDescription(result: PortabilityApplyImportResult): string {export function PortabilitySettings() {const environmentId = usePrimaryEnvironmentId();+ const primaryEnvironment = usePrimaryEnvironment();+ const projectPickerTarget = portabilityProjectPickerTarget(+ primaryEnvironment?.entry.target ?? null,+ );const fileInputRef = useRef<HTMLInputElement>(null);+ const projectFoldersRef = useRef<PortabilityProjectFolderMap>({});+ const importSessionIdRef = useRef(0);+ const previewRequestIdRef = useRef(0);const exportArchive = useAtomCommand(portabilityEnvironment.exportArchive, {reportFailure: false,});@@ -175,17 +247,22 @@ export function PortabilitySettings() {toastManager.add({ type: "error", title: "Could not read archive", description: fileError });return;}+ importSessionIdRef.current += 1;+ const requestId = ++previewRequestIdRef.current;+ projectFoldersRef.current = {};setPending("preview");try {const contents = await file.text();const result = await previewImport({ environmentId, input: { contents } });+ if (requestId !== previewRequestIdRef.current) return;setPending(null);if (result._tag === "Failure") {reportFailure("Could not preview archive", result);return;}- setImportState({ contents, filename: file.name, preview: result.value });+ setImportState({ contents, filename: file.name, preview: result.value, projectFolders: {} });} catch (error) {+ if (requestId !== previewRequestIdRef.current) return;setPending(null);toastManager.add({type: "error",@@ -195,6 +272,81 @@ export function PortabilitySettings() {}};+ const handleProjectFolder = async (projectId: ProjectId, destination: string) => {+ if (environmentId === null || importState === null) return;+ const reviewedProjectFolders = projectFoldersRef.current;+ const projectFolders = updatePortabilityProjectFolderMap(+ projectFoldersRef.current,+ projectId,+ destination,+ );+ projectFoldersRef.current = projectFolders;+ const requestId = ++previewRequestIdRef.current;+ const contents = importState.contents;+ setImportState((current) =>+ current?.contents === contents ? { ...current, projectFolders } : current,+ );+ setPending("preview");+ const result = await previewImport({+ environmentId,+ input: { contents, projectFolders },+ });+ if (requestId !== previewRequestIdRef.current) return;+ setPending(null);+ if (result._tag === "Failure") {+ projectFoldersRef.current = reviewedProjectFolders;+ setImportState((current) =>+ current?.contents === contents+ ? { ...current, projectFolders: reviewedProjectFolders }+ : current,+ );+ reportFailure("Could not use project folder", result);+ return;+ }+ setImportState((current) =>+ current?.contents === contents && current.projectFolders === projectFolders+ ? { ...current, preview: result.value }+ : current,+ );+ };++ const handleProjectFolderPick = async (projectId: ProjectId, destination: string | null) => {+ if (environmentId === null || importState === null) return;+ const importSessionId = importSessionIdRef.current;+ if (!window.desktopBridge || projectPickerTarget === undefined) {+ toastManager.add({+ type: "error",+ title: "Folder picker unavailable",+ description: "Enter an absolute folder path, or open Akeru Bot on desktop.",+ });+ return;+ }+ try {+ const wslConfiguration = await window.desktopBridge.getWslState().catch(() => null);+ const targetEnvironmentId = resolveProjectPickerTarget({+ browseEnvironmentId: environmentId,+ primaryEnvironmentId: environmentId,+ // Settings only targets the primary environment. The WSL state routes a WSL-only primary.+ desktopInstanceId: projectPickerTarget,+ wslConfiguration,+ });+ const picked = await readLocalApi()?.dialogs.pickFolder({+ ...(destination ? { initialPath: destination } : {}),+ ...(targetEnvironmentId ? { targetEnvironmentId } : {}),+ });+ if (picked && importSessionId === importSessionIdRef.current) {+ await handleProjectFolder(projectId, picked);+ }+ } catch (error) {+ if (importSessionId !== importSessionIdRef.current) return;+ toastManager.add({+ type: "error",+ title: "Could not choose project folder",+ description: error instanceof Error ? error.message : "The folder could not be selected.",+ });+ }+ };+const handleApply = async () => {if (environmentId === null || importState === null) return;setPending("apply");@@ -202,6 +354,7 @@ export function PortabilitySettings() {environmentId,input: {contents: importState.contents,+ projectFolders: importState.projectFolders,expectedSnapshotSequence: importState.preview.snapshotSequence,expectedStateChecksum: importState.preview.stateChecksum,},@@ -213,10 +366,14 @@ export function PortabilitySettings() {}const hasFailures = result.value.failed > 0 || result.value.partial > 0;if (hasFailures) setApplyResult(result.value);- else setImportState(null);+ else {+ importSessionIdRef.current += 1;+ projectFoldersRef.current = {};+ setImportState(null);+ }toastManager.add({type: hasFailures ? "error" : "success",- title: hasFailures ? "Archive partly imported" : "Archive imported",+ title: hasFailures ? "Archive partly restored" : "Archive restored",description: importResultDescription(result.value),});};@@ -225,7 +382,7 @@ export function PortabilitySettings() {<><SettingsRow{...searchableSetting("data-portability")}- description="Export safe settings, workspaces, and conversation history, or preview an archive before import."+ description="Export Akeru settings, project links, and history, or restore them on another environment. Project files and credentials are not included."control={<div className="flex items-center gap-1.5"><Button@@ -264,6 +421,10 @@ export function PortabilitySettings() {open={importState !== null}onOpenChange={(open) => {if (!open && pending !== "apply") {+ importSessionIdRef.current += 1;+ previewRequestIdRef.current += 1;+ projectFoldersRef.current = {};+ setPending(null);setImportState(null);setApplyResult(null);}@@ -271,13 +432,28 @@ export function PortabilitySettings() {><DialogPopup className="max-w-2xl"><DialogHeader>- <DialogTitle>Import preview</DialogTitle>+ <DialogTitle>Restore preview</DialogTitle><DialogDescription>- {importState?.filename}. MCP servers stay disabled until you reconnect their secrets.+ {importState?.filename}. Review what Akeru Bot will restore on this environment.</DialogDescription></DialogHeader><DialogPanel>- {importState ? <ImportPreview preview={importState.preview} /> : null}+ {importState ? (+ <ImportPreview+ preview={importState.preview}+ projectFolders={importState.projectFolders}+ canPickProjectFolders={+ window.desktopBridge !== undefined && projectPickerTarget !== undefined+ }+ pending={pending !== null}+ onProjectFolderChange={(projectId, destination) =>+ void handleProjectFolder(projectId, destination)+ }+ onProjectFolderPick={(projectId, destination) =>+ void handleProjectFolderPick(projectId, destination)+ }+ />+ ) : null}{applyResult && applyResult.failures.length > 0 ? (<section className="mt-5 space-y-1.5"><h3 className="text-xs font-semibold text-destructive">Restore failures</h3>@@ -286,7 +462,7 @@ export function PortabilitySettings() {<li key={`${failure.recordType}:${failure.id}`}><span className="font-medium text-foreground/80">{failure.title}</span><span className="block">- {failure.partial ? "Partly applied. " : "Not applied. "}+ {failure.partial ? "Partly restored. " : "Not restored. "}{failure.message}</span></li>@@ -299,20 +475,26 @@ export function PortabilitySettings() {<Buttonvariant="ghost"disabled={pending === "apply"}- onClick={() => setImportState(null)}+ onClick={() => {+ importSessionIdRef.current += 1;+ previewRequestIdRef.current += 1;+ projectFoldersRef.current = {};+ setPending(null);+ setImportState(null);+ }}>Cancel</Button><Buttondisabled={importState === null ||- pending === "apply" ||+ pending !== null ||applyResult !== null ||!canApplyPortabilityPreview(importState.preview)}onClick={() => void handleApply()}>- {pending === "apply" ? "Applying..." : "Apply safe changes"}+ {pending === "apply" ? "Restoring..." : "Restore"}</Button></DialogFooter></DialogPopup>diff --git a/docs/internals/data-portability.md b/docs/internals/data-portability.mdindex eca54c8b2..f7eecbf50 100644--- a/docs/internals/data-portability.md+++ b/docs/internals/data-portability.md@@ -4,8 +4,10 @@ The `akeru.archive` format mirrors data that Akeru owns and can restore without`packages/contracts/src/orchestration.ts` defines the durable read model. It contains projects, bots, groups, MCP servers, and threads. Thread records carry messages, proposed plans, approval activities, avatars, lifecycle state, and workspace or sandbox references. The portability layer restores approval activities as inert `approval.history` rows so an import cannot reopen a provider request.-The same read model has no jobs, routines, or durable memory collection. Provider memory events belong to provider sessions and do not form an Akeru repository. `ServerProvider.skills` in `packages/contracts/src/server.ts` reports discovered provider skills, but Akeru has no persisted skill-assignment model.+The same read model has no jobs or routines collection. Durable memory has a separate SQLite repository and a version 2 memory archive with preview and apply support. The main portability archive does not include these separate domains. `ServerProvider.skills` in `packages/contracts/src/server.ts` reports discovered provider skills, but Akeru has no persisted skill-assignment model.-`packages/contracts/src/usage.ts` defines a read result, not an Akeru repository. `apps/server/src/usage/UsageService.ts` scans provider-owned Claude and Codex transcript files. It has no write or import operation. The archive preview keeps usage history explicit as unsupported until Akeru owns a durable usage repository.+`packages/contracts/src/usage.ts` defines a read result, not an Akeru repository. `apps/server/src/usage/UsageService.ts` scans provider-owned Claude and Codex transcript files. It has no write or import operation, so the main portability archive does not include usage history.Restore preflights the full command list before the first write. Each command still has its own SQLite transaction. Apply results therefore report failed and partly applied records instead of claiming the whole archive succeeded.++Archives omit absolute workspace paths. Preview accepts an explicit project-to-folder map for projects that do not match an existing project ID, repository identity, or workspace name. The server requires existing absolute directories, rejects duplicate or occupied destinations, binds the map to the preview checksum, and restores each mapped project through `project.create` before its threads. Apply skips unmapped projects and their threads while it restores independent records.diff --git a/docs/user/data-portability.md b/docs/user/data-portability.mdindex c52862cbf..7d9134b58 100644--- a/docs/user/data-portability.md+++ b/docs/user/data-portability.md@@ -8,10 +8,10 @@ The archive removes credentials, local paths, project scripts, attachments, imagImported approval rows are history only. An import does not reopen a request or approve an action. Imported MCP servers stay disabled until you reconnect their credentials.-Choose **Import** and select an archive to see a preview. The preview lists additions, changes, conflicts, missing providers, excluded secrets, and records that this environment cannot restore. Review this list before you apply the import.+Choose **Import** and select an archive to see a restore preview. The preview lists additions, changes, conflicts, missing providers, and data that stays on the source device. Review this list before you restore the archive.-Akeru Bot can update a project when its existing workspace reference matches the archive. A missing workspace stays unsupported because an archive does not carry an absolute project path. The preview reports this case before import.+Akeru Bot updates a project when its existing workspace reference matches the archive. For each missing workspace, choose an existing local folder in the preview. Akeru Bot links the restored project to that folder without copying its files, then restores its threads. Import skips unmapped projects and their threads without blocking independent records.Import skips records that need a missing provider. It also skips conflicts when the target has a newer record. If the environment changes after the preview, Akeru Bot stops the import and requires a new preview.-The apply result lists failed records. A partly applied record means at least one write succeeded before another write failed. Review the archive again after any failed or partly applied result.+The restore result lists failed records. A partly restored record means at least one write succeeded before another write failed. Review the archive again after any failed or partly restored result.diff --git a/packages/client-runtime/src/rpc/portability.ts b/packages/client-runtime/src/rpc/portability.tsindex e82cfbcf0..ad3d12192 100644--- a/packages/client-runtime/src/rpc/portability.ts+++ b/packages/client-runtime/src/rpc/portability.ts@@ -1,18 +1,26 @@-import { WS_METHODS, type PortabilityImportPreview } from "@t3tools/contracts";+import {+ WS_METHODS,+ type PortabilityImportPreview,+ type PortabilityProjectFolderMap,+} from "@t3tools/contracts";import { request } from "./client.ts";export const exportPortabilityArchive = () => request(WS_METHODS.portabilityExport, {});-export const previewPortabilityArchive = (contents: string) =>- request(WS_METHODS.portabilityPreviewImport, { contents });+export const previewPortabilityArchive = (+ contents: string,+ projectFolders: PortabilityProjectFolderMap = {},+) => request(WS_METHODS.portabilityPreviewImport, { contents, projectFolders });export const applyPortabilityArchive = (contents: string,preview: Pick<PortabilityImportPreview, "snapshotSequence" | "stateChecksum">,+ projectFolders: PortabilityProjectFolderMap = {},) =>request(WS_METHODS.portabilityApplyImport, {contents,+ projectFolders,expectedSnapshotSequence: preview.snapshotSequence,expectedStateChecksum: preview.stateChecksum,});diff --git a/packages/contracts/src/portability.ts b/packages/contracts/src/portability.tsindex d623e2b80..9a83b8c99 100644--- a/packages/contracts/src/portability.ts+++ b/packages/contracts/src/portability.ts@@ -1,3 +1,4 @@+import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import {@@ -245,6 +246,17 @@ export const PortabilityImportItem = Schema.Struct({});export type PortabilityImportItem = typeof PortabilityImportItem.Type;+export const PortabilityProjectFolderMap = Schema.Record(ProjectId, TrimmedNonEmptyString);+export type PortabilityProjectFolderMap = typeof PortabilityProjectFolderMap.Type;++export const PortabilityProjectFolder = Schema.Struct({+ projectId: ProjectId,+ title: TrimmedNonEmptyString,+ workspaceName: TrimmedNonEmptyString,+ destination: Schema.NullOr(TrimmedNonEmptyString),+});+export type PortabilityProjectFolder = typeof PortabilityProjectFolder.Type;+export const PortabilityUnsupportedItem = Schema.Struct({kind: Schema.Literals(["project",@@ -268,6 +280,9 @@ export const PortabilityImportPreview = Schema.Struct({conflicts: Schema.Array(PortabilityImportItem),missingProviders: Schema.Array(TrimmedNonEmptyString),skippedSecrets: Schema.Array(TrimmedNonEmptyString),+ projectFolders: Schema.Array(PortabilityProjectFolder).pipe(+ Schema.withDecodingDefault(Effect.succeed([])),+ ),unsupported: Schema.Array(PortabilityUnsupportedItem),});export type PortabilityImportPreview = typeof PortabilityImportPreview.Type;@@ -280,11 +295,13 @@ export type PortabilityExportResult = typeof PortabilityExportResult.Type;export const PortabilityPreviewImportInput = Schema.Struct({contents: PortabilityArchiveText,+ projectFolders: Schema.optional(PortabilityProjectFolderMap),});export type PortabilityPreviewImportInput = typeof PortabilityPreviewImportInput.Type;export const PortabilityApplyImportInput = Schema.Struct({contents: PortabilityArchiveText,+ projectFolders: Schema.optional(PortabilityProjectFolderMap),expectedSnapshotSequence: NonNegativeInt,expectedStateChecksum: ArchiveChecksum,});