Skip to content
Open
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
31 changes: 28 additions & 3 deletions packages/core/src/control-plane/move-session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
export * as MoveSession from "./move-session"

import { Context, DateTime, Effect, Layer, Schema } from "effect"
import { Database } from "../database/database"
import { FSUtil } from "../fs-util"
import { ProjectTable } from "../project/sql"
import { makeGlobalNode } from "../effect/app-node"
import { EventV2 } from "../event"
import { Git } from "../git"
Expand All @@ -22,6 +25,7 @@ export const Input = Schema.Struct({
sessionID: SessionSchema.ID,
destination: Destination,
moveChanges: Schema.optional(Schema.Boolean),
allowCrossProject: Schema.optional(Schema.Boolean),
}).annotate({ identifier: "MoveSession.Input" })
export type Input = typeof Input.Type

Expand Down Expand Up @@ -73,20 +77,40 @@ const layer = Layer.effect(
const events = yield* EventV2.Service
const project = yield* ProjectV2.Service
const sessions = yield* SessionStore.Service
const fs = yield* FSUtil.Service
const { db } = yield* Database.Service

const moveSession = Effect.fn("MoveSession.moveSession")(function* (input: Input) {
const current = yield* sessions.get(input.sessionID)
if (!current) return yield* new SessionV2.NotFoundError({ sessionID: input.sessionID })
const directory = AbsolutePath.make(input.destination.directory)
if (current.location.directory === directory) return

// Ensure target directory exists on disk
yield* fs.ensureDir(directory).pipe(Effect.ignore)

const source = yield* project.resolve(current.location.directory)
const destination = yield* project.resolve(directory)
if (current.projectID !== destination.id) {
const isCrossProject = current.projectID !== destination.id
if (isCrossProject && input.allowCrossProject === false) {
return yield* new DestinationProjectMismatchError({ expected: current.projectID, actual: destination.id })
}

const moveChanges = input.moveChanges && source.directory !== destination.directory
if (isCrossProject) {
yield* db
.insert(ProjectTable)
.values({
id: destination.id,
worktree: destination.directory,
vcs: destination.vcs?.type,
sandboxes: [],
})
.onConflictDoNothing()
.run()
.pipe(Effect.orDie)
}

const moveChanges = !isCrossProject && input.moveChanges && source.directory !== destination.directory
const sourceRepository = moveChanges ? yield* git.repo.discover(current.location.directory) : undefined
if (moveChanges && !sourceRepository)
return yield* new CaptureChangesError({ message: "Source is not a Git repository" })
Expand All @@ -107,6 +131,7 @@ const layer = Layer.effect(
sessionID: input.sessionID,
location: Location.Ref.make({ directory }),
subdirectory: RelativePath.make(path.relative(destination.directory, directory).replaceAll("\\", "/")),
projectID: destination.id,
timestamp: yield* DateTime.now,
})

Expand Down Expand Up @@ -144,5 +169,5 @@ const layer = Layer.effect(
export const node = makeGlobalNode({
service: Service,
layer,
deps: [Git.node, EventV2.node, ProjectV2.node, SessionStore.node],
deps: [Git.node, EventV2.node, ProjectV2.node, SessionStore.node, FSUtil.node, Database.node],
})
1 change: 1 addition & 0 deletions packages/core/src/session/projector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ const layer = Layer.effectDiscard(
.set({
directory: event.data.location.directory,
path: event.data.subdirectory,
project_id: event.data.projectID ?? sql`${SessionTable.project_id}`,
workspace_id: event.data.location.workspaceID ? WorkspaceV2.ID.make(event.data.location.workspaceID) : null,
time_updated: DateTime.toEpochMillis(event.data.timestamp),
})
Expand Down
66 changes: 66 additions & 0 deletions packages/core/test/move-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,70 @@ describe("MoveSession", () => {
expect(yield* Effect.promise(() => fs.readFile(path.join(source, "untracked.txt"), "utf8"))).toBe("unrelated\n")
}),
)

it.live("moves session across distinct project repositories without transferring git changes", () =>
Effect.gen(function* () {
const rootA = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
)
const rootB = yield* Effect.acquireRelease(
Effect.promise(() => tmpdir()),
(dir) => Effect.promise(() => dir[Symbol.asyncDispose]()),
)
yield* Effect.promise(() => initRepo(rootA.path))
yield* Effect.promise(async () => {
await $`git init`.cwd(rootB.path).quiet()
await $`git config core.autocrlf false`.cwd(rootB.path).quiet()
await $`git config core.fsmonitor false`.cwd(rootB.path).quiet()
await $`git config commit.gpgsign false`.cwd(rootB.path).quiet()
await $`git config user.email testB@opencode.test`.cwd(rootB.path).quiet()
await $`git config user.name TestB`.cwd(rootB.path).quiet()
await fs.writeFile(path.join(rootB.path, "other.txt"), "other content\n")
await $`git add other.txt`.cwd(rootB.path).quiet()
await $`git commit -m "different root"`.cwd(rootB.path).quiet()
})

const source = abs(yield* Effect.promise(() => fs.realpath(rootA.path)))
const destination = abs(yield* Effect.promise(() => fs.realpath(rootB.path)))

const projectIDA = (yield* Project.Service.use((service) => service.resolve(source))).id
const projectIDB = (yield* Project.Service.use((service) => service.resolve(destination))).id
expect(projectIDA).not.toBe(projectIDB)

const sessionID = SessionV2.ID.make("ses_cross_project")
const { db } = yield* Database.Service
yield* db
.insert(ProjectTable)
.values({ id: projectIDA, worktree: source, sandboxes: [], time_created: 1, time_updated: 1 })
.run()
.pipe(Effect.orDie)
yield* db
.insert(SessionTable)
.values({
id: sessionID,
project_id: projectIDA,
slug: "cross",
directory: source,
title: "cross project",
version: "test",
time_created: 1,
time_updated: 1,
})
.run()
.pipe(Effect.orDie)

yield* MoveSession.Service.use((service) =>
service.moveSession({ sessionID, destination: { directory: destination } }),
)

const updated = yield* db
.select({ directory: SessionTable.directory, project_id: SessionTable.project_id })
.from(SessionTable)
.where(eq(SessionTable.id, sessionID))
.get()

expect(updated).toEqual({ directory: destination, project_id: projectIDB })
}),
)
})
2 changes: 2 additions & 0 deletions packages/schema/src/session-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { DateTimeUtcFromMillis, NonNegativeInt, RelativePath } from "./schema"
import { FileAttachment, Prompt } from "./prompt"
import { SessionID } from "./session-id"
import { Location } from "./location"
import { ProjectID } from "./project-id"
import { SessionMessage } from "./session-message"
import { Revert } from "./revert"

Expand Down Expand Up @@ -80,6 +81,7 @@ export const Moved = Event.define({
...Base,
location: Location.Ref,
subdirectory: RelativePath.pipe(optional),
projectID: ProjectID.pipe(optional),
},
})
export type Moved = typeof Moved.Type
Expand Down
50 changes: 50 additions & 0 deletions packages/schema/test/session-event.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, test } from "bun:test"
import { Schema } from "effect"
import { SessionEvent } from "../src/session-event"
import { ProjectID } from "../src/project-id"
import { AbsolutePath } from "../src/schema"

