mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Feat/assistant session list (#198)
* feat: add assistant mode integration and fix test environment - Add assistant-mode service for managing assistant workspace files (AGENTS.md, opencode.json) - Add backend GET/POST routes for assistant-mode status and initialization - Add AssistantRedirect page and useAssistantSessionLauncher hook - Update mobile navigation to include Assistant tab (replaces Alerts) - Fix React.act compatibility by setting NODE_ENV=test in vitest config - Add shared Zod schemas for AssistantMode types and requests * feat: enhance assistant mode with session list view and legacy config migration - Add session list view for assistant mode with full workspace management - Migrate legacy opencode.json permission format to granular permissions - Enable assistant navigation from mobile tab bar and repo switcher - Preserve assistant context in session routes via query params - Auto-restart OpenCode server after assistant mode initialization - Add comprehensive tests for legacy config detection and navigation
This commit is contained in:
1 parent
0a2e337efc
commit
c894ff5756
22 files changed
+1347
-154
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { DiscoverReposRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName } from '../db/queries'
|
||||
import * as repoService from '../services/repo'
|
||||
import * as archiveService from '../services/archive'
|
||||
@@ -16,6 +16,7 @@ import { createRepoGitRoutes } from './repo-git'
|
||||
import { createScheduleRoutes } from './schedules'
|
||||
import type { GitAuthService } from '../services/git-auth'
|
||||
import { ScheduleService } from '../services/schedules'
|
||||
import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode'
|
||||
import path from 'path'
|
||||
|
||||
export function createRepoRoutes(database: Database, gitAuthService: GitAuthService, scheduleService: ScheduleService) {
|
||||
@@ -376,6 +377,47 @@ app.get('/', async (c) => {
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/assistant-mode', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const status = await getAssistantModeStatus(repo)
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to get assistant mode status:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/assistant-mode', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const options = AssistantModeInitRequestSchema.parse(body)
|
||||
|
||||
const status = await ensureAssistantMode(repo, options)
|
||||
if (status.files.opencodeJson.created) {
|
||||
opencodeServerManager.clearStartupError()
|
||||
await opencodeServerManager.restart()
|
||||
}
|
||||
return c.json(status)
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to initialize assistant mode:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import path from 'path'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import type {
|
||||
AssistantModeStatus,
|
||||
AssistantModeInitRequest,
|
||||
OpenCodeConfigInput,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import {
|
||||
readFileContent,
|
||||
writeFileContent,
|
||||
fileExists,
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
const ASSISTANT_MODE_DIR = 'assistant'
|
||||
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
|
||||
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
|
||||
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
|
||||
|
||||
export function getAssistantModeDirectory(): string {
|
||||
const reposPath = getReposPath()
|
||||
const assistantDir = path.join(reposPath, ASSISTANT_MODE_DIR)
|
||||
const resolvedReposRoot = path.resolve(reposPath)
|
||||
const resolvedAssistantDir = path.resolve(assistantDir)
|
||||
|
||||
if (!resolvedAssistantDir.startsWith(resolvedReposRoot)) {
|
||||
throw new Error('Assistant mode directory must be within repos root')
|
||||
}
|
||||
|
||||
return resolvedAssistantDir
|
||||
}
|
||||
|
||||
export function buildAssistantAgentsMd(): string {
|
||||
return `# Assistant Mode Instructions
|
||||
|
||||
This folder is the shared Assistant mode workspace for OpenCode Manager.
|
||||
|
||||
## Purpose
|
||||
|
||||
Assistant mode provides an isolated space for:
|
||||
- Self-editing agent instructions and preferences
|
||||
- Customized workflows specific to this assistant workspace
|
||||
- Iterative improvement of assistant behavior
|
||||
|
||||
## Self-Editing Rules
|
||||
|
||||
The agent MAY self-edit the following files within this workspace:
|
||||
- \`AGENTS.md\` - Assistant instructions, persona, and durable preferences
|
||||
- \`opencode.json\` - OpenCode configuration for this workspace
|
||||
|
||||
## Constraints
|
||||
|
||||
- Changes outside this workspace require explicit user direction
|
||||
- Self-edits should be concise and auditable
|
||||
- Preserve user-customized content when modifying files
|
||||
- Always ask for confirmation before making significant changes
|
||||
|
||||
## Guidelines
|
||||
|
||||
1. Keep instructions clear and actionable
|
||||
2. Update AGENTS.md when learning durable preferences
|
||||
3. Maintain version control awareness
|
||||
4. Document significant changes in commit messages
|
||||
`
|
||||
}
|
||||
|
||||
export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
|
||||
const config: OpenCodeConfigInput = {
|
||||
instructions: [
|
||||
'AGENTS.md',
|
||||
],
|
||||
permission: {
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
},
|
||||
}
|
||||
|
||||
const result = OpenCodeConfigSchema.safeParse(config)
|
||||
if (!result.success) {
|
||||
throw new Error(`Generated OpenCode config is invalid: ${result.error.message}`)
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
export async function ensureAssistantMode(
|
||||
repo: Repo,
|
||||
options?: AssistantModeInitRequest
|
||||
): Promise<AssistantModeStatus> {
|
||||
const assistantDir = getAssistantModeDirectory()
|
||||
|
||||
await ensureDirectoryExists(assistantDir)
|
||||
|
||||
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
|
||||
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
|
||||
|
||||
const agentsMdExists = await fileExists(agentsMdPath)
|
||||
const opencodeJsonExists = await fileExists(opencodeJsonPath)
|
||||
|
||||
const overwriteAgentsMd = options?.overwriteAgentsMd ?? false
|
||||
const overwriteOpenCodeConfig = options?.overwriteOpenCodeConfig ?? false
|
||||
|
||||
if (!agentsMdExists || overwriteAgentsMd) {
|
||||
const content = buildAssistantAgentsMd()
|
||||
await writeFileContent(agentsMdPath, content)
|
||||
}
|
||||
|
||||
const hasLegacyOpenCodeConfig = opencodeJsonExists && await isLegacyAssistantOpenCodeConfig(opencodeJsonPath)
|
||||
|
||||
if (!opencodeJsonExists || overwriteOpenCodeConfig || hasLegacyOpenCodeConfig) {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
await writeFileContent(opencodeJsonPath, JSON.stringify(config, null, 2))
|
||||
}
|
||||
|
||||
return {
|
||||
repoId: repo.id,
|
||||
directory: assistantDir,
|
||||
relativePath: ASSISTANT_MODE_RELATIVE_PATH,
|
||||
files: {
|
||||
agentsMd: {
|
||||
path: agentsMdPath,
|
||||
exists: true,
|
||||
created: !agentsMdExists || overwriteAgentsMd,
|
||||
},
|
||||
opencodeJson: {
|
||||
path: opencodeJsonPath,
|
||||
exists: true,
|
||||
created: !opencodeJsonExists || overwriteOpenCodeConfig || hasLegacyOpenCodeConfig,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function isLegacyAssistantOpenCodeConfig(opencodeJsonPath: string): Promise<boolean> {
|
||||
try {
|
||||
const content = await readFileContent(opencodeJsonPath)
|
||||
const config = JSON.parse(content) as { permission?: { allow?: unknown; ask?: unknown } }
|
||||
return Array.isArray(config.permission?.allow) || Array.isArray(config.permission?.ask)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeStatus> {
|
||||
const assistantDir = getAssistantModeDirectory()
|
||||
|
||||
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
|
||||
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
|
||||
|
||||
const agentsMdExists = await fileExists(agentsMdPath)
|
||||
const opencodeJsonExists = await fileExists(opencodeJsonPath)
|
||||
|
||||
return {
|
||||
repoId: repo.id,
|
||||
directory: assistantDir,
|
||||
relativePath: ASSISTANT_MODE_RELATIVE_PATH,
|
||||
files: {
|
||||
agentsMd: {
|
||||
path: agentsMdPath,
|
||||
exists: agentsMdExists,
|
||||
created: false,
|
||||
},
|
||||
opencodeJson: {
|
||||
path: opencodeJsonPath,
|
||||
exists: opencodeJsonExists,
|
||||
created: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -21,10 +21,26 @@ vi.mock('../../src/services/repo', () => ({
|
||||
getCurrentBranch: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/assistant-mode', () => ({
|
||||
getAssistantModeStatus: vi.fn(),
|
||||
ensureAssistantMode: vi.fn(),
|
||||
getAssistantModeDirectory: vi.fn(),
|
||||
buildAssistantOpenCodeConfig: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-single-server', () => ({
|
||||
opencodeServerManager: {
|
||||
clearStartupError: vi.fn(),
|
||||
restart: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
import * as db from '../../src/db/queries'
|
||||
import { createRepoRoutes } from '../../src/routes/repos'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { ScheduleService } from '../../src/services/schedules'
|
||||
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
|
||||
import { getAssistantModeStatus, ensureAssistantMode } from '../../src/services/assistant-mode'
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({})
|
||||
@@ -98,4 +114,134 @@ describe('Repo Routes', () => {
|
||||
expect(body.error).toBe('Database error')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /:id/assistant-mode', () => {
|
||||
it('should return 404 when repo not found', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(null)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const res = await app.request('/1/assistant-mode', { method: 'GET' })
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('Repo not found')
|
||||
})
|
||||
|
||||
it('should call getAssistantModeStatus and return status', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
lastAccessedAt: Date.now(),
|
||||
}
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
|
||||
const mockStatus: AssistantModeStatus = {
|
||||
repoId: 1,
|
||||
directory: '/tmp/workspace/repos/assistant',
|
||||
relativePath: 'repos/assistant',
|
||||
files: {
|
||||
agentsMd: { path: '/tmp/workspace/repos/assistant/AGENTS.md', exists: false, created: false },
|
||||
opencodeJson: { path: '/tmp/workspace/repos/assistant/opencode.json', exists: false, created: false },
|
||||
},
|
||||
}
|
||||
|
||||
vi.mocked(getAssistantModeStatus).mockResolvedValue(mockStatus)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const res = await app.request('/1/assistant-mode', { method: 'GET' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as typeof mockStatus
|
||||
expect(body.repoId).toBe(1)
|
||||
expect(body.relativePath).toBe('repos/assistant')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:id/assistant-mode', () => {
|
||||
it('should return 404 when repo not found', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(null)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const res = await app.request('/1/assistant-mode', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
const body = await res.json() as { error: string }
|
||||
expect(body.error).toBe('Repo not found')
|
||||
})
|
||||
|
||||
it('should validate body and call ensureAssistantMode', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
lastAccessedAt: Date.now(),
|
||||
}
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
|
||||
const mockStatus: AssistantModeStatus = {
|
||||
repoId: 1,
|
||||
directory: '/tmp/workspace/repos/assistant',
|
||||
relativePath: 'repos/assistant',
|
||||
files: {
|
||||
agentsMd: { path: '/tmp/workspace/repos/assistant/AGENTS.md', exists: true, created: true },
|
||||
opencodeJson: { path: '/tmp/workspace/repos/assistant/opencode.json', exists: true, created: true },
|
||||
},
|
||||
}
|
||||
|
||||
vi.mocked(ensureAssistantMode).mockResolvedValue(mockStatus)
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const res = await app.request('/1/assistant-mode', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ overwriteAgentsMd: true }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
it('should handle errors from ensureAssistantMode', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo',
|
||||
localPath: 'repos/test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
lastAccessedAt: Date.now(),
|
||||
}
|
||||
vi.mocked(db.getRepoById).mockReturnValue(mockRepo)
|
||||
|
||||
vi.mocked(ensureAssistantMode).mockRejectedValue(new Error('Test error'))
|
||||
|
||||
const app = createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService)
|
||||
const res = await app.request('/1/assistant-mode', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it, beforeEach, vi } from 'vitest'
|
||||
import path from 'path'
|
||||
import type { Repo } from '@opencode-manager/shared/types'
|
||||
import {
|
||||
ensureAssistantMode,
|
||||
getAssistantModeStatus,
|
||||
getAssistantModeDirectory,
|
||||
buildAssistantOpenCodeConfig,
|
||||
} from '../../src/services/assistant-mode'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
const mockRepo: Repo = {
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/example/test-repo.git',
|
||||
localPath: 'test-repo',
|
||||
fullPath: '/tmp/test-repo',
|
||||
sourcePath: '/tmp/test-repo/.git',
|
||||
branch: 'main',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
lastPulled: Date.now(),
|
||||
lastAccessedAt: Date.now(),
|
||||
openCodeConfigName: 'default',
|
||||
isWorktree: false,
|
||||
isLocal: false,
|
||||
}
|
||||
|
||||
const fsMocks = vi.hoisted(() => ({
|
||||
writeFile: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
access: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
}))
|
||||
|
||||
const { writeFile, mkdir, access, readFile } = fsMocks
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
default: {
|
||||
writeFile: fsMocks.writeFile,
|
||||
readFile: fsMocks.readFile,
|
||||
mkdir: fsMocks.mkdir,
|
||||
access: fsMocks.access,
|
||||
stat: fsMocks.stat,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
promises: {
|
||||
writeFile: fsMocks.writeFile,
|
||||
readFile: fsMocks.readFile,
|
||||
mkdir: fsMocks.mkdir,
|
||||
access: fsMocks.access,
|
||||
stat: fsMocks.stat,
|
||||
},
|
||||
}))
|
||||
|
||||
describe('getAssistantModeDirectory', () => {
|
||||
it('returns the shared assistant path within repos root', () => {
|
||||
const result = getAssistantModeDirectory()
|
||||
expect(result).toBe(path.join(getReposPath(), 'assistant'))
|
||||
})
|
||||
|
||||
it('resolves path correctly', () => {
|
||||
const result = getAssistantModeDirectory()
|
||||
expect(result).toContain(path.join('repos', 'assistant'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildAssistantOpenCodeConfig', () => {
|
||||
it('returns valid OpenCode config', () => {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
const result = OpenCodeConfigSchema.safeParse(config)
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('includes instructions for AGENTS.md', () => {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
expect(config.instructions).toEqual(['AGENTS.md'])
|
||||
})
|
||||
|
||||
it('has permission rules for the assistant workspace', () => {
|
||||
const config = buildAssistantOpenCodeConfig()
|
||||
expect(config.permission).toEqual({
|
||||
read: 'allow',
|
||||
edit: 'allow',
|
||||
glob: 'allow',
|
||||
grep: 'allow',
|
||||
list: 'allow',
|
||||
bash: 'allow',
|
||||
external_directory: 'ask',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureAssistantMode', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
readFile.mockResolvedValue(JSON.stringify(buildAssistantOpenCodeConfig()))
|
||||
})
|
||||
|
||||
it('creates the shared assistant workspace and files when missing', async () => {
|
||||
access.mockRejectedValue(new Error('File not found'))
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
|
||||
expect(result.directory).toBe(path.join(getReposPath(), 'assistant'))
|
||||
expect(result.relativePath).toBe('repos/assistant')
|
||||
expect(result.files.agentsMd.exists).toBe(true)
|
||||
expect(result.files.opencodeJson.exists).toBe(true)
|
||||
})
|
||||
|
||||
it('does not overwrite existing customized files by default', async () => {
|
||||
access.mockResolvedValue(undefined)
|
||||
mkdir.mockResolvedValue(undefined)
|
||||
writeFile.mockResolvedValue(undefined)
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
|
||||
expect(result.files.agentsMd.exists).toBe(true)
|
||||
expect(result.files.agentsMd.created).toBe(false)
|
||||
expect(result.files.opencodeJson.exists).toBe(true)
|
||||
expect(result.files.opencodeJson.created).toBe(false)
|
||||
|
||||
expect(writeFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('overwrites only files whose overwrite option is true', async () => {
|
||||
access.mockResolvedValue(undefined)
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo, {
|
||||
overwriteAgentsMd: true,
|
||||
overwriteOpenCodeConfig: true,
|
||||
})
|
||||
|
||||
expect(result.files.agentsMd.created).toBe(true)
|
||||
expect(result.files.opencodeJson.created).toBe(true)
|
||||
})
|
||||
|
||||
it('overwrites legacy invalid assistant opencode config', async () => {
|
||||
access.mockResolvedValue(undefined)
|
||||
readFile.mockResolvedValue(JSON.stringify({
|
||||
instructions: ['AGENTS.md'],
|
||||
permission: {
|
||||
allow: ['**/*'],
|
||||
ask: ['../**/*'],
|
||||
},
|
||||
}))
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
|
||||
expect(result.files.opencodeJson.created).toBe(true)
|
||||
const content = writeFile.mock.calls[0]?.[1]
|
||||
expect(Buffer.isBuffer(content)).toBe(true)
|
||||
expect((content as Buffer).toString('utf8')).toContain('external_directory')
|
||||
})
|
||||
|
||||
it('returns a directory under the repos root', async () => {
|
||||
access.mockRejectedValue(new Error('File not found'))
|
||||
mkdir.mockResolvedValue(undefined)
|
||||
writeFile.mockResolvedValue(undefined)
|
||||
|
||||
const result = await ensureAssistantMode(mockRepo)
|
||||
|
||||
expect(result.directory).toBe(path.join(getReposPath(), 'assistant'))
|
||||
expect(result.directory.startsWith(getReposPath())).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAssistantModeStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('reports existence for folder files', async () => {
|
||||
access
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
|
||||
const result = await getAssistantModeStatus(mockRepo)
|
||||
|
||||
expect(result.repoId).toBe(mockRepo.id)
|
||||
expect(result.relativePath).toBe('repos/assistant')
|
||||
expect(result.files.agentsMd.exists).toBe(true)
|
||||
expect(result.files.opencodeJson.exists).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -12,6 +12,7 @@ import { GlobalSchedules } from './pages/GlobalSchedules'
|
||||
import { Login } from './pages/Login'
|
||||
import { Register } from './pages/Register'
|
||||
import { Setup } from './pages/Setup'
|
||||
import { AssistantRedirect } from './pages/AssistantRedirect'
|
||||
import { SettingsDialog } from './components/settings/SettingsDialog'
|
||||
import { VersionNotifier } from './components/VersionNotifier'
|
||||
import { PwaUpdatePrompt } from '@/components/PwaUpdatePrompt'
|
||||
@@ -188,11 +189,21 @@ const router = createBrowserRouter([
|
||||
element: <Repos />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/assistant',
|
||||
element: <AssistantRedirect />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id',
|
||||
element: <RepoDetail />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id/assistant',
|
||||
element: <AssistantRedirect />,
|
||||
loader: protectedLoader,
|
||||
},
|
||||
{
|
||||
path: '/repos/:id/sessions/:sessionId',
|
||||
element: <SessionDetail />,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Repo } from './types'
|
||||
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { DiscoverReposResponse } from '@opencode-manager/shared/types'
|
||||
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
|
||||
|
||||
export interface CreateRepoOptions {
|
||||
repoUrl?: string
|
||||
@@ -166,3 +166,20 @@ export async function touchRepoActivity(id: number): Promise<void> {
|
||||
method: 'POST',
|
||||
})
|
||||
}
|
||||
|
||||
export async function getAssistantModeStatus(id: number): Promise<AssistantModeStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, {
|
||||
method: 'GET',
|
||||
})
|
||||
}
|
||||
|
||||
export async function initializeAssistantMode(
|
||||
id: number,
|
||||
options?: AssistantModeInitRequest
|
||||
): Promise<AssistantModeStatus> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/assistant-mode`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(options ?? {}),
|
||||
})
|
||||
}
|
||||
@@ -1,22 +1,25 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('@/hooks/useMobile')
|
||||
vi.mock('@/contexts/EventContext', () => ({
|
||||
usePendingAlerts: vi.fn(),
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, it, expect, beforeEach } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MobileTabBar } from './MobileTabBar'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { usePendingAlerts } from '@/contexts/EventContext'
|
||||
|
||||
function LocationSpy() {
|
||||
const { pathname, search } = useLocation()
|
||||
return <div data-testid="location">{`${pathname}${search}`}</div>
|
||||
}
|
||||
|
||||
describe('MobileTabBar', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('renders nothing when useMobile returns false', () => {
|
||||
@@ -59,6 +62,65 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders global tabs on assistant session list path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123/assistant?view=sessions']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Assistant')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('navigates to assistant route when repo id is present', async () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/repos/123']}>
|
||||
<Routes>
|
||||
<Route path="*" element={<>
|
||||
<MobileTabBar />
|
||||
<LocationSpy />
|
||||
</>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Assistant' }))
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/123/assistant')
|
||||
})
|
||||
|
||||
it('navigates to assistant route when assistant is clicked without repo id', async () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/schedules']}>
|
||||
<Routes>
|
||||
<Route path="*" element={<>
|
||||
<MobileTabBar />
|
||||
<LocationSpy />
|
||||
</>} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Assistant' }))
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/assistant')
|
||||
})
|
||||
|
||||
it('renders schedule tabs on /repos/:id/schedules path', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
@@ -72,7 +134,7 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByText('Jobs')).toBeInTheDocument()
|
||||
expect(screen.getByText('Detail')).toBeInTheDocument()
|
||||
expect(screen.getByText('Runs')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Alerts')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Assistant')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders tab bar on root path', () => {
|
||||
@@ -87,7 +149,7 @@ describe('MobileTabBar', () => {
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Files')).toBeInTheDocument()
|
||||
expect(screen.getByText('Alerts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Assistant')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
expect(screen.getByText('More')).toBeInTheDocument()
|
||||
})
|
||||
@@ -106,36 +168,6 @@ describe('MobileTabBar', () => {
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows badge when usePendingAlerts returns true', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const badge = document.querySelector('.bg-orange-500')
|
||||
expect(badge).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show badge when usePendingAlerts returns false', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
vi.mocked(usePendingAlerts).mockReturnValue(false)
|
||||
const queryClient = new QueryClient()
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<MobileTabBar />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
const badge = document.querySelector('.bg-orange-500')
|
||||
expect(badge).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('Repos tab is active when pathname is / and no sheet is open', () => {
|
||||
vi.mocked(useMobile).mockReturnValue(true)
|
||||
const queryClient = new QueryClient()
|
||||
@@ -218,7 +250,7 @@ describe('MobileTabBar', () => {
|
||||
)
|
||||
expect(screen.getByText('Repos')).toBeInTheDocument()
|
||||
expect(screen.getByText('Files')).toBeInTheDocument()
|
||||
expect(screen.getByText('Alerts')).toBeInTheDocument()
|
||||
expect(screen.getByText('Assistant')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedules')).toBeInTheDocument()
|
||||
expect(screen.getByText('More')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { memo, useMemo } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { FolderGit2, FolderOpen, Bell, CalendarClock, Menu, Info, History } from 'lucide-react'
|
||||
import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useMobileTabBar, useScheduleTab, type ScheduleTabKey } from '@/hooks/useMobileTabBar'
|
||||
import { usePendingAlerts } from '@/contexts/EventContext'
|
||||
|
||||
interface TabDef {
|
||||
key: string
|
||||
@@ -17,24 +16,75 @@ interface TabDef {
|
||||
|
||||
interface GlobalTabsArgs {
|
||||
pathname: string
|
||||
search: string
|
||||
openSheet: ReturnType<typeof useMobileTabBar>['openSheet']
|
||||
open: ReturnType<typeof useMobileTabBar>['open']
|
||||
close: ReturnType<typeof useMobileTabBar>['close']
|
||||
navigate: ReturnType<typeof useNavigate>
|
||||
hasPending: boolean
|
||||
isInsideRepo: boolean
|
||||
repoId: string | null
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId }: GlobalTabsArgs): TabDef[] {
|
||||
type TabBarMode = 'hidden' | 'global' | 'schedule'
|
||||
|
||||
interface MobileTabRouteState {
|
||||
mode: TabBarMode
|
||||
isInsideRepo: boolean
|
||||
repoId: string | null
|
||||
}
|
||||
|
||||
function getMobileTabRouteState(pathname: string): MobileTabRouteState {
|
||||
const repoMatch = pathname.match(/^\/repos\/(\d+)(?:\/([^/]+))?/)
|
||||
const repoId = repoMatch?.[1] ?? null
|
||||
const repoSection = repoMatch?.[2]
|
||||
|
||||
if (pathname === '/' || pathname === '/schedules') {
|
||||
return { mode: 'global', isInsideRepo: false, repoId: null }
|
||||
}
|
||||
|
||||
if (!repoId) {
|
||||
return { mode: 'hidden', isInsideRepo: false, repoId: null }
|
||||
}
|
||||
|
||||
switch (repoSection) {
|
||||
case undefined:
|
||||
case 'memories':
|
||||
case 'assistant':
|
||||
return { mode: 'global', isInsideRepo: true, repoId }
|
||||
case 'schedules':
|
||||
return { mode: 'schedule', isInsideRepo: true, repoId }
|
||||
default:
|
||||
return { mode: 'hidden', isInsideRepo: false, repoId }
|
||||
}
|
||||
}
|
||||
|
||||
function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, isInsideRepo, repoId }: GlobalTabsArgs): TabDef[] {
|
||||
const navigateWithSearch = (params: URLSearchParams) => {
|
||||
const nextSearch = params.toString()
|
||||
navigate(nextSearch ? `${pathname}?${nextSearch}` : pathname, { replace: true })
|
||||
}
|
||||
|
||||
const handleFilesClick = () => {
|
||||
if (isInsideRepo && repoId) {
|
||||
const newParams = new URLSearchParams({ dialog: 'files' })
|
||||
navigate(`${pathname}?${newParams.toString()}`, { replace: true })
|
||||
const newParams = new URLSearchParams(search)
|
||||
newParams.set('dialog', 'files')
|
||||
navigateWithSearch(newParams)
|
||||
} else {
|
||||
open('files')
|
||||
}
|
||||
}
|
||||
|
||||
const handleAssistantClick = () => {
|
||||
if (repoId) {
|
||||
close()
|
||||
navigate(`/repos/${repoId}/assistant`)
|
||||
return
|
||||
}
|
||||
|
||||
close()
|
||||
navigate('/assistant')
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
key: 'repos',
|
||||
@@ -51,12 +101,11 @@ function buildGlobalTabs({ pathname, openSheet, open, navigate, hasPending, isIn
|
||||
active: openSheet === 'files',
|
||||
},
|
||||
{
|
||||
key: 'notifications',
|
||||
label: 'Alerts',
|
||||
icon: Bell,
|
||||
onClick: () => open('notifications'),
|
||||
badge: hasPending,
|
||||
active: openSheet === 'notifications',
|
||||
key: 'assistant',
|
||||
label: 'Assistant',
|
||||
icon: Bot,
|
||||
onClick: handleAssistantClick,
|
||||
active: false,
|
||||
},
|
||||
{
|
||||
key: 'schedules',
|
||||
@@ -137,42 +186,41 @@ const TabBarRow = memo(function TabBarRow({ tabs }: TabBarRowProps) {
|
||||
})
|
||||
|
||||
export const MobileTabBar = memo(function MobileTabBar() {
|
||||
const { pathname } = useLocation()
|
||||
const { pathname, search } = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const { openSheet, open } = useMobileTabBar()
|
||||
const { openSheet, open, close } = useMobileTabBar()
|
||||
const { scheduleTab, setScheduleTab } = useScheduleTab()
|
||||
const hasPending = usePendingAlerts()
|
||||
|
||||
const isOnRepoSchedules = /^\/repos\/\d+\/schedules$/.test(pathname)
|
||||
const isRepoMemories = /^\/repos\/\d+\/memories$/.test(pathname)
|
||||
const isMobile = useMobile()
|
||||
const isRoot = pathname === '/'
|
||||
const isGlobalSchedules = pathname === '/schedules'
|
||||
const isRepoDetail = /^\/repos\/\d+$/.test(pathname)
|
||||
const isInsideRepo = isRepoDetail || isOnRepoSchedules || isRepoMemories
|
||||
const isRepoSession = /^\/repos\/\d+\/sessions\/\w+/.test(pathname)
|
||||
const allow = isRoot || isGlobalSchedules || (isInsideRepo && !isRepoSession)
|
||||
|
||||
const repoIdMatch = pathname.match(/^\/repos\/(\d+)/)
|
||||
const repoId = repoIdMatch ? repoIdMatch[1] : null
|
||||
const routeState = useMemo(() => getMobileTabRouteState(pathname), [pathname])
|
||||
|
||||
const tabs = useMemo<TabDef[]>(
|
||||
() => (isOnRepoSchedules
|
||||
() => (routeState.mode === 'schedule'
|
||||
? buildScheduleTabs(scheduleTab, setScheduleTab)
|
||||
: buildGlobalTabs({
|
||||
pathname,
|
||||
openSheet,
|
||||
open,
|
||||
navigate,
|
||||
hasPending,
|
||||
isInsideRepo,
|
||||
repoId,
|
||||
})),
|
||||
[isOnRepoSchedules, scheduleTab, setScheduleTab, pathname, openSheet, open, navigate, hasPending, isInsideRepo, repoId],
|
||||
pathname,
|
||||
search,
|
||||
openSheet,
|
||||
open,
|
||||
close,
|
||||
navigate,
|
||||
isInsideRepo: routeState.isInsideRepo,
|
||||
repoId: routeState.repoId,
|
||||
})),
|
||||
[
|
||||
routeState,
|
||||
scheduleTab,
|
||||
setScheduleTab,
|
||||
pathname,
|
||||
search,
|
||||
openSheet,
|
||||
open,
|
||||
close,
|
||||
navigate,
|
||||
],
|
||||
)
|
||||
|
||||
if (!isMobile) return null
|
||||
if (!allow) return null
|
||||
if (routeState.mode === 'hidden') return null
|
||||
|
||||
return <TabBarRow tabs={tabs} />
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
|
||||
import { listRepos } from '@/api/repos'
|
||||
@@ -24,6 +24,11 @@ function createWrapper() {
|
||||
)
|
||||
}
|
||||
|
||||
function LocationSpy() {
|
||||
const { pathname, search } = useLocation()
|
||||
return <div data-testid="location">{`${pathname}${search}`}</div>
|
||||
}
|
||||
|
||||
describe('RepoQuickSwitchSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
@@ -117,4 +122,46 @@ describe('RepoQuickSwitchSheet', () => {
|
||||
fireEvent.click(screen.getByText('repo1'))
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('navigates directly to assistant when mobileTabAction is assistant', async () => {
|
||||
vi.mocked(listRepos).mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
repoUrl: 'https://github.com/test/repo1.git',
|
||||
localPath: '/path/to/repo1',
|
||||
sourcePath: null,
|
||||
currentBranch: 'main',
|
||||
isLocal: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<MemoryRouter initialEntries={['/schedules?mobileTab=repos&mobileTabAction=assistant']}>
|
||||
<Routes>
|
||||
<Route
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
|
||||
<LocationSpy />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('repo1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
fireEvent.click(screen.getByText('repo1'))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/assistant')
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -43,6 +43,13 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
|
||||
if (pendingAction === 'assistant') {
|
||||
navigate(`/repos/${id}/assistant`)
|
||||
return
|
||||
}
|
||||
|
||||
navigate(`/repos/${id}`, { replace: true })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
getAssistantModeStatus,
|
||||
initializeAssistantMode,
|
||||
} from '@/api/repos'
|
||||
import type { AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
|
||||
|
||||
export function useAssistantMode(repoId: number) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const statusQuery = useQuery<AssistantModeStatus>({
|
||||
queryKey: ['repo', repoId, 'assistant-mode'],
|
||||
queryFn: () => getAssistantModeStatus(repoId),
|
||||
enabled: !!repoId,
|
||||
})
|
||||
|
||||
const initializeMutation = useMutation({
|
||||
mutationFn: (options?: AssistantModeInitRequest) =>
|
||||
initializeAssistantMode(repoId, options),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['repo', repoId, 'assistant-mode'],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
status: statusQuery.data,
|
||||
isLoading: statusQuery.isLoading,
|
||||
isError: statusQuery.isError,
|
||||
error: statusQuery.error,
|
||||
initialize: initializeMutation.mutateAsync,
|
||||
isInitializing: initializeMutation.isPending,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { useAssistantSessionLauncher } from './useAssistantSessionLauncher'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { initializeAssistantMode } from '@/api/repos'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listSessions: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
initializeAssistantMode: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
initializeAssistantMode: mocks.initializeAssistantMode,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
OpenCodeClient: vi.fn(() => ({
|
||||
listSessions: mocks.listSessions,
|
||||
createSession: mocks.createSession,
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('useAssistantSessionLauncher', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.initializeAssistantMode.mockResolvedValue({ directory: '/assistant' })
|
||||
})
|
||||
|
||||
it('opens the latest root session in the assistant directory', async () => {
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'older', directory: '/assistant', time: { updated: 10 } },
|
||||
{ id: 'newest-child', parentID: 'newest', directory: '/assistant', time: { updated: 40 } },
|
||||
{ id: 'different-directory', directory: '/other', time: { updated: 50 } },
|
||||
{ id: 'newest', directory: '/assistant', time: { updated: 30 } },
|
||||
])
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(initializeAssistantMode).toHaveBeenCalledWith(123)
|
||||
expect(OpenCodeClient).toHaveBeenCalledWith('http://localhost:5551', '/assistant')
|
||||
expect(onNavigate).toHaveBeenCalledWith('newest')
|
||||
expect(mocks.createSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('creates a session when the assistant directory has no root sessions', async () => {
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'other', directory: '/other', time: { updated: 50 } },
|
||||
])
|
||||
mocks.createSession.mockResolvedValue({ id: 'created' })
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(mocks.createSession).toHaveBeenCalledWith({ title: 'Assistant' })
|
||||
expect(onNavigate).toHaveBeenCalledWith('created')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useCallback } from 'react'
|
||||
import { initializeAssistantMode } from '@/api/repos'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
|
||||
interface UseAssistantSessionLauncherOptions {
|
||||
repoId: number
|
||||
opcodeUrl: string
|
||||
onNavigate: (sessionId: string) => void
|
||||
}
|
||||
|
||||
export function useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
onNavigate,
|
||||
}: UseAssistantSessionLauncherOptions) {
|
||||
const openAssistant = useCallback(async () => {
|
||||
const assistant = await initializeAssistantMode(repoId)
|
||||
const client = new OpenCodeClient(opcodeUrl, assistant.directory)
|
||||
const sessions = await client.listSessions()
|
||||
|
||||
const assistantDirectory = assistant.directory
|
||||
|
||||
const rootSessions = sessions.filter(
|
||||
(session) => !session.parentID
|
||||
)
|
||||
|
||||
const assistantSessions = rootSessions.filter(
|
||||
(session) => session.directory === assistantDirectory
|
||||
)
|
||||
|
||||
const newest = assistantSessions.sort(
|
||||
(a, b) => b.time.updated - a.time.updated
|
||||
)[0]
|
||||
|
||||
if (newest) {
|
||||
onNavigate(newest.id)
|
||||
} else {
|
||||
const session = await client.createSession({ title: 'Assistant' })
|
||||
onNavigate(session.id)
|
||||
}
|
||||
}, [repoId, opcodeUrl, onNavigate])
|
||||
|
||||
return { openAssistant }
|
||||
}
|
||||
@@ -25,10 +25,10 @@ describe('useSwipeBack', () => {
|
||||
|
||||
it('calls onClose when swipe completes and canBack is false', () => {
|
||||
mockCanBack.mockReturnValue(false)
|
||||
|
||||
|
||||
const element = document.createElement('div')
|
||||
document.body.appendChild(element)
|
||||
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useSwipeBack(mockOnClose, {
|
||||
enabled: true,
|
||||
@@ -39,7 +39,7 @@ describe('useSwipeBack', () => {
|
||||
)
|
||||
|
||||
const cleanup = result.current.bind(element)
|
||||
|
||||
|
||||
const touchStart = new TouchEvent('touchstart', {
|
||||
touches: [{ clientX: 10, clientY: 100 }] as any,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { useParams, useNavigate, useLocation } from "react-router-dom"
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
import { getRepo, initializeAssistantMode, listRepos } from "@/api/repos"
|
||||
import { useAssistantSessionLauncher } from "@/hooks/useAssistantSessionLauncher"
|
||||
import { useCreateSession } from "@/hooks/useOpenCode"
|
||||
import { useDialogParam } from "@/hooks/useDialogParam"
|
||||
import { useMemoryPluginStatus } from "@/hooks/useMemoryPluginStatus"
|
||||
import { useSSE } from "@/hooks/useSSE"
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Header } from "@/components/ui/header"
|
||||
import { SessionList } from "@/components/session/SessionList"
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog"
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"
|
||||
import { SourceControlPanel } from "@/components/source-control"
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
|
||||
import { invalidateConfigCaches } from "@/lib/queryInvalidation"
|
||||
import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog"
|
||||
import { Brain, CalendarClock, FolderOpen, GitCommitHorizontal, Loader2, Plug, Plus, ShieldOff, Sparkles } from "lucide-react"
|
||||
|
||||
export function AssistantRedirect() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const queryClient = useQueryClient()
|
||||
const repoId = Number(id) || 0
|
||||
const showSessionList = new URLSearchParams(location.search).get('view') === 'sessions'
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files')
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp')
|
||||
const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills')
|
||||
const [sourceControlOpen, setSourceControlOpen] = useDialogParam('sourceControl')
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions')
|
||||
const [switchConfigOpen, setSwitchConfigOpen] = useState(false)
|
||||
const [status, setStatus] = useState<"preparing" | "opening" | "creating" | "error">("preparing")
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus()
|
||||
|
||||
const { data: repo } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
enabled: showSessionList && !!repoId,
|
||||
})
|
||||
|
||||
const handleNavigate = useCallback((sessionId: string) => {
|
||||
setStatus("opening")
|
||||
navigate(`/repos/${repoId}/sessions/${sessionId}?assistant=1`)
|
||||
}, [navigate, repoId])
|
||||
|
||||
const { openAssistant } = useAssistantSessionLauncher({
|
||||
repoId,
|
||||
opcodeUrl,
|
||||
onNavigate: handleNavigate,
|
||||
})
|
||||
|
||||
const { data: assistantMode, isLoading: assistantModeLoading, error: assistantModeError } = useQuery({
|
||||
queryKey: ["repo", repoId, "assistant-mode"],
|
||||
queryFn: () => initializeAssistantMode(repoId),
|
||||
enabled: showSessionList && !!repoId,
|
||||
})
|
||||
|
||||
const assistantDirectory = assistantMode?.directory
|
||||
const assistantFileBasePath = assistantDirectory?.split('/').filter(Boolean).at(-1)
|
||||
|
||||
useSSE(opcodeUrl, assistantDirectory)
|
||||
|
||||
const createSessionMutation = useCreateSession(opcodeUrl, assistantDirectory, (session) => {
|
||||
navigate(`/repos/${repoId}/sessions/${session.id}?assistant=1`)
|
||||
})
|
||||
|
||||
const handleCreateSession = async () => {
|
||||
await createSessionMutation.mutateAsync({ agent: undefined })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function loadAndOpen() {
|
||||
try {
|
||||
if (showSessionList) return
|
||||
setStatus("preparing")
|
||||
if (!repoId) {
|
||||
const repos = await listRepos()
|
||||
const fallbackRepo = repos.sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))[0]
|
||||
if (!fallbackRepo) throw new Error("No repository available to open Assistant")
|
||||
navigate(`/repos/${fallbackRepo.id}/assistant`, { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
await getRepo(repoId)
|
||||
if (cancelled) return
|
||||
setStatus("creating")
|
||||
await openAssistant()
|
||||
} catch (error) {
|
||||
if (cancelled) return
|
||||
setStatus("error")
|
||||
setErrorMessage(error instanceof Error ? error.message : "Failed to open Assistant")
|
||||
}
|
||||
}
|
||||
|
||||
loadAndOpen()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [repoId, openAssistant, navigate, showSessionList])
|
||||
|
||||
if (showSessionList) {
|
||||
return (
|
||||
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
|
||||
<Header>
|
||||
<Header.BackButton to={`/repos/${repoId}`} />
|
||||
<Header.Title>Assistant</Header.Title>
|
||||
<Header.Actions>
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => setMcpDialogOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<Plug className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">MCP</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSkillsDialogOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<Sparkles className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Skills</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSourceControlOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<GitCommitHorizontal className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Source</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setFileBrowserOpen(true)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setResetPermissionsOpen(true)} size="sm" className="hidden lg:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<ShieldOff className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Reset Permissions</span>
|
||||
</Button>
|
||||
{memoryPluginEnabled && (
|
||||
<Button variant="outline" onClick={() => navigate(`/repos/${repoId}/memories`)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => navigate(`/repos/${repoId}/schedules`)} size="sm" className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105">
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Button onClick={() => handleCreateSession()} disabled={!opcodeUrl || !assistantDirectory || createSessionMutation.isPending} size="sm" className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button onClick={() => handleCreateSession()} disabled={!opcodeUrl || !assistantDirectory || createSessionMutation.isPending} size="sm" className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105">
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{assistantModeError ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">Failed to load Assistant sessions</div>
|
||||
) : assistantModeLoading || !assistantMode ? (
|
||||
<div className="p-4 text-sm text-muted-foreground">Loading Assistant sessions...</div>
|
||||
) : (
|
||||
<SessionList
|
||||
opcodeUrl={opcodeUrl}
|
||||
directory={assistantDirectory}
|
||||
onSelectSession={(sessionId) => navigate(`/repos/${repoId}/sessions/${sessionId}?assistant=1`)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{assistantDirectory && (
|
||||
<>
|
||||
<FileBrowserSheet isOpen={fileBrowserOpen} onClose={() => setFileBrowserOpen(false)} basePath={assistantFileBasePath} repoName="Assistant" repoId={repoId} />
|
||||
<RepoMcpDialog open={mcpDialogOpen} onOpenChange={setMcpDialogOpen} directory={assistantDirectory} />
|
||||
<RepoSkillsDialog open={skillsDialogOpen} onOpenChange={setSkillsDialogOpen} repoId={repoId} />
|
||||
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
|
||||
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} repoDirectory={assistantDirectory} />
|
||||
</>
|
||||
)}
|
||||
{repo && (
|
||||
<SwitchConfigDialog
|
||||
open={switchConfigOpen}
|
||||
onOpenChange={setSwitchConfigOpen}
|
||||
repoId={repoId}
|
||||
currentConfigName={repo.openCodeConfigName}
|
||||
onConfigSwitched={(configName) => {
|
||||
queryClient.setQueryData(["repo", repoId], { ...repo, openCodeConfigName: configName })
|
||||
invalidateConfigCaches(queryClient)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-background">
|
||||
<div className="text-center max-w-md px-4">
|
||||
{status === "error" ? (
|
||||
<>
|
||||
<p className="text-muted-foreground mb-4">{errorMessage}</p>
|
||||
<Button
|
||||
onClick={() => navigate(`/repos/${repoId}`)}
|
||||
variant="outline"
|
||||
>
|
||||
Go Back
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => window.location.reload()}
|
||||
className="ml-2"
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
{status === "preparing" && "Preparing Assistant workspace..."}
|
||||
{status === "creating" && "Opening your last session chat..."}
|
||||
{status === "opening" && "Opening your last session chat..."}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -111,20 +111,16 @@ export function RepoDetail() {
|
||||
<div
|
||||
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0"
|
||||
>
|
||||
<Header>
|
||||
<Header.BackButton to="/" />
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Header.Title>{repoName}</Header.Title>
|
||||
{isWorktree ? (
|
||||
<Badge className="text-xs px-1.5 sm:px-2.5 py-0.5 bg-purple-600/20 text-purple-400 border-purple-600/40" title="Worktree">
|
||||
<GitBranch className="h-3 w-3 sm:mr-1" />
|
||||
<span className="hidden sm:inline">WT: {currentBranch}</span>
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
<Header>
|
||||
<Header.BackButton to="/" />
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Header.Title>{repoName}</Header.Title>
|
||||
{isWorktree ? (
|
||||
<Badge className="text-xs px-1.5 sm:px-2.5 py-0.5 bg-purple-600/20 text-purple-400 border-purple-600/40" title="Worktree">
|
||||
<GitBranch className="h-3 w-3 sm:mr-1" />
|
||||
<span className="hidden sm:inline">WT: {currentBranch}</span>
|
||||
</Badge>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -186,42 +182,98 @@ export function RepoDetail() {
|
||||
{memoryPluginEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
onClick={() => setMcpDialogOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
<Plug className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">MCP</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/schedules`)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSkillsDialogOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Sparkles className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Skills</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setSourceControlOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<GitCommitHorizontal className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Source</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setResetPermissionsOpen(true)}
|
||||
size="sm"
|
||||
className="hidden lg:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<ShieldOff className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Reset Permissions</span>
|
||||
</Button>
|
||||
{memoryPluginEnabled && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/memories`)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Brain className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Memory</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/repos/${repoId}/schedules`)}
|
||||
size="sm"
|
||||
className="hidden md:flex text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<CalendarClock className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Schedules</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => navigate(`/repos/${repoId}/assistant`)}
|
||||
disabled={!opcodeUrl}
|
||||
size="sm"
|
||||
className="hidden sm:inline-flex bg-purple-600 hover:bg-purple-700 text-white transition-all duration-200 hover:scale-105"
|
||||
aria-label="Open Assistant"
|
||||
>
|
||||
<Bot className="w-4 h-4 mr-2" />
|
||||
<span>Assistant</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="hidden sm:inline-flex bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
<span>New Session</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="sm:hidden h-10 w-10 p-0 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
</Button>
|
||||
</Header.Actions>
|
||||
</Header>
|
||||
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{opcodeUrl && repoDirectory && (
|
||||
|
||||
@@ -24,7 +24,7 @@ export function Repos() {
|
||||
<Header.Title logo>OpenCode</Header.Title>
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate, Navigate } from "react-router-dom";
|
||||
import { useParams, useNavigate, Navigate, useLocation } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getRepo } from "@/api/repos";
|
||||
import { getRepo, initializeAssistantMode } from "@/api/repos";
|
||||
import { MessageThread } from "@/components/message/MessageThread";
|
||||
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
|
||||
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
|
||||
@@ -62,7 +62,9 @@ const compareMessageIds = (id1: string, id2: string): number => {
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const repoId = Number(id) || 0;
|
||||
const isAssistantSession = new URLSearchParams(location.search).get('assistant') === '1';
|
||||
const { preferences, updateSettings } = useSettings();
|
||||
const { open: openSettings } = useSettingsDialog();
|
||||
const messageContainerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -109,13 +111,20 @@ export function SessionDetail() {
|
||||
enabled: !!repoId,
|
||||
});
|
||||
|
||||
const { data: assistantMode, isLoading: assistantModeLoading } = useQuery({
|
||||
queryKey: ["repo", repoId, "assistant-mode"],
|
||||
queryFn: () => initializeAssistantMode(repoId),
|
||||
enabled: isAssistantSession && !!repoId,
|
||||
});
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo));
|
||||
|
||||
const { memoryPluginEnabled } = useMemoryPluginStatus();
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
const repoDirectory = isAssistantSession ? assistantMode?.directory : repo?.fullPath;
|
||||
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
|
||||
|
||||
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory);
|
||||
const { data: session, isLoading: sessionLoading } = useSession(
|
||||
@@ -189,12 +198,12 @@ export function SessionDetail() {
|
||||
try {
|
||||
const newSession = await createSession.mutateAsync({ agent: undefined });
|
||||
if (newSession?.id) {
|
||||
navigate(`/repos/${repoId}/sessions/${newSession.id}`);
|
||||
navigate(`/repos/${repoId}/sessions/${newSession.id}${sessionRouteSuffix}`);
|
||||
}
|
||||
} catch {
|
||||
showToast.error('Failed to create new session');
|
||||
}
|
||||
}, [createSession, navigate, repoId]);
|
||||
}, [createSession, navigate, repoId, sessionRouteSuffix]);
|
||||
|
||||
const handleCompact = useCallback(async () => {
|
||||
if (!opcodeUrl || !sessionId) return;
|
||||
@@ -241,17 +250,17 @@ export function SessionDetail() {
|
||||
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
|
||||
const forkedSession = await client.forkSession(sessionId);
|
||||
if (forkedSession?.id) {
|
||||
navigate(`/repos/${repoId}/sessions/${forkedSession.id}`);
|
||||
navigate(`/repos/${repoId}/sessions/${forkedSession.id}${sessionRouteSuffix}`);
|
||||
showToast.success('Session forked');
|
||||
}
|
||||
} catch (error) {
|
||||
showToast.error(`Fork failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId]);
|
||||
}, [opcodeUrl, sessionId, repoDirectory, navigate, repoId, sessionRouteSuffix]);
|
||||
|
||||
const handleCloseSession = useCallback(() => {
|
||||
navigate(`/repos/${repoId}`);
|
||||
}, [navigate, repoId]);
|
||||
navigate(isAssistantSession ? `/repos/${repoId}/assistant?view=sessions` : `/repos/${repoId}`);
|
||||
}, [navigate, repoId, isAssistantSession]);
|
||||
|
||||
const { leaderActive } = useKeyboardShortcuts({
|
||||
openModelDialog: () => setModelDialogOpen(true),
|
||||
@@ -312,14 +321,14 @@ export function SessionDetail() {
|
||||
}, [setFileBrowserOpen]);
|
||||
|
||||
const handleChildSessionClick = useCallback((childSessionId: string) => {
|
||||
navigate(`/repos/${repoId}/sessions/${childSessionId}`)
|
||||
}, [navigate, repoId]);
|
||||
navigate(`/repos/${repoId}/sessions/${childSessionId}${sessionRouteSuffix}`)
|
||||
}, [navigate, repoId, sessionRouteSuffix]);
|
||||
|
||||
const handleParentSessionClick = useCallback(() => {
|
||||
if (session?.parentID) {
|
||||
navigate(`/repos/${repoId}/sessions/${session.parentID}`)
|
||||
navigate(`/repos/${repoId}/sessions/${session.parentID}${sessionRouteSuffix}`)
|
||||
}
|
||||
}, [navigate, repoId, session?.parentID]);
|
||||
}, [navigate, repoId, session?.parentID, sessionRouteSuffix]);
|
||||
|
||||
const handleToggleDetails = useCallback(() => {
|
||||
const newValue = !preferences?.expandToolCalls
|
||||
@@ -366,6 +375,11 @@ export function SessionDetail() {
|
||||
);
|
||||
}
|
||||
|
||||
const workspaceDisplayName = isAssistantSession ? 'Assistant' : getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
|
||||
const assistantFileBasePath = assistantMode?.directory.split('/').filter(Boolean).at(-1);
|
||||
const workspaceBasePath = (isAssistantSession ? assistantFileBasePath : repo.localPath) ?? repo.localPath;
|
||||
const sessionBackPath = isAssistantSession ? `/repos/${repoId}/assistant?view=sessions` : `/repos/${repoId}`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col"
|
||||
@@ -385,20 +399,20 @@ export function SessionDetail() {
|
||||
<span className="hidden sm:inline text-xs">Parent</span>
|
||||
</Button>
|
||||
<div className="hidden sm:block">
|
||||
<Header.BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
|
||||
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<Header.BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
|
||||
<Header.BackButton to={sessionBackPath} className="text-xs sm:text-sm" />
|
||||
)}
|
||||
<Header.EditableTitle
|
||||
value={session?.title || "Untitled Session"}
|
||||
onChange={handleSessionTitleUpdate}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}</span>}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{workspaceDisplayName}</span>}
|
||||
/>
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<ContextUsageIndicator
|
||||
@@ -488,7 +502,7 @@ export function SessionDetail() {
|
||||
|
||||
<div className="flex-1 overflow-hidden flex flex-col relative">
|
||||
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + 16 }}>
|
||||
{repoLoading || sessionLoading || messagesLoading ? (
|
||||
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
|
||||
<MessageSkeleton />
|
||||
) : opcodeUrl && repoDirectory ? (
|
||||
<MessageThread
|
||||
@@ -595,7 +609,7 @@ export function SessionDetail() {
|
||||
directory={repoDirectory}
|
||||
activeSessionID={sessionId || undefined}
|
||||
onSelectSession={(sessionID) => {
|
||||
navigate(`/repos/${repoId}/sessions/${sessionID}`)
|
||||
navigate(`/repos/${repoId}/sessions/${sessionID}${sessionRouteSuffix}`)
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
/>
|
||||
@@ -607,8 +621,8 @@ export function SessionDetail() {
|
||||
<FileBrowserSheet
|
||||
isOpen={fileBrowserOpen}
|
||||
onClose={handleFileBrowserClose}
|
||||
basePath={repo.localPath}
|
||||
repoName={getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
|
||||
basePath={workspaceBasePath}
|
||||
repoName={workspaceDisplayName}
|
||||
repoId={repoId}
|
||||
initialSelectedFile={selectedFilePath}
|
||||
/>
|
||||
@@ -637,7 +651,7 @@ export function SessionDetail() {
|
||||
isOpen={sourceControlOpen}
|
||||
onClose={() => setSourceControlOpen(false)}
|
||||
currentBranch={repo.currentBranch || repo.branch || "main"}
|
||||
repoName={getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}
|
||||
repoName={workspaceDisplayName}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
|
||||
@@ -1 +1 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
@@ -7,6 +7,9 @@ export default defineConfig({
|
||||
test: {
|
||||
environment: "jsdom",
|
||||
globals: true,
|
||||
env: {
|
||||
NODE_ENV: "test",
|
||||
},
|
||||
setupFiles: ["./src/test/setup.ts"],
|
||||
include: ["src/**/*.test.{ts,tsx}"],
|
||||
},
|
||||
|
||||
@@ -50,3 +50,24 @@ export const DiscoverReposResponseSchema = z.object({
|
||||
})
|
||||
),
|
||||
})
|
||||
|
||||
export const AssistantModeFileSchema = z.object({
|
||||
path: z.string(),
|
||||
exists: z.boolean(),
|
||||
created: z.boolean(),
|
||||
})
|
||||
|
||||
export const AssistantModeStatusSchema = z.object({
|
||||
repoId: z.number(),
|
||||
directory: z.string(),
|
||||
relativePath: z.literal('repos/assistant'),
|
||||
files: z.object({
|
||||
agentsMd: AssistantModeFileSchema,
|
||||
opencodeJson: AssistantModeFileSchema,
|
||||
}),
|
||||
})
|
||||
|
||||
export const AssistantModeInitRequestSchema = z.object({
|
||||
overwriteAgentsMd: z.boolean().optional(),
|
||||
overwriteOpenCodeConfig: z.boolean().optional(),
|
||||
})
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
DiscoverReposRequestSchema,
|
||||
DiscoverReposResponseSchema,
|
||||
RepoStatusSchema,
|
||||
AssistantModeStatusSchema,
|
||||
AssistantModeInitRequestSchema,
|
||||
} from '../schemas/repo'
|
||||
import {
|
||||
FileInfoSchema,
|
||||
@@ -53,6 +55,8 @@ export type CreateRepoRequest = z.infer<typeof CreateRepoRequestSchema>
|
||||
export type DiscoverReposRequest = z.infer<typeof DiscoverReposRequestSchema>
|
||||
export type DiscoverReposResponse = z.infer<typeof DiscoverReposResponseSchema>
|
||||
export type RepoStatus = z.infer<typeof RepoStatusSchema>
|
||||
export type AssistantModeStatus = z.infer<typeof AssistantModeStatusSchema>
|
||||
export type AssistantModeInitRequest = z.infer<typeof AssistantModeInitRequestSchema>
|
||||
|
||||
export type FileInfo = z.infer<typeof FileInfoSchema>
|
||||
export type CreateFileRequest = z.infer<typeof CreateFileRequestSchema>
|
||||
|
||||
Reference in new issue
Block a user