mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Chat folders, ChatService and the /api/chats REST API
This commit is contained in:
1 parent
c6c13335e5
commit
666c1f0e0a
12 files changed
+623
-2
No files matched your search
@@ -39,6 +39,7 @@ import { createAuth } from './auth'
|
||||
import { createAuthMiddleware } from './auth/middleware'
|
||||
import { createPromptTemplateRoutes } from './routes/prompt-templates'
|
||||
import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createChatRoutes } from './routes/chats'
|
||||
import { createSessionPermissionModeRoutes } from './routes/session-permission-modes'
|
||||
import { createSessionSandboxRoutes } from './routes/session-sandbox'
|
||||
import { createMultiRunRoutes } from './routes/multi-runs'
|
||||
@@ -69,6 +70,7 @@ import { SessionAncestry } from './services/session-ancestry'
|
||||
import { GoalOutcomeTracker } from './services/goal-outcomes'
|
||||
import { MultiRunService } from './services/multi-runs'
|
||||
import { ChangeWalkthroughService } from './services/change-walkthroughs'
|
||||
import { ChatService } from './services/chats'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { OpenCodeServerRegistry } from './services/opencode-server-registry'
|
||||
@@ -95,6 +97,7 @@ import { logger } from './utils/logger'
|
||||
import {
|
||||
getWorkspacePath,
|
||||
getReposPath,
|
||||
getChatsPath,
|
||||
getConfigPath,
|
||||
getAgentsMdPath,
|
||||
getDatabasePath,
|
||||
@@ -220,6 +223,7 @@ try {
|
||||
|
||||
await ensureDirectoryExists(getWorkspacePath())
|
||||
await ensureDirectoryExists(getReposPath())
|
||||
await ensureDirectoryExists(getChatsPath())
|
||||
await ensureDirectoryExists(getConfigPath())
|
||||
logger.info('Workspace directories initialized')
|
||||
|
||||
@@ -305,6 +309,7 @@ const goalOutcomes = new GoalOutcomeTracker()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
|
||||
const chatService = new ChatService(openCodeClient)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionSandboxService.handleEvent(directory, event).catch((err) => {
|
||||
@@ -420,6 +425,7 @@ protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/secrets', createGlobalSecretRoutes(secretsService, 'secret'))
|
||||
protectedApi.route('/variables', createGlobalSecretRoutes(secretsService, 'variable'))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/chats', createChatRoutes(chatService))
|
||||
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resolveServerTerminalService))
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Hono } from 'hono'
|
||||
import { CreateChatRequestSchema, ListChatsQuerySchema } from '@opencode-manager/shared/schemas'
|
||||
import { ChatNotFoundError, ChatSessionMismatchError, type ChatService } from '../services/chats'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { handleOpenCodeError, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
export function createChatRoutes(chatService: ChatService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', async (c) => {
|
||||
const parsedQuery = ListChatsQuerySchema.safeParse(c.req.query())
|
||||
if (!parsedQuery.success) {
|
||||
return c.json({ error: 'Invalid query', details: parsedQuery.error.issues }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
return c.json(await chatService.list(parsedQuery.data))
|
||||
} catch (error) {
|
||||
logger.error('Failed to list chats', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:chatId', async (c) => {
|
||||
try {
|
||||
const chat = await chatService.resolve(c.req.param('chatId'))
|
||||
return chat ? c.json(chat) : c.json({ error: 'Chat not found' }, 404)
|
||||
} catch (error) {
|
||||
logger.error('Failed to read chat', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/', async (c) => {
|
||||
const body = await parseJsonBody(c, CreateChatRequestSchema, { allowEmpty: true })
|
||||
if (!body.ok) {
|
||||
return body.response
|
||||
}
|
||||
|
||||
try {
|
||||
return c.json(await chatService.create(body.data), 201)
|
||||
} catch (error) {
|
||||
return handleOpenCodeError(c, error, 'Chat request failed')
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:chatId/sessions/:sessionId', async (c) => {
|
||||
try {
|
||||
return c.json(await chatService.deleteSession(c.req.param('chatId'), c.req.param('sessionId')))
|
||||
} catch (error) {
|
||||
if (error instanceof ChatNotFoundError) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
if (error instanceof ChatSessionMismatchError) {
|
||||
return c.json({ error: error.message }, 400)
|
||||
}
|
||||
return handleOpenCodeError(c, error, 'Chat session delete failed')
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import path from 'path'
|
||||
import { randomBytes } from 'crypto'
|
||||
import fs from 'fs/promises'
|
||||
import { getChatsPath, getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import { parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
ChatIdSchema,
|
||||
parseChatIdCreatedAt,
|
||||
type Chat,
|
||||
type CreateChatRequest,
|
||||
type DeleteChatSessionResponse,
|
||||
type ListChatsQuery,
|
||||
type ListChatsResponse,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { ensureDirectoryExists } from './file-operations'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
|
||||
const CHAT_ID_ATTEMPTS = 5
|
||||
|
||||
export class ChatNotFoundError extends Error {
|
||||
constructor(chatId: string) {
|
||||
super(`Chat not found: ${chatId}`)
|
||||
this.name = 'ChatNotFoundError'
|
||||
}
|
||||
}
|
||||
|
||||
export class ChatSessionMismatchError extends Error {
|
||||
constructor(sessionId: string, chatId: string) {
|
||||
super(`Session ${sessionId} does not belong to chat ${chatId}`)
|
||||
this.name = 'ChatSessionMismatchError'
|
||||
}
|
||||
}
|
||||
|
||||
function formatChatTimestamp(now: Date): string {
|
||||
const iso = now.toISOString()
|
||||
return [
|
||||
iso.slice(0, 4),
|
||||
iso.slice(5, 7),
|
||||
iso.slice(8, 10),
|
||||
'-',
|
||||
iso.slice(11, 13),
|
||||
iso.slice(14, 16),
|
||||
iso.slice(17, 19),
|
||||
].join('')
|
||||
}
|
||||
|
||||
/** Owns the lifecycle of chat folders and the OpenCode sessions created inside them. */
|
||||
export class ChatService {
|
||||
constructor(
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly root: () => string = getChatsPath,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
async list({ limit, cursor }: ListChatsQuery): Promise<ListChatsResponse> {
|
||||
const chatIds = await this.listChatIds()
|
||||
const ordered = cursor ? chatIds.filter((id) => id < cursor) : chatIds
|
||||
const page = ordered.slice(0, limit)
|
||||
const nextCursor = ordered.length > limit ? page[page.length - 1] : undefined
|
||||
|
||||
return {
|
||||
chats: page.map((id) => this.toChat(id)),
|
||||
...(nextCursor ? { nextCursor } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
async resolve(chatId: string): Promise<Chat | null> {
|
||||
if (!ChatIdSchema.safeParse(chatId).success) return null
|
||||
|
||||
try {
|
||||
const stats = await fs.stat(path.join(this.root(), chatId))
|
||||
return stats.isDirectory() ? this.toChat(chatId) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async findByDirectory(directory: string): Promise<Chat | null> {
|
||||
const target = canonicalPathSync(path.resolve(directory))
|
||||
for (const id of await this.listChatIds()) {
|
||||
const chat = this.toChat(id)
|
||||
if (canonicalPathSync(chat.directory) === target) return chat
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async create(input: CreateChatRequest): Promise<{ chat: Chat; sessionId: string }> {
|
||||
const root = this.root()
|
||||
await ensureDirectoryExists(root)
|
||||
|
||||
const { id, directory } = await this.createFolder(root)
|
||||
try {
|
||||
const model = input.model ? parseOpenCodeModelRef(input.model) : undefined
|
||||
const session = await this.openCodeClient.api.session.create({
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.agent !== undefined ? { agent: input.agent } : {}),
|
||||
...(model ? { model } : {}),
|
||||
location: { directory },
|
||||
})
|
||||
return { chat: this.toChat(id), sessionId: session.id }
|
||||
} catch (error) {
|
||||
await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSession(chatId: string, sessionId: string): Promise<DeleteChatSessionResponse> {
|
||||
const chat = await this.resolve(chatId)
|
||||
if (!chat) throw new ChatNotFoundError(chatId)
|
||||
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
const sessionDirectory = canonicalPathSync(path.resolve(session.location.directory))
|
||||
if (sessionDirectory !== canonicalPathSync(chat.directory)) {
|
||||
throw new ChatSessionMismatchError(sessionId, chatId)
|
||||
}
|
||||
|
||||
await this.openCodeClient.api.session.remove({ sessionID: sessionId })
|
||||
const remaining = await this.openCodeClient.api.session.list({
|
||||
directory: chat.directory,
|
||||
limit: 1,
|
||||
})
|
||||
|
||||
const folderRemoved = remaining.data.length === 0
|
||||
if (folderRemoved) {
|
||||
await fs.rm(chat.directory, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
return { deleted: true, folderRemoved }
|
||||
}
|
||||
|
||||
private async listChatIds(): Promise<string[]> {
|
||||
const root = this.root()
|
||||
await ensureDirectoryExists(root)
|
||||
const entries = await fs.readdir(root, { withFileTypes: true })
|
||||
return entries
|
||||
.filter((entry) => entry.isDirectory() && ChatIdSchema.safeParse(entry.name).success)
|
||||
.map((entry) => entry.name)
|
||||
.sort((a, b) => (a < b ? 1 : a > b ? -1 : 0))
|
||||
}
|
||||
|
||||
private async createFolder(root: string): Promise<{ id: string; directory: string }> {
|
||||
for (let attempt = 0; attempt < CHAT_ID_ATTEMPTS; attempt++) {
|
||||
const id = `${formatChatTimestamp(this.now())}-${randomBytes(3).toString('hex')}`
|
||||
const directory = path.join(root, id)
|
||||
try {
|
||||
await fs.mkdir(directory)
|
||||
return { id, directory }
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
|
||||
}
|
||||
}
|
||||
throw new Error('Failed to allocate a unique chat folder')
|
||||
}
|
||||
|
||||
private toChat(id: string): Chat {
|
||||
const directory = path.join(this.root(), id)
|
||||
return {
|
||||
id,
|
||||
directory,
|
||||
filesPath: path.relative(getReposPath(), directory),
|
||||
createdAt: parseChatIdCreatedAt(id),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
getOpenCodeGlobalSkillsPath,
|
||||
getOpenCodeToolOutputPath,
|
||||
getOpenCodeWorktreesPath,
|
||||
getChatsPath,
|
||||
getReposPath,
|
||||
getScheduleWorktreesPath,
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
@@ -174,7 +175,7 @@ export function buildSandboxVerifyProvisionArgs(name: string): string[] {
|
||||
}
|
||||
|
||||
export function sandboxProjectRoots(): string[] {
|
||||
return [getReposPath(), getScheduleWorktreesPath(), getOpenCodeWorktreesPath(), getForgeWorktreesPath()]
|
||||
return [getReposPath(), getChatsPath(), getScheduleWorktreesPath(), getOpenCodeWorktreesPath(), getForgeWorktreesPath()]
|
||||
}
|
||||
|
||||
export function sandboxMountRoots(): string[] {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { ChatService } from '../../src/services/chats'
|
||||
import { createChatRoutes } from '../../src/routes/chats'
|
||||
|
||||
function createFakeClient() {
|
||||
const session = {
|
||||
create: vi.fn(async ({ location }: { location: { directory: string } }) => ({
|
||||
id: 'ses_created',
|
||||
location,
|
||||
})),
|
||||
get: vi.fn(async ({ sessionID }: { sessionID: string }) => ({
|
||||
id: sessionID,
|
||||
location: { directory: '/tmp/other-chat' },
|
||||
})),
|
||||
remove: vi.fn(async () => undefined),
|
||||
list: vi.fn(async () => ({ data: [], cursor: {} })),
|
||||
}
|
||||
return { client: { api: { session } } as unknown as OpenCodeClient, session }
|
||||
}
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function createApp(root: string) {
|
||||
const fake = createFakeClient()
|
||||
const app = new Hono()
|
||||
app.route('/chats', createChatRoutes(new ChatService(fake.client, () => root)))
|
||||
return { app, ...fake }
|
||||
}
|
||||
|
||||
function createRoot(): string {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'chats-routes-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (roots.length > 0) {
|
||||
rmSync(roots.pop()!, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('chat routes', () => {
|
||||
it('lists chats and pages with the returned cursor', async () => {
|
||||
const root = createRoot()
|
||||
for (const id of ['20260101-000000-aaaaaa', '20260102-000000-bbbbbb']) {
|
||||
mkdirSync(path.join(root, id))
|
||||
}
|
||||
const { app } = createApp(root)
|
||||
|
||||
const first = await app.request('/chats?limit=1')
|
||||
expect(first.status).toBe(200)
|
||||
const firstBody = await first.json() as { chats: Array<{ id: string }>; nextCursor?: string }
|
||||
expect(firstBody.chats.map((chat) => chat.id)).toEqual(['20260102-000000-bbbbbb'])
|
||||
expect(firstBody.nextCursor).toBe('20260102-000000-bbbbbb')
|
||||
|
||||
const second = await app.request(`/chats?limit=1&cursor=${firstBody.nextCursor}`)
|
||||
const secondBody = await second.json() as { chats: Array<{ id: string }>; nextCursor?: string }
|
||||
expect(secondBody.chats.map((chat) => chat.id)).toEqual(['20260101-000000-aaaaaa'])
|
||||
expect(secondBody.nextCursor).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects an invalid limit', async () => {
|
||||
const { app } = createApp(createRoot())
|
||||
|
||||
const res = await app.request('/chats?limit=0')
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns a chat and 404 for unknown or malformed ids', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
mkdirSync(path.join(root, id))
|
||||
const { app } = createApp(root)
|
||||
|
||||
const found = await app.request(`/chats/${id}`)
|
||||
expect(found.status).toBe(200)
|
||||
const body = await found.json() as { id: string; directory: string }
|
||||
expect(body.id).toBe(id)
|
||||
expect(body.directory).toBe(path.join(root, id))
|
||||
|
||||
expect((await app.request('/chats/20260203-040506-aaaaaa')).status).toBe(404)
|
||||
expect((await app.request('/chats/not-a-chat')).status).toBe(404)
|
||||
})
|
||||
|
||||
it('creates a chat from an empty body', async () => {
|
||||
const root = createRoot()
|
||||
const { app, session } = createApp(root)
|
||||
|
||||
const res = await app.request('/chats', { method: 'POST' })
|
||||
expect(res.status).toBe(201)
|
||||
const body = await res.json() as { chat: { id: string; directory: string }; sessionId: string }
|
||||
expect(body.chat.id).toMatch(/^\d{8}-\d{6}-[0-9a-f]{6}$/)
|
||||
expect(body.sessionId).toBe('ses_created')
|
||||
expect(existsSync(body.chat.directory)).toBe(true)
|
||||
expect(session.create).toHaveBeenCalledWith({ location: { directory: body.chat.directory } })
|
||||
})
|
||||
|
||||
it('deletes a chat session and reports the folder outcome', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
const directory = path.join(root, id)
|
||||
mkdirSync(directory)
|
||||
const { app, session } = createApp(root)
|
||||
session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } })
|
||||
|
||||
const res = await app.request(`/chats/${id}/sessions/ses_1`, { method: 'DELETE' })
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({ deleted: true, folderRemoved: true })
|
||||
expect(existsSync(directory)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns 400 for a session in another folder and 404 for an unknown chat', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
mkdirSync(path.join(root, id))
|
||||
const { app } = createApp(root)
|
||||
|
||||
const mismatch = await app.request(`/chats/${id}/sessions/ses_1`, { method: 'DELETE' })
|
||||
expect(mismatch.status).toBe(400)
|
||||
|
||||
const unknown = await app.request('/chats/20260203-040506-aaaaaa/sessions/ses_1', { method: 'DELETE' })
|
||||
expect(unknown.status).toBe(404)
|
||||
|
||||
const malformed = await app.request('/chats/../../etc/sessions/ses_1', { method: 'DELETE' })
|
||||
expect(malformed.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,177 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { ChatNotFoundError, ChatService, ChatSessionMismatchError } from '../../src/services/chats'
|
||||
|
||||
const CHAT_ID_PATTERN = /^\d{8}-\d{6}-[0-9a-f]{6}$/
|
||||
|
||||
interface FakeClient {
|
||||
client: OpenCodeClient
|
||||
session: {
|
||||
create: ReturnType<typeof vi.fn>
|
||||
get: ReturnType<typeof vi.fn>
|
||||
remove: ReturnType<typeof vi.fn>
|
||||
list: ReturnType<typeof vi.fn>
|
||||
}
|
||||
}
|
||||
|
||||
function createFakeClient(): FakeClient {
|
||||
const session = {
|
||||
create: vi.fn(async () => ({ id: 'ses_new' })),
|
||||
get: vi.fn(async ({ sessionID }: { sessionID: string }) => ({
|
||||
id: sessionID,
|
||||
location: { directory: '/tmp/other-chat' },
|
||||
})),
|
||||
remove: vi.fn(async () => undefined),
|
||||
list: vi.fn(async () => ({ data: [], cursor: {} })),
|
||||
}
|
||||
return { client: { api: { session } } as unknown as OpenCodeClient, session }
|
||||
}
|
||||
|
||||
function createChatFolder(root: string, id: string): string {
|
||||
const directory = path.join(root, id)
|
||||
mkdirSync(directory, { recursive: true })
|
||||
return directory
|
||||
}
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function createRoot(): string {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'chats-service-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (roots.length > 0) {
|
||||
rmSync(roots.pop()!, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('ChatService', () => {
|
||||
it('creates a chat folder matching the id format and leaves it empty', async () => {
|
||||
const root = createRoot()
|
||||
const fake = createFakeClient()
|
||||
const service = new ChatService(fake.client, () => root, () => new Date('2026-01-02T03:04:05Z'))
|
||||
|
||||
const result = await service.create({ title: 'Hello' })
|
||||
|
||||
expect(result.sessionId).toBe('ses_new')
|
||||
expect(result.chat.id).toMatch(CHAT_ID_PATTERN)
|
||||
expect(result.chat.id.startsWith('20260102-030405-')).toBe(true)
|
||||
expect(result.chat.directory).toBe(path.join(root, result.chat.id))
|
||||
expect(result.chat.createdAt).toBe(Date.UTC(2026, 0, 2, 3, 4, 5))
|
||||
expect(readdirSync(result.chat.directory)).toEqual([])
|
||||
expect(fake.session.create).toHaveBeenCalledWith({
|
||||
title: 'Hello',
|
||||
location: { directory: result.chat.directory },
|
||||
})
|
||||
})
|
||||
|
||||
it('removes the new folder when session creation fails', async () => {
|
||||
const root = createRoot()
|
||||
const fake = createFakeClient()
|
||||
fake.session.create.mockRejectedValueOnce(new Error('session failed'))
|
||||
const service = new ChatService(fake.client, () => root)
|
||||
|
||||
await expect(service.create({})).rejects.toThrow('session failed')
|
||||
expect(readdirSync(root)).toEqual([])
|
||||
})
|
||||
|
||||
it('lists chats newest first, pages with a cursor, and ignores non-chat entries', async () => {
|
||||
const root = createRoot()
|
||||
const ids = ['20260101-000000-aaaaaa', '20260102-000000-bbbbbb', '20260103-000000-cccccc']
|
||||
for (const id of ids) createChatFolder(root, id)
|
||||
createChatFolder(root, 'not-a-chat')
|
||||
mkdirSync(path.join(root, '.hidden'))
|
||||
const service = new ChatService(createFakeClient().client, () => root)
|
||||
|
||||
const first = await service.list({ limit: 2 })
|
||||
expect(first.chats.map((chat) => chat.id)).toEqual([ids[2], ids[1]])
|
||||
expect(first.nextCursor).toBe(ids[1])
|
||||
|
||||
const second = await service.list({ limit: 2, cursor: first.nextCursor })
|
||||
expect(second.chats.map((chat) => chat.id)).toEqual([ids[0]])
|
||||
expect(second.nextCursor).toBeUndefined()
|
||||
|
||||
const last = await service.list({ limit: 2, cursor: ids[0] })
|
||||
expect(last.chats).toEqual([])
|
||||
expect(last.nextCursor).toBeUndefined()
|
||||
})
|
||||
|
||||
it('resolves only existing chat folders and rejects malformed ids', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
createChatFolder(root, id)
|
||||
const service = new ChatService(createFakeClient().client, () => root)
|
||||
|
||||
expect((await service.resolve(id))?.id).toBe(id)
|
||||
expect(await service.resolve('20260203-040506-aaaaaa')).toBeNull()
|
||||
expect(await service.resolve('../../etc')).toBeNull()
|
||||
expect(await service.resolve('not-a-chat')).toBeNull()
|
||||
})
|
||||
|
||||
it('finds a chat by its canonical directory', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
const directory = createChatFolder(root, id)
|
||||
const service = new ChatService(createFakeClient().client, () => root)
|
||||
|
||||
expect((await service.findByDirectory(directory))?.id).toBe(id)
|
||||
expect(await service.findByDirectory(path.join(root, 'missing'))).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the folder when another session remains after a delete', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
const directory = createChatFolder(root, id)
|
||||
const fake = createFakeClient()
|
||||
fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } })
|
||||
fake.session.list.mockResolvedValueOnce({ data: [{ id: 'ses_fork' }], cursor: {} })
|
||||
const service = new ChatService(fake.client, () => root)
|
||||
|
||||
const result = await service.deleteSession(id, 'ses_1')
|
||||
|
||||
expect(result).toEqual({ deleted: true, folderRemoved: false })
|
||||
expect(fake.session.remove).toHaveBeenCalledWith({ sessionID: 'ses_1' })
|
||||
expect(fake.session.list).toHaveBeenCalledWith({ directory, limit: 1 })
|
||||
expect(existsSync(directory)).toBe(true)
|
||||
})
|
||||
|
||||
it('removes the folder when no session remains after a delete', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
const directory = createChatFolder(root, id)
|
||||
const fake = createFakeClient()
|
||||
fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory } })
|
||||
const service = new ChatService(fake.client, () => root)
|
||||
|
||||
const result = await service.deleteSession(id, 'ses_1')
|
||||
|
||||
expect(result).toEqual({ deleted: true, folderRemoved: true })
|
||||
expect(existsSync(directory)).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects a session that belongs to another folder', async () => {
|
||||
const root = createRoot()
|
||||
const id = '20260203-040506-abcdef'
|
||||
createChatFolder(root, id)
|
||||
const fake = createFakeClient()
|
||||
fake.session.get.mockResolvedValueOnce({ id: 'ses_1', location: { directory: '/tmp/other-chat' } })
|
||||
const service = new ChatService(fake.client, () => root)
|
||||
|
||||
await expect(service.deleteSession(id, 'ses_1')).rejects.toBeInstanceOf(ChatSessionMismatchError)
|
||||
expect(fake.session.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an unknown chat id before touching sessions', async () => {
|
||||
const fake = createFakeClient()
|
||||
const service = new ChatService(fake.client, () => createRoot())
|
||||
|
||||
await expect(service.deleteSession('20260203-040506-abcdef', 'ses_1')).rejects.toBeInstanceOf(ChatNotFoundError)
|
||||
await expect(service.deleteSession('../escape', 'ses_1')).rejects.toBeInstanceOf(ChatNotFoundError)
|
||||
expect(fake.session.get).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import { spawnSync } from 'child_process'
|
||||
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { ENV, getAssistantOpenCodeDir, getForgeWorktreesPath, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getOpenCodeWorktreesPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import { ENV, getAssistantOpenCodeDir, getChatsPath, getForgeWorktreesPath, getOpenCodeAgentTmpPath, getOpenCodeGlobalSkillsPath, getOpenCodeToolOutputPath, getOpenCodeWorktreesPath, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
SESSION_SANDBOX_NAME_PATTERN,
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
sandboxDockerDataVolumeName,
|
||||
sandboxMountRoots,
|
||||
sandboxNetworkPolicyMismatch,
|
||||
sandboxProjectRoots,
|
||||
sandboxVmMountRoots,
|
||||
sessionSandboxName,
|
||||
type SandboxVmSpec,
|
||||
@@ -243,6 +244,14 @@ describe('sandbox command builders', () => {
|
||||
expect(args.indexOf(ENV.SANDBOX.IMAGE)).toBeGreaterThan(entrypointIndex + 1)
|
||||
})
|
||||
|
||||
it('includes the chats root in the sandbox project roots', () => {
|
||||
const roots = sandboxProjectRoots()
|
||||
|
||||
expect(roots).toContain(getChatsPath())
|
||||
expect(roots).toContain(getReposPath())
|
||||
expect(sandboxMountRoots()).toContain(getChatsPath())
|
||||
})
|
||||
|
||||
it('mounts only the worktree, skills, tool-output, and agent tmp directories from outside the repo roots', () => {
|
||||
const workspacePath = path.dirname(getReposPath())
|
||||
const roots = sandboxMountRoots()
|
||||
|
||||
@@ -29,6 +29,7 @@ export const DEFAULTS = {
|
||||
WORKSPACE: {
|
||||
BASE_PATH: './workspace',
|
||||
REPOS_DIR: 'repos',
|
||||
CHATS_DIR: 'chats',
|
||||
SCHEDULE_WORKTREES_DIR: 'schedule-worktrees',
|
||||
WALKTHROUGHS_DIR: 'walkthroughs',
|
||||
CONFIG_DIR: '.config/opencode',
|
||||
|
||||
@@ -87,6 +87,7 @@ export const ENV = {
|
||||
get BASE_PATH() { return resolveWorkspacePath() },
|
||||
get BROWSE_ROOT() { return resolveBrowseRoot() },
|
||||
REPOS_DIR: DEFAULTS.WORKSPACE.REPOS_DIR,
|
||||
CHATS_DIR: DEFAULTS.WORKSPACE.CHATS_DIR,
|
||||
SCHEDULE_WORKTREES_DIR: DEFAULTS.WORKSPACE.SCHEDULE_WORKTREES_DIR,
|
||||
WALKTHROUGHS_DIR: DEFAULTS.WORKSPACE.WALKTHROUGHS_DIR,
|
||||
CONFIG_DIR: DEFAULTS.WORKSPACE.CONFIG_DIR,
|
||||
@@ -148,6 +149,7 @@ export const ENV = {
|
||||
export const getWorkspacePath = () => ENV.WORKSPACE.BASE_PATH
|
||||
export const getBrowseRootPath = () => ENV.WORKSPACE.BROWSE_ROOT
|
||||
export const getReposPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.REPOS_DIR)
|
||||
export const getChatsPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CHATS_DIR)
|
||||
export const getScheduleWorktreesPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.SCHEDULE_WORKTREES_DIR)
|
||||
export const getWalkthroughsPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.WALKTHROUGHS_DIR)
|
||||
export const getAssistantModePath = () => path.join(getReposPath(), ASSISTANT_REPO_PATH)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const CHAT_ID_PATTERN = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-[0-9a-f]{6}$/
|
||||
|
||||
export const ChatIdSchema = z.string().regex(CHAT_ID_PATTERN, 'Invalid chat id')
|
||||
|
||||
export const ChatSchema = z.object({
|
||||
id: ChatIdSchema,
|
||||
directory: z.string(),
|
||||
filesPath: z.string(),
|
||||
createdAt: z.number(),
|
||||
})
|
||||
|
||||
export const ListChatsQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(50).default(10),
|
||||
cursor: ChatIdSchema.optional(),
|
||||
})
|
||||
|
||||
export const ListChatsResponseSchema = z.object({
|
||||
chats: z.array(ChatSchema),
|
||||
nextCursor: ChatIdSchema.optional(),
|
||||
})
|
||||
|
||||
export const CreateChatRequestSchema = z.object({
|
||||
title: z.string().optional(),
|
||||
agent: z.string().optional(),
|
||||
model: z.string().optional(),
|
||||
})
|
||||
|
||||
export const CreateChatResponseSchema = z.object({
|
||||
chat: ChatSchema,
|
||||
sessionId: z.string(),
|
||||
})
|
||||
|
||||
export const DeleteChatSessionResponseSchema = z.object({
|
||||
deleted: z.literal(true),
|
||||
folderRemoved: z.boolean(),
|
||||
})
|
||||
|
||||
export type Chat = z.infer<typeof ChatSchema>
|
||||
export type ListChatsQuery = z.infer<typeof ListChatsQuerySchema>
|
||||
export type ListChatsResponse = z.infer<typeof ListChatsResponseSchema>
|
||||
export type CreateChatRequest = z.infer<typeof CreateChatRequestSchema>
|
||||
export type CreateChatResponse = z.infer<typeof CreateChatResponseSchema>
|
||||
export type DeleteChatSessionResponse = z.infer<typeof DeleteChatSessionResponseSchema>
|
||||
|
||||
/** Reads the UTC creation time encoded in a chat id. */
|
||||
export function parseChatIdCreatedAt(id: string): number {
|
||||
const match = CHAT_ID_PATTERN.exec(id)
|
||||
if (!match) return NaN
|
||||
const [, year, month, day, hour, minute, second] = match
|
||||
return Date.UTC(
|
||||
Number(year),
|
||||
Number(month) - 1,
|
||||
Number(day),
|
||||
Number(hour),
|
||||
Number(minute),
|
||||
Number(second),
|
||||
)
|
||||
}
|
||||
@@ -24,3 +24,4 @@ export * from './change-walkthroughs'
|
||||
export * from './opencode-servers'
|
||||
export * from './secrets'
|
||||
export * from './device-pairing'
|
||||
export * from './chats'
|
||||
@@ -22,6 +22,10 @@ export function buildSessionPath(
|
||||
return `/repos/${repoId}/sessions/${sessionId}${search ? `?${search}` : ''}`
|
||||
}
|
||||
|
||||
export function buildChatSessionPath(chatId: string, sessionId: string): string {
|
||||
return `/chats/${encodeURIComponent(chatId)}/sessions/${encodeURIComponent(sessionId)}`
|
||||
}
|
||||
|
||||
export function buildServerSessionPath(serverId: string, sessionId: string): string {
|
||||
return `/servers/${encodeURIComponent(serverId)}/sessions/${encodeURIComponent(sessionId)}`
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user