mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)
* feat(opencode): migrate OpenCode Manager to OpenCode 2 Port the backend lifecycle, generated plugins, event aggregation, schedules, worktrees, provider credentials, MCP, config handling, the frontend chat model, and the ocm CLI to OpenCode 2. Adopt @opencode/client 2.0.15 as the single typed V2 API contract, require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every V1-only code path. * refactor(opencode): reload config in place and drop v1 compatibility shims Route config/skill/AGENTS.md changes through the OpenCode location reload API instead of a full server restart, stop auto-resuming interrupted sessions, remove the restart coordinator and v1 MCP/version shims, and pin support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries, service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers. * refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows - extract shared semver and model-ref utilities, reuse across version checks - share the OpenCode release download script across Docker, entrypoint, dev setup - unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN - scope the repo proxy location rewrite and surface ocm proxy errors - rework frontend session projection, permission lookup, and cache invalidation * fix(schedules): reject unavailable agents before creating a session * feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
1 parent
6c2ebd764b
commit
dacde879d6
383 files changed
+29905
-46566
No files matched your search
@@ -1,9 +1,8 @@
|
||||
import { useContextUsage } from '@/hooks/useContextUsage'
|
||||
|
||||
interface ContextUsageIndicatorProps {
|
||||
opcodeUrl: string | null
|
||||
sessionID: string | undefined
|
||||
directory?: string
|
||||
sessionID: string | undefined
|
||||
isConnected: boolean
|
||||
isReconnecting?: boolean
|
||||
}
|
||||
@@ -14,8 +13,8 @@ const getUsageTextColor = (percentage: number) => {
|
||||
return 'text-red-700 dark:text-red-400'
|
||||
}
|
||||
|
||||
export function ContextUsageIndicator({ opcodeUrl, sessionID, directory, isConnected, isReconnecting }: ContextUsageIndicatorProps) {
|
||||
const { totalTokens, contextLimit, usagePercentage, isLoading } = useContextUsage(opcodeUrl, sessionID, directory)
|
||||
export function ContextUsageIndicator({ directory, sessionID, isConnected, isReconnecting }: ContextUsageIndicatorProps) {
|
||||
const { totalTokens, contextLimit, usagePercentage, isLoading } = useContextUsage(sessionID, directory)
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,615 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { FormPrompt } from './FormPrompt'
|
||||
|
||||
const selectForm: FormInfo = {
|
||||
id: 'form-1',
|
||||
sessionID: 'session-1',
|
||||
title: 'Deploy to prod?',
|
||||
fields: [
|
||||
{
|
||||
key: 'q0',
|
||||
title: 'Environment',
|
||||
type: 'string',
|
||||
options: [
|
||||
{ value: 'staging', label: 'Staging' },
|
||||
{ value: 'production', label: 'Production' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
describe('FormPrompt', () => {
|
||||
it('submits the selected option keyed by field key', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
render(<FormPrompt form={selectForm} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByText('Production'))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() => expect(onReply).toHaveBeenCalledWith('form-1', { q0: 'production' }))
|
||||
})
|
||||
|
||||
it('collects multiselect, boolean, and number answers', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-2',
|
||||
sessionID: 'session-1',
|
||||
title: 'Configure',
|
||||
fields: [
|
||||
{
|
||||
key: 'features',
|
||||
type: 'multiselect',
|
||||
options: [
|
||||
{ value: 'a', label: 'Alpha' },
|
||||
{ value: 'b', label: 'Beta' },
|
||||
],
|
||||
},
|
||||
{ key: 'enabled', type: 'boolean' },
|
||||
{ key: 'count', type: 'integer', minimum: 1 },
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByText('Alpha'))
|
||||
await userEvent.click(screen.getByText('No'))
|
||||
const numberInput = screen.getByRole('spinbutton')
|
||||
await userEvent.clear(numberInput)
|
||||
await userEvent.type(numberInput, '3')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-2', { features: ['a'], enabled: false, count: 3 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('cancels the form', async () => {
|
||||
const onCancel = vi.fn().mockResolvedValue(undefined)
|
||||
render(<FormPrompt form={selectForm} onReply={vi.fn()} onCancel={onCancel} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
|
||||
|
||||
await waitFor(() => expect(onCancel).toHaveBeenCalledWith('form-1'))
|
||||
})
|
||||
|
||||
describe('field defaults', () => {
|
||||
it('initializes a required numeric default and allows submission as displayed', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-numeric-default',
|
||||
sessionID: 'session-1',
|
||||
title: 'Configure',
|
||||
fields: [{ key: 'count', title: 'Count', type: 'integer', required: true, default: 3 }],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
const input = screen.getByLabelText(/Count/) as HTMLInputElement
|
||||
expect(input.value).toBe('3')
|
||||
const submit = screen.getByRole('button', { name: 'Submit' })
|
||||
expect(submit).toBeEnabled()
|
||||
|
||||
await userEvent.click(submit)
|
||||
await waitFor(() => expect(onReply).toHaveBeenCalledWith('form-numeric-default', { count: 3 }))
|
||||
})
|
||||
|
||||
it('keeps a cleared numeric default cleared and re-enables gating', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-numeric-clear',
|
||||
sessionID: 'session-1',
|
||||
title: 'Configure',
|
||||
fields: [{ key: 'count', title: 'Count', type: 'integer', required: true, default: 3 }],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
const input = screen.getByLabelText(/Count/) as HTMLInputElement
|
||||
const submit = screen.getByRole('button', { name: 'Submit' })
|
||||
|
||||
await userEvent.clear(input)
|
||||
expect(input.value).toBe('')
|
||||
expect(submit).toBeDisabled()
|
||||
|
||||
await userEvent.type(input, '5')
|
||||
expect(submit).toBeEnabled()
|
||||
await userEvent.click(submit)
|
||||
await waitFor(() => expect(onReply).toHaveBeenCalledWith('form-numeric-clear', { count: 5 }))
|
||||
})
|
||||
|
||||
it('initializes string, boolean, and multiselect defaults', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-mixed-defaults',
|
||||
sessionID: 'session-1',
|
||||
title: 'Configure',
|
||||
fields: [
|
||||
{ key: 'name', title: 'Name', type: 'string', required: true, default: 'Ada' },
|
||||
{ key: 'enabled', title: 'Enabled', type: 'boolean', required: true, default: false },
|
||||
{
|
||||
key: 'features',
|
||||
title: 'Features',
|
||||
type: 'multiselect',
|
||||
required: true,
|
||||
options: [
|
||||
{ value: 'a', label: 'Alpha' },
|
||||
{ value: 'b', label: 'Beta' },
|
||||
],
|
||||
default: ['a'],
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
expect((screen.getByLabelText(/Name/) as HTMLTextAreaElement).value).toBe('Ada')
|
||||
expect(screen.getByRole('button', { name: 'No' })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getByRole('button', { name: 'Alpha' })).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-mixed-defaults', {
|
||||
name: 'Ada',
|
||||
enabled: false,
|
||||
features: ['a'],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps a predefined string default as an explicit selection', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-string-default-option',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'answer',
|
||||
title: 'Answer',
|
||||
type: 'string',
|
||||
required: true,
|
||||
options: [{ value: 'Yes', label: 'Yes' }],
|
||||
custom: true,
|
||||
default: 'Yes',
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Yes' })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.queryByRole('button', { name: 'Other...' })).not.toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-string-default-option', { answer: 'Yes' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows a custom string default and preserves it when Other opens', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-string-default',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'answer',
|
||||
title: 'Answer',
|
||||
type: 'string',
|
||||
required: true,
|
||||
options: [{ value: 'Yes', label: 'Yes' }],
|
||||
custom: true,
|
||||
default: 'Yesterday',
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('Yesterday')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Answer') as HTMLTextAreaElement
|
||||
expect(customInput.value).toBe('Yesterday')
|
||||
|
||||
await userEvent.clear(customInput)
|
||||
await userEvent.type(customInput, 'Tomorrow')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-string-default', { answer: 'Tomorrow' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows custom multiselect defaults, removes them, and appends Other without stale entries', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-multiselect-default',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'features',
|
||||
title: 'Features',
|
||||
type: 'multiselect',
|
||||
required: true,
|
||||
options: [
|
||||
{ value: 'Yes', label: 'Yes' },
|
||||
{ value: 'No', label: 'No' },
|
||||
],
|
||||
custom: true,
|
||||
default: ['Yes', 'Yesterday', 'Tomorrow'],
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Yes' })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getByRole('button', { name: 'Yesterday' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Tomorrow' })).toBeInTheDocument()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Yesterday' }))
|
||||
expect(screen.queryByRole('button', { name: 'Yesterday' })).not.toBeInTheDocument()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Features')
|
||||
await userEvent.type(customInput, 'Later')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-multiselect-default', {
|
||||
features: ['Yes', 'Tomorrow', 'Later'],
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('custom answers', () => {
|
||||
it('submits typed custom text for a string field without pressing Enter', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-string',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'environment',
|
||||
title: 'Environment',
|
||||
type: 'string',
|
||||
required: true,
|
||||
options: [{ value: 'staging', label: 'Staging' }],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
await userEvent.type(screen.getByLabelText('Other answer for Environment'), 'custom-value')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-string', { environment: 'custom-value' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('submits a multiselect custom answer alongside predefined selections without Enter', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-multiselect',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'features',
|
||||
title: 'Features',
|
||||
type: 'multiselect',
|
||||
required: true,
|
||||
options: [
|
||||
{ value: 'a', label: 'Alpha' },
|
||||
{ value: 'b', label: 'Beta' },
|
||||
],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Alpha' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Features')
|
||||
await userEvent.type(customInput, 'gamma')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-multiselect', { features: ['a', 'gamma'] }),
|
||||
)
|
||||
})
|
||||
|
||||
it('replaces an edited multiselect custom value instead of appending stale entries', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-edit',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'features',
|
||||
title: 'Features',
|
||||
type: 'multiselect',
|
||||
required: true,
|
||||
options: [{ value: 'a', label: 'Alpha' }],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Alpha' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Features')
|
||||
await userEvent.type(customInput, 'gamma')
|
||||
await userEvent.clear(customInput)
|
||||
await userEvent.type(customInput, 'delta')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-edit', { features: ['a', 'delta'] }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('custom option prefix collisions', () => {
|
||||
it('keeps custom text visible and submits it when a predefined option is a prefix of the answer', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-prefix-string',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'answer',
|
||||
title: 'Answer',
|
||||
type: 'string',
|
||||
required: true,
|
||||
options: [{ value: 'Yes', label: 'Yes' }],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Answer')
|
||||
await userEvent.type(customInput, 'Yesterday')
|
||||
|
||||
expect((customInput as HTMLTextAreaElement).value).toBe('Yesterday')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-prefix-string', { answer: 'Yesterday' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not turn a custom value colliding with a predefined option into a phantom selection', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-prefix-multiselect',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'features',
|
||||
title: 'Features',
|
||||
type: 'multiselect',
|
||||
required: true,
|
||||
options: [
|
||||
{ value: 'Yes', label: 'Yes' },
|
||||
{ value: 'No', label: 'No' },
|
||||
],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'No' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const customInput = screen.getByLabelText('Other answer for Features')
|
||||
await userEvent.type(customInput, 'Yesterday')
|
||||
|
||||
expect((customInput as HTMLTextAreaElement).value).toBe('Yesterday')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-prefix-multiselect', {
|
||||
features: ['No', 'Yesterday'],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves custom text across collapse and reopen, replacing it on edit', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
const form: FormInfo = {
|
||||
id: 'form-custom-reopen',
|
||||
sessionID: 'session-1',
|
||||
title: 'Choose',
|
||||
fields: [
|
||||
{
|
||||
key: 'answer',
|
||||
title: 'Answer',
|
||||
type: 'string',
|
||||
required: true,
|
||||
options: [{ value: 'Yes', label: 'Yes' }],
|
||||
custom: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
await userEvent.type(screen.getByLabelText('Other answer for Answer'), 'Yesterday')
|
||||
await userEvent.keyboard('{Enter}')
|
||||
|
||||
expect(screen.getByText('Yesterday')).toBeInTheDocument()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Other...' }))
|
||||
const reopened = screen.getByLabelText('Other answer for Answer') as HTMLTextAreaElement
|
||||
expect(reopened.value).toBe('Yesterday')
|
||||
|
||||
await userEvent.clear(reopened)
|
||||
await userEvent.type(reopened, 'Tomorrow')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-custom-reopen', { answer: 'Tomorrow' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accessibility', () => {
|
||||
it('exposes labels, group names, selected state, and named dismiss controls', async () => {
|
||||
const form: FormInfo = {
|
||||
id: 'form-a11y',
|
||||
sessionID: 'session-1',
|
||||
title: 'Configure',
|
||||
fields: [
|
||||
{ key: 'q0', title: 'Count', type: 'integer', required: true, default: 3 },
|
||||
{ key: 'q1', title: 'Notes', type: 'string' },
|
||||
{ key: 'q2', title: 'Enabled', type: 'boolean' },
|
||||
{
|
||||
key: 'q3',
|
||||
title: 'Features',
|
||||
type: 'multiselect',
|
||||
options: [{ value: 'a', label: 'Alpha' }],
|
||||
},
|
||||
{
|
||||
key: 'q4',
|
||||
title: 'Extras',
|
||||
type: 'multiselect',
|
||||
options: [{ value: 'a', label: 'Alpha' }],
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={vi.fn()} onCancel={vi.fn()} />)
|
||||
|
||||
expect(screen.getByLabelText(/Count/)).toHaveAttribute('type', 'number')
|
||||
expect(screen.getByLabelText(/Notes/).tagName).toBe('TEXTAREA')
|
||||
expect(screen.getByRole('group', { name: /Enabled/ })).toBeInTheDocument()
|
||||
const featuresGroup = screen.getByRole('group', { name: /Features/ })
|
||||
const extrasGroup = screen.getByRole('group', { name: /Extras/ })
|
||||
expect(featuresGroup).toBeInTheDocument()
|
||||
expect(extrasGroup).toBeInTheDocument()
|
||||
|
||||
const featuresAlpha = within(featuresGroup).getByRole('button', { name: 'Alpha' })
|
||||
expect(featuresAlpha).toHaveAttribute('aria-pressed', 'false')
|
||||
await userEvent.click(featuresAlpha)
|
||||
expect(featuresAlpha).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Dismiss form' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Dismiss' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('conditional and external fields', () => {
|
||||
const conditionalForm: FormInfo = {
|
||||
id: 'form-conditional',
|
||||
sessionID: 'session-1',
|
||||
title: 'Configure',
|
||||
fields: [
|
||||
{
|
||||
key: 'deploymentType',
|
||||
title: 'Deployment',
|
||||
type: 'string',
|
||||
options: [
|
||||
{ value: 'github.com', label: 'GitHub.com' },
|
||||
{ value: 'enterprise', label: 'GitHub Enterprise' },
|
||||
],
|
||||
default: 'github.com',
|
||||
},
|
||||
{
|
||||
key: 'enterpriseUrl',
|
||||
title: 'Enterprise URL',
|
||||
type: 'string',
|
||||
required: true,
|
||||
when: [{ key: 'deploymentType', op: 'eq', value: 'enterprise' }],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
it('submits while a conditional required field stays hidden', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
render(<FormPrompt form={conditionalForm} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
expect(screen.queryByLabelText(/Enterprise URL/)).not.toBeInTheDocument()
|
||||
const submit = screen.getByRole('button', { name: 'Submit' })
|
||||
expect(submit).toBeEnabled()
|
||||
|
||||
await userEvent.click(submit)
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-conditional', { deploymentType: 'github.com' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('reveals and requires the conditional field once its condition matches', async () => {
|
||||
const onReply = vi.fn().mockResolvedValue(undefined)
|
||||
render(<FormPrompt form={conditionalForm} onReply={onReply} onCancel={vi.fn()} />)
|
||||
|
||||
await userEvent.click(screen.getByText('GitHub Enterprise'))
|
||||
|
||||
const submit = screen.getByRole('button', { name: 'Submit' })
|
||||
expect(submit).toBeDisabled()
|
||||
|
||||
await userEvent.type(screen.getByLabelText(/Enterprise URL/), 'company.ghe.com')
|
||||
expect(submit).toBeEnabled()
|
||||
|
||||
await userEvent.click(submit)
|
||||
await waitFor(() =>
|
||||
expect(onReply).toHaveBeenCalledWith('form-conditional', {
|
||||
deploymentType: 'enterprise',
|
||||
enterpriseUrl: 'company.ghe.com',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('renders an external field as a link card', () => {
|
||||
const form: FormInfo = {
|
||||
id: 'form-external',
|
||||
sessionID: 'session-1',
|
||||
title: 'Approve',
|
||||
fields: [
|
||||
{
|
||||
key: 'approve',
|
||||
type: 'external',
|
||||
url: 'https://example.com/approve',
|
||||
title: 'Approve access',
|
||||
description: 'Do it in the provider dashboard',
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={vi.fn()} onCancel={vi.fn()} />)
|
||||
|
||||
const link = screen.getByRole('link', { name: /Approve access/ })
|
||||
expect(link).toHaveAttribute('href', 'https://example.com/approve')
|
||||
expect(link).toHaveAttribute('target', '_blank')
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
expect(screen.getByText('Do it in the provider dashboard')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not render an external field with a non-http url', () => {
|
||||
const form: FormInfo = {
|
||||
id: 'form-external-unsafe',
|
||||
sessionID: 'session-1',
|
||||
title: 'Approve',
|
||||
fields: [
|
||||
{
|
||||
key: 'approve',
|
||||
type: 'external',
|
||||
url: 'javascript:alert(1)',
|
||||
title: 'Approve access',
|
||||
},
|
||||
],
|
||||
}
|
||||
render(<FormPrompt form={form} onReply={vi.fn()} onCancel={vi.fn()} />)
|
||||
|
||||
expect(screen.queryByRole('link', { name: /Approve access/ })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,551 @@
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
|
||||
import { X, ChevronDown, ChevronUp, Check, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { ExternalFieldCard } from '@/components/ui/external-field-card'
|
||||
import type { FormAnswer, FormField, FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { buildAnswer, hasMissingAnswers, visibleFields } from '@/lib/formFields'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
type AnswerableFormField = Exclude<FormField, { type: 'external' }>
|
||||
|
||||
function isAnswerableField(field: FormField): field is AnswerableFormField {
|
||||
return field.type !== 'external' && field.hidden !== true
|
||||
}
|
||||
|
||||
function getFieldDefault(field: AnswerableFormField): FormAnswer[string] | undefined {
|
||||
if (field.type === 'multiselect') {
|
||||
return Array.isArray(field.default) ? [...field.default] : undefined
|
||||
}
|
||||
return field.default
|
||||
}
|
||||
|
||||
function isPredefinedValue(field: AnswerableFormField, value: string): boolean {
|
||||
if (!('options' in field)) return false
|
||||
return (field.options ?? []).some((option) => option.value === value)
|
||||
}
|
||||
|
||||
function usesCustomInput(field: AnswerableFormField): boolean {
|
||||
return field.type === 'string' && field.custom === true && (field.options?.length ?? 0) > 0
|
||||
}
|
||||
|
||||
interface FormPromptState {
|
||||
answer: FormAnswer
|
||||
customValues: Record<string, string[]>
|
||||
customDrafts: Record<string, string>
|
||||
}
|
||||
|
||||
function buildInitialState(fields: AnswerableFormField[]): FormPromptState {
|
||||
const answer: FormAnswer = {}
|
||||
const customValues: Record<string, string[]> = {}
|
||||
const customDrafts: Record<string, string> = {}
|
||||
for (const field of fields) {
|
||||
const value = getFieldDefault(field)
|
||||
if (value === undefined) continue
|
||||
if (field.type === 'multiselect') {
|
||||
const entries = Array.isArray(value) ? value : []
|
||||
const predefined = entries.filter((entry) => isPredefinedValue(field, entry))
|
||||
const custom = entries.filter((entry) => !isPredefinedValue(field, entry))
|
||||
if (predefined.length > 0) answer[field.key] = predefined
|
||||
if (custom.length > 0) customValues[field.key] = [...new Set(custom)]
|
||||
continue
|
||||
}
|
||||
if (typeof value === 'string' && usesCustomInput(field) && !isPredefinedValue(field, value)) {
|
||||
customDrafts[field.key] = value
|
||||
continue
|
||||
}
|
||||
answer[field.key] = value
|
||||
}
|
||||
return { answer, customValues, customDrafts }
|
||||
}
|
||||
|
||||
interface FormPromptProps {
|
||||
form: FormInfo
|
||||
onReply: (formID: string, answer: FormAnswer) => Promise<void>
|
||||
onCancel: (formID: string) => Promise<void>
|
||||
onMinimize?: () => void
|
||||
}
|
||||
|
||||
export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptProps) {
|
||||
const candidateFields = form.fields.filter(isAnswerableField)
|
||||
const [state, setState] = useState<FormPromptState>(() => buildInitialState(candidateFields))
|
||||
const { answer, customValues, customDrafts } = state
|
||||
const [expandedCustom, setExpandedCustom] = useState<string | null>(null)
|
||||
const [isMinimized, setIsMinimized] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const formControlId = useId()
|
||||
|
||||
const controlId = (key: string) => `${formControlId}-${key}`
|
||||
|
||||
const setFieldAnswer = (key: string, value: FormAnswer[string]) => {
|
||||
setState((prev) => ({ ...prev, answer: { ...prev.answer, [key]: value } }))
|
||||
}
|
||||
|
||||
const setCustomDraft = (key: string, value: string) => {
|
||||
setState((prev) => ({ ...prev, customDrafts: { ...prev.customDrafts, [key]: value } }))
|
||||
}
|
||||
|
||||
const removeCustomValue = (key: string, value: string) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
customValues: {
|
||||
...prev.customValues,
|
||||
[key]: (prev.customValues[key] ?? []).filter((entry) => entry !== value),
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
const toggleMultiOption = (key: string, optionValue: string, selected: string[]) => {
|
||||
setFieldAnswer(
|
||||
key,
|
||||
selected.includes(optionValue)
|
||||
? selected.filter((entry) => entry !== optionValue)
|
||||
: [...selected, optionValue],
|
||||
)
|
||||
}
|
||||
|
||||
const getEffectiveAnswer = (field: AnswerableFormField): FormAnswer[string] | undefined => {
|
||||
const value = answer[field.key]
|
||||
if (field.type === 'multiselect') {
|
||||
const predefined = Array.isArray(value) ? value : []
|
||||
const custom = customValues[field.key] ?? []
|
||||
const draft = (customDrafts[field.key] ?? '').trim()
|
||||
const combined = [...new Set([...predefined, ...custom, ...(draft === '' ? [] : [draft])])]
|
||||
return combined.length > 0 ? combined : undefined
|
||||
}
|
||||
if (usesCustomInput(field)) {
|
||||
const draft = customDrafts[field.key]
|
||||
if (draft !== undefined && draft !== '') return draft
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
const effectiveAnswers: FormAnswer = {}
|
||||
for (const field of candidateFields) {
|
||||
const value = getEffectiveAnswer(field)
|
||||
if (value !== undefined) effectiveAnswers[field.key] = value
|
||||
}
|
||||
|
||||
const renderFields = visibleFields(form.fields, effectiveAnswers)
|
||||
const canSubmit = !hasMissingAnswers(form.fields, effectiveAnswers)
|
||||
const buildSubmission = (): FormAnswer => buildAnswer(form.fields, effectiveAnswers)
|
||||
|
||||
const handleMinimize = () => {
|
||||
setIsMinimized(true)
|
||||
onMinimize?.()
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!canSubmit) return
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await onReply(form.id, buildSubmission())
|
||||
} catch {
|
||||
showToast.error('Failed to submit form')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = async () => {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await onCancel(form.id)
|
||||
} catch {
|
||||
showToast.error('Failed to dismiss form')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && !isMinimized && !expandedCustom) {
|
||||
setIsMinimized(true)
|
||||
onMinimize?.()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [isMinimized, expandedCustom, onMinimize])
|
||||
|
||||
const renderField = (field: AnswerableFormField) => {
|
||||
const value = answer[field.key]
|
||||
const label = field.title ?? field.key
|
||||
const required = field.required === true
|
||||
const inputId = controlId(field.key)
|
||||
const descriptionId = field.description ? `${inputId}-description` : undefined
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
const selected = typeof value === 'boolean' ? value : undefined
|
||||
return (
|
||||
<FieldGroup key={field.key} label={label} description={field.description} required={required}>
|
||||
<div className="flex gap-1.5 sm:gap-2">
|
||||
<OptionButton selected={selected === true} label="Yes" onClick={() => setFieldAnswer(field.key, true)} />
|
||||
<OptionButton selected={selected === false} label="No" onClick={() => setFieldAnswer(field.key, false)} />
|
||||
</div>
|
||||
</FieldGroup>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'number' || field.type === 'integer') {
|
||||
const numberValue = typeof value === 'number' || typeof value === 'string' ? value : ''
|
||||
return (
|
||||
<div key={field.key} className="space-y-2">
|
||||
<FieldLabel id={inputId} label={label} description={field.description} required={required} />
|
||||
<input
|
||||
id={inputId}
|
||||
type="number"
|
||||
aria-describedby={descriptionId}
|
||||
value={numberValue}
|
||||
min={typeof field.minimum === 'number' ? field.minimum : undefined}
|
||||
max={typeof field.maximum === 'number' ? field.maximum : undefined}
|
||||
step={field.type === 'integer' ? 1 : 'any'}
|
||||
onChange={(e) => setFieldAnswer(field.key, e.target.value === '' ? '' : Number(e.target.value))}
|
||||
className="w-full rounded-lg border border-border bg-white/60 dark:bg-white/5 px-3 py-2 text-sm focus:border-blue-500 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.type === 'multiselect') {
|
||||
const selected = Array.isArray(value) ? value : []
|
||||
const customEntries = customValues[field.key] ?? []
|
||||
const customValue = customDrafts[field.key] ?? ''
|
||||
return (
|
||||
<FieldGroup key={field.key} label={label} description={field.description} required={required}>
|
||||
<div className="space-y-1.5 sm:space-y-2">
|
||||
{field.options.map((option) => (
|
||||
<OptionButton
|
||||
key={option.value}
|
||||
selected={selected.includes(option.value)}
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
onClick={() => toggleMultiOption(field.key, option.value, selected)}
|
||||
/>
|
||||
))}
|
||||
{customEntries.map((entry) => (
|
||||
<OptionButton
|
||||
key={`custom-${entry}`}
|
||||
selected
|
||||
label={entry}
|
||||
onClick={() => removeCustomValue(field.key, entry)}
|
||||
/>
|
||||
))}
|
||||
{field.custom && (
|
||||
<CustomOption
|
||||
fieldLabel={label}
|
||||
expanded={expandedCustom === field.key}
|
||||
selected={customValue.trim() !== ''}
|
||||
value={customValue}
|
||||
onExpand={() => setExpandedCustom(field.key)}
|
||||
onCollapse={() => setExpandedCustom(null)}
|
||||
onChange={(input) => setCustomDraft(field.key, input)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</FieldGroup>
|
||||
)
|
||||
}
|
||||
|
||||
if (field.options && field.options.length > 0) {
|
||||
const selected = typeof value === 'string' ? value : ''
|
||||
const customValue = customDrafts[field.key] ?? ''
|
||||
return (
|
||||
<FieldGroup key={field.key} label={label} description={field.description} required={required}>
|
||||
<div className="space-y-1.5 sm:space-y-2">
|
||||
{field.options.map((option) => (
|
||||
<OptionButton
|
||||
key={option.value}
|
||||
selected={selected === option.value}
|
||||
label={option.label}
|
||||
description={option.description}
|
||||
onClick={() => {
|
||||
setFieldAnswer(field.key, option.value)
|
||||
setCustomDraft(field.key, '')
|
||||
setExpandedCustom(null)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{field.custom && (
|
||||
<CustomOption
|
||||
fieldLabel={label}
|
||||
expanded={expandedCustom === field.key}
|
||||
selected={customValue !== ''}
|
||||
value={customValue}
|
||||
onExpand={() => {
|
||||
setFieldAnswer(field.key, '')
|
||||
setExpandedCustom(field.key)
|
||||
}}
|
||||
onCollapse={() => setExpandedCustom(null)}
|
||||
onChange={(input) => setCustomDraft(field.key, input)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</FieldGroup>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={field.key} className="space-y-2">
|
||||
<FieldLabel id={inputId} label={label} description={field.description} required={required} />
|
||||
<Textarea
|
||||
id={inputId}
|
||||
aria-describedby={descriptionId}
|
||||
value={typeof value === 'string' ? value : ''}
|
||||
onChange={(e) => setFieldAnswer(field.key, e.target.value)}
|
||||
placeholder={field.placeholder ?? 'Type your answer...'}
|
||||
className="min-h-[60px] sm:min-h-[80px] text-[16px] sm:text-xs md:text-sm resize-none border-blue-500/30 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full bg-gradient-to-br from-blue-100 to-blue-200 dark:from-blue-950 dark:to-blue-900 border-2 border-blue-300 dark:border-blue-700 rounded-xl shadow-lg shadow-blue-500/20 mb-1 overflow-hidden">
|
||||
<div className="flex items-center px-3 py-2 sm:px-4 sm:py-2.5 border-b border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/50">
|
||||
<button
|
||||
onClick={() => (isMinimized ? setIsMinimized(false) : handleMinimize())}
|
||||
aria-expanded={!isMinimized}
|
||||
className="flex items-center gap-1.5 flex-1 text-left text-xs sm:text-sm font-semibold text-blue-600 dark:text-white"
|
||||
>
|
||||
{isMinimized ? (
|
||||
<ChevronUp className="w-3 h-3 opacity-60 flex-shrink-0" />
|
||||
) : (
|
||||
<ChevronDown className="w-3 h-3 opacity-60 flex-shrink-0" />
|
||||
)}
|
||||
{form.title || 'Form'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
disabled={isSubmitting}
|
||||
aria-label="Dismiss form"
|
||||
className="p-1.5 sm:p-2 hover:bg-red-500/20 text-muted-foreground hover:text-red-500 transition-colors"
|
||||
>
|
||||
<X className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!isMinimized && (
|
||||
<div className="p-2 sm:p-3 max-h-[50vh] sm:max-h-[70vh] overflow-y-auto overflow-x-hidden bg-background/60 dark:bg-black/30 space-y-3">
|
||||
{renderFields.map((field) =>
|
||||
field.type === 'external' ? (
|
||||
<ExternalFieldCard key={field.key} field={field} />
|
||||
) : (
|
||||
renderField(field)
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-1.5 sm:gap-2 px-2 py-2 sm:px-3 sm:py-3 border-t border-blue-200 dark:border-blue-800">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleCancel}
|
||||
disabled={isSubmitting}
|
||||
className="flex-1 h-8 sm:h-10 text-xs sm:text-sm bg-muted hover:bg-muted/80 text-foreground"
|
||||
>
|
||||
Dismiss
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !canSubmit}
|
||||
className="flex-1 h-8 sm:h-10 text-xs sm:text-sm bg-emerald-600 hover:bg-emerald-700 text-white"
|
||||
>
|
||||
{isSubmitting ? <Loader2 className="w-3.5 h-3.5 sm:w-4 sm:h-4 animate-spin" /> : 'Submit'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldLabel({
|
||||
id,
|
||||
label,
|
||||
description,
|
||||
required,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
description?: string
|
||||
required: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
<label htmlFor={id} className="block text-xs sm:text-sm font-semibold text-foreground">
|
||||
{label}
|
||||
{required && <span className="text-red-500 ml-0.5">*</span>}
|
||||
</label>
|
||||
{description && (
|
||||
<p id={`${id}-description`} className="text-[10px] sm:text-xs text-foreground/70">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FieldGroup({
|
||||
label,
|
||||
description,
|
||||
required,
|
||||
children,
|
||||
}: {
|
||||
label: string
|
||||
description?: string
|
||||
required: boolean
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-xs sm:text-sm font-semibold text-foreground">
|
||||
{label}
|
||||
{required && <span className="text-red-500 ml-0.5">*</span>}
|
||||
</legend>
|
||||
{description && <p className="text-[10px] sm:text-xs text-foreground/70">{description}</p>}
|
||||
{children}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
|
||||
function OptionButton({
|
||||
selected,
|
||||
label,
|
||||
description,
|
||||
onClick,
|
||||
}: {
|
||||
selected: boolean
|
||||
label: string
|
||||
description?: string
|
||||
onClick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'w-full text-left p-2 sm:p-3 rounded-lg transition-all duration-200 active:scale-[0.98]',
|
||||
selected
|
||||
? 'bg-blue-200 dark:bg-blue-700/50'
|
||||
: 'bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start gap-1.5 sm:gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
'w-4 h-4 sm:w-5 sm:h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-colors',
|
||||
selected ? 'border-blue-500 bg-blue-500' : 'border-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{selected && <Check className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs sm:text-sm font-semibold',
|
||||
selected ? 'text-blue-600 dark:text-blue-300' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
{description && (
|
||||
<p className="text-[10px] sm:text-xs text-foreground/70 mt-0.5">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function CustomOption({
|
||||
fieldLabel,
|
||||
expanded,
|
||||
selected,
|
||||
value,
|
||||
onExpand,
|
||||
onCollapse,
|
||||
onChange,
|
||||
}: {
|
||||
fieldLabel: string
|
||||
expanded: boolean
|
||||
selected: boolean
|
||||
value: string
|
||||
onExpand: () => void
|
||||
onCollapse: () => void
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (expanded && textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
textareaRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}, [expanded])
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
onClick={() => (expanded ? onCollapse() : onExpand())}
|
||||
className={cn(
|
||||
'w-full text-left p-2 sm:p-3 rounded-lg transition-all duration-200',
|
||||
expanded || selected
|
||||
? 'bg-blue-200 dark:bg-blue-700/50'
|
||||
: 'bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
<div
|
||||
className={cn(
|
||||
'w-4 h-4 sm:w-5 sm:h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-colors',
|
||||
selected ? 'border-blue-500 bg-blue-500' : 'border-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{selected && <Check className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />}
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
'text-xs sm:text-sm font-semibold',
|
||||
expanded || selected ? 'text-blue-600 dark:text-blue-300' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
Other...
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{expanded && (
|
||||
<div className="ml-5 sm:ml-7 space-y-1.5 sm:space-y-2 animate-in slide-in-from-top-2 duration-200">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
aria-label={`Other answer for ${fieldLabel}`}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="Type your own answer..."
|
||||
className="min-h-[60px] sm:min-h-[80px] text-[16px] sm:text-xs md:text-sm resize-none border-blue-500/30 focus:border-blue-500"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
onCollapse()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
onCollapse()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!expanded && selected && (
|
||||
<div className="ml-5 sm:ml-7 text-[10px] sm:text-xs text-muted-foreground">
|
||||
{value}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
+7
-15
@@ -1,20 +1,14 @@
|
||||
import { X } from 'lucide-react'
|
||||
import type { QuestionRequest } from '@/api/types'
|
||||
import type { FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { getFormText } from '@opencode-manager/shared/notifications'
|
||||
|
||||
interface MinimizedQuestionIndicatorProps {
|
||||
question: QuestionRequest
|
||||
interface MinimizedFormIndicatorProps {
|
||||
form: FormInfo
|
||||
onRestore: () => void
|
||||
onDismiss: () => void
|
||||
}
|
||||
|
||||
export function MinimizedQuestionIndicator({
|
||||
question,
|
||||
onRestore,
|
||||
onDismiss
|
||||
}: MinimizedQuestionIndicatorProps) {
|
||||
const questionCount = question.questions.length
|
||||
const firstQuestionHeader = question.questions[0]?.header
|
||||
|
||||
export function MinimizedFormIndicator({ form, onRestore, onDismiss }: MinimizedFormIndicatorProps) {
|
||||
return (
|
||||
<div className="w-full bg-gradient-to-br from-orange-100 to-orange-200 dark:from-orange-950 dark:to-orange-900 border-2 border-orange-300 dark:border-orange-700 rounded-lg shadow-lg mb-2 overflow-hidden">
|
||||
<div className="flex items-center px-3 py-2 sm:px-4 sm:py-2.5 border-b border-orange-200 dark:border-orange-800 bg-orange-50 dark:bg-orange-900/50">
|
||||
@@ -22,13 +16,11 @@ export function MinimizedQuestionIndicator({
|
||||
onClick={onRestore}
|
||||
className="flex-1 text-left text-xs font-semibold text-orange-600 dark:text-white"
|
||||
>
|
||||
{questionCount === 1
|
||||
? `Question: ${firstQuestionHeader || 'Question pending'}`
|
||||
: `${questionCount} questions pending`
|
||||
}
|
||||
{getFormText(form) || 'Form pending'}
|
||||
</button>
|
||||
<button
|
||||
onClick={onDismiss}
|
||||
aria-label="Dismiss form"
|
||||
className="p-1.5 hover:bg-red-500/20 text-muted-foreground hover:text-red-500 transition-colors hidden sm:block"
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
@@ -0,0 +1,103 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { PermissionRequestDialog } from './PermissionRequestDialog'
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: {
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const permission: PermissionRequest = {
|
||||
id: 'perm-1',
|
||||
sessionID: 'session-1',
|
||||
action: 'shell',
|
||||
resources: ['rm -rf node_modules'],
|
||||
metadata: {},
|
||||
}
|
||||
|
||||
const secondPermission: PermissionRequest = {
|
||||
...permission,
|
||||
id: 'perm-2',
|
||||
resources: ['git push origin main'],
|
||||
}
|
||||
|
||||
describe('PermissionRequestDialog', () => {
|
||||
it('renders the action label and command detail', () => {
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('Run Command')).toBeInTheDocument()
|
||||
expect(screen.getByText('rm -rf node_modules')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('replies with the selected decision for the permission request', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Allow Once' }))
|
||||
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'once', undefined)
|
||||
})
|
||||
|
||||
it('forwards an optional rejection reason when denying', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'reject', 'not allowed'),
|
||||
)
|
||||
})
|
||||
|
||||
it('denies without a reason when none is supplied', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
|
||||
await waitFor(() => expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'reject', undefined))
|
||||
})
|
||||
|
||||
it('omits the reason for allow decisions', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Allow Always' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(onRespond).toHaveBeenCalledWith('perm-1', 'session-1', 'always', undefined),
|
||||
)
|
||||
})
|
||||
|
||||
it('resets the rejection reason when the permission identity changes', async () => {
|
||||
const onRespond = vi.fn().mockResolvedValue(undefined)
|
||||
const { rerender } = render(
|
||||
<PermissionRequestDialog permission={permission} pendingCount={2} onRespond={onRespond} />,
|
||||
)
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
expect((screen.getByLabelText('Reason (optional)') as HTMLTextAreaElement).value).toBe('not allowed')
|
||||
|
||||
rerender(<PermissionRequestDialog permission={secondPermission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await waitFor(() =>
|
||||
expect((screen.getByLabelText('Reason (optional)') as HTMLTextAreaElement).value).toBe(''),
|
||||
)
|
||||
})
|
||||
|
||||
it('retains the rejection reason when the request fails', async () => {
|
||||
const onRespond = vi.fn().mockRejectedValueOnce(new Error('network'))
|
||||
render(<PermissionRequestDialog permission={permission} pendingCount={1} onRespond={onRespond} />)
|
||||
|
||||
await userEvent.type(screen.getByLabelText('Reason (optional)'), 'not allowed')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
|
||||
await waitFor(() => expect(onRespond).toHaveBeenCalledTimes(1))
|
||||
expect((screen.getByLabelText('Reason (optional)') as HTMLTextAreaElement).value).toBe('not allowed')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { PermissionRequest, PermissionResponse } from '@/api/types'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import type { PermissionResponse } from '@/api/types'
|
||||
import type { PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { getPermissionLabel, getPermissionDetail } from '@opencode-manager/shared/notifications'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
@@ -19,7 +21,12 @@ interface PermissionRequestDialogProps {
|
||||
isFromDifferentSession?: boolean
|
||||
sessionTitle?: string
|
||||
repoDirectory?: string | null
|
||||
onRespond: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
|
||||
onRespond: (
|
||||
permissionID: string,
|
||||
sessionID: string,
|
||||
response: PermissionResponse,
|
||||
message?: string,
|
||||
) => Promise<void>
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
@@ -36,6 +43,12 @@ export function PermissionRequestDialog({
|
||||
}: PermissionRequestDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [loadingAction, setLoadingAction] = useState<PermissionResponse | null>(null)
|
||||
const [rejectReason, setRejectReason] = useState('')
|
||||
const reasonInputId = useId()
|
||||
|
||||
useEffect(() => {
|
||||
setRejectReason('')
|
||||
}, [permission?.id])
|
||||
|
||||
if (!permission) return null
|
||||
if (parentOpen === false) return null
|
||||
@@ -43,8 +56,9 @@ export function PermissionRequestDialog({
|
||||
const handleResponse = async (response: PermissionResponse) => {
|
||||
setIsLoading(true)
|
||||
setLoadingAction(response)
|
||||
const message = response === 'reject' ? rejectReason.trim() : ''
|
||||
try {
|
||||
await onRespond(permission.id, permission.sessionID, response)
|
||||
await onRespond(permission.id, permission.sessionID, response, message === '' ? undefined : message)
|
||||
} catch {
|
||||
showToast.error('Failed to respond to permission. Please try again.')
|
||||
} finally {
|
||||
@@ -53,7 +67,7 @@ export function PermissionRequestDialog({
|
||||
}
|
||||
}
|
||||
|
||||
const typeLabel = getPermissionLabel(permission.permission)
|
||||
const typeLabel = getPermissionLabel(permission.action)
|
||||
const details = getPermissionDetail(permission)
|
||||
const hasMultiple = pendingCount > 1
|
||||
const displaySessionName = sessionTitle || `Session ${permission.sessionID.slice(0, 8)}...`
|
||||
@@ -116,6 +130,20 @@ export function PermissionRequestDialog({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor={reasonInputId} className="text-xs font-medium text-muted-foreground">
|
||||
Reason (optional)
|
||||
</label>
|
||||
<Textarea
|
||||
id={reasonInputId}
|
||||
value={rejectReason}
|
||||
onChange={(e) => setRejectReason(e.target.value)}
|
||||
placeholder="Explain why this request is denied..."
|
||||
disabled={isLoading}
|
||||
className="min-h-[60px] text-[16px] sm:text-xs md:text-sm resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex-col-reverse gap-2 sm:flex-row sm:gap-2 mt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
@@ -1,504 +0,0 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { X, ChevronRight, ChevronDown, ChevronUp, Check, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import type { QuestionRequest, QuestionInfo } from '@/api/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
interface QuestionPromptProps {
|
||||
question: QuestionRequest
|
||||
onReply: (requestID: string, answers: string[][]) => Promise<void>
|
||||
onReject: (requestID: string) => Promise<void>
|
||||
onMinimize?: () => void
|
||||
}
|
||||
|
||||
export function QuestionPrompt({ question, onReply, onReject, onMinimize }: QuestionPromptProps) {
|
||||
const questions = question.questions
|
||||
const isSingleSelect = questions.length === 1 && !questions[0]?.multiple
|
||||
const totalSteps = isSingleSelect ? 1 : questions.length + 1
|
||||
|
||||
const [isMinimized, setIsMinimized] = useState(false)
|
||||
const [currentIndex, setCurrentIndex] = useState(0)
|
||||
const [answers, setAnswers] = useState<string[][]>(() => questions.map(() => []))
|
||||
const [customInputs, setCustomInputs] = useState<string[]>(() => questions.map(() => ''))
|
||||
const [confirmedCustoms, setConfirmedCustoms] = useState<string[]>(() => questions.map(() => ''))
|
||||
const [expandedOther, setExpandedOther] = useState<number | null>(null)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [touchStartY, setTouchStartY] = useState<number | null>(null)
|
||||
|
||||
const handleMinimize = useCallback(() => {
|
||||
setIsMinimized(true)
|
||||
onMinimize?.()
|
||||
}, [onMinimize])
|
||||
|
||||
const handleTouchStart = useCallback((e: React.TouchEvent) => {
|
||||
setTouchStartY(e.touches[0].clientY)
|
||||
}, [])
|
||||
|
||||
const handleTouchMove = useCallback((e: React.TouchEvent) => {
|
||||
if (touchStartY === null) return
|
||||
const touchY = e.touches[0].clientY
|
||||
const diff = touchY - touchStartY
|
||||
if (diff > 100) {
|
||||
handleMinimize()
|
||||
setTouchStartY(null)
|
||||
}
|
||||
}, [touchStartY, handleMinimize])
|
||||
|
||||
const handleTouchEnd = useCallback(() => {
|
||||
setTouchStartY(null)
|
||||
}, [])
|
||||
|
||||
const isConfirmStep = !isSingleSelect && currentIndex === questions.length
|
||||
const currentQuestion = isConfirmStep ? null : questions[currentIndex]
|
||||
const isMultiSelect = currentQuestion?.multiple === true
|
||||
|
||||
const goToNext = useCallback(() => {
|
||||
if (currentIndex < totalSteps - 1) {
|
||||
setCurrentIndex(prev => prev + 1)
|
||||
setExpandedOther(null)
|
||||
}
|
||||
}, [currentIndex, totalSteps])
|
||||
|
||||
const handleSubmitSingle = useCallback(async (label: string) => {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await onReply(question.id, [[label]])
|
||||
} catch {
|
||||
showToast.error('Failed to submit answer')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}, [onReply, question.id])
|
||||
|
||||
const selectOption = useCallback((questionIndex: number, label: string) => {
|
||||
const isMultiple = questions[questionIndex]?.multiple
|
||||
|
||||
setAnswers(prev => {
|
||||
const updated = [...prev]
|
||||
const current = updated[questionIndex] ?? []
|
||||
|
||||
if (isMultiple) {
|
||||
const exists = current.includes(label)
|
||||
updated[questionIndex] = exists
|
||||
? current.filter(l => l !== label)
|
||||
: [...current, label]
|
||||
} else {
|
||||
updated[questionIndex] = [label]
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
if (!isMultiple) {
|
||||
if (isSingleSelect) {
|
||||
handleSubmitSingle(label)
|
||||
} else {
|
||||
setTimeout(() => goToNext(), 150)
|
||||
}
|
||||
}
|
||||
}, [questions, isSingleSelect, goToNext, handleSubmitSingle])
|
||||
|
||||
const handleCustomInput = useCallback((questionIndex: number, value: string) => {
|
||||
setCustomInputs(prev => {
|
||||
const updated = [...prev]
|
||||
updated[questionIndex] = value
|
||||
return updated
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handleExpandOther = useCallback((questionIndex: number) => {
|
||||
if (!isMultiSelect) {
|
||||
setAnswers(prev => {
|
||||
const updated = [...prev]
|
||||
updated[questionIndex] = []
|
||||
return updated
|
||||
})
|
||||
}
|
||||
setConfirmedCustoms(prev => {
|
||||
const updated = [...prev]
|
||||
updated[questionIndex] = ''
|
||||
return updated
|
||||
})
|
||||
setExpandedOther(questionIndex)
|
||||
}, [isMultiSelect])
|
||||
|
||||
const confirmCustomInput = useCallback((questionIndex: number) => {
|
||||
const value = customInputs[questionIndex]?.trim()
|
||||
if (!value) {
|
||||
setExpandedOther(null)
|
||||
return
|
||||
}
|
||||
|
||||
const oldCustom = confirmedCustoms[questionIndex]
|
||||
|
||||
setAnswers(prev => {
|
||||
const updated = [...prev]
|
||||
const current = updated[questionIndex] ?? []
|
||||
|
||||
if (questions[questionIndex]?.multiple) {
|
||||
const withoutOld = oldCustom ? current.filter(l => l !== oldCustom) : current
|
||||
updated[questionIndex] = [...withoutOld, value]
|
||||
} else {
|
||||
updated[questionIndex] = [value]
|
||||
if (!isSingleSelect) {
|
||||
setTimeout(() => goToNext(), 150)
|
||||
}
|
||||
}
|
||||
return updated
|
||||
})
|
||||
|
||||
setConfirmedCustoms(prev => {
|
||||
const updated = [...prev]
|
||||
updated[questionIndex] = value
|
||||
return updated
|
||||
})
|
||||
setExpandedOther(null)
|
||||
|
||||
if (isSingleSelect) {
|
||||
handleSubmitSingle(value)
|
||||
}
|
||||
}, [customInputs, confirmedCustoms, questions, isSingleSelect, goToNext, handleSubmitSingle])
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
if (expandedOther === currentIndex) {
|
||||
confirmCustomInput(currentIndex)
|
||||
} else {
|
||||
goToNext()
|
||||
}
|
||||
}, [expandedOther, currentIndex, confirmCustomInput, goToNext])
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await onReply(question.id, answers)
|
||||
} catch {
|
||||
showToast.error('Failed to submit answers')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReject = async () => {
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
await onReject(question.id)
|
||||
} catch {
|
||||
showToast.error('Failed to dismiss question')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const hasAnswerForQuestion = (index: number) => {
|
||||
return (answers[index]?.length ?? 0) > 0
|
||||
}
|
||||
|
||||
const allQuestionsAnswered = questions.every((_, i) => hasAnswerForQuestion(i))
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && !isMinimized && !expandedOther) {
|
||||
handleMinimize()
|
||||
onMinimize?.()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown)
|
||||
}
|
||||
}, [isMinimized, expandedOther, handleMinimize, onMinimize])
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-full bg-gradient-to-br from-blue-100 to-blue-200 dark:from-blue-950 dark:to-blue-900 border-2 border-blue-300 dark:border-blue-700 rounded-xl shadow-lg shadow-blue-500/20 mb-1 overflow-hidden"
|
||||
>
|
||||
<div className="flex items-center px-3 py-2 sm:px-4 sm:py-2.5 border-b border-blue-200 dark:border-blue-800 bg-blue-50 dark:bg-blue-900/50">
|
||||
<button
|
||||
onClick={() => isMinimized ? setIsMinimized(false) : handleMinimize()}
|
||||
className="flex items-center gap-1.5 flex-1 text-left text-xs sm:text-sm font-semibold text-blue-600 dark:text-white"
|
||||
>
|
||||
{isMinimized
|
||||
? <ChevronUp className="w-3 h-3 opacity-60 flex-shrink-0" />
|
||||
: <ChevronDown className="w-3 h-3 opacity-60 flex-shrink-0" />
|
||||
}
|
||||
{isConfirmStep ? 'Review' : (currentQuestion?.header || 'Question')}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleReject}
|
||||
disabled={isSubmitting}
|
||||
className="p-1.5 sm:p-2 hover:bg-red-500/20 text-muted-foreground hover:text-red-500 transition-colors"
|
||||
>
|
||||
<X className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!isMinimized ? (
|
||||
<div
|
||||
className="p-2 sm:p-3 max-h-[50vh] sm:max-h-[70vh] overflow-y-auto overflow-x-hidden bg-background/60 dark:bg-black/30"
|
||||
onTouchStart={handleTouchStart}
|
||||
onTouchMove={handleTouchMove}
|
||||
onTouchEnd={handleTouchEnd}
|
||||
>
|
||||
{isConfirmStep ? (
|
||||
<ConfirmStep
|
||||
questions={questions}
|
||||
answers={answers}
|
||||
onEditQuestion={setCurrentIndex}
|
||||
/>
|
||||
) : currentQuestion && (
|
||||
<QuestionStep
|
||||
question={currentQuestion}
|
||||
answers={answers[currentIndex] ?? []}
|
||||
customInput={customInputs[currentIndex] ?? ''}
|
||||
confirmedCustom={confirmedCustoms[currentIndex] ?? ''}
|
||||
expandedOther={expandedOther === currentIndex}
|
||||
isMultiSelect={isMultiSelect}
|
||||
onSelectOption={(label) => selectOption(currentIndex, label)}
|
||||
onExpandOther={() => handleExpandOther(currentIndex)}
|
||||
onCustomInputChange={(value) => handleCustomInput(currentIndex, value)}
|
||||
onConfirmCustomInput={() => confirmCustomInput(currentIndex)}
|
||||
onCollapseOther={() => setExpandedOther(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-1.5 sm:gap-2 px-2 py-2 sm:px-3 sm:py-3 border-t border-blue-200 dark:border-blue-800">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleReject}
|
||||
disabled={isSubmitting}
|
||||
className="flex-1 h-8 sm:h-10 text-xs sm:text-sm bg-muted hover:bg-muted/80 text-foreground"
|
||||
>
|
||||
Dismiss
|
||||
</Button>
|
||||
{!isSingleSelect && (
|
||||
isConfirmStep ? (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !allQuestionsAnswered}
|
||||
className="flex-1 h-8 sm:h-10 text-xs sm:text-sm bg-emerald-600 hover:bg-emerald-700 text-white"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="w-3.5 h-3.5 sm:w-4 sm:h-4 animate-spin" />
|
||||
) : (
|
||||
'Submit'
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleNext}
|
||||
disabled={isSubmitting || (expandedOther === currentIndex && !customInputs[currentIndex]?.trim())}
|
||||
className="flex-1 h-8 sm:h-10 text-xs sm:text-sm bg-emerald-600 hover:bg-emerald-700 text-white"
|
||||
>
|
||||
{expandedOther === currentIndex ? 'Confirm' : 'Next'}
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface QuestionStepProps {
|
||||
question: QuestionInfo
|
||||
answers: string[]
|
||||
customInput: string
|
||||
confirmedCustom: string
|
||||
expandedOther: boolean
|
||||
isMultiSelect: boolean
|
||||
onSelectOption: (label: string) => void
|
||||
onExpandOther: () => void
|
||||
onCustomInputChange: (value: string) => void
|
||||
onConfirmCustomInput: () => void
|
||||
onCollapseOther: () => void
|
||||
}
|
||||
|
||||
function QuestionStep({
|
||||
question,
|
||||
answers,
|
||||
customInput,
|
||||
confirmedCustom,
|
||||
expandedOther,
|
||||
isMultiSelect,
|
||||
onSelectOption,
|
||||
onExpandOther,
|
||||
onCustomInputChange,
|
||||
onConfirmCustomInput,
|
||||
onCollapseOther,
|
||||
}: QuestionStepProps) {
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (expandedOther && textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
textareaRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}
|
||||
}, [expandedOther])
|
||||
|
||||
const isCustomSelected = confirmedCustom && answers.includes(confirmedCustom)
|
||||
|
||||
return (
|
||||
<div className="space-y-2 sm:space-y-3">
|
||||
<p className="text-xs sm:text-sm font-semibold text-foreground">
|
||||
{question.question}
|
||||
{isMultiSelect && (
|
||||
<span className="text-foreground/60 font-normal ml-1">(select all that apply)</span>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className="space-y-1.5 sm:space-y-2">
|
||||
{question.options.map((option, i) => {
|
||||
const isSelected = answers.includes(option.label)
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => onSelectOption(option.label)}
|
||||
className={cn(
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg transition-all duration-200 active:scale-[0.98]",
|
||||
isSelected
|
||||
? "bg-blue-200 dark:bg-blue-700/50"
|
||||
: "bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-1.5 sm:gap-2">
|
||||
<div className="flex items-center gap-1.5 sm:gap-2 min-w-0">
|
||||
<div className={cn(
|
||||
"w-4 h-4 sm:w-5 sm:h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-colors",
|
||||
isSelected
|
||||
? "border-blue-500 bg-blue-500"
|
||||
: "border-muted-foreground"
|
||||
)}>
|
||||
{isSelected && <Check className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />}
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-xs sm:text-sm font-semibold",
|
||||
isSelected ? "text-blue-600 dark:text-blue-300" : "text-foreground"
|
||||
)}>
|
||||
{option.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{option.description && (
|
||||
<p className="text-[10px] sm:text-xs text-foreground/70 mt-0.5 sm:mt-1 ml-5 sm:ml-7">
|
||||
{option.description}
|
||||
</p>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
if (expandedOther) {
|
||||
onCollapseOther()
|
||||
} else {
|
||||
onExpandOther()
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg transition-all duration-200",
|
||||
expandedOther || isCustomSelected
|
||||
? "bg-blue-200 dark:bg-blue-700/50"
|
||||
: "bg-white/40 dark:bg-white/5 hover:bg-white/60 dark:hover:bg-white/10"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
<div className={cn(
|
||||
"w-4 h-4 sm:w-5 sm:h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 transition-colors",
|
||||
isCustomSelected
|
||||
? "border-blue-500 bg-blue-500"
|
||||
: "border-muted-foreground"
|
||||
)}>
|
||||
{isCustomSelected && <Check className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-white" />}
|
||||
</div>
|
||||
<span className={cn(
|
||||
"text-xs sm:text-sm font-semibold",
|
||||
expandedOther || isCustomSelected ? "text-blue-600 dark:text-blue-300" : "text-foreground"
|
||||
)}>
|
||||
Other...
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{expandedOther && (
|
||||
<div className="ml-5 sm:ml-7 space-y-1.5 sm:space-y-2 animate-in slide-in-from-top-2 duration-200">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={customInput}
|
||||
onChange={(e) => onCustomInputChange(e.target.value)}
|
||||
placeholder="Type your own answer..."
|
||||
className="min-h-[60px] sm:min-h-[80px] text-[16px] sm:text-xs md:text-sm resize-none border-blue-500/30 focus:border-blue-500"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
onConfirmCustomInput()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
onCollapseOther()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!expandedOther && isCustomSelected && (
|
||||
<div className="ml-5 sm:ml-7 text-[10px] sm:text-xs text-muted-foreground">
|
||||
{confirmedCustom}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface ConfirmStepProps {
|
||||
questions: QuestionInfo[]
|
||||
answers: string[][]
|
||||
onEditQuestion: (index: number) => void
|
||||
}
|
||||
|
||||
function ConfirmStep({ questions, answers, onEditQuestion }: ConfirmStepProps) {
|
||||
return (
|
||||
<div className="space-y-2 sm:space-y-3">
|
||||
<p className="text-xs sm:text-sm font-semibold text-foreground">Review your answers</p>
|
||||
|
||||
<div className="space-y-1.5 sm:space-y-2">
|
||||
{questions.map((q, i) => {
|
||||
const answer = answers[i] ?? []
|
||||
const hasAnswer = answer.length > 0
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => onEditQuestion(i)}
|
||||
className={cn(
|
||||
"w-full text-left p-2 sm:p-3 rounded-lg transition-colors",
|
||||
hasAnswer
|
||||
? "bg-green-50 dark:bg-green-900/30 hover:bg-green-100 dark:hover:bg-green-900/50"
|
||||
: "bg-red-50 dark:bg-red-900/30 hover:bg-red-100 dark:hover:bg-red-900/50"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-1.5 sm:gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">{q.header}</p>
|
||||
<p className={cn(
|
||||
"text-xs sm:text-sm font-semibold mt-0.5",
|
||||
hasAnswer ? "text-green-700 dark:text-green-400" : "text-red-700 dark:text-red-400"
|
||||
)}>
|
||||
{hasAnswer ? answer.join(', ') : '(not answered)'}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-foreground/50 flex-shrink-0 mt-0.5 sm:mt-1" />
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -8,14 +8,14 @@ import { SessionList } from './SessionList'
|
||||
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
|
||||
createSessionMock: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; parentID?: string; time: { updated: number } }>,
|
||||
sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
|
||||
createSessionState: { directory: undefined as string | undefined },
|
||||
fetchNextPageMock: vi.fn(),
|
||||
hasNextPageRef: { current: false },
|
||||
isFetchingNextPageRef: { current: false },
|
||||
isFetchNextPageErrorRef: { current: false },
|
||||
useRealSessionsHookRef: { current: false },
|
||||
lastSessionsHookArgs: { current: undefined as { opcodeUrl: string; directories: string[]; options?: { search?: string; limit?: number } } | undefined },
|
||||
lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number } } | undefined },
|
||||
sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
|
||||
togglePinMock: vi.fn(),
|
||||
}))
|
||||
@@ -24,11 +24,11 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (opcodeUrl: string, directories: string[], options?: { search?: string; limit?: number }) => {
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => {
|
||||
if (useRealSessionsHookRef.current) {
|
||||
return actual.useSessionsAcrossDirectories(opcodeUrl, directories, options)
|
||||
return actual.useSessionsAcrossDirectories(directories, options)
|
||||
}
|
||||
lastSessionsHookArgs.current = { opcodeUrl, directories, options }
|
||||
lastSessionsHookArgs.current = { directories, options }
|
||||
const data = options?.search ? [] : sessionsData
|
||||
return {
|
||||
data,
|
||||
@@ -39,7 +39,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
isFetchNextPageError: isFetchNextPageErrorRef.current,
|
||||
}
|
||||
},
|
||||
useCreateSession: (_opcodeUrl: string, directory?: string) => {
|
||||
useCreateSession: (directory?: string) => {
|
||||
createSessionState.directory = directory
|
||||
return { mutate: createSessionMock }
|
||||
},
|
||||
@@ -55,9 +55,9 @@ vi.mock('@/hooks/useSessionPins', () => ({
|
||||
describe('SessionList', () => {
|
||||
beforeEach(() => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', workspaceID: 'wrk_a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/b', workspaceID: 'wrk_b', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/c', workspaceID: 'wrk_c', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', location: { directory: '/w/a' }, time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', location: { directory: '/w/b' }, time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', location: { directory: '/w/c' }, time: { updated: Date.now() } },
|
||||
)
|
||||
createSessionMock.mockReset()
|
||||
createSessionState.directory = undefined
|
||||
@@ -73,12 +73,11 @@ describe('SessionList', () => {
|
||||
togglePinMock.mockReset()
|
||||
})
|
||||
|
||||
it('selects duplicate session IDs independently by workspace directory', async () => {
|
||||
it('selects duplicate session IDs independently by directory', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/b', '/w/c']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -99,9 +98,9 @@ describe('SessionList', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
expect(deleteSessionMock).toHaveBeenCalledWith([
|
||||
{ id: 'ses_same', directory: '/w/a', workspaceID: 'wrk_a' },
|
||||
{ id: 'ses_same', directory: '/w/b', workspaceID: 'wrk_b' },
|
||||
{ id: 'ses_same', directory: '/w/c', workspaceID: 'wrk_c' },
|
||||
{ id: 'ses_same', directory: '/w/a' },
|
||||
{ id: 'ses_same', directory: '/w/b' },
|
||||
{ id: 'ses_same', directory: '/w/c' },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -109,14 +108,13 @@ describe('SessionList', () => {
|
||||
it('deduplicates repeated session records from the same workspace directory', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', location: { directory: '/w/a' }, time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', location: { directory: '/w/a' }, time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', location: { directory: '/w/a' }, time: { updated: Date.now() } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/a', '/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -136,7 +134,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/b']}
|
||||
createDirectory="/w/b"
|
||||
onSelectSession={vi.fn()}
|
||||
@@ -154,7 +151,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -174,7 +170,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -198,7 +193,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -222,7 +216,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -242,7 +235,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -258,7 +250,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -271,15 +262,14 @@ describe('SessionList', () => {
|
||||
|
||||
it('auto-fetches next page when all visible sessions are filtered out as child sessions', async () => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'child1', title: 'child session', directory: '/w/a', parentID: 'parent1', time: { updated: Date.now() } },
|
||||
{ id: 'child2', title: 'child session 2', directory: '/w/a', parentID: 'parent2', time: { updated: Date.now() } },
|
||||
{ id: 'child1', title: 'child session', location: { directory: '/w/a' }, parentID: 'parent1', time: { updated: Date.now() } },
|
||||
{ id: 'child2', title: 'child session 2', location: { directory: '/w/a' }, parentID: 'parent2', time: { updated: Date.now() } },
|
||||
)
|
||||
hasNextPageRef.current = true
|
||||
isFetchingNextPageRef.current = false
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -292,14 +282,14 @@ describe('SessionList', () => {
|
||||
|
||||
it('auto-fetches next page when filtered sessions underfill the scroll viewport', async () => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'root1', title: 'root session 1', directory: '/w/a', time: { updated: 4 } },
|
||||
{ id: 'root2', title: 'root session 2', directory: '/w/a', time: { updated: 3 } },
|
||||
{ id: 'root3', title: 'root session 3', directory: '/w/a', time: { updated: 2 } },
|
||||
{ id: 'root4', title: 'root session 4', directory: '/w/a', time: { updated: 1 } },
|
||||
{ id: 'root1', title: 'root session 1', location: { directory: '/w/a' }, time: { updated: 4 } },
|
||||
{ id: 'root2', title: 'root session 2', location: { directory: '/w/a' }, time: { updated: 3 } },
|
||||
{ id: 'root3', title: 'root session 3', location: { directory: '/w/a' }, time: { updated: 2 } },
|
||||
{ id: 'root4', title: 'root session 4', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
...Array.from({ length: 21 }, (_, index) => ({
|
||||
id: `child${index}`,
|
||||
title: `child session ${index}`,
|
||||
directory: '/w/a',
|
||||
location: { directory: '/w/a' },
|
||||
parentID: `root${index}`,
|
||||
time: { updated: index },
|
||||
})),
|
||||
@@ -313,8 +303,7 @@ describe('SessionList', () => {
|
||||
try {
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
@@ -340,12 +329,11 @@ describe('SessionList', () => {
|
||||
const pinnedTime = Date.now()
|
||||
sessionPinsData.push({ sessionId: 'ses_a', directory: '/w/a', pinnedAt: pinnedTime })
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_a', title: 'pinned session', directory: '/w/a', time: { updated: pinnedTime } },
|
||||
{ id: 'ses_a', title: 'pinned session', location: { directory: '/w/a' }, time: { updated: pinnedTime } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -360,12 +348,11 @@ describe('SessionList', () => {
|
||||
it('calls togglePinMock with correct args when Pin to top is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_x', title: 'test session', directory: '/w/a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_x', title: 'test session', location: { directory: '/w/a' }, time: { updated: Date.now() } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -386,7 +373,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -413,7 +399,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -431,7 +416,6 @@ describe('SessionList', () => {
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
@@ -451,6 +435,7 @@ describe('SessionList', () => {
|
||||
projectID: 'proj_1',
|
||||
title: `root session ${index}`,
|
||||
time: { created: 100 + index, updated: 100 + index },
|
||||
location: { directory: '/w/a' },
|
||||
})),
|
||||
...Array.from({ length: 21 }, (_, index) => ({
|
||||
id: `child${index}`,
|
||||
@@ -458,6 +443,7 @@ describe('SessionList', () => {
|
||||
parentID: `root${index}`,
|
||||
title: `child session ${index}`,
|
||||
time: { created: index, updated: index },
|
||||
location: { directory: '/w/a' },
|
||||
})),
|
||||
]
|
||||
|
||||
@@ -479,7 +465,7 @@ describe('SessionList', () => {
|
||||
})
|
||||
}
|
||||
return Promise.resolve(new Response(JSON.stringify({
|
||||
items: pageOneItems,
|
||||
data: pageOneItems,
|
||||
cursor: { next: 'cursor_next' },
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
})
|
||||
@@ -496,8 +482,7 @@ describe('SessionList', () => {
|
||||
try {
|
||||
const rendered = render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a']}
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
{ wrapper },
|
||||
@@ -532,7 +517,8 @@ describe('SessionList', () => {
|
||||
expect(screen.queryByText('child session 0')).toBeNull()
|
||||
|
||||
resolveRecovery?.(new Response(JSON.stringify({
|
||||
items: [{ id: 'older_root', projectID: 'proj_1', title: 'older root session', time: { created: 1, updated: 1 } }],
|
||||
data: [{ id: 'older_root', projectID: 'proj_1', title: 'older root session', time: { created: 1, updated: 1 }, location: { directory: '/w/a' } }],
|
||||
cursor: {},
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
|
||||
await waitFor(() => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useState, useMemo, useEffect, useRef } from "react";
|
||||
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
|
||||
import type { Session } from "@/api/types";
|
||||
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins';
|
||||
import { buildSessionKey } from '@/lib/sessionKey';
|
||||
import { partitionSessions } from './session-partition';
|
||||
@@ -12,7 +13,6 @@ import { Input } from "@/components/ui/input";
|
||||
import { Search, Trash2, Pencil, X } from "lucide-react";
|
||||
|
||||
interface SessionListProps {
|
||||
opcodeUrl: string;
|
||||
directory?: string;
|
||||
directories?: string[];
|
||||
createDirectory?: string;
|
||||
@@ -22,7 +22,6 @@ interface SessionListProps {
|
||||
}
|
||||
|
||||
export const SessionList = ({
|
||||
opcodeUrl,
|
||||
directory,
|
||||
directories,
|
||||
createDirectory,
|
||||
@@ -37,13 +36,13 @@ export const SessionList = ({
|
||||
const directorySet = useMemo(() => new Set(directoriesList), [directoriesList]);
|
||||
const primaryDirectory = directoriesList[0];
|
||||
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
|
||||
const getSessionSelectionKey = useCallback((session: { id: string; directory?: string }) =>
|
||||
buildSessionKey(session.directory ?? primaryDirectory, session.id),
|
||||
[primaryDirectory]);
|
||||
const getSessionSelectionKey = useCallback((session: Session) =>
|
||||
buildSessionKey(session.location.directory, session.id),
|
||||
[]);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(opcodeUrl, directoriesList, { search: searchQuery, limit: 25 });
|
||||
const deleteSession = useDeleteSession(opcodeUrl, directoriesList);
|
||||
const createSession = useCreateSession(opcodeUrl, sessionCreateDirectory, (newSession) => {
|
||||
const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search: searchQuery, limit: 25 });
|
||||
const deleteSession = useDeleteSession(directoriesList);
|
||||
const createSession = useCreateSession(sessionCreateDirectory, (newSession) => {
|
||||
onSelectSession(newSession.id);
|
||||
});
|
||||
const { data: sessionPins } = useSessionPins();
|
||||
@@ -63,7 +62,7 @@ export const SessionList = ({
|
||||
|
||||
const filtered = sessions.filter((session) => {
|
||||
if (session.parentID) return false;
|
||||
if (directorySet.size > 0 && session.directory && !directorySet.has(session.directory)) return false;
|
||||
if (directorySet.size > 0 && !directorySet.has(session.location.directory)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -83,8 +82,8 @@ export const SessionList = ({
|
||||
[filteredSessions, pinnedKeys, getSessionSelectionKey],
|
||||
);
|
||||
|
||||
const handleTogglePin = (session: { id: string; directory?: string }) => {
|
||||
const directory = session.directory ?? primaryDirectory ?? '';
|
||||
const handleTogglePin = (session: Session) => {
|
||||
const directory = session.location.directory;
|
||||
const key = getSessionSelectionKey(session);
|
||||
togglePin.mutate({ sessionId: session.id, directory, pinned: !pinnedKeys.has(key) });
|
||||
};
|
||||
@@ -153,18 +152,12 @@ export const SessionList = ({
|
||||
}
|
||||
}
|
||||
|
||||
const getDeleteTarget = (session: { id: string; directory?: string; workspaceID?: string }): DeleteSessionTarget => {
|
||||
const target: Extract<DeleteSessionTarget, { id: string }> = {
|
||||
id: session.id,
|
||||
directory: session.directory ?? primaryDirectory,
|
||||
};
|
||||
if (session.workspaceID) {
|
||||
target.workspaceID = session.workspaceID;
|
||||
}
|
||||
return target;
|
||||
};
|
||||
const getDeleteTarget = (session: Session): DeleteSessionTarget => ({
|
||||
id: session.id,
|
||||
directory: session.location.directory,
|
||||
});
|
||||
|
||||
const handleDelete = (session: { id: string; directory?: string; workspaceID?: string }, e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
const handleDelete = (session: Session, e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
setSessionToDelete(getDeleteTarget(session));
|
||||
setDeleteDialogOpen(true);
|
||||
@@ -187,7 +180,7 @@ export const SessionList = ({
|
||||
setManageMode(false);
|
||||
};
|
||||
|
||||
const toggleSessionSelection = (session: { id: string; directory?: string }, selected: boolean) => {
|
||||
const toggleSessionSelection = (session: Session, selected: boolean) => {
|
||||
const selectionKey = getSessionSelectionKey(session);
|
||||
const newSelected = new Set(selectedSessions);
|
||||
if (selected) {
|
||||
@@ -230,7 +223,7 @@ export const SessionList = ({
|
||||
isSelected={selectedSessions.has(key)}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
workspaceLabel={directoryLabels?.[session.location.directory]}
|
||||
isPinned={isPinned}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
|
||||
@@ -111,18 +111,6 @@ describe('SessionSendErrorBanner', () => {
|
||||
expect(screen.getByText('Connection Failed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a session-kind error even while disconnected', () => {
|
||||
useSendErrorStore.getState().setQueuedPrompt('test-session', 'queued message')
|
||||
useSendErrorStore.getState().failQueuedPrompt({
|
||||
sessionID: 'test-session',
|
||||
title: 'Session error',
|
||||
message: 'Server reported failure',
|
||||
})
|
||||
|
||||
render(<SessionSendErrorBanner sessionId="test-session" isConnected={false} isReconnecting={false} />)
|
||||
expect(screen.getByText('Session error')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a previously hidden network error after reconnecting', () => {
|
||||
useSendErrorStore.getState().setError({
|
||||
sessionID: 'test-session',
|
||||
|
||||
@@ -6,15 +6,16 @@ function createSession(id: string, updated: number, directory = '/test'): Sessio
|
||||
return {
|
||||
id,
|
||||
projectID: 'proj-1',
|
||||
directory,
|
||||
title: `Session ${id}`,
|
||||
version: '1',
|
||||
time: { created: updated - 10000, updated },
|
||||
location: { directory },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
}
|
||||
}
|
||||
|
||||
const keyFn = (s: { id: string; directory?: string }) =>
|
||||
`${s.directory ?? ''}:${s.id}`
|
||||
const keyFn = (s: Session) =>
|
||||
`${s.location.directory}:${s.id}`
|
||||
|
||||
describe('partitionSessions', () => {
|
||||
it('places pinned sessions in pinned array sorted by updated desc', () => {
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface PartitionedSessions {
|
||||
export function partitionSessions(
|
||||
sessions: Session[],
|
||||
pinnedKeys: Set<string>,
|
||||
keyFn: (session: { id: string; directory?: string }) => string,
|
||||
keyFn: (session: Session) => string,
|
||||
now: number = Date.now(),
|
||||
): PartitionedSessions {
|
||||
const startOfDay = new Date(now)
|
||||
|
||||
Reference in new issue
Block a user