diff --git a/.github/workflows/duplicate-issues.yml b/.github/workflows/duplicate-issues.yml index 3972247dafc6..5b05675a686c 100644 --- a/.github/workflows/duplicate-issues.yml +++ b/.github/workflows/duplicate-issues.yml @@ -6,7 +6,7 @@ on: jobs: check-duplicates: - if: github.event.action == 'opened' + if: github.repository == 'anomalyco/opencode' && github.event.action == 'opened' runs-on: blacksmith-4vcpu-ubuntu-2404 permissions: contents: read @@ -140,7 +140,7 @@ jobs: Remember: post at most ONE comment combining all findings. If everything is fine, post nothing." recheck-compliance: - if: github.event.action == 'edited' && contains(github.event.issue.labels.*.name, 'needs:compliance') + if: github.repository == 'anomalyco/opencode' && github.event.action == 'edited' && contains(github.event.issue.labels.*.name, 'needs:compliance') runs-on: blacksmith-4vcpu-ubuntu-2404 permissions: contents: read diff --git a/.github/workflows/generate.yml b/.github/workflows/generate.yml index 324cfec02001..fa2414c3c3ce 100644 --- a/.github/workflows/generate.yml +++ b/.github/workflows/generate.yml @@ -7,6 +7,7 @@ on: jobs: generate: + if: github.repository == 'anomalyco/opencode' runs-on: blacksmith-4vcpu-ubuntu-2404 permissions: contents: write diff --git a/.github/workflows/nix-eval.yml b/.github/workflows/nix-eval.yml index 75332695a1ad..654ef65ac613 100644 --- a/.github/workflows/nix-eval.yml +++ b/.github/workflows/nix-eval.yml @@ -16,7 +16,7 @@ permissions: jobs: nix-eval: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'internetisalie/opencode' && 'ubuntu-24.04' || 'blacksmith-4vcpu-ubuntu-2404' }} timeout-minutes: 15 steps: - name: Checkout repository diff --git a/.github/workflows/pr-management.yml b/.github/workflows/pr-management.yml index b6aa4e589d89..3b624707571e 100644 --- a/.github/workflows/pr-management.yml +++ b/.github/workflows/pr-management.yml @@ -6,6 +6,7 @@ on: jobs: check-duplicates: + if: github.repository == 'anomalyco/opencode' runs-on: blacksmith-4vcpu-ubuntu-2404 permissions: contents: read diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c86a1fda1353..55ff3ed22f51 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -407,7 +407,7 @@ jobs: - build-cli - sign-cli-windows - build-electron - if: always() && !failure() && !cancelled() + if: always() && github.repository == 'anomalyco/opencode' && !failure() && !cancelled() runs-on: blacksmith-4vcpu-ubuntu-2404 steps: - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 diff --git a/.github/workflows/release-github-action.yml b/.github/workflows/release-github-action.yml index 4a1d7218bb2c..fa1eb10060d1 100644 --- a/.github/workflows/release-github-action.yml +++ b/.github/workflows/release-github-action.yml @@ -14,6 +14,7 @@ permissions: jobs: release: + if: github.repository == 'anomalyco/opencode' runs-on: blacksmith-4vcpu-ubuntu-2404 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c69de1d93b0d..d4c5a0a61504 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,16 +22,12 @@ env: jobs: unit: - name: unit (${{ matrix.settings.name }}) + name: unit (${{ matrix.platform }}) strategy: fail-fast: false matrix: - settings: - - name: linux - host: blacksmith-4vcpu-ubuntu-2404 - - name: windows - host: blacksmith-4vcpu-windows-2025 - runs-on: ${{ matrix.settings.host }} + platform: ${{ fromJSON(github.repository == 'internetisalie/opencode' && '["linux"]' || '["linux","windows"]') }} + runs-on: ${{ matrix.platform == 'linux' && (github.repository == 'internetisalie/opencode' && 'ubuntu-24.04' || 'blacksmith-4vcpu-ubuntu-2404') || 'blacksmith-4vcpu-windows-2025' }} defaults: run: shell: bash @@ -80,16 +76,12 @@ jobs: run: bun run test:httpapi e2e: - name: e2e (${{ matrix.settings.name }}) + name: e2e (${{ matrix.platform }}) strategy: fail-fast: false matrix: - settings: - - name: linux - host: blacksmith-4vcpu-ubuntu-2404 - - name: windows - host: blacksmith-4vcpu-windows-2025 - runs-on: ${{ matrix.settings.host }} + platform: ${{ fromJSON(github.repository == 'internetisalie/opencode' && '["linux"]' || '["linux","windows"]') }} + runs-on: ${{ matrix.platform == 'linux' && (github.repository == 'internetisalie/opencode' && 'ubuntu-24.04' || 'blacksmith-4vcpu-ubuntu-2404') || 'blacksmith-4vcpu-windows-2025' }} env: PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.playwright-browsers defaults: diff --git a/.github/workflows/triage.yml b/.github/workflows/triage.yml index 0350e43877c4..18f864e7b616 100644 --- a/.github/workflows/triage.yml +++ b/.github/workflows/triage.yml @@ -6,6 +6,7 @@ on: jobs: triage: + if: github.repository == 'anomalyco/opencode' runs-on: blacksmith-4vcpu-ubuntu-2404 permissions: contents: read diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index fc9a52797c1d..dc76d3ae27e5 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -9,7 +9,7 @@ on: jobs: typecheck: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'internetisalie/opencode' && 'ubuntu-24.04' || 'blacksmith-4vcpu-ubuntu-2404' }} steps: - name: Checkout repository uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 diff --git a/.husky/pre-push b/.husky/pre-push index 5d3cc53411be..4660c37952b9 100755 --- a/.husky/pre-push +++ b/.husky/pre-push @@ -17,4 +17,4 @@ if (process.versions.bun !== expectedBunVersion) { console.warn(`Warning: Bun version ${process.versions.bun} differs from expected ${expectedBunVersion}`); } ' -bun typecheck +bun turbo typecheck --concurrency=2 diff --git a/packages/core/schema.json b/packages/core/schema.json index d0eeeebd5c41..ac4bc22ef33d 100644 --- a/packages/core/schema.json +++ b/packages/core/schema.json @@ -1,8 +1,8 @@ { "version": "7", "dialect": "sqlite", - "id": "f14a9b18-8207-487e-a3d3-227e629ba9ad", - "prevIds": ["169a0f0f-d58f-479f-b024-fa1c7b9a09db"], + "id": "d834b448-3c91-409a-91e9-797db24fb4b1", + "prevIds": ["f14a9b18-8207-487e-a3d3-227e629ba9ad"], "ddl": [ { "name": "workspace", @@ -40,6 +40,10 @@ "name": "permission", "entityType": "tables" }, + { + "name": "project_association", + "entityType": "tables" + }, { "name": "project_directory", "entityType": "tables" @@ -600,6 +604,46 @@ "entityType": "columns", "table": "permission" }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "directory", + "entityType": "columns", + "table": "project_association" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "project_id", + "entityType": "columns", + "table": "project_association" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "strategy", + "entityType": "columns", + "table": "project_association" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_created", + "entityType": "columns", + "table": "project_association" + }, { "type": "text", "notNull": true, @@ -1524,6 +1568,17 @@ "entityType": "fks", "table": "permission" }, + { + "columns": ["project_id"], + "tableTo": "project", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_project_association_project_id_project_id_fk", + "entityType": "fks", + "table": "project_association" + }, { "columns": ["project_id"], "tableTo": "project", @@ -1700,6 +1755,13 @@ "table": "permission", "entityType": "pks" }, + { + "columns": ["directory"], + "nameExplicit": false, + "name": "project_association_pk", + "table": "project_association", + "entityType": "pks" + }, { "columns": ["id"], "nameExplicit": false, @@ -1818,6 +1880,20 @@ "entityType": "indexes", "table": "permission" }, + { + "columns": [ + { + "value": "project_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "project_association_project_id_idx", + "entityType": "indexes", + "table": "project_association" + }, { "columns": [ { @@ -2068,4 +2144,4 @@ } ], "renames": [] -} +} \ No newline at end of file diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts index e6ea4eaa1477..0b0c37ab5fe9 100644 --- a/packages/core/src/database/migration.gen.ts +++ b/packages/core/src/database/migration.gen.ts @@ -40,5 +40,6 @@ export const migrations = ( import("./migration/20260622142730_simplify_session_context_epoch"), import("./migration/20260622170816_reset_v2_session_state"), import("./migration/20260622202450_simplify_session_input"), + import("./migration/20260925144545_project-association"), ]) ).map((module) => module.default) satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration/20260925144545_project-association.ts b/packages/core/src/database/migration/20260925144545_project-association.ts new file mode 100644 index 000000000000..7861c96382d1 --- /dev/null +++ b/packages/core/src/database/migration/20260925144545_project-association.ts @@ -0,0 +1,27 @@ +import { Effect } from "effect" +import type { DatabaseMigration } from "../migration" + +export default { + id: "20260925144545_project-association", + up(tx) { + return Effect.gen(function* () { + yield* tx.run(` + CREATE TABLE \`project_association\` ( + \`directory\` text PRIMARY KEY, + \`project_id\` text NOT NULL, + \`strategy\` text, + \`time_created\` integer NOT NULL, + CONSTRAINT \`fk_project_association_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(`CREATE INDEX \`project_association_project_id_idx\` ON \`project_association\` (\`project_id\`);`) + yield* tx.run(` + INSERT OR REPLACE INTO \`project_association\` (\`directory\`, \`project_id\`, \`strategy\`, \`time_created\`) + SELECT \`directory\`, \`project_id\`, \`strategy\`, \`time_created\` + FROM \`project_directory\` + WHERE \`type\` = 'association'; + `) + yield* tx.run(`DELETE FROM \`project_directory\` WHERE \`type\` = 'association';`) + }) + }, +} satisfies DatabaseMigration.Migration diff --git a/packages/core/src/database/schema.gen.ts b/packages/core/src/database/schema.gen.ts index ed60fde6c55f..fd745a4c82dc 100644 --- a/packages/core/src/database/schema.gen.ts +++ b/packages/core/src/database/schema.gen.ts @@ -97,6 +97,15 @@ export default { CONSTRAINT \`fk_permission_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE ); `) + yield* tx.run(` + CREATE TABLE \`project_association\` ( + \`directory\` text PRIMARY KEY, + \`project_id\` text NOT NULL, + \`strategy\` text, + \`time_created\` integer NOT NULL, + CONSTRAINT \`fk_project_association_project_id_project_id_fk\` FOREIGN KEY (\`project_id\`) REFERENCES \`project\`(\`id\`) ON DELETE CASCADE + ); + `) yield* tx.run(` CREATE TABLE \`project_directory\` ( \`project_id\` text NOT NULL, @@ -241,6 +250,7 @@ export default { yield* tx.run( `CREATE UNIQUE INDEX \`permission_project_action_resource_idx\` ON \`permission\` (\`project_id\`,\`action\`,\`resource\`);`, ) + yield* tx.run(`CREATE INDEX \`project_association_project_id_idx\` ON \`project_association\` (\`project_id\`);`) yield* tx.run( `CREATE INDEX \`message_session_time_created_id_idx\` ON \`message\` (\`session_id\`,\`time_created\`,\`id\`);`, ) diff --git a/packages/core/src/project.ts b/packages/core/src/project.ts index 49e054d7cc9a..5294c6f39c68 100644 --- a/packages/core/src/project.ts +++ b/packages/core/src/project.ts @@ -32,10 +32,28 @@ export interface Resolved { readonly id: ID readonly directory: AbsolutePath readonly vcs?: Vcs + readonly associated?: boolean } +export const AssociateInput = Schema.Struct({ + projectID: ID, + directory: AbsolutePath, + strategy: Schema.optional(Schema.String), +}).annotate({ identifier: "Project.AssociateInput" }) +export type AssociateInput = typeof AssociateInput.Type + +export const DissociateInput = Schema.Struct({ + projectID: ID, + directory: AbsolutePath, +}).annotate({ identifier: "Project.DissociateInput" }) +export type DissociateInput = typeof DissociateInput.Type + export interface Interface { readonly directories: (input: DirectoriesInput) => Effect.Effect + /** Associate a directory with a project, and return the project's directories. */ + readonly associate: (input: AssociateInput) => Effect.Effect + /** Remove a directory's association with a project, and return what remains. */ + readonly dissociate: (input: DissociateInput) => Effect.Effect readonly resolve: (input: AbsolutePath) => Effect.Effect /** * Temporary bridge method for writing the resolved project ID to the repo-local cache. @@ -59,7 +77,27 @@ const layer = Layer.effect( const projectDirectories = yield* ProjectDirectories.Service const directories = Effect.fn("Project.directories")(function* (input: DirectoriesInput) { - return yield* projectDirectories.list(input.projectID) + const recorded = yield* projectDirectories.list(input.projectID) + const associated = yield* projectDirectories.associations(input.projectID) + const known = new Set(recorded.map((item) => item.directory)) + return [...recorded, ...associated.filter((item) => !known.has(item.directory))] + }) + + const associate = Effect.fn("Project.associate")(function* (input: AssociateInput) { + yield* projectDirectories.associate({ + projectID: input.projectID, + directory: AbsolutePath.make(yield* fs.resolve(input.directory)), + strategy: input.strategy, + }) + return yield* directories({ projectID: input.projectID }) + }) + + const dissociate = Effect.fn("Project.dissociate")(function* (input: DissociateInput) { + yield* projectDirectories.dissociate({ + projectID: input.projectID, + directory: AbsolutePath.make(yield* fs.resolve(input.directory)), + }) + return yield* directories({ projectID: input.projectID }) }) const cached = Effect.fnUntraced(function* (dir: string) { @@ -109,7 +147,15 @@ const layer = Layer.effect( const resolve = Effect.fn("Project.resolve")(function* (input: AbsolutePath) { const repo = yield* git.repo.discover(input) - if (!repo) return { id: ID.global, directory: AbsolutePath.make(path.parse(input).root), vcs: undefined } + if (!repo) { + // An exact, explicit association gives a non-repository directory a project. + // + // Deliberately a fallback: git discovery still wins where it succeeds, so an + // association can never silently re-home a directory that is a worktree. + const owner = yield* projectDirectories.ownerOf(input) + if (owner) return { id: owner, directory: input, vcs: undefined, associated: true } + return { id: ID.global, directory: AbsolutePath.make(path.parse(input).root), vcs: undefined } + } const previous = yield* cached(repo.commonDirectory) const id = (yield* remote(repo)) ?? previous ?? (yield* root(repo)) @@ -125,7 +171,7 @@ const layer = Layer.effect( yield* fs.writeFileString(path.join(input.store, "opencode"), input.id).pipe(Effect.ignore) }) - return Service.of({ directories, resolve, commit }) + return Service.of({ directories, associate, dissociate, resolve, commit }) }), ) diff --git a/packages/core/src/project/directories.ts b/packages/core/src/project/directories.ts index 6c9ad2e51594..235a63e29c32 100644 --- a/packages/core/src/project/directories.ts +++ b/packages/core/src/project/directories.ts @@ -6,7 +6,7 @@ import { Database } from "../database/database" import { makeGlobalNode } from "../effect/app-node" import { AbsolutePath, optional } from "../schema" import { ProjectSchema } from "./schema" -import { ProjectDirectoryTable } from "./sql" +import { ProjectAssociationTable, ProjectDirectoryTable } from "./sql" import type { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite" export interface Directory { @@ -46,11 +46,21 @@ export type ListOutput = typeof ListOutput.Type export interface Interface { readonly list: (projectID: ProjectSchema.ID) => Effect.Effect> + readonly associations: (projectID: ProjectSchema.ID) => Effect.Effect> readonly get: (input: { projectID: ProjectSchema.ID directory: AbsolutePath }) => Effect.Effect readonly contains: (input: { projectID: ProjectSchema.ID; directory: AbsolutePath }) => Effect.Effect + /** + * The project a directory has been explicitly associated with, if any. + * + * Keyed by directory alone, so it can answer for a directory that is not a git + * worktree and therefore resolves to no project of its own. + */ + readonly ownerOf: (directory: AbsolutePath) => Effect.Effect + readonly associate: (input: { projectID: ProjectSchema.ID; directory: AbsolutePath; strategy?: string }) => Effect.Effect + readonly dissociate: (input: { projectID: ProjectSchema.ID; directory: AbsolutePath }) => Effect.Effect readonly create: (input: CreateInput, tx?: Transaction) => Effect.Effect readonly remove: (input: RemoveInput, tx?: Transaction) => Effect.Effect } @@ -108,6 +118,17 @@ const layer = Layer.effect( return rows.map((row) => ({ directory: row.directory, strategy: row.strategy ?? undefined })) }) + const associations = Effect.fn("ProjectDirectories.associations")(function* (projectID: ProjectSchema.ID) { + const rows = yield* db + .select({ directory: ProjectAssociationTable.directory, strategy: ProjectAssociationTable.strategy }) + .from(ProjectAssociationTable) + .where(eq(ProjectAssociationTable.project_id, projectID)) + .orderBy(asc(ProjectAssociationTable.directory)) + .all() + .pipe(Effect.orDie) + return rows.map((row) => ({ directory: row.directory, strategy: row.strategy ?? undefined })) + }) + const contains = Effect.fn("ProjectDirectories.contains")(function* (input: { projectID: ProjectSchema.ID directory: AbsolutePath @@ -145,10 +166,56 @@ const layer = Layer.effect( return row ? { directory: row.directory, strategy: row.strategy ?? undefined } : undefined }) + const ownerOf = Effect.fn("ProjectDirectories.ownerOf")(function* (directory: AbsolutePath) { + const row = yield* db + .select({ projectID: ProjectAssociationTable.project_id }) + .from(ProjectAssociationTable) + .where(eq(ProjectAssociationTable.directory, directory)) + .get() + .pipe(Effect.orDie) + return row?.projectID + }) + + const associate = Effect.fn("ProjectDirectories.associate")(function* (input: { + projectID: ProjectSchema.ID + directory: AbsolutePath + strategy?: string + }) { + yield* db + .insert(ProjectAssociationTable) + .values({ project_id: input.projectID, directory: input.directory, strategy: input.strategy }) + .onConflictDoUpdate({ + target: ProjectAssociationTable.directory, + set: { project_id: input.projectID, strategy: input.strategy ?? null }, + }) + .run() + .pipe(Effect.orDie) + }) + + const dissociate = Effect.fn("ProjectDirectories.dissociate")(function* (input: { + projectID: ProjectSchema.ID + directory: AbsolutePath + }) { + yield* db + .delete(ProjectAssociationTable) + .where( + and( + eq(ProjectAssociationTable.project_id, input.projectID), + eq(ProjectAssociationTable.directory, input.directory), + ), + ) + .run() + .pipe(Effect.orDie) + }) + return Service.of({ list, + associations, get, contains, + ownerOf, + associate, + dissociate, create, remove, }) diff --git a/packages/core/src/project/sql.ts b/packages/core/src/project/sql.ts index ab05fdac4a1a..86858641685e 100644 --- a/packages/core/src/project/sql.ts +++ b/packages/core/src/project/sql.ts @@ -1,4 +1,4 @@ -import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core" +import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core" import * as DatabasePath from "../database/path" import { Timestamps } from "../database/schema.sql" import { ProjectSchema } from "./schema" @@ -33,3 +33,19 @@ export const ProjectDirectoryTable = sqliteTable( }, (table) => [primaryKey({ columns: [table.project_id, table.directory] })], ) + +export const ProjectAssociationTable = sqliteTable( + "project_association", + { + directory: DatabasePath.absoluteColumn().primaryKey(), + project_id: text() + .$type() + .notNull() + .references(() => ProjectTable.id, { onDelete: "cascade" }), + strategy: text(), + time_created: integer() + .notNull() + .$default(() => Date.now()), + }, + (table) => [index("project_association_project_id_idx").on(table.project_id)], +) diff --git a/packages/core/test/database-migration.test.ts b/packages/core/test/database-migration.test.ts index 464ce2695a76..30c21654fab3 100644 --- a/packages/core/test/database-migration.test.ts +++ b/packages/core/test/database-migration.test.ts @@ -16,6 +16,7 @@ import eventSourcedSessionInputMigration from "@opencode-ai/core/database/migrat import contextEpochAgentMigration from "@opencode-ai/core/database/migration/20260605042240_add_context_epoch_agent" import simplifyIntegrationCredentialsMigration from "@opencode-ai/core/database/migration/20260611192811_lush_chimera" import simplifySessionInputMigration from "@opencode-ai/core/database/migration/20260622202450_simplify_session_input" +import projectAssociationMigration from "@opencode-ai/core/database/migration/20260925144545_project-association" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { EventV2 } from "@opencode-ai/core/event" @@ -39,6 +40,40 @@ const run = (effect: Effect.Effect) => const makeDb = EffectDrizzleSqlite.makeWithDefaults() describe("DatabaseMigration", () => { + test("moves legacy project associations without losing discovered directories", async () => { + await run( + Effect.gen(function* () { + const db = yield* makeDb + yield* db.run(sql`CREATE TABLE project (id text PRIMARY KEY)`) + yield* db.run(sql` + CREATE TABLE project_directory ( + project_id text NOT NULL, + directory text NOT NULL, + type text, + strategy text, + time_created integer NOT NULL, + PRIMARY KEY (project_id, directory) + ) + `) + yield* db.run(sql`INSERT INTO project (id) VALUES ('project-1')`) + yield* db.run(sql` + INSERT INTO project_directory (project_id, directory, type, strategy, time_created) + VALUES ('project-1', '/checkout', 'git_worktree', 'copy', 1), + ('project-1', '/workspace', 'association', 'manual', 2) + `) + + yield* DatabaseMigration.applyOnly(db, [projectAssociationMigration]) + + expect(yield* db.all(sql`SELECT directory, project_id, strategy, time_created FROM project_association`)).toEqual([ + { directory: "/workspace", project_id: "project-1", strategy: "manual", time_created: 2 }, + ]) + expect(yield* db.all(sql`SELECT directory, type, strategy FROM project_directory`)).toEqual([ + { directory: "/checkout", type: "git_worktree", strategy: "copy" }, + ]) + }), + ) + }) + test("defaults missing workspace names while preserving legacy workspace data", async () => { await run( Effect.gen(function* () { diff --git a/packages/core/test/effect/layer-node/node-build.test.ts b/packages/core/test/effect/layer-node/node-build.test.ts index e9ff2fc149e7..60e28d26a379 100644 --- a/packages/core/test/effect/layer-node/node-build.test.ts +++ b/packages/core/test/effect/layer-node/node-build.test.ts @@ -79,6 +79,8 @@ describe("node build", () => { return Project.Service.of({ directories: () => Effect.succeed([]), resolve: (directory) => Effect.succeed({ id: Project.ID.global, directory }), + associate: () => Effect.succeed([]), + dissociate: () => Effect.succeed([]), commit: () => Effect.void, }) }), diff --git a/packages/core/test/location.test.ts b/packages/core/test/location.test.ts index 77e9e96745bb..a546be888223 100644 --- a/packages/core/test/location.test.ts +++ b/packages/core/test/location.test.ts @@ -19,6 +19,8 @@ const projectLayer = Layer.succeed( directory: AbsolutePath.make("/repo"), vcs: { type: "git", store: AbsolutePath.make("/repo/.git") }, }), + associate: () => Effect.succeed([]), + dissociate: () => Effect.succeed([]), commit: () => Effect.void, }), ) diff --git a/packages/core/test/project-copy.test.ts b/packages/core/test/project-copy.test.ts index d37f6302074a..39983873a4c6 100644 --- a/packages/core/test/project-copy.test.ts +++ b/packages/core/test/project-copy.test.ts @@ -397,4 +397,17 @@ describe("ProjectCopy", () => { expect(yield* stored(input.projectID)).not.toContainEqual({ directory: missing, strategy: null }) }), ) + + it.live("refresh preserves an association to a temporarily missing directory", () => + Effect.gen(function* () { + const input = yield* setup() + const missing = abs(`${input.root.path}-missing-association`) + const directories = yield* ProjectDirectories.Service + yield* directories.associate({ projectID: input.projectID, directory: missing }) + + const copy = yield* ProjectCopy.Service + expect(yield* copy.refresh({ projectID: input.projectID })).toEqual({ updated: [], removed: [] }) + expect(yield* directories.ownerOf(missing)).toBe(input.projectID) + }), + ) }) diff --git a/packages/core/test/project.test.ts b/packages/core/test/project.test.ts index fa709a8b2bf5..58bb1dfdb74e 100644 --- a/packages/core/test/project.test.ts +++ b/packages/core/test/project.test.ts @@ -4,6 +4,9 @@ import fs from "fs/promises" import path from "path" import { Effect, Schema } from "effect" import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { Database } from "@opencode-ai/core/database/database" +import { ProjectDirectoryTable, ProjectTable } from "@opencode-ai/core/project/sql" import { ProjectV2 } from "@opencode-ai/core/project" import { AbsolutePath } from "@opencode-ai/core/schema" import { Hash } from "@opencode-ai/core/util/hash" @@ -11,6 +14,27 @@ import { tmpdir } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" const it = testEffect(AppNodeBuilder.build(ProjectV2.node)) +const itDb = testEffect(AppNodeBuilder.build(LayerNode.group([Database.node, ProjectV2.node]))) + +const associatedID = ProjectV2.ID.make("project-associated-directory") + +function seedProject(id: ProjectV2.ID, worktree: AbsolutePath) { + return Database.Service.use(({ db }) => + db + .insert(ProjectTable) + .values({ id, worktree, sandboxes: [], time_created: 1, time_updated: 1 }) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie), + ) +} + +function tmp() { + return Effect.acquireRelease( + Effect.promise(() => tmpdir()), + (value) => Effect.promise(() => value[Symbol.asyncDispose]()), + ) +} function remoteID(remote: string) { return ProjectV2.ID.make(Hash.fast(`git-remote:${remote}`)) @@ -219,3 +243,132 @@ describe("ProjectV2.resolve", () => { }), ) }) + +describe("ProjectV2.resolve with an associated directory", () => { + itDb.live("resolves a non-git directory to the project it is associated with", () => + Effect.gen(function* () { + const dir = yield* tmp() + const project = yield* ProjectV2.Service + const directory = yield* real(dir.path) + + // Without the association the directory is unattributable. + expect((yield* project.resolve(directory)).id).toBe(ProjectV2.ID.make("global")) + + yield* seedProject(associatedID, directory) + yield* project.associate({ projectID: associatedID, directory }) + + const result = yield* project.resolve(directory) + + expect(result.id).toBe(associatedID) + expect(result.directory).toBe(directory) + expect(result.vcs).toBeUndefined() + expect(result.associated).toBe(true) + }), + ) + + itDb.live("git discovery still wins over an association", () => + Effect.gen(function* () { + const dir = yield* tmp() + yield* Effect.promise(() => initRepo(dir.path, { remote: "https://github.com/owner/repo.git" })) + const project = yield* ProjectV2.Service + const directory = yield* real(dir.path) + + yield* seedProject(associatedID, directory) + yield* project.associate({ projectID: associatedID, directory }) + + const result = yield* project.resolve(directory) + + // The association is a fallback, never an override: a directory that is a git + // worktree keeps the identity git gives it. + expect(result.id).toBe(remoteID("github.com/owner/repo")) + expect(result.id).not.toBe(associatedID) + expect(result.vcs?.type).toBe("git") + }), + ) + + itDb.live("dissociating restores the global result", () => + Effect.gen(function* () { + const dir = yield* tmp() + const project = yield* ProjectV2.Service + const directory = yield* real(dir.path) + + yield* seedProject(associatedID, directory) + yield* project.associate({ projectID: associatedID, directory }) + expect((yield* project.resolve(directory)).id).toBe(associatedID) + + expect(yield* project.dissociate({ projectID: associatedID, directory })).toEqual([]) + expect((yield* project.resolve(directory)).id).toBe(ProjectV2.ID.make("global")) + }), + ) + + itDb.live("ignores an implicit directory record and transfers an explicit association", () => + Effect.gen(function* () { + const dir = yield* tmp() + const directory = yield* real(dir.path) + const project = yield* ProjectV2.Service + const oldID = ProjectV2.ID.make("old-project") + yield* seedProject(oldID, directory) + yield* seedProject(associatedID, directory) + + yield* Database.Service.use(({ db }) => + db + .insert(ProjectDirectoryTable) + .values({ project_id: oldID, directory }) + .run() + .pipe(Effect.orDie), + ) + expect((yield* project.resolve(directory)).id).toBe(ProjectV2.ID.global) + + yield* project.associate({ projectID: oldID, directory }) + expect((yield* project.resolve(directory)).id).toBe(oldID) + + yield* project.associate({ projectID: associatedID, directory }) + expect((yield* project.resolve(directory)).id).toBe(associatedID) + expect(yield* project.directories({ projectID: oldID })).toEqual([{ directory }]) + + yield* project.dissociate({ projectID: associatedID, directory }) + expect((yield* project.resolve(directory)).id).toBe(ProjectV2.ID.global) + }), + ) + + itDb.live("keeps an automatically recorded directory after dissociation", () => + Effect.gen(function* () { + const dir = yield* tmp() + const directory = yield* real(dir.path) + const project = yield* ProjectV2.Service + yield* seedProject(associatedID, directory) + yield* Database.Service.use(({ db }) => + db + .insert(ProjectDirectoryTable) + .values({ project_id: associatedID, directory, strategy: "git_worktree" }) + .run() + .pipe(Effect.orDie), + ) + + yield* project.associate({ projectID: associatedID, directory }) + expect(yield* project.directories({ projectID: associatedID })).toEqual([ + { directory, strategy: "git_worktree" }, + ]) + yield* project.dissociate({ projectID: associatedID, directory }) + expect(yield* project.directories({ projectID: associatedID })).toEqual([ + { directory, strategy: "git_worktree" }, + ]) + expect((yield* project.resolve(directory)).id).toBe(ProjectV2.ID.global) + }), + ) + + itDb.live("matches only the associated directory, not its descendants", () => + Effect.gen(function* () { + const dir = yield* tmp() + const directory = yield* real(dir.path) + const nested = AbsolutePath.make(path.join(directory, "inputs")) + yield* Effect.promise(() => fs.mkdir(nested)) + const project = yield* ProjectV2.Service + yield* seedProject(associatedID, directory) + yield* project.associate({ projectID: associatedID, directory }) + + expect((yield* project.resolve(directory)).id).toBe(associatedID) + expect((yield* project.resolve(nested)).id).toBe(ProjectV2.ID.global) + }), + ) +}) diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index 4688ede82d18..6b27c578103e 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -32,6 +32,8 @@ const projects = Layer.succeed( ProjectV2.Service.of({ resolve: (directory) => Effect.succeed({ id: ProjectV2.ID.global, directory }), directories: () => Effect.succeed([]), + associate: () => Effect.succeed([]), + dissociate: () => Effect.succeed([]), commit: () => Effect.void, }), ) diff --git a/packages/core/test/session-history.test.ts b/packages/core/test/session-history.test.ts index c67f776d2930..b2dfb1b51740 100644 --- a/packages/core/test/session-history.test.ts +++ b/packages/core/test/session-history.test.ts @@ -20,6 +20,8 @@ const projects = Layer.succeed( ProjectV2.Service.of({ resolve: (directory) => Effect.succeed({ id: ProjectV2.ID.global, directory }), directories: () => Effect.succeed([]), + associate: () => Effect.succeed([]), + dissociate: () => Effect.succeed([]), commit: () => Effect.void, }), ) diff --git a/packages/opencode/src/control-plane/workspace.ts b/packages/opencode/src/control-plane/workspace.ts index 188cd383bb46..929e3ba4d453 100644 --- a/packages/opencode/src/control-plane/workspace.ts +++ b/packages/opencode/src/control-plane/workspace.ts @@ -1,6 +1,6 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { httpClient } from "@opencode-ai/core/effect/app-node-platform" -import { Context, Effect, FiberMap, Iterable, Layer, Schema, Stream } from "effect" +import { Cause, Context, Effect, FiberMap, Iterable, Layer, Schema, Stream } from "effect" import { serviceUse } from "@opencode-ai/core/effect/service-use" import { FetchHttpClient, HttpBody, HttpClient, HttpClientError, HttpClientRequest } from "effect/unstable/http" import { Database } from "@opencode-ai/core/database/database" @@ -144,6 +144,7 @@ export interface Interface { timeout?: number, ) => Effect.Effect readonly startWorkspaceSyncing: (projectID: ProjectV2.ID) => Effect.Effect + readonly resumeWorkspaceSyncing: (projectID: ProjectV2.ID) => Effect.Effect } export class Service extends Context.Service()("@opencode/Workspace") {} @@ -164,6 +165,8 @@ const layer = Layer.effect( const { db } = yield* Database.Service const connections = new Map() const syncFibers = yield* FiberMap.make() + // Tracks projects scanned in this service lifetime, not live connection state. + const resumedProjects = new Set() const setStatus = (id: WorkspaceV2.ID, status: ConnectionStatus["status"]) => { const prev = connections.get(id) @@ -364,29 +367,47 @@ const layer = Layer.effect( }) const syncWorkspaceLoop = Effect.fn("Workspace.syncWorkspaceLoop")(function* (space: Info) { - const target = yield* WorkspaceAdapterRuntime.target(space) - - if (target.type === "local") return - let attempt = 0 while (true) { setStatus(space.id, "connecting") - const stream = yield* connectSSE(target.url, target.headers).pipe( - Effect.tap(() => syncHistory(space, target.url, target.headers)), - Effect.catch((err) => + const target = yield* WorkspaceAdapterRuntime.target(space).pipe( + Effect.catchCause((cause) => Effect.gen(function* () { + if (Cause.hasInterrupts(cause)) return yield* Effect.failCause(cause) setStatus(space.id, "error") - yield* Effect.logWarning("failed to connect to global sync", { - workspace: space.name, - error: errorData(err), + yield* Effect.logWarning("failed to resolve workspace target", { + workspaceID: space.id, + error: errorData(Cause.squash(cause)), }) return null }), ), ) + if (target?.type === "local") { + setStatus(space.id, (yield* fs.existsSafe(target.directory)) ? "connected" : "error") + return + } + + const stream = target + ? yield* connectSSE(target.url, target.headers).pipe( + Effect.tap(() => syncHistory(space, target.url, target.headers)), + Effect.catchCause((cause) => + Effect.gen(function* () { + if (Cause.hasInterrupts(cause)) return yield* Effect.failCause(cause) + setStatus(space.id, "error") + yield* Effect.logWarning("failed to connect to global sync", { + workspace: space.name, + error: errorData(Cause.squash(cause)), + }) + return null + }), + ), + ) + : null + if (stream) { attempt = 0 @@ -426,6 +447,15 @@ const layer = Layer.effect( }) } }), + ).pipe( + Effect.catchCause((cause) => + Cause.hasInterrupts(cause) + ? Effect.failCause(cause) + : Effect.logWarning("workspace event stream ended with an error", { + workspaceID: space.id, + error: errorData(Cause.squash(cause)), + }), + ), ) setStatus(space.id, "disconnected") @@ -441,29 +471,30 @@ const layer = Layer.effect( const startSync = Effect.fn("Workspace.startSync")(function* (space: Info) { if (!flags.experimentalWorkspaces) return + // A listener in error may still be retrying; keep its backoff and target resolution in place. + if (yield* FiberMap.has(syncFibers, space.id)) return + const target = yield* WorkspaceAdapterRuntime.target(space).pipe( - Effect.catch((error) => + Effect.catchCause((cause) => Effect.gen(function* () { - setStatus(space.id, "error") + if (Cause.hasInterrupts(cause)) return yield* Effect.failCause(cause) yield* Effect.logWarning("workspace target failed", { workspaceID: space.id, - error: errorData(error), + error: errorData(Cause.squash(cause)), }) return null }), ), ) - if (!target) return - - if (target.type === "local") { + // Another start may have installed a listener while target() was pending. + if (yield* FiberMap.has(syncFibers, space.id)) return + if (target === null) setStatus(space.id, "error") + if (target?.type === "local") { setStatus(space.id, (yield* fs.existsSafe(target.directory)) ? "connected" : "error") return } - const exists = yield* FiberMap.has(syncFibers, space.id) - if (exists && connections.get(space.id)?.status !== "error") return - - setStatus(space.id, "disconnected") + if (target !== null) setStatus(space.id, "disconnected") yield* FiberMap.run( syncFibers, @@ -872,6 +903,20 @@ const layer = Layer.effect( } }) + const resumeWorkspaceSyncing = Effect.fn("Workspace.resumeWorkspaceSyncing")(function* (projectID: ProjectV2.ID) { + if (!flags.experimentalWorkspaces || resumedProjects.has(projectID)) return + resumedProjects.add(projectID) + yield* startWorkspaceSyncing(projectID).pipe( + Effect.catchCause((cause) => + Effect.gen(function* () { + resumedProjects.delete(projectID) + if (Cause.hasInterrupts(cause)) return yield* Effect.failCause(cause) + yield* Effect.logWarning("workspace sync recovery failed", { projectID, cause }) + }), + ), + ) + }) + return Service.of({ create, sessionWarp, @@ -883,6 +928,7 @@ const layer = Layer.effect( isSyncing, waitForSync, startWorkspaceSyncing, + resumeWorkspaceSyncing, }) }), ) diff --git a/packages/opencode/src/plugin/index.ts b/packages/opencode/src/plugin/index.ts index 6f05329a0833..406f27e2f78f 100644 --- a/packages/opencode/src/plugin/index.ts +++ b/packages/opencode/src/plugin/index.ts @@ -2,6 +2,7 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import type { Hooks, PluginInput, + PluginHttpHandler, Plugin as PluginInstance, PluginModule, WorkspaceAdapter as PluginWorkspaceAdapter, @@ -36,6 +37,8 @@ import { InstallationChannel } from "@opencode-ai/core/installation/version" type State = { hooks: Hooks[] + registered: Map + duplicates: Set } // Hook names that follow the (input, output) => Promise trigger pattern @@ -54,6 +57,7 @@ export interface Interface { output: Output, ) => Effect.Effect readonly list: () => Effect.Effect + readonly http: (id: string) => Effect.Effect readonly init: () => Effect.Effect } @@ -111,16 +115,24 @@ function getLegacyPlugins(mod: Record) { return result } -async function applyPlugin(load: PluginLoader.Loaded, input: PluginInput, hooks: Hooks[]) { +async function applyPlugin(load: PluginLoader.Loaded, input: PluginInput, state: State) { const plugin = readV1Plugin(load.mod, load.spec, "server", "detect") if (plugin) { - await resolvePluginId(load.source, load.spec, load.target, readPluginId(plugin.id, load.spec), load.pkg) - hooks.push(await (plugin as PluginModule).server(input, load.options)) + const id = await resolvePluginId(load.source, load.spec, load.target, readPluginId(plugin.id, load.spec), load.pkg) + if (state.duplicates.has(id)) throw new TypeError(`Plugin id ${id} is duplicated`) + if (state.registered.has(id)) { + state.registered.delete(id) + state.duplicates.add(id) + throw new TypeError(`Plugin id ${id} is duplicated`) + } + const hooks = await (plugin as PluginModule).server(input, load.options) + state.registered.set(id, hooks) + state.hooks.push(hooks) return } for (const server of getLegacyPlugins(load.mod)) { - hooks.push(await server(input, load.options)) + state.hooks.push(await server(input, load.options)) } } @@ -134,6 +146,8 @@ const layer = Layer.effect( const state = yield* InstanceState.make( Effect.fn("Plugin.state")(function* (ctx) { const hooks: Hooks[] = [] + const registered = new Map() + const duplicates = new Set() const bridge = yield* EffectBridge.make() function publishPluginError(message: string) { @@ -222,7 +236,7 @@ const layer = Layer.effect( // Keep plugin execution sequential so hook registration and execution // order remains deterministic across plugin runs. yield* Effect.tryPromise({ - try: () => applyPlugin(load, input, hooks), + try: () => applyPlugin(load, input, { hooks, registered, duplicates }), catch: (err) => { const message = errorMessage(err) return message @@ -277,7 +291,7 @@ const layer = Layer.effect( ), ) - return { hooks } + return { hooks, registered, duplicates } }), ) @@ -301,11 +315,16 @@ const layer = Layer.effect( return s.hooks }) + const http = Effect.fn("Plugin.http")(function* (id: string) { + const s = yield* InstanceState.get(state) + return s.registered.get(id)?.http + }) + const init = Effect.fn("Plugin.init")(function* () { yield* InstanceState.get(state) }) - return Service.of({ trigger, list, init }) + return Service.of({ trigger, list, http, init }) }), ) diff --git a/packages/opencode/src/project/project.ts b/packages/opencode/src/project/project.ts index 9870377b2169..00fa71296698 100644 --- a/packages/opencode/src/project/project.ts +++ b/packages/opencode/src/project/project.ts @@ -1,7 +1,7 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { and, eq, sql } from "drizzle-orm" import { Database } from "@opencode-ai/core/database/database" -import { ProjectDirectoryTable, ProjectTable } from "@opencode-ai/core/project/sql" +import { ProjectAssociationTable, ProjectDirectoryTable, ProjectTable } from "@opencode-ai/core/project/sql" import { ProjectDirectories } from "@opencode-ai/core/project/directories" import { SessionTable } from "@opencode-ai/core/session/sql" import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" @@ -173,6 +173,13 @@ const layer = Layer.effect( // list and rely on it being re-populated to ensure // accuracy yield* d.delete(ProjectDirectoryTable).where(eq(ProjectDirectoryTable.project_id, oldID)).run() + // Explicit associations describe logical ownership, not discovered + // checkouts, and must follow the project when its ID changes. + yield* d + .update(ProjectAssociationTable) + .set({ project_id: newID }) + .where(eq(ProjectAssociationTable.project_id, oldID)) + .run() yield* d .update(SessionTable) @@ -235,11 +242,12 @@ const layer = Layer.effect( const result: Info = { ...existing, worktree: projectID === ProjectV2.ID.global ? worktree : existing.worktree, - vcs: data.vcs?.type ?? fakeVcs, + vcs: data.associated ? existing.vcs : (data.vcs?.type ?? fakeVcs), time: { ...existing.time, updated: Date.now() }, } if ( projectID !== ProjectV2.ID.global && + !data.associated && data.directory !== result.worktree && !result.sandboxes.includes(data.directory) ) diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts index 3ce34442dd10..7a34f2fef201 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/project.ts @@ -1,14 +1,19 @@ import { Project } from "@/project/project" import { ProjectV2 } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" import { Schema } from "effect" import { HttpApi, HttpApiEndpoint, HttpApiError, HttpApiGroup, OpenApi } from "effect/unstable/httpapi" import { ProjectNotFoundError } from "../errors" import { Authorization } from "../middleware/authorization" import { InstanceContextMiddleware } from "../middleware/instance-context" -import { WorkspaceRoutingMiddleware, WorkspaceRoutingQuery } from "../middleware/workspace-routing" +import { WorkspaceRoutingMiddleware, WorkspaceRoutingQuery, WorkspaceRoutingQueryFields } from "../middleware/workspace-routing" import { described } from "./metadata" const root = "/project" +const DirectoryPayload = Schema.Struct({ + directory: AbsolutePath, + strategy: Schema.optional(Schema.String), +}) const UpdatePayload = Schema.Struct({ name: Schema.optional(Schema.String), icon: Schema.optional(Project.Info.fields.icon), @@ -73,6 +78,32 @@ export const ProjectApi = HttpApi.make("project") description: "List known local absolute directories for a project.", }), ), + HttpApiEndpoint.post("directoryCreate", `${root}/:projectID/directories`, { + params: { projectID: ProjectV2.ID }, + query: WorkspaceRoutingQuery, + payload: DirectoryPayload, + success: described(ProjectV2.Directories, "Project directories after the association"), + error: [HttpApiError.BadRequest, ProjectNotFoundError], + }).annotateMerge( + OpenApi.annotations({ + identifier: "project.directoryCreate", + summary: "Associate a directory with a project", + description: + "Associate this exact local absolute directory with a project. Non-Git sessions run at this directory resolve to the project instead of `global`; subdirectories are not included. Git discovery still takes precedence where it succeeds.", + }), + ), + HttpApiEndpoint.delete("directoryRemove", `${root}/:projectID/directories`, { + params: { projectID: ProjectV2.ID }, + query: Schema.Struct({ ...WorkspaceRoutingQueryFields, directory: AbsolutePath }), + success: described(ProjectV2.Directories, "Project directories after the removal"), + error: [HttpApiError.BadRequest, ProjectNotFoundError], + }).annotateMerge( + OpenApi.annotations({ + identifier: "project.directoryRemove", + summary: "Remove a directory association", + description: "Remove the exact directory's explicit association with a project. Pass the directory as a query parameter.", + }), + ), ) .annotateMerge( OpenApi.annotations({ diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts index 3c5351aee2ab..88b148d3cab6 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/project.ts @@ -1,11 +1,13 @@ import * as InstanceState from "@/effect/instance-state" import { Project } from "@/project/project" import { ProjectV2 } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" +import { isAbsolute } from "path" import { Effect } from "effect" -import { HttpApiBuilder } from "effect/unstable/httpapi" +import { HttpApiBuilder, HttpApiError } from "effect/unstable/httpapi" import { InstanceHttpApi } from "../api" import { ProjectNotFoundError } from "../errors" -import { markInstanceForReload } from "../lifecycle" +import { markDirectoryForDisposal, markInstanceForReload } from "../lifecycle" export const projectHandlers = HttpApiBuilder.group(InstanceHttpApi, "project", (handlers) => Effect.gen(function* () { @@ -53,11 +55,49 @@ export const projectHandlers = HttpApiBuilder.group(InstanceHttpApi, "project", project.directories({ projectID: ctx.params.projectID }), ) + // The association table has a foreign key onto `project`, so an unknown id would + // surface as a defect rather than a 404. Check first and fail with the error the + // route already declares. + const known = Effect.fn("ProjectHttpApi.known")(function* (projectID: ProjectV2.ID) { + if (yield* svc.get(projectID)) return + return yield* Effect.fail( + new ProjectNotFoundError({ projectID, message: `Project not found: ${projectID}` }), + ) + }) + + const directoryCreate = Effect.fn("ProjectHttpApi.directoryCreate")(function* (ctx: { + params: { projectID: ProjectV2.ID } + payload: { directory: AbsolutePath; strategy?: string } + }) { + if (!isAbsolute(ctx.payload.directory)) return yield* new HttpApiError.BadRequest({}) + yield* known(ctx.params.projectID) + const result = yield* project.associate({ + projectID: ctx.params.projectID, + directory: ctx.payload.directory, + strategy: ctx.payload.strategy, + }) + yield* markDirectoryForDisposal(ctx.payload.directory) + return result + }) + + const directoryRemove = Effect.fn("ProjectHttpApi.directoryRemove")(function* (ctx: { + params: { projectID: ProjectV2.ID } + query: { directory: AbsolutePath } + }) { + if (!isAbsolute(ctx.query.directory)) return yield* new HttpApiError.BadRequest({}) + yield* known(ctx.params.projectID) + const result = yield* project.dissociate({ projectID: ctx.params.projectID, directory: ctx.query.directory }) + yield* markDirectoryForDisposal(ctx.query.directory) + return result + }) + return handlers .handle("list", list) .handle("current", current) .handle("initGit", initGit) .handle("update", update) .handle("directories", directories) + .handle("directoryCreate", directoryCreate) + .handle("directoryRemove", directoryRemove) }), ) diff --git a/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts b/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts index bb7321e3ad4f..e31492cb7321 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/lifecycle.ts @@ -32,6 +32,15 @@ export const markInstanceForDisposal = (ctx: InstanceContext) => ) }) +export const markDirectoryForDisposal = (directory: string) => + Effect.gen(function* () { + const store = yield* InstanceStore.Service + const bridge = yield* EffectBridge.make() + return yield* HttpEffect.appendPreResponseHandler((_request, response) => + Effect.as(Effect.uninterruptible(bridge.run(store.disposeDirectory(directory))), response), + ) + }) + export const markInstanceForReload = (ctx: InstanceContext, next: InstanceStore.LoadInput) => Effect.gen(function* () { const marked = yield* mark(ctx) diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts index e39eb7394a50..ceea5ba6c822 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/instance-context.ts @@ -1,5 +1,6 @@ import { InstanceRef, WorkspaceRef } from "@/effect/instance-ref" import { InstanceStore } from "@/project/instance-store" +import { Workspace } from "@/control-plane/workspace" import { Effect, Layer } from "effect" import { HttpServerResponse } from "effect/unstable/http" import { HttpApiMiddleware } from "effect/unstable/httpapi" @@ -20,13 +21,16 @@ function decode(input: string): string { } } -function provideInstanceContext( +export function provideInstanceContext( effect: Effect.Effect, store: InstanceStore.Interface, + workspace: Workspace.Interface, ): Effect.Effect { return Effect.gen(function* () { const route = yield* WorkspaceRouteContext const ctx = yield* store.load({ directory: decode(route.directory) }) + // Loading the project initializes its plugins and registers its adapters. + yield* workspace.resumeWorkspaceSyncing(ctx.project.id) return yield* effect.pipe( Effect.provideService(InstanceRef, ctx), Effect.provideService(WorkspaceRef, route.workspaceID), @@ -38,6 +42,7 @@ export const instanceContextLayer = Layer.effect( InstanceContextMiddleware, Effect.gen(function* () { const store = yield* InstanceStore.Service - return InstanceContextMiddleware.of((effect) => provideInstanceContext(effect, store)) + const workspace = yield* Workspace.Service + return InstanceContextMiddleware.of((effect) => provideInstanceContext(effect, store, workspace)) }), ) diff --git a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts index 873abd834938..ade26520bea7 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/middleware/workspace-routing.ts @@ -209,7 +209,7 @@ function routeWorkspace( }) } -function routeHttpApiWorkspace( +export function routeHttpApiWorkspace( client: HttpClient.HttpClient, effect: Effect.Effect, ): Effect.Effect< diff --git a/packages/opencode/src/server/routes/instance/httpapi/plugin.ts b/packages/opencode/src/server/routes/instance/httpapi/plugin.ts new file mode 100644 index 000000000000..b06ef056605a --- /dev/null +++ b/packages/opencode/src/server/routes/instance/httpapi/plugin.ts @@ -0,0 +1,84 @@ +import { Plugin } from "@/plugin" +import { Effect } from "effect" +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http" +import { IncomingMessage } from "node:http" +import { Readable } from "node:stream" + +function pluginURL(request: HttpServerRequest.HttpServerRequest) { + const url = + request.source instanceof Request + ? new URL(request.source.url) + : new URL(request.url, `http://${request.headers.host ?? "localhost"}`) + const match = /^\/api\/plugins\/[^/]+(\/.*)?$/.exec(url.pathname) + url.pathname = match?.[1] || "/" + return url +} + +function requestAbort(source: unknown) { + if (source instanceof Request) return { signal: source.signal, cleanup() {} } + if (!(source instanceof IncomingMessage)) return { signal: undefined, cleanup() {} } + + const controller = new AbortController() + const abort = () => controller.abort() + if (source.aborted) abort() + source.on("aborted", abort) + return { + signal: controller.signal, + cleanup() { + source.off("aborted", abort) + }, + } +} + +function webBody(source: Readable) { + // Node and DOM declare separate ReadableStream types despite compatible runtime objects. + // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion + return Readable.toWeb(source) as unknown as ReadableStream +} + +function pluginRequest(request: HttpServerRequest.HttpServerRequest) { + const abort = requestAbort(request.source) + const body = + request.method === "GET" || request.method === "HEAD" + ? undefined + : request.source instanceof Request + ? (request.source.body ?? undefined) + : request.source instanceof Readable + ? webBody(request.source) + : undefined + + return { + request: new Request(pluginURL(request), { + method: request.method, + headers: request.headers, + body, + signal: abort.signal, + duplex: body ? "half" : undefined, + } as RequestInit & { duplex?: "half" }), + cleanup: abort.cleanup, + } +} + +export const pluginRoutes = HttpRouter.use((router) => + Effect.gen(function* () { + const plugin = yield* Plugin.Service + const serve = (request: HttpServerRequest.HttpServerRequest) => + Effect.gen(function* () { + const route = yield* HttpRouter.RouteContext + const id = route.params.pluginID + if (!id) return HttpServerResponse.empty({ status: 404 }) + const http = yield* plugin.http(id) + if (!http) return HttpServerResponse.empty({ status: 404 }) + const input = pluginRequest(request) + yield* Effect.addFinalizer(() => Effect.sync(input.cleanup)) + const response = yield* Effect.promise(async () => { + const result = await http.fetch(input.request) + if (!(result instanceof Response)) throw new TypeError(`Plugin ${id} returned a non-Response`) + return result + }) + return HttpServerResponse.fromWeb(response) + }) + + yield* router.add("*", "/api/plugins/:pluginID/*", serve) + }), +) diff --git a/packages/opencode/src/server/routes/instance/httpapi/server.ts b/packages/opencode/src/server/routes/instance/httpapi/server.ts index fb9d2db65621..3b23081540d1 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/server.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/server.ts @@ -106,8 +106,9 @@ import { sessionLocationLayer } from "@opencode-ai/server/middleware/session-loc import { PtyEnvironment } from "@opencode-ai/server/pty-environment" import { schemaErrorLayer as v2SchemaErrorLayer } from "@opencode-ai/server/middleware/schema-error" import { workspaceHandlers } from "./handlers/workspace" -import { instanceContextLayer } from "./middleware/instance-context" -import { workspaceRoutingLayer } from "./middleware/workspace-routing" +import { instanceContextLayer, provideInstanceContext } from "./middleware/instance-context" +import { routeHttpApiWorkspace, workspaceRoutingLayer } from "./middleware/workspace-routing" +import { pluginRoutes } from "./plugin" import { disposeMiddleware } from "./lifecycle" import { memoMap } from "@opencode-ai/core/effect/memo-map" import { compressionLayer } from "./middleware/compression" @@ -138,6 +139,25 @@ const httpApiAuthLayer = authorizationLayer.pipe(Layer.provide(ServerAuth.Config const ptyConnectHttpApiAuthLayer = ptyConnectAuthorizationLayer.pipe(Layer.provide(ServerAuth.Config.layer)) const serverHttpApiAuthLayer = serverAuthorizationLayer.pipe(Layer.provide(ServerAuth.Config.layer)) const workspaceRoutingLive = workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)) +const pluginContextRouterLayer = HttpRouter.middleware()( + Effect.gen(function* () { + const store = yield* InstanceStore.Service + const makeWebSocket = yield* Socket.WebSocketConstructor + const workspace = yield* Workspace.Service + const session = yield* Session.Service + const client = yield* HttpClient.HttpClient + return (effect) => + routeHttpApiWorkspace(client, provideInstanceContext(effect, store, workspace)).pipe( + Effect.provideService(Socket.WebSocketConstructor, makeWebSocket), + Effect.provideService(Workspace.Service, workspace), + Effect.provideService(Session.Service, session), + ) + }), +) +const pluginHttpMiddlewareLive = pluginContextRouterLayer + .combine(authorizationRouterMiddleware) + .layer.pipe(Layer.provide([ServerAuth.Config.layer, Socket.layerWebSocketConstructorGlobal])) +const pluginHttpRoutes = pluginRoutes.pipe(Layer.provide(pluginHttpMiddlewareLive)) const rootApiRoutes = HttpApiBuilder.layer(RootHttpApi).pipe( Layer.provide([controlHandlers, controlPlaneHandlers, globalHandlers]), Layer.provide(schemaErrorLayer), @@ -279,6 +299,7 @@ export function createRoutes( ptyConnectApiRoutes, instanceRoutes, serverRoutes, + pluginHttpRoutes, docRoute, uiRoute, ).pipe( diff --git a/packages/opencode/test/cli/run/run-process.test.ts b/packages/opencode/test/cli/run/run-process.test.ts index d2d4bae87921..6a2ff0058874 100644 --- a/packages/opencode/test/cli/run/run-process.test.ts +++ b/packages/opencode/test/cli/run/run-process.test.ts @@ -65,20 +65,20 @@ describe("opencode run (non-interactive subprocess)", () => { // Regression for #27371: an unknown model used to hang the process forever // waiting on a session.status === idle event that never arrived. The fix // makes the SDK call surface an error promptly so the process exits nonzero. - // We assert nonzero exit AND wall-clock under the harness timeout — a hang - // would expire the timeout and produce a different (signal-killed) failure. + // A real CLI error exits with a positive code. The harness returns -1 when + // its timeout kills a hung process, so a wall-clock assertion is unnecessary + // and can fail when CI is busy after the child has already exited. cliIt.concurrent( "exits nonzero promptly when the model is unknown (regression for #27371)", ({ opencode }) => Effect.gen(function* () { const result = yield* opencode.run("say hi", { model: "test/nonexistent-model", - timeoutMs: 15_000, + timeoutMs: 30_000, }) - expect(result.exitCode).not.toBe(0) - expect(result.durationMs).toBeLessThan(15_000) + expect(result.exitCode).toBeGreaterThan(0) }), - 30_000, + 45_000, ) // The test provider's SSE error item is interpreted by the SDK as an unknown diff --git a/packages/opencode/test/control-plane/workspace.test.ts b/packages/opencode/test/control-plane/workspace.test.ts index 6d90eee2ae57..5eb68574959e 100644 --- a/packages/opencode/test/control-plane/workspace.test.ts +++ b/packages/opencode/test/control-plane/workspace.test.ts @@ -1278,6 +1278,257 @@ describe("workspace sync state", () => { }) }) + it.live("concurrent starts keep the first listener while target resolution is pending", () => { + let connections = 0 + return Effect.gen(function* () { + yield* HttpServer.serveEffect()( + Effect.gen(function* () { + const req = yield* HttpServerRequest.HttpServerRequest + const pathname = new URL(req.url, "http://localhost").pathname + if (pathname === "/concurrent/global/event") { + connections += 1 + return HttpServerResponse.fromWeb(eventStreamResponse()) + } + if (pathname === "/concurrent/sync/history") return HttpServerResponse.fromWeb(Response.json([])) + return HttpServerResponse.text("unexpected", { status: 500 }) + }), + ) + const url = yield* serverUrl() + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const workspace = yield* Workspace.Service + const instance = yield* requireInstance + const type = unique("remote-concurrent-start") + const info = workspaceInfo(instance.project.id, type) + let calls = 0 + let releaseFirst = () => {} + let rejectSecond = () => {} + yield* insertWorkspace(info) + registerAdapter( + instance.project.id, + type, + recordedAdapter({ + target() { + calls += 1 + const target: Target = { type: "remote", url: `${url}/concurrent` } + if (calls === 1) + return new Promise((resolve) => { + releaseFirst = () => resolve(target) + }) + if (calls === 2) + return new Promise((_, reject) => { + rejectSecond = () => reject(new Error("late target failure")) + }) + return target + }, + }).adapter, + ) + + yield* workspace.startWorkspaceSyncing(instance.project.id) + yield* workspace.startWorkspaceSyncing(instance.project.id) + yield* eventuallyEffect(Effect.sync(() => expect(calls).toBe(2))) + releaseFirst() + yield* eventuallyEffect( + Effect.gen(function* () { + expect(calls).toBe(3) + expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe( + "connected", + ) + }), + ) + rejectSecond() + yield* Effect.sleep("50 millis") + expect(calls).toBe(3) + expect(connections).toBe(1) + expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe("connected") + expect(yield* workspace.isSyncing(info.id)).toBe(true) + yield* workspace.remove(info.id) + }), + { git: true }, + ) + }) + }) + + it.live("remote event stream failure reconnects and replays history", () => { + let stream: ReadableStreamDefaultController | undefined + let connections = 0 + let histories = 0 + return Effect.gen(function* () { + yield* HttpServer.serveEffect()( + Effect.gen(function* () { + const req = yield* HttpServerRequest.HttpServerRequest + const url = new URL(req.url, "http://localhost") + if (url.pathname === "/reconnect/global/event") { + connections += 1 + if (connections > 1) return HttpServerResponse.fromWeb(eventStreamResponse()) + return HttpServerResponse.fromWeb( + new Response( + new ReadableStream({ + start(controller) { + stream = controller + controller.enqueue(new TextEncoder().encode(":\n\n")) + }, + }), + { status: 200, headers: { "content-type": "text/event-stream" } }, + ), + ) + } + if (url.pathname === "/reconnect/sync/history") { + histories += 1 + return HttpServerResponse.fromWeb(Response.json([])) + } + return HttpServerResponse.text("unexpected", { status: 500 }) + }), + ) + const url = yield* serverUrl() + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const workspace = yield* Workspace.Service + const sessionSvc = yield* SessionNs.Service + const instance = yield* requireInstance + const type = unique("remote-reconnect") + const info = workspaceInfo(instance.project.id, type) + yield* insertWorkspace(info) + registerAdapter(instance.project.id, type, remoteAdapter(`${url}/reconnect`).adapter) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + + yield* workspace.startWorkspaceSyncing(instance.project.id) + yield* eventuallyEffect( + Effect.gen(function* () { + expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe( + "connected", + ) + expect(histories).toBe(1) + }), + ) + + expect(stream).toBeDefined() + stream?.error(new Error("remote proxy restarted")) + + yield* eventuallyEffect( + Effect.gen(function* () { + expect(connections).toBe(2) + expect(histories).toBe(2) + expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe( + "connected", + ) + }), + 4000, + ) + expect(yield* workspace.isSyncing(info.id)).toBe(true) + yield* workspace.remove(info.id) + }), + { git: true }, + ) + }) + }) + + it.live("remote target failure retries until the proxy is available", () => { + let attempts = 0 + let histories = 0 + return Effect.gen(function* () { + yield* HttpServer.serveEffect()( + Effect.gen(function* () { + const req = yield* HttpServerRequest.HttpServerRequest + const url = new URL(req.url, "http://localhost") + if (url.pathname === "/target-recovery/global/event") + return HttpServerResponse.fromWeb(eventStreamResponse()) + if (url.pathname === "/target-recovery/sync/history") { + histories += 1 + return HttpServerResponse.fromWeb(Response.json([])) + } + return HttpServerResponse.text("unexpected", { status: 500 }) + }), + ) + const url = yield* serverUrl() + yield* provideTmpdirInstance( + () => + Effect.gen(function* () { + const workspace = yield* Workspace.Service + const sessionSvc = yield* SessionNs.Service + const instance = yield* requireInstance + const type = unique("remote-target-recovery") + const info = workspaceInfo(instance.project.id, type) + yield* insertWorkspace(info) + registerAdapter( + instance.project.id, + type, + recordedAdapter({ + target() { + attempts += 1 + if (attempts < 3) throw new Error("proxy unavailable") + return { type: "remote", url: `${url}/target-recovery` } + }, + }).adapter, + ) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + + yield* workspace.startWorkspaceSyncing(instance.project.id) + yield* eventuallyEffect( + Effect.gen(function* () { + expect(attempts).toBeGreaterThanOrEqual(3) + expect(histories).toBe(1) + expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe( + "connected", + ) + }), + 4000, + ) + expect(yield* workspace.isSyncing(info.id)).toBe(true) + yield* workspace.remove(info.id) + }), + { git: true }, + ) + }) + }) + + it.live("repeated start keeps retry backoff and removal cancels retries", () => + provideTmpdirInstance( + () => + Effect.gen(function* () { + const workspace = yield* Workspace.Service + const sessionSvc = yield* SessionNs.Service + const instance = yield* requireInstance + const type = unique("remote-retry-stop") + const info = workspaceInfo(instance.project.id, type) + let attempts = 0 + yield* insertWorkspace(info) + registerAdapter( + instance.project.id, + type, + recordedAdapter({ + target() { + attempts += 1 + throw new Error("proxy unavailable") + }, + }).adapter, + ) + yield* attachSessionToWorkspace((yield* sessionSvc.create({})).id, info.id) + + yield* workspace.startWorkspaceSyncing(instance.project.id) + yield* eventuallyEffect( + Effect.gen(function* () { + expect(attempts).toBe(2) + expect((yield* workspace.status()).find((item) => item.workspaceID === info.id)?.status).toBe("error") + }), + ) + + yield* workspace.startWorkspaceSyncing(instance.project.id) + yield* Effect.sleep("100 millis") + expect(attempts).toBe(2) + + yield* workspace.remove(info.id) + expect(yield* workspace.isSyncing(info.id)).toBe(false) + const stoppedAt = attempts + yield* Effect.sleep("1200 millis") + expect(attempts).toBe(stoppedAt) + }), + { git: true }, + ), + ) + it.live("remote connection HTTP failures set error and clear syncing", () => Effect.gen(function* () { yield* HttpServer.serveEffect()( diff --git a/packages/opencode/test/lib/cli-process.ts b/packages/opencode/test/lib/cli-process.ts index a4d3b36c1dae..3dd14631ea62 100644 --- a/packages/opencode/test/lib/cli-process.ts +++ b/packages/opencode/test/lib/cli-process.ts @@ -63,6 +63,8 @@ function isolatedEnv(home: string, configJson: string): Record { return { OPENCODE_TEST_HOME: home, HOME: home, + // `opencode run` selects its project from PWD even when the child has cwd=home. + PWD: home, XDG_CONFIG_HOME: path.join(home, ".config"), XDG_DATA_HOME: path.join(home, ".local/share"), XDG_STATE_HOME: path.join(home, ".local/state"), diff --git a/packages/opencode/test/plugin/loader-shared.test.ts b/packages/opencode/test/plugin/loader-shared.test.ts index 005a6e78cb55..36eb2973b6fa 100644 --- a/packages/opencode/test/plugin/loader-shared.test.ts +++ b/packages/opencode/test/plugin/loader-shared.test.ts @@ -36,7 +36,7 @@ function withTmp( }) } -function load(dir: string, flags?: Parameters[0]) { +function load(dir: string, flags?: Parameters[0], httpID?: string) { const source = path.join(dir, "opencode.json") return Effect.gen(function* () { const config = yield* Effect.promise( @@ -46,6 +46,8 @@ function load(dir: string, flags?: Parameters[0]) { return yield* Effect.gen(function* () { const plugin = yield* Plugin.Service yield* plugin.list() + if (!httpID) return undefined + return yield* plugin.http(httpID) }).pipe( Effect.provide( LayerNode.compile(Plugin.node, [ @@ -173,6 +175,55 @@ describe("plugin.loader.shared", () => { ), ) + it.live("rejects duplicate v1 plugin ids before initializing the duplicate", () => + withTmp( + async (dir) => { + const first = path.join(dir, "first.ts") + const second = path.join(dir, "second.ts") + const firstMark = path.join(dir, "first.txt") + const secondMark = path.join(dir, "second.txt") + await Bun.write( + first, + [ + "export default {", + ' id: "demo.duplicate",', + " server: async () => {", + ` await Bun.write(${JSON.stringify(firstMark)}, "first")`, + ' return { http: { fetch: async () => new Response("first") } }', + " },", + "}", + "", + ].join("\n"), + ) + await Bun.write( + second, + [ + "export default {", + ' id: "demo.duplicate",', + " server: async () => {", + ` await Bun.write(${JSON.stringify(secondMark)}, "second")`, + " return {}", + " },", + "}", + "", + ].join("\n"), + ) + await Bun.write( + path.join(dir, "opencode.json"), + JSON.stringify({ plugin: [pathToFileURL(first).href, pathToFileURL(second).href] }, null, 2), + ) + return { firstMark, secondMark } + }, + (tmp) => + Effect.gen(function* () { + const http = yield* load(tmp.path, undefined, "demo.duplicate") + expect(yield* Effect.promise(() => Bun.file(tmp.extra.firstMark).text())).toBe("first") + expect(yield* Effect.promise(() => Bun.file(tmp.extra.secondMark).exists())).toBe(false) + expect(http).toBeUndefined() + }), + ), + ) + it.live("rejects v1 file server plugin without id", () => withTmp( async (dir) => { diff --git a/packages/opencode/test/project/project.test.ts b/packages/opencode/test/project/project.test.ts index 804b92b08ec4..be3fecd5a8a0 100644 --- a/packages/opencode/test/project/project.test.ts +++ b/packages/opencode/test/project/project.test.ts @@ -5,7 +5,7 @@ import path from "path" import { tmpdirScoped } from "../fixture/fixture" import { GlobalBus } from "../../src/bus/global" import { Database } from "@opencode-ai/core/database/database" -import { ProjectTable } from "@opencode-ai/core/project/sql" +import { ProjectAssociationTable, ProjectTable } from "@opencode-ai/core/project/sql" import { SessionTable } from "@opencode-ai/core/session/sql" import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" import { eq } from "drizzle-orm" @@ -15,6 +15,7 @@ import { WorkspaceV2 } from "@opencode-ai/core/workspace" import { Cause, Effect, Exit, Layer, Stream } from "effect" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" import { ProjectV2 } from "@opencode-ai/core/project" +import { AbsolutePath } from "@opencode-ai/core/schema" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { testEffect } from "../lib/effect" import { RuntimeFlags } from "@/effect/runtime-flags" @@ -83,6 +84,8 @@ function projectV2FailureLayer() { directory: input, vcs: { type: "git" as const, store: input }, }), + associate: () => Effect.succeed([]), + dissociate: () => Effect.succeed([]), commit: () => Effect.void, }), ) @@ -148,6 +151,50 @@ describe("Project.fromDirectory", () => { }), ) + it.live("keeps the owning Git project intact when opening an associated workspace", () => + Effect.gen(function* () { + const { db } = yield* Database.Service + const projects = yield* Project.Service + const checkout = yield* tmpdirScoped({ git: true }) + const workspace = yield* tmpdirScoped() + const owner = (yield* projects.fromDirectory(checkout)).project + const global = (yield* projects.fromDirectory(workspace)).project + const sessionID = crypto.randomUUID() as SessionID + + yield* db + .insert(SessionTable) + .values({ + id: sessionID, + project_id: global.id, + slug: sessionID, + directory: workspace, + title: "before association", + version: "0.0.0-test", + time_created: Date.now(), + time_updated: Date.now(), + }) + .run() + .pipe(Effect.orDie) + yield* db + .insert(ProjectAssociationTable) + .values({ project_id: owner.id, directory: AbsolutePath.make(workspace) }) + .run() + .pipe(Effect.orDie) + + const opened = (yield* projects.fromDirectory(workspace)).project + const stored = yield* projects.get(owner.id) + const session = yield* db.select().from(SessionTable).where(eq(SessionTable.id, sessionID)).get().pipe(Effect.orDie) + + expect(opened.id).toBe(owner.id) + expect(opened.worktree).toBe(checkout) + expect(opened.vcs).toBe("git") + expect(opened.sandboxes).not.toContain(workspace) + expect(stored?.worktree).toBe(checkout) + expect(stored?.vcs).toBe("git") + expect(session?.project_id).toBe(owner.id) + }), + ) + it.live("derives stable project ID from root commit", () => Effect.gen(function* () { const project = yield* Project.Service @@ -196,6 +243,13 @@ describe("Project.fromDirectory", () => { const remoteID = remoteProjectID("github.com/acme/app") const sessionID = crypto.randomUUID() as SessionID const workspaceID = WorkspaceV2.ID.ascending() + const associatedDirectory = AbsolutePath.make(yield* tmpdirScoped()) + + yield* db + .insert(ProjectAssociationTable) + .values({ project_id: rootProject.id, directory: associatedDirectory }) + .run() + .pipe(Effect.orDie) yield* db .insert(SessionTable) @@ -232,6 +286,15 @@ describe("Project.fromDirectory", () => { (yield* db.select().from(WorkspaceTable).where(eq(WorkspaceTable.id, workspaceID)).get().pipe(Effect.orDie)) ?.project_id, ).toBe(remoteID) + expect( + (yield* db + .select() + .from(ProjectAssociationTable) + .where(eq(ProjectAssociationTable.directory, associatedDirectory)) + .get() + .pipe(Effect.orDie))?.project_id, + ).toBe(remoteID) + expect((yield* projects.fromDirectory(associatedDirectory)).project.id).toBe(remoteID) }), ) }) diff --git a/packages/opencode/test/server/httpapi-exercise/index.ts b/packages/opencode/test/server/httpapi-exercise/index.ts index c8e11ea8451b..5d250a63ba79 100644 --- a/packages/opencode/test/server/httpapi-exercise/index.ts +++ b/packages/opencode/test/server/httpapi-exercise/index.ts @@ -222,6 +222,31 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), })) .json(200, array, "status"), + http.protected + .post("/project/{projectID}/directories", "project.directoryCreate") + .mutating() + .seeded((ctx) => ctx.project()) + .at((ctx) => ({ + path: route("/project/{projectID}/directories", { projectID: ctx.state.id }), + headers: ctx.headers(), + body: { directory: exerciseGlobalRoot }, + })) + .json(200, (body) => { + array(body) + check( + body.some((item) => isRecord(item) && item.directory === exerciseGlobalRoot), + "directory create should list the new association", + ) + }), + http.protected + .delete("/project/{projectID}/directories", "project.directoryRemove") + .mutating() + .seeded((ctx) => ctx.project()) + .at((ctx) => ({ + path: `${route("/project/{projectID}/directories", { projectID: ctx.state.id })}?directory=${encodeURIComponent(exerciseGlobalRoot)}`, + headers: ctx.headers(), + })) + .json(200, array), http.protected .post("/experimental/project/{projectID}/copy/generate-name", "experimental.projectCopy.generateName") .seeded((ctx) => ctx.project()) diff --git a/packages/opencode/test/server/httpapi-instance-context.test.ts b/packages/opencode/test/server/httpapi-instance-context.test.ts index 845324b34aab..596116c84399 100644 --- a/packages/opencode/test/server/httpapi-instance-context.test.ts +++ b/packages/opencode/test/server/httpapi-instance-context.test.ts @@ -8,6 +8,8 @@ import { mkdir } from "node:fs/promises" import path from "node:path" import { registerAdapter } from "../../src/control-plane/adapters" import { WorkspaceV2 } from "@opencode-ai/core/workspace" +import { WorkspaceTable } from "@opencode-ai/core/control-plane/workspace.sql" +import { Database } from "@opencode-ai/core/database/database" import type { WorkspaceAdapter } from "../../src/control-plane/types" import { Workspace } from "../../src/control-plane/workspace" import { InstanceRef, WorkspaceRef } from "../../src/effect/instance-ref" @@ -143,6 +145,46 @@ const serveDisposeProbe = () => ) describe("HttpApi instance context middleware", () => { + it.live("resumes a persisted workspace after loading its project", () => + Effect.gen(function* () { + const dir = yield* tmpdirScoped({ git: true }) + const project = yield* Project.use.fromDirectory(dir) + const workspaceDir = path.join(dir, ".workspace-recovered") + const id = WorkspaceV2.ID.ascending() + yield* Effect.promise(() => mkdir(workspaceDir, { recursive: true })) + registerAdapter(project.project.id, "instance-context-recovered", localAdapter(workspaceDir)) + yield* Database.Service.use(({ db }) => + db + .insert(WorkspaceTable) + .values({ + id, + type: "instance-context-recovered", + branch: null, + name: "persisted", + directory: workspaceDir, + extra: null, + project_id: project.project.id, + time_used: Date.now(), + }) + .run(), + ) + yield* serveProbe() + const connected = yield* waitGlobalBusEvent({ + message: "persisted workspace did not reconnect", + predicate: (event) => + event.workspace === id && + event.payload.type === Workspace.Event.Status.type && + event.payload.properties.status === "connected", + }).pipe(Effect.forkScoped({ startImmediately: true })) + + const response = yield* HttpClient.get(`/probe?directory=${encodeURIComponent(dir)}`) + + expect(response.status).toBe(200) + yield* Fiber.join(connected) + expect((yield* Workspace.use.status()).find((item) => item.workspaceID === id)?.status).toBe("connected") + }), + ) + it.live("provides instance context from the routed directory", () => Effect.gen(function* () { const dir = yield* tmpdirScoped({ git: true }) diff --git a/packages/opencode/test/server/httpapi-instance-route-auth.test.ts b/packages/opencode/test/server/httpapi-instance-route-auth.test.ts index 9933a28bdc8e..cab436b0f4d2 100644 --- a/packages/opencode/test/server/httpapi-instance-route-auth.test.ts +++ b/packages/opencode/test/server/httpapi-instance-route-auth.test.ts @@ -8,6 +8,9 @@ import { ServerAuth } from "../../src/server/auth" import { PtyID } from "@opencode-ai/core/pty/schema" import { resetDatabase } from "../fixture/db" import { disposeAllInstances, tmpdir } from "../fixture/fixture" +import { markPluginDependenciesReady } from "../fixture/plugin" +import { mkdir } from "fs/promises" +import path from "path" function app(input: { password?: string; username?: string }) { const handler = HttpRouter.toWebHandler( @@ -40,6 +43,33 @@ async function cancelBody(response: Response) { await response.body?.cancel().catch(() => {}) } +async function writeHttpPlugin(directory: string) { + const serverMarker = path.join(directory, "plugin-server-ran") + const fetchMarker = path.join(directory, "plugin-fetch-ran") + await markPluginDependenciesReady(path.join(directory, ".opencode")) + await mkdir(path.join(directory, ".opencode", "plugin"), { recursive: true }) + await Bun.write( + path.join(directory, ".opencode", "plugin", "http.ts"), + [ + "export default {", + ' id: "auth-test",', + " server: async () => {", + ` await Bun.write(${JSON.stringify(serverMarker)}, "ran")`, + " return {", + " http: {", + " fetch: async () => {", + ` await Bun.write(${JSON.stringify(fetchMarker)}, "ran")`, + " return Response.json({ ok: true })", + " },", + " },", + " }", + " },", + "}", + "", + ].join("\n"), + ) +} + afterEach(async () => { await disposeAllInstances() await resetDatabase() @@ -78,4 +108,30 @@ describe("HttpApi instance route authorization", () => { await cancelBody(authed) expect(authed.status).toBe(404) }) + + test("requires configured auth before dispatching plugin routes", async () => { + await using tmp = await tmpdir({ + git: true, + config: { formatter: false, lsp: false }, + init: writeHttpPlugin, + }) + const server = app({ password: "secret" }) + const route = "/api/plugins/auth-test" + const headers = { "x-opencode-directory": tmp.path } + const serverMarker = path.join(tmp.path, "plugin-server-ran") + const fetchMarker = path.join(tmp.path, "plugin-fetch-ran") + + const missing = await server.request(route, { headers }) + expect(missing.status).toBe(401) + expect(await Bun.file(serverMarker).exists()).toBe(false) + expect(await Bun.file(fetchMarker).exists()).toBe(false) + + const authed = await server.request(route, { + headers: { ...headers, authorization: basic("opencode", "secret") }, + }) + expect(authed.status).toBe(200) + expect(await authed.json()).toEqual({ ok: true }) + expect(await Bun.file(serverMarker).exists()).toBe(true) + expect(await Bun.file(fetchMarker).exists()).toBe(true) + }) }) diff --git a/packages/opencode/test/server/httpapi-listen.test.ts b/packages/opencode/test/server/httpapi-listen.test.ts index 585c59cb4317..97fb03a61dc3 100644 --- a/packages/opencode/test/server/httpapi-listen.test.ts +++ b/packages/opencode/test/server/httpapi-listen.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test" +import Http from "node:http" import net from "node:net" import path from "node:path" import { pathToFileURL } from "node:url" @@ -353,6 +354,229 @@ describe("HttpApi Server.listen", () => { } }) + test("dispatches authenticated plugin HTTP requests in instance context", async () => { + await using tmp = await tmpdir({ + init: async (directory) => { + const plugin = path.join(directory, "plugin.ts") + await Bun.write( + plugin, + [ + "export default {", + ' id: "http-probe",', + " server: async (input) => ({", + " http: {", + " fetch: async (request) => new Response(JSON.stringify({", + " directory: input.directory,", + " method: request.method,", + " url: request.url,", + ' header: request.headers.get("x-probe"),', + " body: await request.text(),", + " aborted: request.signal.aborted,", + " }), {", + " status: 202,", + ' headers: { "content-type": "application/json", "x-plugin": "http-probe" },', + " }),", + " },", + " }),", + "}", + "", + ].join("\n"), + ) + await Bun.write( + path.join(directory, "opencode.json"), + JSON.stringify({ formatter: false, lsp: false, plugin: [pathToFileURL(plugin).href] }), + ) + }, + }) + const listener = await startListener() + try { + const path = `/api/plugins/http-probe/echo/nested?directory=${encodeURIComponent(tmp.path)}&value=kept` + const unauthorized = await fetch(new URL(path, listener.url), { method: "POST", body: "blocked" }) + expect(unauthorized.status).toBe(401) + + const missing = await fetch( + new URL(`/api/plugins/missing?directory=${encodeURIComponent(tmp.path)}`, listener.url), + { + headers: { authorization: authorization() }, + }, + ) + expect(missing.status).toBe(404) + + const base = await fetch( + new URL(`/api/plugins/http-probe?directory=${encodeURIComponent(tmp.path)}`, listener.url), + { headers: { authorization: authorization() } }, + ) + expect(base.status).toBe(202) + expect(await base.json()).toMatchObject({ + directory: tmp.path, + method: "GET", + url: `http://${listener.hostname}:${listener.port}/?directory=${encodeURIComponent(tmp.path)}`, + }) + + const response = await fetch(new URL(path, listener.url), { + method: "POST", + headers: { + authorization: authorization(), + "content-type": "text/plain", + "x-probe": "preserved", + }, + body: "streamed request", + }) + + expect(response.status).toBe(202) + expect(response.headers.get("x-plugin")).toBe("http-probe") + expect(await response.json()).toEqual({ + directory: tmp.path, + method: "POST", + url: `http://${listener.hostname}:${listener.port}/echo/nested?directory=${encodeURIComponent(tmp.path)}&value=kept`, + header: "preserved", + body: "streamed request", + aborted: false, + }) + } finally { + await stop(listener, "timed out cleaning up plugin HTTP listener").catch(() => undefined) + } + }) + + test("streams plugin request bodies before the client finishes sending", async () => { + await using tmp = await tmpdir({ + init: async (directory) => { + const plugin = path.join(directory, "plugin.ts") + const firstChunk = path.join(directory, "first-chunk") + await Bun.write( + plugin, + [ + "export default {", + ' id: "stream-probe",', + " server: async () => ({", + " http: {", + " fetch: async (request) => {", + " const reader = request.body.getReader()", + " const decoder = new TextDecoder()", + " const first = await reader.read()", + ` await Bun.write(${JSON.stringify(firstChunk)}, decoder.decode(first.value))`, + " let body = decoder.decode(first.value)", + " while (true) {", + " const next = await reader.read()", + " if (next.done) break", + " body += decoder.decode(next.value)", + " }", + " return Response.json({ body })", + " },", + " },", + " }),", + "}", + "", + ].join("\n"), + ) + await Bun.write( + path.join(directory, "opencode.json"), + JSON.stringify({ formatter: false, lsp: false, plugin: [pathToFileURL(plugin).href] }), + ) + return { firstChunk } + }, + }) + const listener = await startListener() + try { + const response = new Promise<{ status: number; body: string }>((resolve, reject) => { + const request = Http.request(new URL("/api/plugins/stream-probe", listener.url), { + method: "POST", + headers: { + authorization: authorization(), + "content-type": "text/plain", + "x-opencode-directory": tmp.path, + }, + }) + request.on("error", reject) + request.on("response", (incoming) => { + let body = "" + incoming.setEncoding("utf8") + incoming.on("data", (chunk) => (body += chunk)) + incoming.on("end", () => resolve({ status: incoming.statusCode ?? 0, body })) + }) + request.write("first") + + void withTimeout( + (async () => { + while (!(await Bun.file(tmp.extra.firstChunk).exists())) await Bun.sleep(10) + })(), + 5_000, + "plugin did not receive the first request chunk", + ).then(() => request.end("second"), reject) + }) + + const result = await withTimeout(response, 10_000, "plugin request stream did not complete") + expect(result.status).toBe(200) + expect(JSON.parse(result.body)).toEqual({ body: "firstsecond" }) + expect(await Bun.file(tmp.extra.firstChunk).text()).toBe("first") + } finally { + await stop(listener, "timed out cleaning up request streaming listener").catch(() => undefined) + } + }, 30_000) + + test("aborts plugin requests when the client disconnects", async () => { + await using tmp = await tmpdir({ + init: async (directory) => { + const plugin = path.join(directory, "plugin.ts") + const started = path.join(directory, "request-started") + const aborted = path.join(directory, "request-aborted") + await Bun.write( + plugin, + [ + "export default {", + ' id: "abort-probe",', + " server: async () => ({", + " http: {", + " fetch: async (request) => {", + ` await Bun.write(${JSON.stringify(started)}, "started")`, + " await new Promise((resolve) => {", + " if (request.signal.aborted) return resolve()", + ' request.signal.addEventListener("abort", resolve, { once: true })', + " })", + ` await Bun.write(${JSON.stringify(aborted)}, "aborted")`, + ' return new Response("aborted")', + " },", + " },", + " }),", + "}", + "", + ].join("\n"), + ) + await Bun.write( + path.join(directory, "opencode.json"), + JSON.stringify({ formatter: false, lsp: false, plugin: [pathToFileURL(plugin).href] }), + ) + return { started, aborted } + }, + }) + const listener = await startListener() + try { + const request = Http.request(new URL("/api/plugins/abort-probe", listener.url), { + headers: { authorization: authorization(), "x-opencode-directory": tmp.path }, + }) + request.on("error", () => {}) + request.end() + + await withTimeout( + (async () => { + while (!(await Bun.file(tmp.extra.started).exists())) await Bun.sleep(10) + })(), + 5_000, + "plugin request did not start", + ) + request.destroy() + await withTimeout( + (async () => { + while (!(await Bun.file(tmp.extra.aborted).exists())) await Bun.sleep(10) + })(), + 5_000, + "plugin request signal did not abort", + ) + } finally { + await stop(listener, "timed out cleaning up abort listener").catch(() => undefined) + } + }, 30_000) + test("port 0 prefers 4096 when free", async () => { if (!(await isPortFree(4096))) return const listener = await startListener() diff --git a/packages/opencode/test/server/httpapi-plugin.test.ts b/packages/opencode/test/server/httpapi-plugin.test.ts new file mode 100644 index 000000000000..f642334f556d --- /dev/null +++ b/packages/opencode/test/server/httpapi-plugin.test.ts @@ -0,0 +1,276 @@ +import { describe, expect } from "bun:test" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Effect, Layer, Option, Stream } from "effect" +import path from "path" +import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" +import { resetDatabase } from "../fixture/db" +import { disposeAllInstances, TestInstance, tmpdirScoped } from "../fixture/fixture" +import { markPluginDependenciesReady } from "../fixture/plugin" +import { testEffect } from "../lib/effect" +import { httpApiLayer, requestInDirectory } from "./httpapi-layer" + +const pluginID = "test-http-plugin" +const projectOptions = { git: true, config: { formatter: false, lsp: false } } + +const testStateLayer = Layer.effectDiscard( + Effect.acquireRelease( + Effect.promise(() => resetDatabase()), + () => Effect.promise(() => resetDatabase()), + ), +) + +const it = testEffect(Layer.mergeAll(testStateLayer, LayerNode.compile(FSUtil.node), httpApiLayer)) + +function pluginSource(id: string, marker: string, http = true, disposeMarker?: string) { + return [ + ...(disposeMarker ? ['import { writeFileSync } from "fs"', ""] : []), + "export default {", + ` id: ${JSON.stringify(id)},`, + " server: async () => ({", + ...(http + ? [ + " http: {", + " fetch: async (request) => {", + " const url = new URL(request.url)", + ' if (url.pathname === "/error") throw new Error("plugin failed")', + ' if (url.pathname === "/non-response") return { nope: true }', + ' if (url.pathname === "/stream") {', + " return new Response(new ReadableStream({", + " start(controller) {", + ' controller.enqueue(new TextEncoder().encode("first"))', + " },", + " }), { headers: { 'content-type': 'text/plain' } })", + " }", + ' if (url.pathname === "/metadata") {', + " const headers = new Headers()", + " headers.append('set-cookie', 'one=1; Path=/')", + " headers.append('set-cookie', 'two=2; Path=/')", + " return new Response('metadata', { status: 299, statusText: 'Plugin Status', headers })", + " }", + ' const body = request.method === "GET" || request.method === "HEAD" ? "" : await request.text()', + " return Response.json({", + ` marker: ${JSON.stringify(marker)},`, + " method: request.method,", + " path: url.pathname,", + " query: Array.from(url.searchParams.entries()),", + " header: request.headers.get('x-plugin-request'),", + " body,", + " }, { status: 201, headers: { 'x-plugin-response': 'preserved' } })", + " },", + " },", + ] + : []), + ...(disposeMarker + ? [` dispose: async () => { writeFileSync(${JSON.stringify(disposeMarker)}, "disposed") },`] + : []), + " }),", + "}", + "", + ].join("\n") +} + +function writePlugins( + files: Array<{ name: string; id: string; marker?: string; http?: boolean; disposeMarker?: string }>, +) { + return (directory: string) => + Effect.gen(function* () { + const fs = yield* FSUtil.Service + yield* Effect.promise(() => markPluginDependenciesReady(path.join(directory, ".opencode"))) + yield* Effect.forEach( + files, + (file) => + fs.writeWithDirs( + path.join(directory, ".opencode", "plugin", `${file.name}.ts`), + pluginSource( + file.id, + file.marker ?? file.name, + file.http, + file.disposeMarker ? path.join(directory, file.disposeMarker) : undefined, + ), + ), + { discard: true }, + ) + }) +} + +function pluginPath(id: string, suffix = "") { + return `/api/plugins/${encodeURIComponent(id)}${suffix}` +} + +function requestFromWebHandler(route: string, directory: string, init: RequestInit = {}) { + const headers = new Headers(init.headers) + headers.set("x-opencode-directory", directory) + return Effect.promise(() => + Promise.resolve( + HttpApiApp.webHandler().handler( + new Request(new URL(route, "http://localhost"), { ...init, headers }), + HttpApiApp.context, + ), + ), + ) +} + +describe("plugin HTTP routes", () => { + it.instance( + "rebases scoped plugin requests and preserves Fetch responses", + Effect.gen(function* () { + const directory = (yield* TestInstance).directory + const scopedID = "@scope/plugin" + + const root = yield* requestInDirectory(`${pluginPath(scopedID)}?value=one&value=two`, directory) + expect(root.status).toBe(201) + expect(root.headers["x-plugin-response"]).toBe("preserved") + expect(yield* root.json).toEqual({ + marker: "primary", + method: "GET", + path: "/", + query: [ + ["value", "one"], + ["value", "two"], + ], + header: null, + body: "", + }) + + const nested = yield* requestInDirectory( + `${pluginPath(scopedID, "/sessions/pty-1/output")}?after=12`, + directory, + { + method: "POST", + headers: { "content-type": "text/plain", "x-plugin-request": "preserved" }, + body: "request body", + }, + ) + expect(nested.status).toBe(201) + expect(yield* nested.json).toMatchObject({ + marker: "primary", + method: "POST", + path: "/sessions/pty-1/output", + query: [["after", "12"]], + header: "preserved", + body: "request body", + }) + }), + { ...projectOptions, init: writePlugins([{ name: "primary", id: "@scope/plugin", marker: "primary" }]) }, + 30000, + ) + + it.instance( + "returns streaming responses without buffering", + Effect.gen(function* () { + const directory = (yield* TestInstance).directory + const response = yield* requestInDirectory(pluginPath(pluginID, "/stream"), directory).pipe( + Effect.timeoutOrElse({ duration: "5 seconds", orElse: () => Effect.fail(new Error("response was buffered")) }), + ) + const first = yield* response.stream.pipe( + Stream.runHead, + Effect.timeoutOrElse({ duration: "5 seconds", orElse: () => Effect.fail(new Error("stream did not emit")) }), + ) + + expect(response.status).toBe(200) + expect(Option.map(first, (chunk) => new TextDecoder().decode(chunk))).toEqual(Option.some("first")) + }), + { ...projectOptions, init: writePlugins([{ name: "stream", id: pluginID }]) }, + 30000, + ) + + it.instance( + "preserves status text and repeated Set-Cookie headers", + Effect.gen(function* () { + const directory = (yield* TestInstance).directory + const response = yield* requestFromWebHandler(pluginPath(pluginID, "/metadata"), directory) + + expect(response.status).toBe(299) + expect(response.statusText).toBe("Plugin Status") + expect(response.headers.getSetCookie()).toEqual(["one=1; Path=/", "two=2; Path=/"]) + expect(yield* Effect.promise(() => response.text())).toBe("metadata") + }), + { ...projectOptions, init: writePlugins([{ name: "metadata", id: pluginID }]) }, + 30000, + ) + + it.instance( + "returns 404 for unavailable handlers and duplicate ids", + Effect.gen(function* () { + const directory = (yield* TestInstance).directory + const missing = yield* requestInDirectory(pluginPath("missing"), directory) + const withoutHttp = yield* requestInDirectory(pluginPath("without-http"), directory) + const duplicate = yield* requestInDirectory(pluginPath("duplicate"), directory) + + expect(missing.status).toBe(404) + expect(withoutHttp.status).toBe(404) + expect(duplicate.status).toBe(404) + }), + { + ...projectOptions, + init: writePlugins([ + { name: "without-http", id: "without-http", http: false }, + { name: "duplicate-a", id: "duplicate", marker: "one" }, + { name: "duplicate-b", id: "duplicate", marker: "two" }, + ]), + }, + 30000, + ) + + it.instance( + "maps plugin failures and invalid results through the server error boundary", + Effect.gen(function* () { + const directory = (yield* TestInstance).directory + const thrown = yield* requestInDirectory(pluginPath(pluginID, "/error"), directory) + const invalid = yield* requestInDirectory(pluginPath(pluginID, "/non-response"), directory) + + expect(thrown.status).toBe(500) + expect(invalid.status).toBe(500) + }), + { ...projectOptions, init: writePlugins([{ name: "error", id: pluginID }]) }, + 30000, + ) + + it.live( + "disposes plugin hooks and rebuilds the handler registry", + Effect.gen(function* () { + const directory = yield* tmpdirScoped({ + ...projectOptions, + init: writePlugins([{ name: "lifecycle", id: pluginID, disposeMarker: "plugin-disposed" }]), + }) + const fs = yield* FSUtil.Service + const marker = path.join(directory, "plugin-disposed") + + const initial = yield* requestFromWebHandler(pluginPath(pluginID), directory) + expect(initial.status).toBe(201) + expect(yield* fs.exists(marker)).toBe(false) + + yield* Effect.promise(() => disposeAllInstances()) + expect(yield* fs.exists(marker)).toBe(true) + + yield* fs.remove(path.join(directory, ".opencode", "plugin", "lifecycle.ts")) + const stale = yield* requestFromWebHandler(pluginPath(pluginID), directory) + expect(stale.status).toBe(404) + + yield* Effect.promise(() => disposeAllInstances()) + }), + 30000, + ) + + it.live( + "isolates handlers with the same id across directory instances", + Effect.gen(function* () { + const one = yield* tmpdirScoped({ + ...projectOptions, + init: writePlugins([{ name: "same", id: pluginID, marker: "one" }]), + }) + const two = yield* tmpdirScoped({ + ...projectOptions, + init: writePlugins([{ name: "same", id: pluginID, marker: "two" }]), + }) + + const first = yield* requestInDirectory(pluginPath(pluginID), one) + const second = yield* requestInDirectory(pluginPath(pluginID), two) + + expect(yield* first.json).toMatchObject({ marker: "one" }) + expect(yield* second.json).toMatchObject({ marker: "two" }) + }), + 30000, + ) +}) diff --git a/packages/opencode/test/server/httpapi-project-directory.test.ts b/packages/opencode/test/server/httpapi-project-directory.test.ts new file mode 100644 index 000000000000..939dd9bf7bd8 --- /dev/null +++ b/packages/opencode/test/server/httpapi-project-directory.test.ts @@ -0,0 +1,90 @@ +import { afterEach, expect, test } from "bun:test" +import fs from "fs/promises" +import path from "path" +import { HttpRouter } from "effect/unstable/http" +import { HttpApiApp } from "../../src/server/routes/instance/httpapi/server" +import { disposeMiddleware } from "../../src/server/routes/instance/httpapi/lifecycle" +import { resetDatabase } from "../fixture/db" +import { disposeAllInstances, tmpdir } from "../fixture/fixture" + +const handler = HttpRouter.toWebHandler(HttpApiApp.routes, { disableLogger: true, middleware: disposeMiddleware }).handler +const request = (url: string, init?: RequestInit) => + handler(new Request(new URL(url, "http://localhost"), init), HttpApiApp.context) +const route = (path: string, directory: string) => `${path}?directory=${encodeURIComponent(directory)}` + +async function projectAt(directory: string) { + const response = await request(route("/project/current", directory)) + expect(response.status).toBe(200) + return (await response.json()) as { id: string; worktree: string; vcs: string | null; sandboxes: string[] } +} + +afterEach(async () => { + await disposeAllInstances() + await resetDatabase() +}) + +test("associating a previously opened directory takes effect on the next request", async () => { + await using checkout = await tmpdir({ git: true, config: { formatter: false, lsp: false } }) + await using workspace = await tmpdir({ config: { formatter: false, lsp: false } }) + const owner = await projectAt(checkout.path) + expect((await projectAt(workspace.path)).id).toBe("global") + + // Routing to the target first boots its cached global instance. The association + // handler must dispose that instance after responding so the next request resolves again. + const create = await request(route(`/project/${owner.id}/directories`, workspace.path), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ directory: workspace.path, strategy: "manual" }), + }) + expect(create.status).toBe(200) + expect(await create.json()).toEqual(expect.arrayContaining([{ directory: workspace.path, strategy: "manual" }])) + + const associated = await projectAt(workspace.path) + expect(associated.id).toBe(owner.id) + expect(associated.worktree).toBe(checkout.path) + expect(associated.vcs).toBe("git") + expect(associated.sandboxes).not.toContain(workspace.path) + + const remove = await request(route(`/project/${owner.id}/directories`, workspace.path), { method: "DELETE" }) + expect(remove.status).toBe(200) + expect((await projectAt(workspace.path)).id).toBe("global") +}) + +test("association rejects an unknown project", async () => { + await using workspace = await tmpdir({ config: { formatter: false, lsp: false } }) + const response = await request(route("/project/missing/directories", workspace.path), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ directory: workspace.path }), + }) + expect(response.status).toBe(404) +}) + +test("association canonicalizes symlink paths and rejects relative paths", async () => { + await using checkout = await tmpdir({ git: true, config: { formatter: false, lsp: false } }) + await using workspace = await tmpdir({ config: { formatter: false, lsp: false } }) + await using aliases = await tmpdir({ config: { formatter: false, lsp: false } }) + const alias = path.join(aliases.path, "workspace-link") + await fs.symlink(workspace.path, alias) + const owner = await projectAt(checkout.path) + + const relative = await request(route(`/project/${owner.id}/directories`, workspace.path), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ directory: "relative/workspace" }), + }) + expect(relative.status).toBe(400) + + const create = await request(route(`/project/${owner.id}/directories`, workspace.path), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ directory: alias }), + }) + expect(create.status).toBe(200) + expect(await create.json()).toEqual(expect.arrayContaining([{ directory: workspace.path }])) + expect((await projectAt(workspace.path)).id).toBe(owner.id) + + const remove = await request(route(`/project/${owner.id}/directories`, alias), { method: "DELETE" }) + expect(remove.status).toBe(200) + expect((await projectAt(workspace.path)).id).toBe("global") +}) diff --git a/packages/opencode/test/server/httpapi-workspace-routing.test.ts b/packages/opencode/test/server/httpapi-workspace-routing.test.ts index 2f6195a87ebc..5b6bd4961a8b 100644 --- a/packages/opencode/test/server/httpapi-workspace-routing.test.ts +++ b/packages/opencode/test/server/httpapi-workspace-routing.test.ts @@ -370,6 +370,7 @@ describe("HttpApi workspace routing middleware", () => { isSyncing: () => Effect.succeed(true), waitForSync: (id, state) => Ref.set(waited, { workspaceID: id, state }), startWorkspaceSyncing: () => Effect.die("unused"), + resumeWorkspaceSyncing: () => Effect.die("unused"), }) yield* HttpApiBuilder.layer(ProbeApi).pipe( diff --git a/packages/opencode/test/session/tools.test.ts b/packages/opencode/test/session/tools.test.ts index f365f684e6c3..6ab58fb1363e 100644 --- a/packages/opencode/test/session/tools.test.ts +++ b/packages/opencode/test/session/tools.test.ts @@ -45,6 +45,7 @@ function fakeMcp() { const fakePlugin = Plugin.Service.of({ init: () => Effect.void, list: () => Effect.succeed([]), + http: () => Effect.succeed(undefined), trigger: (_name, _input, output) => Effect.succeed(output), } satisfies Plugin.Interface) diff --git a/packages/opencode/test/tool/registry.test.ts b/packages/opencode/test/tool/registry.test.ts index c8c5fac59559..f2e3862e197c 100644 --- a/packages/opencode/test/tool/registry.test.ts +++ b/packages/opencode/test/tool/registry.test.ts @@ -33,6 +33,7 @@ const brokenPluginLayer = Layer.succeed( Plugin.Service, Plugin.Service.of({ init: () => Effect.void, + http: () => Effect.succeed(undefined), trigger: ((_name: unknown, _input: unknown, output: unknown) => Effect.succeed(output)) as Plugin.Interface["trigger"], list: () => diff --git a/packages/plugin/src/index.ts b/packages/plugin/src/index.ts index edfa0139dfca..762136f35ec1 100644 --- a/packages/plugin/src/index.ts +++ b/packages/plugin/src/index.ts @@ -79,6 +79,10 @@ export type PluginModule = { tui?: never } +export interface PluginHttpHandler { + readonly fetch: (request: Request) => Response | Promise +} + type Rule = { key: string op: "eq" | "neq" @@ -221,6 +225,7 @@ export type AuthOuathResult = AuthOAuthResult export interface Hooks { dispose?: () => Promise + http?: PluginHttpHandler event?: (input: { event: Event }) => Promise config?: (input: Config) => Promise tool?: {