From b9236f7f20ddca51252b1000896a105e8b196df6 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 30 May 2026 19:44:07 -0400 Subject: [PATCH] feat(worktree): worktree tabs, server env vars, and multi-directory SSE (#240) * loop: worktree-tabs-2 completed after 4 iterations * loop: server-env-vars completed after 7 iterations * feat(worktree): add worktree tabs and server env vars settings * refactor(worktree): multi-directory SSE support and workspace chip row * feat(workspace): collapsible workspace manager and sibling filtering * feat(workspace): workspace creation endpoint, refactored workspace manager, and tests * refactor(frontend): unify workspace label and remove dead code - extract shared workspaceLabel helper into api/repos and reuse in WorkspaceManager and RepoDetail directoryLabels - remove unused useSessions hook and subscribeToDirectory subscription - drop redundant frontend workspace dedup now guaranteed by backend - align WorktreeTabs empty-state test with create-workspace button --- backend/package.json | 2 +- backend/src/routes/repos.test.ts | 333 ++++++++++++++++++ backend/src/routes/repos.ts | 75 +++- backend/src/routes/settings.test.ts | 293 +++++++++++++++ .../src/services/opencode-single-server.ts | 19 + .../src/services/project-id-resolver.test.ts | 39 ++ backend/src/services/project-id-resolver.ts | 23 ++ backend/src/services/repo.ts | 124 ++++++- backend/vitest.config.ts | 1 + frontend/src/api/fetchWrapper.ts | 16 +- frontend/src/api/opencode.test.ts | 45 +++ frontend/src/api/opencode.ts | 9 +- frontend/src/api/repos.ts | 42 +++ frontend/src/api/types/settings.ts | 6 +- .../src/components/message/PromptInput.tsx | 2 +- .../src/components/repo/WorkspaceManager.tsx | 257 ++++++++++++++ .../src/components/repo/WorktreeTabs.test.tsx | 75 ++++ frontend/src/components/repo/WorktreeTabs.tsx | 59 ++++ .../src/components/session/SessionCard.tsx | 8 + .../components/session/SessionList.test.tsx | 113 ++++++ .../src/components/session/SessionList.tsx | 94 +++-- .../settings/ServerEnvVarsSettings.tsx | 188 ++++++++++ .../components/settings/SettingsDialog.tsx | 19 +- frontend/src/hooks/useOpenCode.test.tsx | 84 +++++ frontend/src/hooks/useOpenCode.ts | 145 ++++++-- frontend/src/hooks/useRepoSiblings.ts | 59 ++++ frontend/src/hooks/useSSE.ts | 78 ++-- frontend/src/hooks/useWorktreeTab.ts | 40 +++ frontend/src/lib/navigation.test.ts | 20 ++ frontend/src/lib/navigation.ts | 11 +- .../__tests__/openCodeEventStream.test.ts | 2 +- .../openCodeEventStream.ts | 17 - frontend/src/pages/RepoDetail.tsx | 192 +++++++++- frontend/src/pages/SessionDetail.tsx | 8 +- package.json | 2 +- shared/src/schemas/settings.ts | 27 ++ shared/src/types/index.ts | 3 + tsconfig.json | 26 ++ 38 files changed, 2423 insertions(+), 133 deletions(-) create mode 100644 backend/src/routes/repos.test.ts create mode 100644 backend/src/routes/settings.test.ts create mode 100644 backend/src/services/project-id-resolver.test.ts create mode 100644 frontend/src/api/opencode.test.ts create mode 100644 frontend/src/components/repo/WorkspaceManager.tsx create mode 100644 frontend/src/components/repo/WorktreeTabs.test.tsx create mode 100644 frontend/src/components/repo/WorktreeTabs.tsx create mode 100644 frontend/src/components/session/SessionList.test.tsx create mode 100644 frontend/src/components/settings/ServerEnvVarsSettings.tsx create mode 100644 frontend/src/hooks/useOpenCode.test.tsx create mode 100644 frontend/src/hooks/useRepoSiblings.ts create mode 100644 frontend/src/hooks/useWorktreeTab.ts create mode 100644 tsconfig.json diff --git a/backend/package.json b/backend/package.json index 637e07c5..3ab073f7 100644 --- a/backend/package.json +++ b/backend/package.json @@ -9,7 +9,7 @@ "build": "bun build src/index.ts --outdir=dist --target=bun", "typecheck": "tsc --noEmit", "test": "pnpm run test:bun && pnpm run test:vitest", - "test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts src/db/model-state.test.ts src/routes/providers.test.ts", + "test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts", "test:vitest": "vitest run", "test:ui": "vitest --ui", "test:watch": "vitest --watch", diff --git a/backend/src/routes/repos.test.ts b/backend/src/routes/repos.test.ts new file mode 100644 index 00000000..595cef83 --- /dev/null +++ b/backend/src/routes/repos.test.ts @@ -0,0 +1,333 @@ +import { describe, it, expect, beforeEach, afterEach, mock } from 'bun:test' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import { migrate } from '../db/migration-runner' +import { allMigrations } from '../db/migrations' +import { createRepoRoutes } from './repos' +import { createRepo } from '../db/queries' +import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client' +import type { GitAuthService } from '../services/git-auth' +import type { OpenCodeClient } from '../services/opencode/client' +import { getReposPath } from '@opencode-manager/shared/config/env' +import path from 'path' + +beforeEach(() => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => null) as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) +}) + +afterEach(() => { + mock.restore() +}) + +const stubGitAuthService = { + getGitEnvironment: () => ({}), + getGitCredentials: async () => [], +} as unknown as GitAuthService + +function createTestApp(db: Database, openCodeClient: OpenCodeClient = createStubOpenCodeClient({ + getJson: mock(async () => []) as any, +})): Hono { + const app = new Hono() + const scheduleService = { + createSchedule: () => {}, + getScheduleById: () => null, + listSchedules: () => [], + updateSchedule: () => {}, + deleteSchedule: () => {}, + } as any + app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient)) + return app +} + +function createTestDb(): Database { + const db = new Database(':memory:') + migrate(db, allMigrations) + return db +} + +describe('GET /api/repos/:id/siblings', () => { + let db: Database + let app: Hono + + beforeEach(() => { + db = createTestDb() + app = createTestApp(db) + }) + + it('returns siblings including self with currentBranch', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: ((path: string) => Promise.resolve( + path.includes('repo-unrelated') ? 'commit-B' : 'commit-A' + )) as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + createRepo(db, { localPath: 'repo-b', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + createRepo(db, { localPath: 'repo-c', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + createRepo(db, { localPath: 'repo-unrelated', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as Array<{ id: number; currentBranch: string | null | undefined }> + expect(data).toHaveLength(3) + expect(data.map((d) => d.id).sort((a, b) => a - b)).toEqual([1, 2, 3]) + }) + + it('includes OpenCode workspaces that are not manager repo rows', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => Promise.resolve('commit-A')) as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + app = createTestApp(db, createStubOpenCodeClient({ + getJson: mock(async () => ([{ + id: 'wrk_test', + type: 'worktree', + name: 'plugin-workspace', + branch: 'plugin-branch', + directory: '/tmp/plugin-workspace', + projectID: 'commit-A', + }])) as any, + })) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as Array<{ id: number; workspaceId?: string; currentBranch?: string }> + expect(data).toHaveLength(2) + expect(data[1]).toMatchObject({ + id: -1, + workspaceId: 'wrk_test', + currentBranch: 'plugin-branch', + }) + }) + + it('deduplicates OpenCode workspaces with the same directory', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => Promise.resolve('commit-A')) as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + app = createTestApp(db, createStubOpenCodeClient({ + getJson: mock(async () => ([ + { + id: 'wrk_first', + type: 'worktree', + name: 'duplicate-workspace', + branch: 'duplicate-branch', + directory: '/tmp/duplicate-workspace', + projectID: 'commit-A', + }, + { + id: 'wrk_second', + type: 'worktree', + name: 'duplicate-workspace', + branch: 'duplicate-branch', + directory: '/tmp/duplicate-workspace/', + projectID: 'commit-A', + }, + ])) as any, + })) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as Array<{ workspaceId?: string }> + expect(data.filter((entry) => entry.workspaceId)).toHaveLength(1) + expect(data.some((entry) => entry.workspaceId === 'wrk_first')).toBe(true) + }) + + it('excludes a workspace pointing at the repo directory so it cannot be deleted', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => Promise.resolve('commit-A')) as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const repoDirectory = path.join(getReposPath(), 'repo-a') + app = createTestApp(db, createStubOpenCodeClient({ + getJson: mock(async () => ([{ + id: 'wrk_self', + type: 'worktree', + name: 'self-workspace', + branch: 'main', + directory: `${repoDirectory}/`, + projectID: 'commit-A', + }])) as any, + })) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as Array<{ id: number; workspaceId?: string }> + expect(data).toHaveLength(1) + expect(data.some((d) => d.workspaceId === 'wrk_self')).toBe(false) + }) + + it('excludes a workspace that is a git main checkout so the main repo cannot be deleted', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => Promise.resolve('commit-A')) as any, + isGitMainCheckout: ((dir: string) => + Promise.resolve(dir === '/Users/dev/main-repo')) as any, + })) + + createRepo(db, { localPath: 'repo-wt', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + app = createTestApp(db, createStubOpenCodeClient({ + getJson: mock(async () => ([ + { + id: 'wrk_main', + type: 'worktree', + name: 'main-checkout', + branch: 'dev', + directory: '/Users/dev/main-repo', + projectID: 'commit-A', + }, + { + id: 'wrk_linked', + type: 'worktree', + name: 'feature', + branch: 'feature/x', + directory: '/Users/dev/worktrees/feature-x', + projectID: 'commit-A', + }, + ])) as any, + })) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as Array<{ workspaceId?: string }> + expect(data.some((d) => d.workspaceId === 'wrk_main')).toBe(false) + expect(data.some((d) => d.workspaceId === 'wrk_linked')).toBe(true) + }) + + it('excludes repos with non-matching projectID', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: ((path: string) => Promise.resolve( + path.includes('repo-only') ? 'commit-X' : 'commit-Y' + )) as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + createRepo(db, { localPath: 'repo-only', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + createRepo(db, { localPath: 'repo-other', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as Array<{ id: number }> + expect(data).toHaveLength(1) + expect(data[0]!.id).toBe(1) + }) + + it('returns empty when target has no projectID', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => null) as any, + })) + + createRepo(db, { localPath: 'repo-no-project', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as unknown[] + expect(data).toEqual([]) + }) + + it('returns empty when target cloneStatus !== ready', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => 'commit-A') as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + createRepo(db, { localPath: 'repo-cloning', defaultBranch: 'main', cloneStatus: 'cloning', clonedAt: Date.now(), isLocal: true }) + + const res = await app.request('/repos/1/siblings') + expect(res.status).toBe(200) + const data = await res.json() as unknown[] + expect(data).toEqual([]) + }) + + it('returns empty when target missing', async () => { + mock.module('../services/project-id-resolver', () => ({ + resolveProjectId: (() => 'commit-A') as any, + isGitMainCheckout: (() => Promise.resolve(false)) as any, + })) + + const res = await app.request('/repos/9999/siblings') + expect(res.status).toBe(200) + const data = await res.json() as unknown[] + expect(data).toEqual([]) + }) + + it('invalid id returns 400', async () => { + const res = await app.request('/repos/abc/siblings') + expect(res.status).toBe(400) + const data = await res.json() as { error: string } + expect(data.error).toBe('Invalid repo id') + }) +}) + +describe('DELETE /api/repos/:id/workspaces/:workspaceId', () => { + let db: Database + let captured: { path: string; directory?: string } | null + + beforeEach(() => { + db = createTestDb() + captured = null + }) + + afterEach(() => { + db.close() + }) + + it('forwards workspace delete to OpenCode with repo directory', async () => { + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const forward = mock(async (req: Parameters[0]) => { + captured = { path: req.path, directory: req.directory } + return new Response(JSON.stringify({ id: 'wrk_test' }), { status: 200 }) + }) + const app = createTestApp(db, createStubOpenCodeClient({ + forward, + })) + + const res = await app.request('/repos/1/workspaces/wrk_test', { method: 'DELETE' }) + + expect(res.status).toBe(200) + expect(captured?.path).toBe('/experimental/workspace/wrk_test') + expect(captured?.directory?.endsWith('/repos/repo-a')).toBe(true) + }) +}) + +describe('POST /api/repos/:id/workspaces', () => { + let db: Database + let captured: { path: string; directory?: string; body?: string } | null + + beforeEach(() => { + db = createTestDb() + captured = null + }) + + afterEach(() => { + db.close() + }) + + it('forwards workspace creation to OpenCode with repo directory', async () => { + createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const forward = mock(async (req: Parameters[0]) => { + captured = { path: req.path, directory: req.directory, body: req.body } + return new Response(JSON.stringify({ id: 'wrk_test', type: 'worktree', directory: '/tmp/wrk-test' }), { status: 200 }) + }) + const app = createTestApp(db, createStubOpenCodeClient({ + forward, + })) + + const res = await app.request('/repos/1/workspaces', { method: 'POST' }) + + expect(res.status).toBe(200) + expect(captured?.path).toBe('/experimental/workspace') + expect(captured?.directory?.endsWith('/repos/repo-a')).toBe(true) + expect(JSON.parse(captured?.body ?? '{}')).toEqual({ type: 'worktree', branch: null }) + expect(await res.json()).toMatchObject({ id: 'wrk_test', type: 'worktree' }) + }) +}) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 30c29b0e..a1cd0041 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -194,6 +194,23 @@ app.get('/', async (c) => { } }) + app.get('/:id/siblings', async (c) => { + try { + const id = parseInt(c.req.param('id')) + if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400) + const siblings = await repoService.getSiblingRepos( + database, + id, + gitAuthService.getGitEnvironment(), + openCodeClient, + ) + return c.json(siblings) + } catch (error: unknown) { + logger.error('Failed to list sibling repos:', error) + return c.json({ error: getErrorMessage(error) }, 500) + } + }) + app.post('/:id/access', async (c) => { try { const id = parseInt(c.req.param('id')) @@ -211,7 +228,63 @@ app.get('/', async (c) => { return c.json({ error: getErrorMessage(error) }, 500) } }) - + + app.delete('/:id/workspaces/:workspaceId', async (c) => { + try { + const id = parseInt(c.req.param('id')) + if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400) + + const repo = getRepoById(database, id) + if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404) + + const workspaceId = c.req.param('workspaceId') + if (!workspaceId.startsWith('wrk')) return c.json({ error: 'Invalid workspace id' }, 400) + + const response = await openCodeClient.forward({ + method: 'DELETE', + path: `/experimental/workspace/${encodeURIComponent(workspaceId)}`, + directory: repo.fullPath, + }) + + if (!response.ok) { + return c.json({ error: await response.text() || 'Failed to delete workspace' }, response.status as ContentfulStatusCode) + } + + return c.json({ success: true }) + } catch (error: unknown) { + logger.error('Failed to delete workspace:', error) + return c.json({ error: getErrorMessage(error) }, 500) + } + }) + + app.post('/:id/workspaces', async (c) => { + try { + const id = parseInt(c.req.param('id')) + if (Number.isNaN(id)) return c.json({ error: 'Invalid repo id' }, 400) + + const repo = getRepoById(database, id) + if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404) + + const response = await openCodeClient.forward({ + method: 'POST', + path: '/experimental/workspace', + directory: repo.fullPath, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ type: 'worktree', branch: null }), + }) + + const body = await response.text() + if (!response.ok) { + return c.json({ error: body || 'Failed to create workspace' }, response.status as ContentfulStatusCode) + } + + return c.json(body ? JSON.parse(body) : { success: true }) + } catch (error: unknown) { + logger.error('Failed to create workspace:', error) + return c.json({ error: getErrorMessage(error) }, 500) + } + }) + app.delete('/:id', async (c) => { try { const id = parseInt(c.req.param('id')) diff --git a/backend/src/routes/settings.test.ts b/backend/src/routes/settings.test.ts new file mode 100644 index 00000000..556e30c4 --- /dev/null +++ b/backend/src/routes/settings.test.ts @@ -0,0 +1,293 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { Hono } from 'hono' +import { Database } from 'bun:sqlite' +import { migrate } from '../db/migration-runner' +import { allMigrations } from '../db/migrations' +import { createSettingsRoutes } from './settings' +import type { GitAuthService } from '../services/git-auth' +import { createStubOpenCodeClient } from '../../test/helpers/stub-opencode-client' + +interface TestUserPreferenceRow { + preferences: string + updated_at: number +} + +interface TestMigrationRow { + version: number + name: string + applied_at: number +} + +interface StatementResult { + get?: (..._params: unknown[]) => TestUserPreferenceRow | TestMigrationRow | { count: number } | { name: string } | { user_id: string; preferences: string } | undefined + run?: (..._params: unknown[]) => { changes: number } + all?: () => Array +} + +class InMemoryDatabase { + private userPreferences = new Map() + private schemaMigrations = new Map() + + private normalizeSql(sql: string): string { + return sql.trim().toLowerCase().replace(/\s+/g, ' ') + } + + private getMigrationRows(): TestMigrationRow[] { + return [...this.schemaMigrations.entries()] + .sort((a, b) => a[0] - b[0]) + .map(([version, value]) => ({ + version, + name: value.name, + applied_at: value.applied_at, + })) + } + + private setUserPreference(userId: string, preferences: string, updatedAt: number): void { + this.userPreferences.set(userId, { preferences, updated_at: updatedAt }) + } + + private createStatement(sql: string): StatementResult { + const normalizedSql = this.normalizeSql(sql) + + if (normalizedSql === 'select version from schema_migrations order by version') { + return { + all: () => this.getMigrationRows(), + } + } + + if (normalizedSql.startsWith('insert into schema_migrations')) { + return { + run: (...params: unknown[]) => { + const [version, name, appliedAt] = params as [number, string, number] + this.schemaMigrations.set(version, { name, applied_at: appliedAt }) + return { changes: 1 } + }, + } + } + + if (normalizedSql === 'select preferences, updated_at from user_preferences where user_id = ?') { + return { + get: (...params: unknown[]) => { + const userId = params[0] + if (typeof userId !== 'string') { + return undefined + } + return this.userPreferences.get(userId) + }, + } + } + + if (normalizedSql.startsWith('insert into user_preferences')) { + return { + run: (...params: unknown[]) => { + const [userId, preferences, updatedAt] = params as [string, string, number] + this.setUserPreference(userId, preferences, updatedAt) + return { changes: 1 } + }, + } + } + + if (normalizedSql.startsWith('delete from user_preferences where user_id = ?')) { + return { + run: (...params: unknown[]) => { + const userId = params[0] + if (typeof userId !== 'string') { + return { changes: 0 } + } + const hadRow = this.userPreferences.delete(userId) + return { changes: hadRow ? 1 : 0 } + }, + } + } + + if (normalizedSql.startsWith('select user_id, preferences from user_preferences')) { + return { + all: () => [...this.userPreferences.entries()].map(([user_id, row]) => ({ + user_id, + preferences: row.preferences, + })), + } + } + + if (normalizedSql.startsWith('pragma table_info(') || normalizedSql.includes('select name from sqlite_master')) { + return { + all: () => [], + get: () => undefined, + } + } + + if (normalizedSql.startsWith('select count(*) as count')) { + return { + get: () => ({ count: 0 }), + } + } + + if ( + normalizedSql.startsWith('create table') || + normalizedSql.startsWith('create index') || + normalizedSql.startsWith('drop table') || + normalizedSql.startsWith('drop index') + ) { + return { + run: () => ({ changes: 0 }), + } + } + + if ( + normalizedSql.startsWith('begin transaction') || + normalizedSql.startsWith('commit') || + normalizedSql.startsWith('rollback') + ) { + return { + run: () => ({ changes: 0 }), + } + } + + return { + get: () => undefined, + run: () => ({ changes: 0 }), + all: () => [], + } + } + + query(sql: string): StatementResult { + return this.createStatement(sql) + } + + prepare(sql: string): StatementResult { + return this.createStatement(sql) + } + + run(sql: string, ...params: unknown[]): { changes: number } { + const statement = this.createStatement(sql) + return statement.run ? statement.run(...params) : { changes: 0 } + } + + close() { + this.userPreferences.clear() + this.schemaMigrations.clear() + } +} + +vi.mock('bun:sqlite', () => ({ + Database: class { + private db = new InMemoryDatabase() + + query(sql: string) { + return this.db.query(sql) + } + + prepare(sql: string) { + return this.db.prepare(sql) + } + + run(sql: string, ...params: unknown[]) { + return this.db.run(sql, ...params) + } + + close() { + return this.db.close() + } + + exec(sql: string) { + return this.db.run(sql) + } + }, +})) + +const mockGitAuthService = { + getGitEnvironment: () => ({}), +} as unknown as GitAuthService + +function createTestDb(): Database { + const db = new Database(':memory:') + migrate(db, allMigrations) + return db +} + +function createTestApp(db: Database): Hono { + const app = new Hono() + app.route('/settings', createSettingsRoutes(db, mockGitAuthService, createStubOpenCodeClient())) + return app +} + +describe('settings routes — serverEnvVars', () => { + let db: Database + let app: Hono + let originalWorkspacePath: string | undefined + + beforeEach(() => { + db = createTestDb() + app = createTestApp(db) + originalWorkspacePath = process.env.WORKSPACE_PATH + process.env.WORKSPACE_PATH = '/tmp/test-workspace-settings-routes' + }) + + afterEach(() => { + if (originalWorkspacePath) { + process.env.WORKSPACE_PATH = originalWorkspacePath + } else { + delete process.env.WORKSPACE_PATH + } + db.close() + }) + + it('GET / returns empty serverEnvVars by default', async () => { + const res = await app.request('/settings') + + expect(res.status).toBe(200) + const data = (await res.json()) as { preferences: { serverEnvVars?: Array<{ key: string; value: string }> } } + expect(data.preferences.serverEnvVars).toEqual([]) + }) + + it('PATCH / saves and returns serverEnvVars', async () => { + const patchRes = await app.request('/settings', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + preferences: { + serverEnvVars: [ + { + key: 'OPENCODE_EXPERIMENTAL_WORKSPACES', + value: 'true', + }, + ], + }, + }), + }) + + expect(patchRes.status).toBe(200) + const data = (await patchRes.json()) as { preferences: { serverEnvVars: Array<{ key: string; value: string }> } } + expect(data.preferences.serverEnvVars).toEqual([ + { + key: 'OPENCODE_EXPERIMENTAL_WORKSPACES', + value: 'true', + }, + ]) + }) + + it('PATCH / persists serverEnvVars and returns on GET', async () => { + await app.request('/settings', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + preferences: { + serverEnvVars: [{ + key: 'MY_FLAG', + value: '1', + }], + }, + }), + }) + + const res = await app.request('/settings') + const data = (await res.json()) as { preferences: { serverEnvVars: Array<{ key: string; value: string }> } } + + expect(data.preferences.serverEnvVars).toEqual([ + { + key: 'MY_FLAG', + value: '1', + }, + ]) + }) +}) diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 97be6041..49827ef3 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -15,6 +15,7 @@ import { parseSSHHost } from '../utils/ssh-key-manager' import { decryptSecret } from '../utils/crypto' +import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@opencode-manager/shared' import { SettingsService } from './settings' import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env' import { parseJsonc } from '@opencode-manager/shared/utils' @@ -199,11 +200,28 @@ class OpenCodeServerManager { let gitCredentials: GitCredential[] = [] let gitIdentityEnv: Record = {} + let userEnvVars: Record = {} if (this.db) { try { const settingsService = new SettingsService(this.db) const settings = settingsService.getSettings('default') gitCredentials = settings.preferences.gitCredentials || [] + const disabledDefaultEnvVars = new Set(settings.preferences.disabledDefaultServerEnvVars || []) + const rawEnvVars = [ + ...DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultEnvVars.has(envVar.key)), + ...(settings.preferences.serverEnvVars || []), + ] + if (rawEnvVars.length > 0) { + userEnvVars = Object.fromEntries( + rawEnvVars + .filter(({ key }) => { + const normalizedKey = key.trim() + return normalizedKey !== '' && !(BLOCKED_SERVER_ENV_KEYS as readonly string[]).includes(normalizedKey) + }) + .map(({ key, value }) => [key.trim(), value]) + ) + logger.info(`Injecting ${Object.keys(userEnvVars).length} custom server env vars`) + } const identity = await resolveGitIdentity(settings.preferences.gitIdentity, gitCredentials) if (identity) { @@ -327,6 +345,7 @@ class OpenCodeServerManager { stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'], env: { ...cleanEnv, + ...userEnvVars, ...gitEnv, ...gitIdentityEnv, GIT_SSH_COMMAND: gitSshCommand, diff --git a/backend/src/services/project-id-resolver.test.ts b/backend/src/services/project-id-resolver.test.ts new file mode 100644 index 00000000..6cc7123f --- /dev/null +++ b/backend/src/services/project-id-resolver.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest' +import { mkdtempSync, rmSync } from 'fs' +import { tmpdir } from 'os' +import path from 'path' +import { execSync } from 'child_process' +import { isGitMainCheckout } from './project-id-resolver' + +describe('isGitMainCheckout', () => { + let base: string + let mainRepo: string + let worktree: string + + beforeAll(() => { + base = mkdtempSync(path.join(tmpdir(), 'oc-main-checkout-')) + mainRepo = path.join(base, 'main') + worktree = path.join(base, 'wt') + execSync(`git init -q "${mainRepo}"`) + execSync(`git -C "${mainRepo}" commit -q --allow-empty -m init`, { + env: { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' }, + }) + execSync(`git -C "${mainRepo}" worktree add -q "${worktree}" -b feature`) + }) + + afterAll(() => { + rmSync(base, { recursive: true, force: true }) + }) + + it('returns true for the main checkout', async () => { + expect(await isGitMainCheckout(mainRepo)).toBe(true) + }) + + it('returns false for a linked worktree', async () => { + expect(await isGitMainCheckout(worktree)).toBe(false) + }) + + it('returns false for a non-git directory', async () => { + expect(await isGitMainCheckout(base)).toBe(false) + }) +}) diff --git a/backend/src/services/project-id-resolver.ts b/backend/src/services/project-id-resolver.ts index 69d0c7b1..225ac505 100644 --- a/backend/src/services/project-id-resolver.ts +++ b/backend/src/services/project-id-resolver.ts @@ -1,5 +1,6 @@ import { exec } from 'child_process' import { readFile } from 'fs/promises' +import path from 'path' import { fileExists } from './file-operations' const projectIdCache = new Map() @@ -66,3 +67,25 @@ export async function resolveProjectId(repoFullPath: string): Promise() + +export async function isGitMainCheckout(repoFullPath: string): Promise { + if (mainCheckoutCache.has(repoFullPath)) { + return mainCheckoutCache.get(repoFullPath) ?? false + } + try { + const gitDir = await executeGitCommand(repoFullPath, ['rev-parse', '--absolute-git-dir']) + const commonDir = await executeGitCommand(repoFullPath, [ + 'rev-parse', + '--path-format=absolute', + '--git-common-dir', + ]) + const isMain = !!gitDir && !!commonDir && path.resolve(gitDir) === path.resolve(commonDir) + mainCheckoutCache.set(repoFullPath, isMain) + return isMain + } catch { + mainCheckoutCache.set(repoFullPath, false) + return false + } +} diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 5e12a5f4..e4b16614 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -1,5 +1,5 @@ import fs from 'fs/promises' -import { existsSync, rmSync } from 'node:fs' +import { existsSync, rmSync, realpathSync } from 'node:fs' import { executeCommand } from '../utils/process' import { ensureDirectoryExists } from './file-operations' import { createRepo, getRepoByLocalPath, getRepoBySourcePath, getRepoById, updateRepoStatus, updateRepoBranch, updateLastPulled, deleteRepo, getRepoByUrlAndBranch } from '../db/queries' @@ -14,11 +14,23 @@ import path from 'path' import { parseSSHHost } from '../utils/ssh-key-manager' import { getErrorMessage } from '../utils/error-utils' import { sseAggregator } from './sse-aggregator' +import { resolveProjectId, isGitMainCheckout } from './project-id-resolver' +import { listRepos } from '../db/queries' +import { SettingsService } from './settings' +import type { OpenCodeClient } from './opencode/client' const GIT_CLONE_TIMEOUT = 300000 const DEFAULT_DISCOVERY_MAX_DEPTH = 4 const DISCOVERY_SKIP_DIRECTORIES = new Set(['.git', 'node_modules']) +function canonical(dir: string): string { + try { + return realpathSync(path.resolve(dir)) + } catch { + return path.resolve(dir) + } +} + function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error { const message = originalMessage.toLowerCase() @@ -1091,3 +1103,113 @@ export function isRepoInUse(db: Database, repoId: number): boolean { return sseAggregator.getActiveDirectories().includes(repo.fullPath) } + +export async function getSiblingRepos( + database: Database, + repoId: number, + gitEnv: Record, + openCodeClient?: OpenCodeClient, +): Promise> { + const settingsService = new SettingsService(database) + const settings = settingsService.getSettings() + const allRepos = listRepos(database, settings.preferences.repoOrder) + + const target = allRepos.find((r) => r.id === repoId) + if (!target || target.cloneStatus !== 'ready') return [] + + const targetProjectId = await resolveProjectId(target.fullPath) + if (!targetProjectId) return [] + + const ready = allRepos.filter((r) => r.cloneStatus === 'ready') + const withProjectIds = await Promise.all( + ready.map(async (repo) => ({ + repo, + projectId: await resolveProjectId(repo.fullPath).catch(() => null), + })), + ) + + const matching = withProjectIds + .filter((entry) => entry.projectId === targetProjectId) + .map((entry) => entry.repo) + + const repoSiblings = await Promise.all( + matching.map(async (repo) => ({ + ...repo, + currentBranch: (await getCurrentBranch(repo, gitEnv)) ?? undefined, + })), + ) + + if (!openCodeClient) return repoSiblings + + try { + const workspaces = await openCodeClient.getJson>('/experimental/workspace', { directory: target.fullPath }) + + // Normalize paths so a workspace pointing at a real repo directory can never + // be exposed as deletable. Deleting an OpenCode workspace recursively removes + // its directory, so the current repo directory and all known managed repo + // directories must be excluded regardless of trailing slashes or symlinks. + // Workspaces that are git main checkouts (not linked worktrees) are also + // excluded so the project's origin/main repository can never be surfaced + // as deletable. + const knownDirectories = new Set(repoSiblings.map((repo) => canonical(repo.fullPath))) + const targetDirectory = canonical(target.fullPath) + const reposRoot = canonical(getReposPath()) + + const candidates = workspaces.filter((workspace) => { + if (workspace.projectID !== targetProjectId) return false + if (!workspace.directory) return false + + const workspaceDirectory = canonical(workspace.directory) + if (workspaceDirectory === targetDirectory) return false + if (workspaceDirectory === reposRoot) return false + if (knownDirectories.has(workspaceDirectory)) return false + + return true + }) + + const mainChecks = await Promise.all( + candidates.map((workspace) => isGitMainCheckout(workspace.directory!).catch(() => false)), + ) + + const uniqueWorkspaces = new Map() + candidates + .filter((_, index) => !mainChecks[index]) + .forEach((workspace) => { + const directory = canonical(workspace.directory!) + if (!uniqueWorkspaces.has(directory)) { + uniqueWorkspaces.set(directory, workspace) + } + }) + + const workspaceSiblings = Array.from(uniqueWorkspaces.values()) + .map((workspace) => ({ + id: -1, + repoUrl: target.repoUrl, + localPath: workspace.name ?? workspace.id, + fullPath: workspace.directory!, + sourcePath: workspace.directory!, + branch: workspace.branch ?? undefined, + defaultBranch: target.defaultBranch, + cloneStatus: 'ready' as const, + clonedAt: Date.now(), + isWorktree: true, + isLocal: true, + currentBranch: workspace.branch ?? undefined, + workspaceId: workspace.id, + workspaceType: workspace.type, + workspaceName: workspace.name ?? undefined, + })) + + return [...repoSiblings, ...workspaceSiblings] + } catch (error) { + logger.warn('Failed to list OpenCode workspaces:', error) + return repoSiblings + } +} diff --git a/backend/vitest.config.ts b/backend/vitest.config.ts index 5299f9f6..da53ef82 100644 --- a/backend/vitest.config.ts +++ b/backend/vitest.config.ts @@ -19,6 +19,7 @@ export default defineConfig({ 'test/routes/internal-repos.test.ts', 'src/db/model-state.test.ts', 'src/routes/providers.test.ts', + 'src/routes/repos.test.ts', ], coverage: { provider: 'v8', diff --git a/frontend/src/api/fetchWrapper.ts b/frontend/src/api/fetchWrapper.ts index b3ab4661..4f301d5d 100644 --- a/frontend/src/api/fetchWrapper.ts +++ b/frontend/src/api/fetchWrapper.ts @@ -29,10 +29,22 @@ function formatDetails(details: unknown): string | undefined { } async function handleResponse(response: Response): Promise { - const data: ApiErrorResponse = await response.json().catch(() => ({ error: 'An error occurred' })) + const text = await response.text().catch(() => '') + const data: ApiErrorResponse = (() => { + if (!text) return { error: 'An error occurred' } + try { + return JSON.parse(text) as ApiErrorResponse + } catch { + return { error: text } + } + })() + const errorData = data as ApiErrorResponse & { message?: string; data?: { message?: unknown } } + const openCodeMessage = typeof errorData.data?.message === 'string' + ? errorData.data.message + : undefined const detail = data.detail || formatDetails(data.details) throw new FetchError( - data.error || 'Request failed', + data.error || errorData.message || openCodeMessage || 'Request failed', response.status, data.code, detail, diff --git a/frontend/src/api/opencode.test.ts b/frontend/src/api/opencode.test.ts new file mode 100644 index 00000000..1ff06641 --- /dev/null +++ b/frontend/src/api/opencode.test.ts @@ -0,0 +1,45 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OpenCodeClient } from './opencode' + +describe('OpenCodeClient', () => { + const fetchMock = vi.fn() + + beforeEach(() => { + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('treats empty successful session deletes as success', async () => { + fetchMock.mockResolvedValue(new Response(null, { status: 204 })) + + await expect(new OpenCodeClient('/api/opencode', '/repo').deleteSession('ses_1')).resolves.toBeUndefined() + + expect(fetchMock).toHaveBeenCalledWith( + 'http://localhost/api/opencode/session/ses_1?directory=%2Frepo', + expect.objectContaining({ method: 'DELETE' }), + ) + }) + + it('deletes workspaces with directory routing', async () => { + fetchMock.mockResolvedValue(new Response(null, { status: 204 })) + + await expect(new OpenCodeClient('/api/opencode', '/repo').deleteWorkspace('wrk_stale')).resolves.toBeUndefined() + + expect(fetchMock).toHaveBeenCalledWith( + 'http://localhost/api/opencode/experimental/workspace/wrk_stale?directory=%2Frepo', + expect.objectContaining({ method: 'DELETE' }), + ) + }) + + it('preserves text error responses', async () => { + fetchMock.mockResolvedValue(new Response('Workspace not found: wrk_stale', { status: 500 })) + + await expect(new OpenCodeClient('/api/opencode', '/repo').deleteSession('ses_1')).rejects.toThrow( + 'Workspace not found: wrk_stale', + ) + }) +}) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 819201e8..2e3b5fc1 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -61,7 +61,14 @@ export class OpenCodeClient { } async deleteSession(sessionID: string) { - return fetchWrapper(`${this.baseURL}/session/${sessionID}`, { + return fetchWrapperVoid(`${this.baseURL}/session/${sessionID}`, { + method: 'DELETE', + params: this.getParams(), + }) + } + + async deleteWorkspace(workspaceID: string) { + return fetchWrapperVoid(`${this.baseURL}/experimental/workspace/${workspaceID}`, { method: 'DELETE', params: this.getParams(), }) diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index e76cd1f5..a69ef241 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -38,6 +38,48 @@ export async function getRepo(id: number): Promise { return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`) } +export type RepoSibling = Repo & { + currentBranch?: string + workspaceId?: string + workspaceType?: string + workspaceName?: string +} + +export function workspaceLabel(workspace: RepoSibling): string { + return ( + workspace.currentBranch || + workspace.branch || + workspace.workspaceName || + workspace.workspaceId || + 'workspace' + ) +} + +export interface RepoWorkspace { + id: string + type: string + name?: string | null + branch?: string | null + directory?: string | null + projectID?: string +} + +export async function getRepoSiblings(id: number): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/siblings`) +} + +export async function deleteRepoWorkspace(repoId: number, workspaceId: string): Promise { + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/workspaces/${workspaceId}`, { + method: 'DELETE', + }) +} + +export async function createRepoWorkspace(repoId: number): Promise { + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, { + method: 'POST', + }) +} + export async function deleteRepo(id: number): Promise { return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}`, { method: 'DELETE', diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index 32598617..b912b5c0 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -4,6 +4,8 @@ import { DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, + BLOCKED_SERVER_ENV_KEYS, + DEFAULT_SERVER_ENV_VARS, type TTSConfig, type STTConfig, type OpenCodeConfigContent, @@ -17,7 +19,7 @@ import { import type { NotificationPreferences } from '@opencode-manager/shared/types' export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } -export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY } +export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } export interface CustomCommand { name: string @@ -63,6 +65,8 @@ export interface UserPreferences { notifications?: NotificationPreferences repoOrder?: number[] repoSortMode?: 'recent' | 'manual' | 'name' + serverEnvVars?: Array<{ key: string; value: string }> + disabledDefaultServerEnvVars?: string[] } export interface SettingsResponse { diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index e4320f38..2f2b6173 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -1251,7 +1251,7 @@ return ( directory={directory} > + {manageMode ? ( + <> + + + + ) : ( + + )} + + + +
+ + setSearchQuery(event.target.value)} + placeholder="Search workspaces..." + className="h-10 w-full rounded-md border border-border bg-background pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground focus:border-primary" + /> +
+ +
+ {filteredWorkspaces.map((workspace) => { + if (!workspace.workspaceId) return null + const workspaceId = workspace.workspaceId + const isChecked = selected.has(workspaceId) + const isActive = !!workspace.fullPath && workspace.fullPath === activeWorkspaceDirectory + const label = workspaceLabel(workspace) + const rowClassName = isActive + ? 'border-purple-500/50 bg-purple-500/10 text-foreground' + : 'border-border bg-muted/30 hover:bg-muted/50' + if (!manageMode) { + return ( + + ) + } + return ( +
+ toggle(workspaceId, checked === true)} + aria-label={`Select workspace ${label}`} + /> + + {label} + {workspace.fullPath && ( + + {workspace.fullPath} + + )} +
+ ) + })} + {filteredWorkspaces.length === 0 && ( +
+ No workspaces found +
+ )} +
+ + + + + setConfirmOpen(false)} + title={selectedCount === 1 ? 'Delete Workspace' : 'Delete Workspaces'} + description={ + selectedCount === 1 + ? 'Are you sure you want to delete this OpenCode workspace? This removes the workspace and its sessions in OpenCode.' + : `Are you sure you want to delete ${selectedCount} OpenCode workspaces? This removes the workspaces and their sessions in OpenCode.` + } + isDeleting={isDeleting} + /> + + ) +} diff --git a/frontend/src/components/repo/WorktreeTabs.test.tsx b/frontend/src/components/repo/WorktreeTabs.test.tsx new file mode 100644 index 00000000..0c6cc303 --- /dev/null +++ b/frontend/src/components/repo/WorktreeTabs.test.tsx @@ -0,0 +1,75 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { WorktreeTabs } from './WorktreeTabs' +import type { RepoSibling } from '@/api/repos' + +const makeWorkspaceSibling = (workspaceId: string, branch: string): RepoSibling => ({ + id: -1, + localPath: branch, + fullPath: `/w/${branch}`, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: 0, + isWorktree: true, + currentBranch: branch, + branch, + workspaceId, + workspaceName: branch, +}) + +const onValueChange = vi.fn() + +beforeEach(() => { + onValueChange.mockReset() +}) + +describe('WorktreeTabs', () => { + it('renders the repo tab with a create-workspace button when there are no workspaces', () => { + render( + + ) + expect(screen.getAllByRole('tab')).toHaveLength(1) + expect(screen.getByText('main')).toBeInTheDocument() + expect(screen.getByText('Workspace')).toBeInTheDocument() + }) + + it('renders Repo and Workspaces tabs when at least one workspace exists', () => { + const workspaces = [makeWorkspaceSibling('wrk_a', 'feature-a')] + render() + + const tabs = screen.getAllByRole('tab') + expect(tabs).toHaveLength(2) + expect(screen.getByText('main')).toBeInTheDocument() + expect(screen.getByText('Workspaces')).toBeInTheDocument() + expect(screen.getByText('(1)')).toBeInTheDocument() + }) + + it('marks the active tab', () => { + const workspaces = [makeWorkspaceSibling('wrk_a', 'feature-a')] + render() + + const tabs = screen.getAllByRole('tab') + expect(tabs[0]).toHaveAttribute('data-state', 'inactive') + expect(tabs[1]).toHaveAttribute('data-state', 'active') + }) + + it('calls onValueChange when a different tab is clicked', async () => { + const workspaces = [makeWorkspaceSibling('wrk_a', 'feature-a')] + render() + + await userEvent.click(screen.getAllByRole('tab')[1]) + expect(onValueChange).toHaveBeenCalledWith('workspaces') + }) + + it('shows the workspace count in the workspaces tab', () => { + const workspaces = [ + makeWorkspaceSibling('wrk_a', 'feature-a'), + makeWorkspaceSibling('wrk_b', 'feature-b'), + makeWorkspaceSibling('wrk_c', 'feature-c'), + ] + render() + + expect(screen.getByText('(3)')).toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/repo/WorktreeTabs.tsx b/frontend/src/components/repo/WorktreeTabs.tsx new file mode 100644 index 00000000..d59424b6 --- /dev/null +++ b/frontend/src/components/repo/WorktreeTabs.tsx @@ -0,0 +1,59 @@ +import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' +import { GitBranch, Layers, Plus } from 'lucide-react' +import type { RepoSibling } from '@/api/repos' +import type { WorktreeTabValue } from '@/hooks/useWorktreeTab' + +interface WorktreeTabsProps { + workspaces: RepoSibling[] + value: WorktreeTabValue + onValueChange: (value: WorktreeTabValue) => void + baseLabel: string + activeWorkspaceLabel?: string + onCreateWorkspace?: () => void + onWorkspaceMenu?: () => void +} + +export function WorktreeTabs({ + workspaces, + value, + onValueChange, + baseLabel, + activeWorkspaceLabel, + onCreateWorkspace, + onWorkspaceMenu, +}: WorktreeTabsProps) { + const hasWorkspaces = workspaces.length > 0 + const workspaceLabel = value === 'workspaces' && activeWorkspaceLabel ? activeWorkspaceLabel : 'Workspaces' + + return ( +
+ onValueChange(next as WorktreeTabValue)} className="min-w-0"> + + + + {baseLabel} + + {hasWorkspaces ? ( + <> + + + {workspaceLabel} + ({workspaces.length}) + + + ) : ( + + )} + + +
+ ) +} diff --git a/frontend/src/components/session/SessionCard.tsx b/frontend/src/components/session/SessionCard.tsx index 28d6438e..f2cb71d4 100644 --- a/frontend/src/components/session/SessionCard.tsx +++ b/frontend/src/components/session/SessionCard.tsx @@ -12,6 +12,7 @@ interface SessionCardProps { isSelected: boolean; isActive: boolean; manageMode: boolean; + workspaceLabel?: string; onSelect: (sessionID: string) => void; onToggleSelection: (selected: boolean) => void; onDelete: (e: React.MouseEvent) => void; @@ -22,6 +23,7 @@ export const SessionCard = ({ isSelected, isActive, manageMode, + workspaceLabel, onSelect, onToggleSelection, onDelete, @@ -107,6 +109,9 @@ export const SessionCard = ({ addSuffix: true, })} + {workspaceLabel ? ( + {workspaceLabel} + ) : null} @@ -122,6 +127,9 @@ export const SessionCard = ({ addSuffix: true, })} + {workspaceLabel ? ( + {workspaceLabel} + ) : null} diff --git a/frontend/src/components/session/SessionList.test.tsx b/frontend/src/components/session/SessionList.test.tsx new file mode 100644 index 00000000..273e0455 --- /dev/null +++ b/frontend/src/components/session/SessionList.test.tsx @@ -0,0 +1,113 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { SessionList } from './SessionList' + +const { createSessionMock, deleteSessionMock, sessionsData, createSessionState } = vi.hoisted(() => ({ + createSessionMock: vi.fn(), + deleteSessionMock: vi.fn(), + sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; time: { updated: number } }>, + createSessionState: { directory: undefined as string | undefined }, +})) + +vi.mock('@/hooks/useOpenCode', () => ({ + useSessionsAcrossDirectories: () => ({ + data: sessionsData, + isLoading: false, + }), + useCreateSession: (_opcodeUrl: string, directory?: string) => { + createSessionState.directory = directory + return { mutate: createSessionMock } + }, + useDeleteSession: () => ({ mutateAsync: deleteSessionMock, isPending: false }), +})) + +describe('SessionList', () => { + beforeEach(() => { + sessionsData.splice(0, sessionsData.length, + { id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', workspaceID: 'wrk_a', time: { updated: Date.now() } }, + { id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/b', workspaceID: 'wrk_b', time: { updated: Date.now() } }, + { id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/c', workspaceID: 'wrk_c', time: { updated: Date.now() } }, + ) + createSessionMock.mockReset() + createSessionState.directory = undefined + deleteSessionMock.mockReset() + deleteSessionMock.mockResolvedValue(undefined) + }) + + it('selects duplicate session IDs independently by workspace directory', async () => { + const user = userEvent.setup() + + render( + , + ) + + await user.click(screen.getByRole('button', { name: 'Manage sessions' })) + await user.click(screen.getByRole('button', { name: 'Select All' })) + + expect(screen.getByText('3 selected')).toBeTruthy() + + await user.click(screen.getByRole('button', { name: 'Delete' })) + + const dialog = screen.getByRole('dialog', { name: 'Delete Sessions' }) + expect(dialog).toBeTruthy() + expect(screen.getByText('3')).toBeTruthy() + + await user.click(within(dialog).getByRole('button', { name: 'Delete' })) + + await waitFor(() => { + expect(deleteSessionMock).toHaveBeenCalledWith([ + { id: 'ses_same', directory: '/w/a', workspaceID: 'wrk_a' }, + { id: 'ses_same', directory: '/w/b', workspaceID: 'wrk_b' }, + { id: 'ses_same', directory: '/w/c', workspaceID: 'wrk_c' }, + ]) + }) + }) + + it('deduplicates repeated session records from the same workspace directory', async () => { + const user = userEvent.setup() + sessionsData.splice(0, sessionsData.length, + { id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } }, + { id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } }, + { id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } }, + ) + + render( + , + ) + + expect(screen.getAllByText('audit: mic-warmup 1/2 #2')).toHaveLength(1) + + await user.click(screen.getByRole('button', { name: 'Manage sessions' })) + await user.click(screen.getByRole('button', { name: 'Select All' })) + + expect(screen.getByText('1 selected')).toBeTruthy() + }) + + it('creates sessions in the explicit create directory', async () => { + const user = userEvent.setup() + sessionsData.splice(0, sessionsData.length) + + render( + , + ) + + await user.click(screen.getByText('No sessions yet')) + + expect(createSessionState.directory).toBe('/w/b') + expect(createSessionMock).toHaveBeenCalledWith({ agent: undefined }) + }) +}) diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index 34ee7d10..0c652aa5 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -1,5 +1,6 @@ -import { useState, useMemo } from "react"; -import { useSessions, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; +import { useCallback, useState, useMemo } from "react"; +import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode"; +import type { DeleteSessionTarget } from "@/hooks/useOpenCode"; import { DeleteSessionDialog } from "./DeleteSessionDialog"; import { SessionCard } from "./SessionCard"; import { Card } from "@/components/ui/card"; @@ -10,6 +11,9 @@ import { Search, Trash2, Pencil, X } from "lucide-react"; interface SessionListProps { opcodeUrl: string; directory?: string; + directories?: string[]; + createDirectory?: string; + directoryLabels?: Record; activeSessionID?: string; onSelectSession: (sessionID: string) => void; } @@ -17,16 +21,29 @@ interface SessionListProps { export const SessionList = ({ opcodeUrl, directory, + directories, + createDirectory, + directoryLabels, activeSessionID, onSelectSession, }: SessionListProps) => { - const { data: sessions, isLoading } = useSessions(opcodeUrl, directory); - const deleteSession = useDeleteSession(opcodeUrl, directory); - const createSession = useCreateSession(opcodeUrl, directory, (newSession) => { + const directoriesList = useMemo(() => { + const source = directories && directories.length > 0 ? directories : directory ? [directory] : []; + return Array.from(new Set(source.filter(Boolean))); + }, [directory, directories]); + const directorySet = useMemo(() => new Set(directoriesList), [directoriesList]); + const primaryDirectory = directoriesList[0]; + const sessionCreateDirectory = createDirectory ?? primaryDirectory; + const getSessionSelectionKey = useCallback((session: { id: string; directory?: string }) => + `${session.directory ?? primaryDirectory ?? ''}:${session.id}`, + [primaryDirectory]); + const { data: sessions, isLoading } = useSessionsAcrossDirectories(opcodeUrl, directoriesList); + const deleteSession = useDeleteSession(opcodeUrl, directoriesList); + const createSession = useCreateSession(opcodeUrl, sessionCreateDirectory, (newSession) => { onSelectSession(newSession.id); }); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); - const [sessionToDelete, setSessionToDelete] = useState(null); + const [sessionToDelete, setSessionToDelete] = useState(null); const [searchQuery, setSearchQuery] = useState(""); const [selectedSessions, setSelectedSessions] = useState>(new Set()); const [manageMode, setManageMode] = useState(false); @@ -36,7 +53,7 @@ export const SessionList = ({ let filtered = sessions.filter((session) => { if (session.parentID) return false; - if (directory && session.directory && session.directory !== directory) return false; + if (directorySet.size > 0 && session.directory && !directorySet.has(session.directory)) return false; return true; }); @@ -47,8 +64,16 @@ export const SessionList = ({ ); } - return filtered.sort((a, b) => b.time.updated - a.time.updated); - }, [sessions, searchQuery, directory]); + const uniqueSessions = new Map(); + filtered.forEach((session) => { + const key = getSessionSelectionKey(session); + if (!uniqueSessions.has(key)) { + uniqueSessions.set(key, session); + } + }); + + return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated); + }, [sessions, searchQuery, directorySet, getSessionSelectionKey]); const todaySessions = useMemo(() => { const today = new Date(); @@ -84,9 +109,20 @@ export const SessionList = ({ ); } - const handleDelete = (sessionId: string, e: React.MouseEvent) => { + const getDeleteTarget = (session: { id: string; directory?: string; workspaceID?: string }): DeleteSessionTarget => { + const target: Extract = { + id: session.id, + directory: session.directory ?? primaryDirectory, + }; + if (session.workspaceID) { + target.workspaceID = session.workspaceID; + } + return target; + }; + + const handleDelete = (session: { id: string; directory?: string; workspaceID?: string }, e: React.MouseEvent) => { e.stopPropagation(); - setSessionToDelete(sessionId); + setSessionToDelete(getDeleteTarget(session)); setDeleteDialogOpen(true); }; @@ -107,31 +143,36 @@ export const SessionList = ({ setManageMode(false); }; - const toggleSessionSelection = (sessionId: string, selected: boolean) => { + const toggleSessionSelection = (session: { id: string; directory?: string }, selected: boolean) => { + const selectionKey = getSessionSelectionKey(session); const newSelected = new Set(selectedSessions); if (selected) { - newSelected.add(sessionId); + newSelected.add(selectionKey); } else { - newSelected.delete(sessionId); + newSelected.delete(selectionKey); } setSelectedSessions(newSelected); }; const allVisibleSelected = filteredSessions.length > 0 && - filteredSessions.every((s) => selectedSessions.has(s.id)); + filteredSessions.every((session) => selectedSessions.has(getSessionSelectionKey(session))); const toggleSelectAll = () => { if (allVisibleSelected) { setSelectedSessions(new Set()); } else { - setSelectedSessions(new Set(filteredSessions.map((s) => s.id))); + setSelectedSessions(new Set(filteredSessions.map(getSessionSelectionKey))); } }; const handleBulkDelete = () => { if (selectedSessions.size > 0) { - setSessionToDelete(Array.from(selectedSessions)); + const selectedTargets = filteredSessions + .filter((session) => selectedSessions.has(getSessionSelectionKey(session))) + .map(getDeleteTarget); + if (selectedTargets.length === 0) return; + setSessionToDelete(selectedTargets); setDeleteDialogOpen(true); } }; @@ -183,6 +224,7 @@ export const SessionList = ({ + + {isOpen && ( +
+ {needsRestart && ( + + + + Restart the OpenCode server to apply environment variable changes. + + + )} + +
+
+
Default variables
+ {DEFAULT_SERVER_ENV_VARS.map((envVar) => { + const isEnabled = !disabledDefaultSet.has(envVar.key) + + return ( +
+
+
{envVar.key}={envVar.value}
+

+ Required for OpenCode workspace listing and deletion. +

+
+ handleDefaultToggle(envVar.key, checked)} + aria-label={`Toggle ${envVar.key}`} + /> +
+ ) + })} +
+ + {envVars.map((envVar, index) => { + const isBlocked = blockedSet.has(envVar.key.trim()) + + return ( +
+
+ handleChange(index, 'key', event.target.value)} + placeholder="VARIABLE_NAME" + className={`font-mono ${isBlocked ? 'border-destructive' : ''}`} + /> + handleChange(index, 'value', event.target.value)} + placeholder="value" + className="font-mono" + /> +
+ +
+ ) + })} + {blockedKeys.length > 0 && ( +

+ Reserved keys cannot be overridden: {blockedKeys.join(', ')} +

+ )} +
+ +
+ + +
+ +

+ Variables are injected into the OpenCode server process at startup. + Changes require a server restart. +

+
+ )} + + ) +} diff --git a/frontend/src/components/settings/SettingsDialog.tsx b/frontend/src/components/settings/SettingsDialog.tsx index d1720183..b9a3ca0a 100644 --- a/frontend/src/components/settings/SettingsDialog.tsx +++ b/frontend/src/components/settings/SettingsDialog.tsx @@ -5,6 +5,7 @@ import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts' import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager' import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings' import { ManagerTokenSettings } from '@/components/settings/ManagerTokenSettings' +import { ServerEnvVarsSettings } from '@/components/settings/ServerEnvVarsSettings' import { ServerHealthStatus } from '@/components/settings/ServerHealthStatus' import { ProviderSettings } from '@/components/settings/ProviderSettings' import { AccountSettings } from '@/components/settings/AccountSettings' @@ -163,6 +164,7 @@ export function SettingsDialog() { + @@ -228,14 +230,15 @@ export function SettingsDialog() { {mobileView === 'voice' &&
} {mobileView === 'git' &&
} {mobileView === 'shortcuts' &&
} - {mobileView === 'opencode' && ( -
- - - - -
- )} + {mobileView === 'opencode' && ( +
+ + + + + +
+ )} {mobileView === 'providers' &&
} diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx new file mode 100644 index 00000000..34483c8b --- /dev/null +++ b/frontend/src/hooks/useOpenCode.test.tsx @@ -0,0 +1,84 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook } from '@testing-library/react' +import type { ReactNode } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useDeleteSession } from './useOpenCode' + +vi.mock('../lib/toast', () => ({ + showToast: { + success: vi.fn(), + error: vi.fn(), + }, +})) + +describe('useDeleteSession', () => { + const fetchMock = vi.fn() + + beforeEach(() => { + fetchMock.mockReset() + vi.stubGlobal('fetch', fetchMock) + }) + + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('falls back to workspace delete for stale workspace session deletes', async () => { + fetchMock + .mockResolvedValueOnce(new Response('Workspace not found: wrk_stale', { status: 500 })) + .mockResolvedValueOnce(new Response(null, { status: 204 })) + + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + + const { result } = renderHook(() => useDeleteSession('/api/opencode', ['/w/stale']), { wrapper }) + + await act(async () => { + await result.current.mutateAsync([ + { id: 'ses_1', directory: '/w/stale', workspaceID: 'wrk_stale' }, + { id: 'ses_2', directory: '/w/stale', workspaceID: 'wrk_stale' }, + ]) + }) + + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(fetchMock).toHaveBeenNthCalledWith( + 1, + 'http://localhost/api/opencode/session/ses_1?directory=%2Fw%2Fstale', + expect.objectContaining({ method: 'DELETE' }), + ) + expect(fetchMock).toHaveBeenNthCalledWith( + 2, + 'http://localhost/api/opencode/experimental/workspace/wrk_stale?directory=%2Fw%2Fstale', + expect.objectContaining({ method: 'DELETE' }), + ) + }) + + it('falls back to workspace delete for OpenCode unknown session delete failures', async () => { + fetchMock + .mockResolvedValueOnce(new Response(JSON.stringify({ + name: 'UnknownError', + data: { message: 'Unexpected server error. Check server logs for details.' }, + }), { status: 500, headers: { 'Content-Type': 'application/json' } })) + .mockResolvedValueOnce(new Response(null, { status: 204 })) + + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ) + + const { result } = renderHook(() => useDeleteSession('/api/opencode', ['/w/existing']), { wrapper }) + + await act(async () => { + await result.current.mutateAsync([{ id: 'ses_1', directory: '/w/existing', workspaceID: 'wrk_existing' }]) + }) + + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(fetchMock).toHaveBeenNthCalledWith( + 2, + 'http://localhost/api/opencode/experimental/workspace/wrk_existing?directory=%2Fw%2Fexisting', + expect.objectContaining({ method: 'DELETE' }), + ) + }) +}) diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 91dcd44a..acceded3 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -1,4 +1,4 @@ -import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { useQueries, useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useMemo, useRef, useEffect, useCallback } from "react"; import { OpenCodeClient } from "../api/opencode"; import { FetchError } from "../api/fetchWrapper"; @@ -36,17 +36,33 @@ export const useOpenCodeClient = (opcodeUrl: string | null | undefined, director ); }; -export const useSessions = (opcodeUrl: string | null | undefined, directory?: string) => { - const client = useOpenCodeClient(opcodeUrl, directory); - - return useQuery({ - queryKey: ["opencode", "sessions", opcodeUrl, directory], - queryFn: () => client!.listSessions(), - enabled: !!client, - refetchOnWindowFocus: true, - refetchOnReconnect: true, - staleTime: 10000, +export const useSessionsAcrossDirectories = ( + opcodeUrl: string | null | undefined, + directories: string[], +) => { + const uniqueDirectories = useMemo( + () => Array.from(new Set(directories.filter(Boolean))), + [directories], + ); + const directoryKey = uniqueDirectories.join('|'); + const queries = useQueries({ + queries: uniqueDirectories.map((directory) => ({ + queryKey: ["opencode", "sessions", opcodeUrl, directory], + queryFn: () => new OpenCodeClient(opcodeUrl!, directory).listSessions(), + enabled: !!opcodeUrl && !!directory, + refetchOnWindowFocus: true, + refetchOnReconnect: true, + staleTime: 10000, + })), }); + + return useMemo(() => { + const data = queries.flatMap((q) => q.data ?? []); + const isLoading = queries.some((q) => q.isLoading); + const isError = queries.some((q) => q.isError); + return { data, isLoading, isError }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [directoryKey, queries.map((q) => q.dataUpdatedAt).join('|'), queries.map((q) => q.isLoading).join('|')]); }; export const useSession = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => { @@ -112,33 +128,114 @@ export const useCreateSession = ( }); }; -export const useDeleteSession = (opcodeUrl: string | null | undefined, directory?: string) => { +export type DeleteSessionTarget = string | { id: string; directory?: string; workspaceID?: string }; + +const getDeleteSessionTargetId = (target: DeleteSessionTarget) => + typeof target === 'string' ? target : target.id; + +const getDeleteSessionTargetDirectory = (target: DeleteSessionTarget, fallbackDirectory?: string) => + typeof target === 'string' ? fallbackDirectory : target.directory ?? fallbackDirectory; + +const getDeleteSessionTargetWorkspaceID = (target: DeleteSessionTarget) => + typeof target === 'string' ? undefined : target.workspaceID; + +const getDeleteSessionTargetKey = (target: DeleteSessionTarget, fallbackDirectory?: string) => + `${getDeleteSessionTargetDirectory(target, fallbackDirectory) ?? ''}:${getDeleteSessionTargetId(target)}`; + +const isMissingWorkspaceError = (error: unknown) => + error instanceof Error && error.message.includes('Workspace not found:'); + +const shouldDeleteWorkspaceForSessionDeleteError = (error: unknown) => + isMissingWorkspaceError(error) || + (error instanceof FetchError && + error.statusCode === 500 && + (error.message.includes('Unexpected server error') || error.message === 'Request failed')); + +export const useDeleteSession = (opcodeUrl: string | null | undefined, directory?: string | string[]) => { const queryClient = useQueryClient(); - const client = useOpenCodeClient(opcodeUrl, directory); + const directories = useMemo( + () => (Array.isArray(directory) ? directory : directory ? [directory] : []), + [directory], + ); + const primaryDirectory = directories[0]; return useMutation({ - mutationFn: async (sessionIDs: string | string[]) => { - if (!client) { + mutationFn: async (sessionIDs: DeleteSessionTarget | DeleteSessionTarget[]) => { + if (!opcodeUrl) { throw new Error('OpenCode client not available'); } - const ids = Array.isArray(sessionIDs) ? sessionIDs : [sessionIDs] + const targets = Array.from( + new Map( + (Array.isArray(sessionIDs) ? sessionIDs : [sessionIDs]).map((target) => [ + getDeleteSessionTargetKey(target, primaryDirectory), + target, + ]), + ).values(), + ) - const deletePromises = ids.map(async (sessionID) => { - await client.deleteSession(sessionID); - }) - - const results = await Promise.allSettled(deletePromises) + const results: PromiseSettledResult[] = [] + const removedWorkspaces = new Set() + for (const target of targets) { + const workspaceID = getDeleteSessionTargetWorkspaceID(target) + if (workspaceID && removedWorkspaces.has(workspaceID)) { + results.push({ status: 'fulfilled', value: undefined }) + continue + } + + const client = new OpenCodeClient( + opcodeUrl, + getDeleteSessionTargetDirectory(target, primaryDirectory), + ) + try { + await client.deleteSession(getDeleteSessionTargetId(target)) + results.push({ status: 'fulfilled', value: undefined }) + } catch (reason) { + if (workspaceID && shouldDeleteWorkspaceForSessionDeleteError(reason)) { + try { + await client.deleteWorkspace(workspaceID) + removedWorkspaces.add(workspaceID) + results.push({ status: 'fulfilled', value: undefined }) + continue + } catch (workspaceReason) { + results.push({ status: 'rejected', reason: workspaceReason }) + continue + } + } + results.push({ status: 'rejected', reason }) + } + } const failures = results.filter(result => result.status === 'rejected') if (failures.length > 0) { throw new Error(`Failed to delete ${failures.length} session(s)`) } - return results + return { deleted: targets.length, results } }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, directory] }); + onSuccess: ({ deleted }) => { + showToast.success(deleted === 1 ? 'Session deleted' : `${deleted} sessions deleted`); + }, + onError: () => { + showToast.error('Failed to delete sessions'); + }, + onSettled: (_data, _error, variables) => { + const targets = variables ? (Array.isArray(variables) ? variables : [variables]) : []; + const affectedDirectories = new Set([ + ...directories, + ...targets + .map((target) => getDeleteSessionTargetDirectory(target)) + .filter((value): value is string => !!value), + ]); + + if (affectedDirectories.size === 0) { + queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl] }); + return; + } + + for (const affectedDirectory of affectedDirectories) { + queryClient.invalidateQueries({ queryKey: ["opencode", "sessions", opcodeUrl, affectedDirectory] }); + } }, }); }; diff --git a/frontend/src/hooks/useRepoSiblings.ts b/frontend/src/hooks/useRepoSiblings.ts new file mode 100644 index 00000000..28035bad --- /dev/null +++ b/frontend/src/hooks/useRepoSiblings.ts @@ -0,0 +1,59 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { createRepoWorkspace, deleteRepoWorkspace, getRepoSiblings, type RepoSibling } from '@/api/repos' +import { showToast } from '@/lib/toast' + +export function useRepoSiblings(repoId: number | undefined) { + return useQuery({ + queryKey: ['repo', 'siblings', repoId], + queryFn: () => getRepoSiblings(repoId!), + enabled: !!repoId && repoId > 0, + staleTime: 30_000, + }) +} + +export function useDeleteRepoWorkspaces(repoId: number | undefined) { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: async (workspaceIds: string[]) => { + if (!repoId) throw new Error('Repo id is required') + const results = await Promise.allSettled( + workspaceIds.map((workspaceId) => deleteRepoWorkspace(repoId, workspaceId)), + ) + const failed = results.filter((result) => result.status === 'rejected').length + return { total: workspaceIds.length, failed } + }, + onSuccess: ({ total, failed }) => { + queryClient.invalidateQueries({ queryKey: ['repo', 'siblings', repoId] }) + const deleted = total - failed + if (failed === 0) { + showToast.success(deleted === 1 ? 'Workspace deleted' : `${deleted} workspaces deleted`) + } else if (deleted === 0) { + showToast.error('Failed to delete workspaces') + } else { + showToast.error(`Deleted ${deleted}, failed ${failed}`) + } + }, + onError: () => { + showToast.error('Failed to delete workspaces') + }, + }) +} + +export function useCreateRepoWorkspace(repoId: number | undefined) { + const queryClient = useQueryClient() + + return useMutation({ + mutationFn: async () => { + if (!repoId) throw new Error('Repo id is required') + return createRepoWorkspace(repoId) + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['repo', 'siblings', repoId] }) + showToast.success('Workspace created') + }, + onError: () => { + showToast.error('Failed to create workspace') + }, + }) +} diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 6d0d351a..5a453405 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState, useCallback } from 'react' +import { useEffect, useRef, useState, useCallback, useMemo } from 'react' import { useQueryClient } from '@tanstack/react-query' import { useOpenCodeClient } from './useOpenCode' import type { SSEEvent, MessageWithParts, Session } from '@/api/types' @@ -46,8 +46,17 @@ const handleRestartServer = async () => { } -export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, currentSessionId?: string) => { - const client = useOpenCodeClient(opcodeUrl, directory) +export const useSSE = (opcodeUrl: string | null | undefined, directory?: string | string[], currentSessionId?: string) => { + const directoriesList = useMemo(() => { + if (!directory) return [] as string[] + if (Array.isArray(directory)) return directory.filter(Boolean) + return [directory] + }, [directory]) + const directoryKey = directoriesList.join('|') + const primaryDirectory = directoriesList[0] + // eslint-disable-next-line react-hooks/exhaustive-deps + const directorySet = useMemo(() => new Set(directoriesList), [directoryKey]) + const client = useOpenCodeClient(opcodeUrl, primaryDirectory) const queryClient = useQueryClient() const mountedRef = useRef(true) const sessionIdRef = useRef(currentSessionId) @@ -63,31 +72,40 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const batcherRef = useRef | null>(null) useEffect(() => { - if (!opcodeUrl || !directory) { + if (!opcodeUrl || !primaryDirectory) { batcherRef.current?.destroy() batcherRef.current = null return } - batcherRef.current = createPartsBatcher(queryClient, opcodeUrl, directory) + batcherRef.current = createPartsBatcher(queryClient, opcodeUrl, primaryDirectory) return () => { batcherRef.current?.destroy() batcherRef.current = null } - }, [queryClient, opcodeUrl, directory]) + }, [queryClient, opcodeUrl, primaryDirectory]) + + const resolveCacheDirectory = useCallback( + (eventDirectory: string | undefined): string | undefined => { + if (!eventDirectory) return primaryDirectory + return directorySet.has(eventDirectory) ? eventDirectory : primaryDirectory + }, + [directorySet, primaryDirectory], + ) const handleSSEEvent = useCallback((event: SSEEvent) => { const eventDirectory = getEventDirectory(event) - if (eventDirectory && directory && eventDirectory !== directory) return + if (eventDirectory && directorySet.size > 0 && !directorySet.has(eventDirectory)) return + const cacheDirectory = resolveCacheDirectory(eventDirectory) switch (event.type) { case 'session.created': case 'session.updated': if ('info' in event.properties) { const session = event.properties.info - const sessionQueryKey = ['opencode', 'session', opcodeUrl, session.id, directory] - const sessionsQueryKey = ['opencode', 'sessions', opcodeUrl, directory] + const sessionQueryKey = ['opencode', 'session', opcodeUrl, session.id, cacheDirectory] + const sessionsQueryKey = ['opencode', 'sessions', opcodeUrl, cacheDirectory] queryClient.setQueryData(sessionQueryKey, session) @@ -104,14 +122,14 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, queryClient.invalidateQueries({ queryKey: sessionsQueryKey }) break } - queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] }) + queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, cacheDirectory] }) break case 'session.deleted': - queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] }) + queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, cacheDirectory] }) if ('sessionID' in event.properties) { queryClient.invalidateQueries({ - queryKey: ['opencode', 'session', opcodeUrl, event.properties.sessionID, directory] + queryKey: ['opencode', 'session', opcodeUrl, event.properties.sessionID, cacheDirectory] }) } break @@ -145,7 +163,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const { info } = event.properties const sessionID = info.sessionID - const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory] + const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, cacheDirectory] const currentData = queryClient.getQueryData(messagesQueryKey) if (!currentData) { queryClient.invalidateQueries({ queryKey: messagesQueryKey }) @@ -178,7 +196,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const { sessionID, messageID } = event.properties queryClient.setQueryData( - ['opencode', 'messages', opcodeUrl, sessionID, directory], + ['opencode', 'messages', opcodeUrl, sessionID, cacheDirectory], (old) => { if (!old) return old return old.filter(msgWithParts => msgWithParts.info.id !== messageID) @@ -205,7 +223,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, showToast.dismiss(`compact-${sessionID}`) showToast.success('Session compacted') queryClient.invalidateQueries({ - queryKey: ['opencode', 'messages', opcodeUrl, sessionID, directory] + queryKey: ['opencode', 'messages', opcodeUrl, sessionID, cacheDirectory] }) break } @@ -219,7 +237,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, batcherRef.current?.flush() - const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory] + const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, cacheDirectory] const currentData = queryClient.getQueryData(messagesQueryKey) if (!currentData) break @@ -268,7 +286,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const { sessionID, todos } = event.properties setSessionTodos(sessionID, todos) queryClient.invalidateQueries({ - queryKey: ['opencode', 'todos', opcodeUrl, sessionID, directory] + queryKey: ['opencode', 'todos', opcodeUrl, sessionID, cacheDirectory] }) } break @@ -317,7 +335,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, if (!('sessionID' in event.properties)) break const { sessionID } = event.properties queryClient.invalidateQueries({ - queryKey: ['opencode', 'messages', opcodeUrl, sessionID, directory] + queryKey: ['opencode', 'messages', opcodeUrl, sessionID, cacheDirectory] }) break } @@ -325,10 +343,10 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, default: break } - }, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos, currentSessionId]) + }, [queryClient, opcodeUrl, directorySet, resolveCacheDirectory, setSessionStatus, setSessionTodos, currentSessionId]) const fetchInitialData = useCallback(async () => { - if (!client || !directory || !mountedRef.current) return + if (!client || !primaryDirectory || !mountedRef.current) return const syncVersion = ++statusSyncVersionRef.current try { @@ -341,27 +359,27 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, throw err } } - }, [client, directory, replaceSessionStatuses]) + }, [client, primaryDirectory, replaceSessionStatuses]) const syncCurrentSession = useCallback(() => { const sessionId = sessionIdRef.current - if (!sessionId || !opcodeUrl || !directory) return + if (!sessionId || !opcodeUrl || !primaryDirectory) return queryClient.invalidateQueries({ - queryKey: ['opencode', 'session', opcodeUrl, sessionId, directory], + queryKey: ['opencode', 'session', opcodeUrl, sessionId, primaryDirectory], }) queryClient.invalidateQueries({ - queryKey: ['opencode', 'messages', opcodeUrl, sessionId, directory], + queryKey: ['opencode', 'messages', opcodeUrl, sessionId, primaryDirectory], }) queryClient.invalidateQueries({ - queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, directory], + queryKey: ['opencode', 'pending-actions', opcodeUrl, sessionId, primaryDirectory], }) - }, [queryClient, opcodeUrl, directory]) + }, [queryClient, opcodeUrl, primaryDirectory]) useEffect(() => { mountedRef.current = true - if (!opcodeUrl || !directory) { + if (!opcodeUrl || directoriesList.length === 0) { statusSyncVersionRef.current += 1 setIsConnected(false) setIsReconnecting(false) @@ -389,8 +407,8 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } } - const subscription = openCodeEventStream.subscribeToDirectory({ - directory, + const subscription = openCodeEventStream.subscribeGlobalMonitor({ + directories: directoriesList, onEvent: handleMessage, onStatusChange: handleStatusChange, }) @@ -420,7 +438,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, eventStreamSubscriptionRef.current = null } } - }, [opcodeUrl, directory, handleSSEEvent, fetchInitialData, syncCurrentSession]) + }, [opcodeUrl, directoryKey, directoriesList, handleSSEEvent, fetchInitialData, syncCurrentSession]) useEffect(() => { if (isConnected && document.visibilityState === 'visible') { diff --git a/frontend/src/hooks/useWorktreeTab.ts b/frontend/src/hooks/useWorktreeTab.ts new file mode 100644 index 00000000..f38e278d --- /dev/null +++ b/frontend/src/hooks/useWorktreeTab.ts @@ -0,0 +1,40 @@ +import { useCallback, useEffect, useMemo, useRef } from 'react' +import { useNavigate, useLocation } from 'react-router-dom' + +export type WorktreeTabValue = 'repo' | 'workspaces' + +export interface UseWorktreeTabReturn { + activeTab: WorktreeTabValue + setActiveTab: (tab: WorktreeTabValue) => void +} + +export function useWorktreeTab(): UseWorktreeTabReturn { + const navigate = useNavigate() + const location = useLocation() + const searchRef = useRef(location.search) + + useEffect(() => { + searchRef.current = location.search + }, [location.search]) + + const activeTab = useMemo(() => { + const searchParams = new URLSearchParams(location.search) + const tabParam = searchParams.get('tab') + return tabParam === 'workspaces' ? 'workspaces' : 'repo' + }, [location.search]) + + const setActiveTab = useCallback((tab: WorktreeTabValue) => { + const newParams = new URLSearchParams(searchRef.current) + if (tab === 'repo') { + newParams.delete('tab') + } else { + newParams.set('tab', tab) + } + navigate({ search: newParams.toString() }, { replace: true }) + }, [navigate]) + + return { + activeTab, + setActiveTab, + } +} diff --git a/frontend/src/lib/navigation.test.ts b/frontend/src/lib/navigation.test.ts index d5bc4f42..1df8aa6b 100644 --- a/frontend/src/lib/navigation.test.ts +++ b/frontend/src/lib/navigation.test.ts @@ -45,6 +45,19 @@ describe('getSessionListPath', () => { expect(getSessionListPath(42, true)).toBe('/assistant?view=sessions'); expect(getSessionListPath('123', true)).toBe('/assistant?view=sessions'); }); + + it('includes tab param when tab is workspaces', () => { + expect(getSessionListPath(42, false, 'workspaces')).toBe('/repos/42?tab=workspaces'); + }); + + it('omits tab param for repo/default tab', () => { + expect(getSessionListPath(42, false, 'repo')).toBe('/repos/42'); + expect(getSessionListPath(42, false, undefined)).toBe('/repos/42'); + }); + + it('ignores tab param for assistant sessions', () => { + expect(getSessionListPath(42, true, 'workspaces')).toBe('/assistant?view=sessions'); + }); }); describe('getSwipeBackTarget', () => { @@ -67,6 +80,13 @@ describe('getSwipeBackTarget', () => { expect(getSwipeBackTarget('/repos/42/sessions/abc', '?assistant=0')).toBe('/repos/42'); expect(getSwipeBackTarget('/repos/42/sessions/abc', '?other=value')).toBe('/repos/42'); }); + + it('preserves tab param in back target', () => { + expect(getSwipeBackTarget('/repos/42/sessions/abc', '?tab=workspaces')).toBe('/repos/42?tab=workspaces'); + expect(getSwipeBackTarget('/repos/42/sessions/abc', '?tab=workspaces&assistant=1')).toBe( + '/assistant?view=sessions' + ); + }); }); describe('assistant route', () => { diff --git a/frontend/src/lib/navigation.ts b/frontend/src/lib/navigation.ts index a4192746..3234dd83 100644 --- a/frontend/src/lib/navigation.ts +++ b/frontend/src/lib/navigation.ts @@ -10,11 +10,15 @@ export function isAssistantPath(pathname: string): boolean { return pathname === '/assistant' || /^\/repos\/[^/]+\/assistant$/.test(pathname); } -export function getSessionListPath(repoId: string | number, isAssistantSession: boolean): string { +export function getSessionListPath(repoId: string | number, isAssistantSession: boolean, tab?: string): string { if (isAssistantSession) { return getAssistantSessionListPath(); } - return `/repos/${String(repoId)}`; + const base = `/repos/${String(repoId)}`; + if (tab && tab !== 'repo') { + return `${base}?tab=${tab}`; + } + return base; } export function getSwipeBackTarget(pathname: string, search = ''): string | null { @@ -25,7 +29,8 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null const repoId = match[1]; const params = new URLSearchParams(search); const isAssistant = params.get('assistant') === '1'; - return getSessionListPath(repoId, isAssistant); + const tab = params.get('tab') ?? undefined; + return getSessionListPath(repoId, isAssistant, tab); } if (isAssistantPath(pathname)) { diff --git a/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts b/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts index a0b2a72e..8ae73320 100644 --- a/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts +++ b/frontend/src/lib/opencode-event-stream/__tests__/openCodeEventStream.test.ts @@ -83,7 +83,7 @@ describe('OpenCodeEventStream', () => { const transport = new TestEventStreamTransport() const stream = new OpenCodeEventStream({ transport }) - const subscription = stream.subscribeToDirectory({ directory: '/repo', onEvent: vi.fn() }) + const subscription = stream.subscribeGlobalMonitor({ directories: ['/repo'], onEvent: vi.fn() }) transport.openConnection() transport.connected('client-1') subscription.reportVisibility(true, 'session-1') diff --git a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts index 1c58caf7..62c6d4c2 100644 --- a/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts +++ b/frontend/src/lib/opencode-event-stream/openCodeEventStream.ts @@ -3,7 +3,6 @@ import { createBrowserEventStreamTransport } from './browserTransport' import type { EventStreamHealthState, EventStreamStatusHandler, - EventStreamSubscription, EventStreamTransport, GlobalMonitorSubscription, OpenCodeEventHandler, @@ -58,22 +57,6 @@ export class OpenCodeEventStream { } } - subscribeToDirectory(input: { - directory: string - onEvent: OpenCodeEventHandler - onStatusChange?: EventStreamStatusHandler - onHealthChange?: (state: EventStreamHealthState) => void - }): EventStreamSubscription { - const id = this.addSubscriber(input.onEvent, input.onStatusChange, input.onHealthChange) - this.updateSubscriberDirectories(id, [input.directory]) - - return { - reconnect: () => this.reconnect(), - reportVisibility: (visible, activeSessionId) => this.reportVisibility(visible, activeSessionId), - dispose: () => this.removeSubscriber(id), - } - } - getHealth(): EventStreamHealthState { return this.buildHealth() } diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index f00b46fb..b2961d1d 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -1,7 +1,7 @@ -import { useState } from "react"; +import { useCallback, useEffect, useMemo, useState } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { getRepo } from "@/api/repos"; +import { getRepo, workspaceLabel } from "@/api/repos"; import { SessionList } from "@/components/session/SessionList"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Header } from "@/components/ui/header"; @@ -11,12 +11,17 @@ import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; import { SourceControlPanel } from "@/components/source-control"; import { useCreateSession } from "@/hooks/useOpenCode"; import { useRepoActivity } from "@/hooks/useRepoActivity"; +import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings"; import { useSSE } from "@/hooks/useSSE"; import { useDialogParam } from "@/hooks/useDialogParam"; +import { useWorktreeTab } from "@/hooks/useWorktreeTab"; +import { WorktreeTabs } from "@/components/repo/WorktreeTabs"; +import { WorkspaceManager } from "@/components/repo/WorkspaceManager"; import { OPENCODE_API_ENDPOINT } from "@/config"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; -import { GitBranch, Plus, Loader2 } from "lucide-react"; +import { GitBranch, Plus, Loader2, Layers } from "lucide-react"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"; import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"; import { invalidateConfigCaches } from "@/lib/queryInvalidation"; @@ -34,6 +39,10 @@ export function RepoDetail() { const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills'); const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl'); const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions'); + const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false); + const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false); + const [activeWorkspaceDirectory, setActiveWorkspaceDirectory] = useState(); + const { activeTab, setActiveTab } = useWorktreeTab(); const { data: repo, isLoading: repoLoading } = useQuery({ queryKey: ["repo", repoId], @@ -43,27 +52,105 @@ export function RepoDetail() { useRepoActivity(repoId, Boolean(repo)); + const { data: siblings } = useRepoSiblings(repoId); + const deleteWorkspaces = useDeleteRepoWorkspaces(repoId); + const createWorkspace = useCreateRepoWorkspace(repoId); + const opcodeUrl = OPENCODE_API_ENDPOINT; - - const repoDirectory = repo?.fullPath; - useSSE(opcodeUrl, repoDirectory); + const workspaceSiblings = useMemo( + () => (siblings ?? []).filter((sibling) => !!sibling.workspaceId && !!sibling.fullPath), + [siblings], + ); - const createSessionMutation = useCreateSession(opcodeUrl, repoDirectory, (session) => { - navigate(`/repos/${repoId}/sessions/${session.id}`); + const workspaceDirectories = useMemo( + () => workspaceSiblings.map((sibling) => sibling.fullPath).filter(Boolean), + [workspaceSiblings], + ); + + const baseDirectory = repo?.fullPath; + const subscriptionDirectories = useMemo(() => { + const set = new Set(); + if (baseDirectory) set.add(baseDirectory); + workspaceDirectories.forEach((dir) => set.add(dir)); + return Array.from(set); + }, [baseDirectory, workspaceDirectories]); + + useEffect(() => { + if (workspaceDirectories.length === 0) { + setActiveWorkspaceDirectory(undefined); + return; + } + + setActiveWorkspaceDirectory((current) => ( + current && workspaceDirectories.includes(current) ? current : workspaceDirectories[0] + )); + }, [workspaceDirectories]); + + const workspaceComposerDirectory = activeWorkspaceDirectory ?? workspaceDirectories[0]; + const sessionListDirectories = activeTab === 'workspaces' ? workspaceDirectories : (baseDirectory ? [baseDirectory] : []); + const composerDirectory = activeTab === 'workspaces' ? workspaceComposerDirectory : baseDirectory; + + const directoryLabels = useMemo(() => { + const labels: Record = {}; + workspaceSiblings.forEach((sibling) => { + if (sibling.fullPath) { + labels[sibling.fullPath] = workspaceLabel(sibling); + } + }); + return labels; + }, [workspaceSiblings]); + + const activeWorkspaceLabel = activeWorkspaceDirectory ? directoryLabels[activeWorkspaceDirectory] : undefined; + + useSSE(opcodeUrl, subscriptionDirectories); + + const sessionUrl = useCallback( + (sessionId: string) => { + const base = `/repos/${repoId}/sessions/${sessionId}`; + return activeTab === 'workspaces' ? `${base}?tab=workspaces` : base; + }, + [repoId, activeTab], + ); + + const createSessionMutation = useCreateSession(opcodeUrl, composerDirectory, (session) => { + navigate(sessionUrl(session.id)); }); const handleCreateSession = async (options?: { agentSlug?: string; promptSlug?: string; }) => { + if (activeTab === 'workspaces' && !workspaceComposerDirectory) { + setCreateWorkspaceOpen(true); + return; + } + await createSessionMutation.mutateAsync({ agent: options?.agentSlug, }); }; + const handleCreateWorkspace = async () => { + const workspace = await createWorkspace.mutateAsync(); + if (workspace.directory) { + setActiveWorkspaceDirectory(workspace.directory); + } + setActiveTab('workspaces'); + setCreateWorkspaceOpen(false); + }; + + const handleOpenWorkspaceSelector = () => { + if (workspaceSiblings.length === 0) { + setCreateWorkspaceOpen(true); + return; + } + setActiveTab('workspaces'); + setWorkspaceSelectorOpen(true); + }; + const handleSelectSession = (sessionId: string) => { - navigate(`/repos/${repoId}/sessions/${sessionId}`); + navigate(sessionUrl(sessionId)); }; useSidebarAction('new-session', () => { @@ -137,16 +224,46 @@ export function RepoDetail() { + setCreateWorkspaceOpen(true)} + onWorkspaceMenu={handleOpenWorkspaceSelector} + /> + + setCreateWorkspaceOpen(true)} + onDelete={(workspaceIds) => deleteWorkspaces.mutate(workspaceIds)} + isDeleting={deleteWorkspaces.isPending} + /> +
- {opcodeUrl && repoDirectory && ( + {opcodeUrl && sessionListDirectories.length > 0 && ( )}
+ + setFileBrowserOpen(false)} @@ -159,7 +276,7 @@ export function RepoDetail() { ); } + +interface CreateWorkspaceDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + onCreate: () => Promise; + isCreating: boolean; +} + +function CreateWorkspaceDialog({ open, onOpenChange, onCreate, isCreating }: CreateWorkspaceDialogProps) { + return ( + + + + + + Create Workspace + + + Create an OpenCode worktree workspace for this repository. + + +
+
+ + Worktree +
+

+ OpenCode will create and manage a git worktree workspace. +

+
+ + + + +
+
+ ); +} diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index acaae0af..a710bf0c 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -313,8 +313,9 @@ export function SessionDetail() { }, [opcodeUrl, sessionId, repoDirectory, navigate, repoId, sessionRouteSuffix]); const handleCloseSession = useCallback(() => { - navigate(getSessionListPath(repoId, isAssistantSession)) - }, [navigate, repoId, isAssistantSession]) + const tab = new URLSearchParams(location.search).get('tab') ?? undefined; + navigate(getSessionListPath(repoId, isAssistantSession, tab)) + }, [navigate, repoId, isAssistantSession, location.search]) const { leaderActive } = useKeyboardShortcuts({ openModelDialog: () => { @@ -437,7 +438,8 @@ export function SessionDetail() { const workspaceDisplayName = isAssistantSession || !repo ? 'Assistant' : getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath); - const sessionBackPath = getSessionListPath(repoId, isAssistantSession); + const tabFromUrl = new URLSearchParams(location.search).get('tab') ?? undefined; + const sessionBackPath = getSessionListPath(repoId, isAssistantSession, tabFromUrl); return (
; +export const ServerEnvVarSchema = z.object({ + key: z.string().min(1), + value: z.string(), +}); + +type ServerEnvVar = z.infer + +export const DEFAULT_SERVER_ENV_VARS = [ + { + key: 'OPENCODE_EXPERIMENTAL_WORKSPACES', + value: 'true', + }, +] as const satisfies readonly ServerEnvVar[]; + +export const BLOCKED_SERVER_ENV_KEYS = [ + 'OPENCODE_SERVER_PASSWORD', + 'OPENCODE_SERVER_USERNAME', + 'OPENCODE_CONFIG', + 'XDG_DATA_HOME', + 'XDG_STATE_HOME', + 'XDG_CONFIG_HOME', +] as const; + export const DEFAULT_GIT_IDENTITY: GitIdentity = { name: 'OpenCode Agent', email: '', @@ -130,6 +153,8 @@ export const UserPreferencesSchema = z.object({ lastKnownGoodConfig: z.string().optional(), repoOrder: z.array(z.number()).optional(), repoSortMode: z.enum(['recent', 'manual', 'name']).optional(), + serverEnvVars: z.array(ServerEnvVarSchema).optional(), + disabledDefaultServerEnvVars: z.array(z.string()).optional(), }); export const DEFAULT_TTS_CONFIG: TTSConfig = { @@ -177,6 +202,8 @@ export const DEFAULT_USER_PREFERENCES = { stt: DEFAULT_STT_CONFIG, notifications: DEFAULT_NOTIFICATION_PREFERENCES, repoSortMode: 'recent' as const, + serverEnvVars: [] as ServerEnvVar[], + disabledDefaultServerEnvVars: [] as string[], }; export const SettingsResponseSchema = z.object({ diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index f88c6d31..836c2e65 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -9,6 +9,7 @@ import { CreateOpenCodeConfigRequestSchema, UpdateOpenCodeConfigRequestSchema, OpenCodeConfigResponseSchema, + ServerEnvVarSchema, } from '../schemas/settings' import { RepoSchema, @@ -51,6 +52,7 @@ export type UserPreferences = z.infer export type SettingsResponse = z.infer export type UpdateSettingsRequest = z.infer export type CustomCommand = z.infer +export type ServerEnvVar = z.infer export type OpenCodeConfig = z.infer export type OpenCodeConfigInput = z.infer export type CreateOpenCodeConfigRequest = z.infer @@ -90,6 +92,7 @@ export type AssistantSettingsPatch = z.infer