mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
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
This commit is contained in:
1 parent
60ed756a0b
commit
b9236f7f20
38 files changed
+2423
-133
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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<OpenCodeClient['forward']>[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<OpenCodeClient['forward']>[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' })
|
||||
})
|
||||
})
|
||||
@@ -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'))
|
||||
|
||||
@@ -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<unknown>
|
||||
}
|
||||
|
||||
class InMemoryDatabase {
|
||||
private userPreferences = new Map<string, TestUserPreferenceRow>()
|
||||
private schemaMigrations = new Map<number, { name: string; applied_at: number }>()
|
||||
|
||||
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',
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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<string, string> = {}
|
||||
let userEnvVars: Record<string, string> = {}
|
||||
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,
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<string, string>()
|
||||
@@ -66,3 +67,25 @@ export async function resolveProjectId(repoFullPath: string): Promise<string | n
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const mainCheckoutCache = new Map<string, boolean>()
|
||||
|
||||
export async function isGitMainCheckout(repoFullPath: string): Promise<boolean> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<string, string>,
|
||||
openCodeClient?: OpenCodeClient,
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined }>> {
|
||||
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<Array<{
|
||||
id: string
|
||||
type: string
|
||||
name: string | null
|
||||
branch: string | null
|
||||
directory: string | null
|
||||
projectID: string
|
||||
}>>('/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<string, typeof candidates[number]>()
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -29,10 +29,22 @@ function formatDetails(details: unknown): string | undefined {
|
||||
}
|
||||
|
||||
async function handleResponse(response: Response): Promise<never> {
|
||||
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,
|
||||
|
||||
@@ -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',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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(),
|
||||
})
|
||||
|
||||
@@ -38,6 +38,48 @@ export async function getRepo(id: number): Promise<Repo> {
|
||||
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<RepoSibling[]> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/siblings`)
|
||||
}
|
||||
|
||||
export async function deleteRepoWorkspace(repoId: number, workspaceId: string): Promise<void> {
|
||||
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/workspaces/${workspaceId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
export async function createRepoWorkspace(repoId: number): Promise<RepoWorkspace> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteRepo(id: number): Promise<void> {
|
||||
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${id}`, {
|
||||
method: 'DELETE',
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1251,7 +1251,7 @@ return (
|
||||
directory={directory}
|
||||
>
|
||||
<button
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer w-full md:w-auto max-w-[130px] md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto max-w-[110px] md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
>
|
||||
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
|
||||
{hasVariants && currentVariant && (
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { GitBranch, Plus, Search, Trash2 } from 'lucide-react'
|
||||
import { workspaceLabel, type RepoSibling } from '@/api/repos'
|
||||
|
||||
interface WorkspaceManagerProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
workspaces: RepoSibling[]
|
||||
onDelete: (workspaceIds: string[]) => void
|
||||
activeWorkspaceDirectory?: string
|
||||
onActiveWorkspaceChange: (directory: string) => void
|
||||
onCreateWorkspace: () => void
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
export function WorkspaceManager({
|
||||
open,
|
||||
onOpenChange,
|
||||
workspaces,
|
||||
onDelete,
|
||||
activeWorkspaceDirectory,
|
||||
onActiveWorkspaceChange,
|
||||
onCreateWorkspace,
|
||||
isDeleting = false,
|
||||
}: WorkspaceManagerProps) {
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [manageMode, setManageMode] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setSearchQuery('')
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const filteredWorkspaces = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return workspaces
|
||||
|
||||
return workspaces.filter((workspace) => {
|
||||
const haystack = [
|
||||
workspaceLabel(workspace),
|
||||
workspace.fullPath,
|
||||
workspace.workspaceName,
|
||||
workspace.workspaceId,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
return haystack.includes(query)
|
||||
})
|
||||
}, [searchQuery, workspaces])
|
||||
|
||||
const selectableIds = useMemo(
|
||||
() => filteredWorkspaces.map((workspace) => workspace.workspaceId).filter((id): id is string => !!id),
|
||||
[filteredWorkspaces],
|
||||
)
|
||||
|
||||
const allSelected = selectableIds.length > 0 && selectableIds.every((id) => selected.has(id))
|
||||
const selectedCount = selected.size
|
||||
|
||||
const toggle = (workspaceId: string, checked: boolean) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (checked) {
|
||||
next.add(workspaceId)
|
||||
} else {
|
||||
next.delete(workspaceId)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const toggleAll = () => {
|
||||
setSelected(allSelected ? new Set() : new Set(selectableIds))
|
||||
}
|
||||
|
||||
const handleConfirm = () => {
|
||||
onDelete(Array.from(selected))
|
||||
setSelected(new Set())
|
||||
setManageMode(false)
|
||||
setConfirmOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="flex flex-col gap-0 overflow-hidden p-0 sm:max-h-[85vh] sm:max-w-[560px]">
|
||||
<DialogHeader className="border-b border-border px-4 py-4">
|
||||
<DialogTitle>Workspaces</DialogTitle>
|
||||
<DialogDescription>Choose where new sessions should start.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
{manageMode ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all workspaces" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedCount > 0 ? `${selectedCount} selected` : 'Select all'}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{activeWorkspaceDirectory ? 'Selected workspace' : 'Select a workspace'}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => {
|
||||
onOpenChange(false)
|
||||
onCreateWorkspace()
|
||||
}}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" />
|
||||
New
|
||||
</Button>
|
||||
{manageMode ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-destructive hover:text-destructive"
|
||||
disabled={selectedCount === 0 || isDeleting}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => {
|
||||
setSelected(new Set())
|
||||
setManageMode(false)
|
||||
}}
|
||||
>
|
||||
Done
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => setManageMode(true)}
|
||||
>
|
||||
Manage
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={(event) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto pr-1">
|
||||
{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 (
|
||||
<button
|
||||
key={workspaceId}
|
||||
type="button"
|
||||
disabled={!workspace.fullPath}
|
||||
onClick={() => {
|
||||
if (!workspace.fullPath) return
|
||||
onActiveWorkspaceChange(workspace.fullPath)
|
||||
onOpenChange(false)
|
||||
}}
|
||||
className={`flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-sm text-left ${rowClassName}`}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{isActive && <span className="text-xs text-purple-400">Selected</span>}
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{workspace.fullPath}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={workspaceId}
|
||||
className="flex min-h-11 items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm hover:bg-muted/50"
|
||||
>
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
disabled={isDeleting}
|
||||
onCheckedChange={(checked) => toggle(workspaceId, checked === true)}
|
||||
aria-label={`Select workspace ${label}`}
|
||||
/>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{workspace.fullPath}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{filteredWorkspaces.length === 0 && (
|
||||
<div className="rounded-md border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground">
|
||||
No workspaces found
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<DeleteDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
onConfirm={handleConfirm}
|
||||
onCancel={() => 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}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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(
|
||||
<WorktreeTabs workspaces={[]} value="repo" onValueChange={onValueChange} baseLabel="main" />
|
||||
)
|
||||
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(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
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(<WorktreeTabs workspaces={workspaces} value="workspaces" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
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(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
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(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
expect(screen.getByText('(3)')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
<Tabs value={value} onValueChange={(next) => onValueChange(next as WorktreeTabValue)} className="min-w-0">
|
||||
<TabsList className="w-full justify-start overflow-hidden">
|
||||
<TabsTrigger value="repo" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3">
|
||||
<GitBranch className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate">{baseLabel}</span>
|
||||
</TabsTrigger>
|
||||
{hasWorkspaces ? (
|
||||
<>
|
||||
<TabsTrigger value="workspaces" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3" onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<span className="min-w-0 truncate">{workspaceLabel}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">({workspaces.length})</span>
|
||||
</TabsTrigger>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCreateWorkspace}
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-background hover:text-foreground sm:flex-none sm:px-3"
|
||||
>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<span className="min-w-0 truncate">Workspace</span>
|
||||
<Plus className="h-3.5 w-3.5 shrink-0" />
|
||||
</button>
|
||||
)}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<HTMLButtonElement>) => void;
|
||||
@@ -22,6 +23,7 @@ export const SessionCard = ({
|
||||
isSelected,
|
||||
isActive,
|
||||
manageMode,
|
||||
workspaceLabel,
|
||||
onSelect,
|
||||
onToggleSelection,
|
||||
onDelete,
|
||||
@@ -107,6 +109,9 @@ export const SessionCard = ({
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
{workspaceLabel ? (
|
||||
<span className="text-purple-400 truncate max-w-[140px]">{workspaceLabel}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -122,6 +127,9 @@ export const SessionCard = ({
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
{workspaceLabel ? (
|
||||
<span className="text-purple-400 truncate max-w-[120px]">{workspaceLabel}</span>
|
||||
) : null}
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/b', '/w/c']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/a', '/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/b']}
|
||||
createDirectory="/w/b"
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('No sessions yet'))
|
||||
|
||||
expect(createSessionState.directory).toBe('/w/b')
|
||||
expect(createSessionMock).toHaveBeenCalledWith({ agent: undefined })
|
||||
})
|
||||
})
|
||||
@@ -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<string, string>;
|
||||
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<string | string[] | null>(null);
|
||||
const [sessionToDelete, setSessionToDelete] = useState<DeleteSessionTarget | DeleteSessionTarget[] | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(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<string, (typeof filtered)[number]>();
|
||||
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<HTMLButtonElement>) => {
|
||||
const getDeleteTarget = (session: { id: string; directory?: string; workspaceID?: string }): DeleteSessionTarget => {
|
||||
const target: Extract<DeleteSessionTarget, { id: string }> = {
|
||||
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<HTMLButtonElement>) => {
|
||||
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 = ({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
aria-label="Manage sessions"
|
||||
className="shrink-0 size-9"
|
||||
onClick={() => {
|
||||
setManageMode(true);
|
||||
@@ -209,14 +251,15 @@ export const SessionList = ({
|
||||
</div>
|
||||
{todaySessions.map((session) => (
|
||||
<SessionCard
|
||||
key={session.id}
|
||||
key={getSessionSelectionKey(session)}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(session.id)}
|
||||
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)}
|
||||
onDelete={(e) => handleDelete(session.id, e)}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
@@ -227,14 +270,15 @@ export const SessionList = ({
|
||||
)}
|
||||
{olderSessions.map((session) => (
|
||||
<SessionCard
|
||||
key={session.id}
|
||||
key={getSessionSelectionKey(session)}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(session.id)}
|
||||
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)}
|
||||
onDelete={(e) => handleDelete(session.id, e)}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { ChevronDown, Plus, Trash2, RotateCcw } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@/api/types/settings'
|
||||
|
||||
interface EnvVar {
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export function ServerEnvVarsSettings() {
|
||||
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [envVars, setEnvVars] = useState<EnvVar[]>([])
|
||||
const [disabledDefaultKeys, setDisabledDefaultKeys] = useState<string[]>([])
|
||||
const [needsRestart, setNeedsRestart] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setEnvVars(preferences?.serverEnvVars ?? [])
|
||||
setDisabledDefaultKeys(preferences?.disabledDefaultServerEnvVars ?? [])
|
||||
}, [preferences?.disabledDefaultServerEnvVars, preferences?.serverEnvVars])
|
||||
|
||||
const blockedSet = useMemo(() => new Set<string>(BLOCKED_SERVER_ENV_KEYS), [])
|
||||
|
||||
const blockedKeys = useMemo(
|
||||
() => envVars
|
||||
.map((envVar) => envVar.key.trim())
|
||||
.filter((key) => key.length > 0 && blockedSet.has(key)),
|
||||
[envVars, blockedSet],
|
||||
)
|
||||
|
||||
const disabledDefaultSet = useMemo(() => new Set(disabledDefaultKeys), [disabledDefaultKeys])
|
||||
const enabledDefaultCount = DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultSet.has(envVar.key)).length
|
||||
|
||||
const handleDefaultToggle = (key: string, enabled: boolean) => {
|
||||
setDisabledDefaultKeys((prev) => enabled
|
||||
? prev.filter((disabledKey) => disabledKey !== key)
|
||||
: [...new Set([...prev, key])])
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
setEnvVars((prev) => [...prev, { key: '', value: '' }])
|
||||
}
|
||||
|
||||
const handleRemove = (index: number) => {
|
||||
setEnvVars((prev) => prev.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const handleChange = (index: number, field: keyof EnvVar, value: string) => {
|
||||
setEnvVars((prev) => prev.map((envVar, i) => (i === index ? { ...envVar, [field]: value } : envVar)))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (blockedKeys.length > 0) return
|
||||
|
||||
const filtered = envVars.filter((envVar) => envVar.key.trim() !== '')
|
||||
|
||||
try {
|
||||
await updateSettingsAsync({
|
||||
serverEnvVars: filtered,
|
||||
disabledDefaultServerEnvVars: disabledDefaultKeys,
|
||||
})
|
||||
setNeedsRestart(true)
|
||||
showToast.success('Environment variables saved')
|
||||
} catch {
|
||||
showToast.error('Failed to save environment variables')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen((value) => !value)}
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<h3 className="text-sm font-semibold truncate">Server Environment Variables</h3>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{enabledDefaultCount + (preferences?.serverEnvVars ?? []).length}
|
||||
</Badge>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="px-4 pb-4 pt-1 border-t border-border space-y-3">
|
||||
{needsRestart && (
|
||||
<Alert>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Restart the OpenCode server to apply environment variable changes.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-md border bg-muted/20 p-3 space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Default variables</div>
|
||||
{DEFAULT_SERVER_ENV_VARS.map((envVar) => {
|
||||
const isEnabled = !disabledDefaultSet.has(envVar.key)
|
||||
|
||||
return (
|
||||
<div key={envVar.key} className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-xs truncate">{envVar.key}={envVar.value}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Required for OpenCode workspace listing and deletion.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={(checked) => handleDefaultToggle(envVar.key, checked)}
|
||||
aria-label={`Toggle ${envVar.key}`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{envVars.map((envVar, index) => {
|
||||
const isBlocked = blockedSet.has(envVar.key.trim())
|
||||
|
||||
return (
|
||||
<div key={index} className="flex gap-2 items-center">
|
||||
<div className="flex-1 flex gap-2">
|
||||
<Input
|
||||
value={envVar.key}
|
||||
onChange={(event) => handleChange(index, 'key', event.target.value)}
|
||||
placeholder="VARIABLE_NAME"
|
||||
className={`font-mono ${isBlocked ? 'border-destructive' : ''}`}
|
||||
/>
|
||||
<Input
|
||||
value={envVar.value}
|
||||
onChange={(event) => handleChange(index, 'value', event.target.value)}
|
||||
placeholder="value"
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemove(index)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{blockedKeys.length > 0 && (
|
||||
<p className="text-xs text-destructive">
|
||||
Reserved keys cannot be overridden: {blockedKeys.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-1">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleAdd}>
|
||||
<Plus className="h-3 w-3 mr-1" />
|
||||
Add variable
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={isUpdating || blockedKeys.length > 0}
|
||||
>
|
||||
{isUpdating ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Variables are injected into the OpenCode server process at startup.
|
||||
Changes require a server restart.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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() {
|
||||
<OpenCodeServerAuthSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
</div>
|
||||
<ServerEnvVarsSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
</TabsContent>
|
||||
@@ -228,14 +230,15 @@ export function SettingsDialog() {
|
||||
{mobileView === 'voice' && <div key="voice"><VoiceSettings /></div>}
|
||||
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
|
||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-6">
|
||||
<ServerHealthStatus />
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
)}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-6">
|
||||
<ServerHealthStatus />
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<ServerEnvVarsSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
)}
|
||||
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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 }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
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 }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
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' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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<void>[] = []
|
||||
const removedWorkspaces = new Set<string>()
|
||||
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] });
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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<RepoSibling[]>({
|
||||
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')
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -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<ReturnType<typeof createPartsBatcher> | 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<MessageWithParts[]>(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<MessageWithParts[]>(
|
||||
['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<MessageWithParts[]>(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') {
|
||||
|
||||
@@ -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<WorktreeTabValue>(() => {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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<string | undefined>();
|
||||
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<string>();
|
||||
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<string, string> = {};
|
||||
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() {
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
<WorktreeTabs
|
||||
workspaces={workspaceSiblings}
|
||||
value={activeTab}
|
||||
onValueChange={setActiveTab}
|
||||
baseLabel={currentBranch}
|
||||
activeWorkspaceLabel={activeWorkspaceLabel}
|
||||
onCreateWorkspace={() => setCreateWorkspaceOpen(true)}
|
||||
onWorkspaceMenu={handleOpenWorkspaceSelector}
|
||||
/>
|
||||
|
||||
<WorkspaceManager
|
||||
open={workspaceSelectorOpen}
|
||||
onOpenChange={setWorkspaceSelectorOpen}
|
||||
workspaces={workspaceSiblings}
|
||||
activeWorkspaceDirectory={activeWorkspaceDirectory}
|
||||
onActiveWorkspaceChange={setActiveWorkspaceDirectory}
|
||||
onCreateWorkspace={() => setCreateWorkspaceOpen(true)}
|
||||
onDelete={(workspaceIds) => deleteWorkspaces.mutate(workspaceIds)}
|
||||
isDeleting={deleteWorkspaces.isPending}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{opcodeUrl && repoDirectory && (
|
||||
{opcodeUrl && sessionListDirectories.length > 0 && (
|
||||
<SessionList
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={repoDirectory}
|
||||
directories={sessionListDirectories}
|
||||
directoryLabels={activeTab === 'workspaces' ? directoryLabels : undefined}
|
||||
createDirectory={activeTab === 'workspaces' ? workspaceComposerDirectory : baseDirectory}
|
||||
onSelectSession={handleSelectSession}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<CreateWorkspaceDialog
|
||||
open={createWorkspaceOpen}
|
||||
onOpenChange={setCreateWorkspaceOpen}
|
||||
onCreate={handleCreateWorkspace}
|
||||
isCreating={createWorkspace.isPending}
|
||||
/>
|
||||
|
||||
<FileBrowserSheet
|
||||
isOpen={fileBrowserOpen}
|
||||
onClose={() => setFileBrowserOpen(false)}
|
||||
@@ -159,7 +276,7 @@ export function RepoDetail() {
|
||||
<RepoMcpDialog
|
||||
open={mcpDialogOpen}
|
||||
onOpenChange={setMcpDialogOpen}
|
||||
directory={repoDirectory}
|
||||
directory={composerDirectory}
|
||||
/>
|
||||
|
||||
<RepoSkillsDialog
|
||||
@@ -196,8 +313,57 @@ export function RepoDetail() {
|
||||
open={resetPermissionsOpen}
|
||||
onOpenChange={setResetPermissionsOpen}
|
||||
repoId={repoId}
|
||||
repoDirectory={repoDirectory}
|
||||
repoDirectory={composerDirectory}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface CreateWorkspaceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCreate: () => Promise<void>;
|
||||
isCreating: boolean;
|
||||
}
|
||||
|
||||
function CreateWorkspaceDialog({ open, onOpenChange, onCreate, isCreating }: CreateWorkspaceDialogProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[420px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Layers className="h-4 w-4 text-purple-400" />
|
||||
Create Workspace
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create an OpenCode worktree workspace for this repository.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="rounded-md border border-border bg-muted/30 p-3 text-sm">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<GitBranch className="h-4 w-4 text-purple-400" />
|
||||
Worktree
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
OpenCode will create and manage a git worktree workspace.
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isCreating}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={() => { void onCreate(); }} disabled={isCreating} className="bg-blue-600 hover:bg-blue-700 text-white">
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
'Create Workspace'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
"scripts": {
|
||||
"predev": "bash scripts/setup-dev.sh",
|
||||
"dev": "concurrently \"pnpm:dev:backend\" \"pnpm:dev:frontend\"",
|
||||
"dev:backend": "bun --watch-path backend/src --watch backend/src/index.ts",
|
||||
"dev:backend": "NODE_ENV=development bun --watch-path backend/src --watch backend/src/index.ts",
|
||||
"dev:frontend": "pnpm --filter frontend dev",
|
||||
"start": "concurrently \"pnpm:start:backend\" \"pnpm:start:frontend\"",
|
||||
"start:backend": "bun run backend/dist/index.js",
|
||||
|
||||
@@ -103,6 +103,29 @@ export const GitIdentitySchema = z.object({
|
||||
|
||||
export type GitIdentity = z.infer<typeof GitIdentitySchema>;
|
||||
|
||||
export const ServerEnvVarSchema = z.object({
|
||||
key: z.string().min(1),
|
||||
value: z.string(),
|
||||
});
|
||||
|
||||
type ServerEnvVar = z.infer<typeof ServerEnvVarSchema>
|
||||
|
||||
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({
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
CreateOpenCodeConfigRequestSchema,
|
||||
UpdateOpenCodeConfigRequestSchema,
|
||||
OpenCodeConfigResponseSchema,
|
||||
ServerEnvVarSchema,
|
||||
} from '../schemas/settings'
|
||||
import {
|
||||
RepoSchema,
|
||||
@@ -51,6 +52,7 @@ export type UserPreferences = z.infer<typeof UserPreferencesSchema>
|
||||
export type SettingsResponse = z.infer<typeof SettingsResponseSchema>
|
||||
export type UpdateSettingsRequest = z.infer<typeof UpdateSettingsRequestSchema>
|
||||
export type CustomCommand = z.infer<typeof CustomCommandSchema>
|
||||
export type ServerEnvVar = z.infer<typeof ServerEnvVarSchema>
|
||||
export type OpenCodeConfig = z.infer<typeof OpenCodeConfigMetadataSchema>
|
||||
export type OpenCodeConfigInput = z.infer<typeof OpenCodeConfigSchema>
|
||||
export type CreateOpenCodeConfigRequest = z.infer<typeof CreateOpenCodeConfigRequestSchema>
|
||||
@@ -90,6 +92,7 @@ export type AssistantSettingsPatch = z.infer<typeof AssistantSettingsPatchSchema
|
||||
|
||||
export { FetchError } from './errors'
|
||||
export type { ApiErrorResponse, ApiErrorCode, GitErrorCode } from './errors'
|
||||
export { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '../schemas/settings'
|
||||
|
||||
export interface SuccessResponse {
|
||||
success: boolean
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"files": ["./shared/src/index.ts"],
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "Preserve",
|
||||
"moduleResolution": "bundler",
|
||||
"moduleDetection": "force",
|
||||
"allowJs": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"jsx": "react-jsx",
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"target": "ESNext",
|
||||
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||
"types": []
|
||||
},
|
||||
"exclude": [
|
||||
"shared/src/**/*.test.ts",
|
||||
"shared/src/**/*.test.tsx",
|
||||
"shared/src/**/*.spec.ts",
|
||||
"shared/src/**/*.spec.tsx"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user