describe("SessionEvent.Moved schema", () => {
test("encodes and decodes moved event with projectID", () => {
const raw = {
id: "evt_123",
type: "session.next.moved",
data: {
timestamp: 1700000000000,
sessionID: "ses_123",
location: {
directory: AbsolutePath.make("/path/to/new/repo"),
},
subdirectory: "sub",
projectID: "proj_456",
},
}

const decoded = Schema.decodeUnknownSync(SessionEvent.Moved)(raw)
expect(decoded.data.projectID).toBe(ProjectID.make("proj_456"))
expect(decoded.data.location.directory).toBe(AbsolutePath.make("/path/to/new/repo"))

const encoded = Schema.encodeSync(SessionEvent.Moved)(decoded)
expect(encoded.data.projectID).toBe("proj_456")
})

test("encodes and decodes moved event without optional projectID", () => {
const raw = {
id: "evt_123",
type: "session.next.moved",
data: {
timestamp: 1700000000000,
sessionID: "ses_123",
location: {
directory: AbsolutePath.make("/path/to/new/repo"),
},
},
}

const decoded = Schema.decodeUnknownSync(SessionEvent.Moved)(raw)
expect(decoded.data.projectID).toBeUndefined()

const encoded = Schema.encodeSync(SessionEvent.Moved)(decoded)
expect(encoded.data.projectID).toBeUndefined()
})
})
Loading
Loading