mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(assistant): self-configuring assistant mode (#244)
* test(backend): replace better-sqlite3 test mock with node:sqlite Reimplement the bun:sqlite test mock on top of node:sqlite with an explicit BEGIN/COMMIT/ROLLBACK transaction wrapper. * feat(assistant): self-configuring assistant mode Add a self-editable assistant workspace and the APIs that support it: - POST /assistant/reload disposes and re-bootstraps the assistant instance (directory-scoped, rate-limited) so agent.md edits apply. - Internal settings API accepts non-secret TTS/STT patches via dedicated partial schemas. - Strip the generated agent persona from opencode.json on repair so user-customized agents are preserved across config recovery. - Cache the last assistant session id to avoid redundant session listing on launch. * style(repo): align worktree and workspace tabs with primary/orange theme
This commit is contained in:
1 parent
eedbbfb94e
commit
dbd6866682
22 files changed
+733
-156
No files matched your search
@@ -3,6 +3,9 @@ import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
|
||||
|
||||
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
|
||||
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
|
||||
type SessionListParams = NonNullable<paths['/session']['get']['parameters']['query']> & {
|
||||
roots?: boolean
|
||||
}
|
||||
type CreateSessionRequest = NonNullable<paths['/session']['post']['requestBody']>['content']['application/json']
|
||||
type MessageListResponse = paths['/session/{sessionID}/message']['get']['responses']['200']['content']['application/json']
|
||||
type SendPromptRequest = NonNullable<paths['/session/{sessionID}/message']['post']['requestBody']>['content']['application/json']
|
||||
@@ -67,9 +70,9 @@ export class OpenCodeClient {
|
||||
return { ...params, directory: this.directory }
|
||||
}
|
||||
|
||||
async listSessions() {
|
||||
async listSessions(params?: SessionListParams) {
|
||||
return fetchWrapper<SessionListResponse>(`${this.baseURL}/session`, {
|
||||
params: this.getParams(),
|
||||
params: this.getParams(params),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ export function WorkspaceManager({
|
||||
const isActive = !!workspace.fullPath && workspace.fullPath === activeWorkspaceDirectory
|
||||
const label = workspaceLabel(workspace)
|
||||
const rowClassName = isActive
|
||||
? 'border-purple-500/50 bg-purple-500/10 text-foreground'
|
||||
? 'border-primary/50 bg-primary/10 text-foreground'
|
||||
: 'border-border bg-muted/30 hover:bg-muted/50'
|
||||
if (!manageMode) {
|
||||
return (
|
||||
@@ -197,9 +197,9 @@ export function WorkspaceManager({
|
||||
className={`flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-sm text-left ${rowClassName}`}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{isActive && <span className="text-xs text-purple-400">Selected</span>}
|
||||
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
<span className={isActive ? 'truncate text-orange-600 dark:text-orange-400' : 'truncate'}>{label}</span>
|
||||
{isActive && <span className="text-xs text-orange-600 dark:text-orange-400">Selected</span>}
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{workspace.fullPath}
|
||||
@@ -219,7 +219,7 @@ export function WorkspaceManager({
|
||||
onCheckedChange={(checked) => toggle(workspaceId, checked === true)}
|
||||
aria-label={`Select workspace ${label}`}
|
||||
/>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
|
||||
@@ -24,30 +24,33 @@ export function WorktreeTabs({
|
||||
}: WorktreeTabsProps) {
|
||||
const hasWorkspaces = workspaces.length > 0
|
||||
const workspaceLabel = value === 'workspaces' && activeWorkspaceLabel ? activeWorkspaceLabel : 'Workspaces'
|
||||
const tabClassName =
|
||||
'group min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3 data-[state=active]:border data-[state=active]:border-primary/50 data-[state=active]:bg-primary/10 data-[state=inactive]:hover:bg-accent data-[state=inactive]:hover:text-foreground'
|
||||
const activeLabelClassName = 'group-data-[state=active]:text-orange-600 dark:group-data-[state=active]:text-orange-400'
|
||||
|
||||
return (
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
<Tabs value={value} onValueChange={(next) => onValueChange(next as WorktreeTabValue)} className="min-w-0">
|
||||
<TabsList className="w-full justify-start overflow-hidden">
|
||||
<TabsTrigger value="repo" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3">
|
||||
<TabsList className="w-full justify-start gap-1 overflow-hidden">
|
||||
<TabsTrigger value="repo" className={tabClassName}>
|
||||
<GitBranch className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate">{baseLabel}</span>
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{baseLabel}</span>
|
||||
</TabsTrigger>
|
||||
{hasWorkspaces ? (
|
||||
<>
|
||||
<TabsTrigger value="workspaces" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3" onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<span className="min-w-0 truncate">{workspaceLabel}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">({workspaces.length})</span>
|
||||
<TabsTrigger value="workspaces" className={tabClassName} onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{workspaceLabel}</span>
|
||||
<span className={`shrink-0 text-xs text-muted-foreground ${activeLabelClassName}`}>({workspaces.length})</span>
|
||||
</TabsTrigger>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCreateWorkspace}
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-background hover:text-foreground sm:flex-none sm:px-3"
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground sm:flex-none sm:px-3"
|
||||
>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className="min-w-0 truncate">Workspace</span>
|
||||
<Plus className="h-3.5 w-3.5 shrink-0" />
|
||||
</button>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { initializeAssistantMode } from '@/api/repos'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listSessions: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
sendPromptAsync: vi.fn(),
|
||||
initializeAssistantMode: vi.fn(),
|
||||
@@ -18,6 +19,7 @@ vi.mock('@/api/repos', () => ({
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
OpenCodeClient: vi.fn(() => ({
|
||||
listSessions: mocks.listSessions,
|
||||
getSession: mocks.getSession,
|
||||
createSession: mocks.createSession,
|
||||
sendPromptAsync: mocks.sendPromptAsync,
|
||||
})),
|
||||
@@ -30,9 +32,29 @@ beforeEach(() => {
|
||||
describe('useAssistantSessionLauncher', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
mocks.initializeAssistantMode.mockResolvedValue({ directory: '/assistant' })
|
||||
})
|
||||
|
||||
it('opens the cached assistant session without listing sessions', async () => {
|
||||
localStorage.setItem('ocm:assistant:last-session:123:/assistant', 'cached')
|
||||
mocks.getSession.mockResolvedValue({ id: 'cached', directory: '/assistant', time: { updated: 20 } })
|
||||
const onNavigate = vi.fn()
|
||||
const { result } = renderHook(() => useAssistantSessionLauncher({
|
||||
repoId: 123,
|
||||
opcodeUrl: 'http://localhost:5551',
|
||||
onNavigate,
|
||||
}))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.openAssistant()
|
||||
})
|
||||
|
||||
expect(mocks.getSession).toHaveBeenCalledWith('cached')
|
||||
expect(mocks.listSessions).not.toHaveBeenCalled()
|
||||
expect(onNavigate).toHaveBeenCalledWith('cached')
|
||||
})
|
||||
|
||||
it('opens the latest root session in the assistant directory', async () => {
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'older', directory: '/assistant', time: { updated: 10 } },
|
||||
@@ -53,11 +75,36 @@ describe('useAssistantSessionLauncher', () => {
|
||||
|
||||
expect(initializeAssistantMode).toHaveBeenCalledWith(123)
|
||||
expect(OpenCodeClient).toHaveBeenCalledWith('http://localhost:5551', '/assistant')
|
||||
expect(mocks.listSessions).toHaveBeenCalledWith({ limit: 1, roots: true })
|
||||
expect(onNavigate).toHaveBeenCalledWith('newest')
|
||||
expect(localStorage.getItem('ocm:assistant:last-session:123:/assistant')).toBe('newest')
|
||||
expect(mocks.createSession).not.toHaveBeenCalled()
|
||||
expect(mocks.sendPromptAsync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to latest lookup when the cached session is stale', async () => {
|
||||
localStorage.setItem('ocm:assistant:last-session:123:/assistant', 'stale')
|
||||
mocks.getSession.mockRejectedValueOnce(new Error('not found'))
|
||||
mocks.listSessions.mockResolvedValue([
|
||||
{ id: 'latest', 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(mocks.getSession).toHaveBeenCalledWith('stale')
|
||||
expect(mocks.listSessions).toHaveBeenCalledWith({ limit: 1, roots: true })
|
||||
expect(onNavigate).toHaveBeenCalledWith('latest')
|
||||
expect(localStorage.getItem('ocm:assistant:last-session:123:/assistant')).toBe('latest')
|
||||
})
|
||||
|
||||
it('notifies an existing assistant session when some generated updates were preserved', async () => {
|
||||
mocks.initializeAssistantMode.mockResolvedValue({
|
||||
directory: '/assistant',
|
||||
@@ -84,6 +131,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
})
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith('existing')
|
||||
expect(mocks.listSessions).toHaveBeenCalledWith({ limit: 1, roots: true })
|
||||
expect(mocks.sendPromptAsync).toHaveBeenCalledWith('existing', {
|
||||
parts: [
|
||||
expect.objectContaining({
|
||||
@@ -122,6 +170,7 @@ describe('useAssistantSessionLauncher', () => {
|
||||
],
|
||||
})
|
||||
expect(onNavigate).toHaveBeenCalledWith('created')
|
||||
expect(localStorage.getItem('ocm:assistant:last-session:123:/assistant')).toBe('created')
|
||||
|
||||
const promptCall = mocks.sendPromptAsync.mock.calls[0]
|
||||
const promptText = promptCall[1].parts[0].text as string
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback } from 'react'
|
||||
import { initializeAssistantMode } from '@/api/repos'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
|
||||
interface UseAssistantSessionLauncherOptions {
|
||||
repoId: number
|
||||
@@ -9,6 +10,79 @@ interface UseAssistantSessionLauncherOptions {
|
||||
onNavigate: (sessionId: string) => void
|
||||
}
|
||||
|
||||
type OpenCodeSession = components['schemas']['Session']
|
||||
|
||||
const LAST_ASSISTANT_SESSION_KEY_PREFIX = 'ocm:assistant:last-session'
|
||||
|
||||
function getLastAssistantSessionKey(repoId: number, directory: string): string {
|
||||
return `${LAST_ASSISTANT_SESSION_KEY_PREFIX}:${repoId}:${directory}`
|
||||
}
|
||||
|
||||
function getCachedAssistantSessionId(repoId: number, directory: string): string | undefined {
|
||||
try {
|
||||
return localStorage.getItem(getLastAssistantSessionKey(repoId, directory)) || undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function setCachedAssistantSessionId(repoId: number, directory: string, sessionId: string): void {
|
||||
try {
|
||||
localStorage.setItem(getLastAssistantSessionKey(repoId, directory), sessionId)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function removeCachedAssistantSessionId(repoId: number, directory: string): void {
|
||||
try {
|
||||
localStorage.removeItem(getLastAssistantSessionKey(repoId, directory))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
function isAssistantRootSession(session: OpenCodeSession, assistantDirectory: string): boolean {
|
||||
return !session.parentID && session.directory === assistantDirectory
|
||||
}
|
||||
|
||||
function findNewestRootAssistantSession(sessions: OpenCodeSession[], assistantDirectory: string): OpenCodeSession | undefined {
|
||||
return sessions
|
||||
.filter((session) => isAssistantRootSession(session, assistantDirectory))
|
||||
.sort((a, b) => b.time.updated - a.time.updated)[0]
|
||||
}
|
||||
|
||||
async function getCachedAssistantSession(
|
||||
client: OpenCodeClient,
|
||||
repoId: number,
|
||||
assistantDirectory: string,
|
||||
): Promise<OpenCodeSession | undefined> {
|
||||
const cachedSessionId = getCachedAssistantSessionId(repoId, assistantDirectory)
|
||||
if (!cachedSessionId) return undefined
|
||||
|
||||
try {
|
||||
const session = await client.getSession(cachedSessionId)
|
||||
if (isAssistantRootSession(session, assistantDirectory)) return session
|
||||
removeCachedAssistantSessionId(repoId, assistantDirectory)
|
||||
} catch {
|
||||
removeCachedAssistantSessionId(repoId, assistantDirectory)
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
async function getLatestAssistantSession(
|
||||
client: OpenCodeClient,
|
||||
assistantDirectory: string,
|
||||
): Promise<OpenCodeSession | undefined> {
|
||||
const latestSessions = await client.listSessions({ limit: 1, roots: true })
|
||||
const latestRootSession = findNewestRootAssistantSession(latestSessions, assistantDirectory)
|
||||
if (latestRootSession || latestSessions.length === 0) return latestRootSession
|
||||
|
||||
const sessions = await client.listSessions()
|
||||
return findNewestRootAssistantSession(sessions, assistantDirectory)
|
||||
}
|
||||
|
||||
const ASSISTANT_WELCOME_PROMPT = `Welcome to OpenCode Manager! I'm your assistant and I'm here to help you work with your code.
|
||||
|
||||
To get started, let's set up your assistant:
|
||||
@@ -77,27 +151,18 @@ export function useAssistantSessionLauncher({
|
||||
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]
|
||||
const newest = await getCachedAssistantSession(client, repoId, assistantDirectory)
|
||||
?? await getLatestAssistantSession(client, assistantDirectory)
|
||||
|
||||
if (newest) {
|
||||
setCachedAssistantSessionId(repoId, assistantDirectory, newest.id)
|
||||
onNavigate(newest.id)
|
||||
void sendAssistantModeWarningsPrompt(client, newest.id, assistant)
|
||||
} else {
|
||||
const session = await client.createSession({ title: 'Assistant' })
|
||||
setCachedAssistantSessionId(repoId, assistantDirectory, session.id)
|
||||
onNavigate(session.id)
|
||||
void sendAssistantWelcomePrompt(client, session.id, assistant)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user