feat(schedules): support scheduling jobs for the Assistant workspace (#254)

* feat(schedules): support scheduling jobs for the Assistant workspace

* refactor(schedules): extract assistant repo constants, rename workspace to schedule-target

* feat(navigation): add schedules link to session drawer menu

* fix(schedules): document Assistant repoId=0 in generated schedule-management skill
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-05 11:16:31 -04:00
1 parent 9479e1f662
commit 70cb62b77b
18 files changed
+402 -115

No files matched your search

+19 -15
View File
@@ -9,6 +9,7 @@ import {
type ScheduleRunStatus,
type ScheduleRunTriggerSource,
} from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
interface ScheduleJobRow {
@@ -376,8 +377,8 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
}
interface ScheduleJobWithRepoRow extends ScheduleJobRow {
repo_url: string
repo_path: string
repo_url: string | null
repo_path: string | null
}
function repoNameFromPath(repoPath: string): string {
@@ -385,13 +386,18 @@ function repoNameFromPath(repoPath: string): string {
return repoPath.split(/[\\/]/).pop() ?? repoPath
}
function resolveRepoDisplay(repoId: number, repoPath: string | null): { repoName: string; repoPath: string } {
if (repoId === ASSISTANT_REPO_ID) {
return { repoName: ASSISTANT_REPO_NAME, repoPath: ASSISTANT_REPO_PATH }
}
return { repoName: repoNameFromPath(repoPath ?? ''), repoPath: repoPath ?? '' }
}
function rowToScheduleJobWithRepo(row: ScheduleJobWithRepoRow): ScheduleJobWithRepo {
const job = rowToScheduleJob(row)
return {
...job,
repoName: repoNameFromPath(row.repo_path),
repoPath: row.repo_path,
repoUrl: row.repo_url,
...rowToScheduleJob(row),
...resolveRepoDisplay(row.repo_id, row.repo_path),
repoUrl: row.repo_url ?? '',
}
}
@@ -399,8 +405,8 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[
const stmt = db.prepare(`
SELECT sj.*, r.repo_url, r.local_path as repo_path
FROM schedule_jobs sj
JOIN repos r ON sj.repo_id = r.id
ORDER BY r.local_path, sj.name
LEFT JOIN repos r ON sj.repo_id = r.id
ORDER BY COALESCE(r.local_path, ''), sj.name
`)
const rows = stmt.all() as ScheduleJobWithRepoRow[]
return rows.map(rowToScheduleJobWithRepo)
@@ -414,16 +420,14 @@ export interface ScheduleRunWithContext extends ScheduleRun {
interface ScheduleRunWithContextRow extends ScheduleRunRow {
job_name: string
repo_path: string
repo_path: string | null
}
function rowToScheduleRunWithContext(row: ScheduleRunWithContextRow): ScheduleRunWithContext {
const run = rowToScheduleRun(row)
return {
...run,
...rowToScheduleRun(row),
jobName: row.job_name,
repoName: repoNameFromPath(row.repo_path),
repoPath: row.repo_path,
...resolveRepoDisplay(row.repo_id, row.repo_path),
}
}
@@ -469,7 +473,7 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
sj.name AS job_name, r.local_path AS repo_path
FROM schedule_runs sr
JOIN schedule_jobs sj ON sr.job_id = sj.id
JOIN repos r ON sr.repo_id = r.id
LEFT JOIN repos r ON sr.repo_id = r.id
${whereClause}
ORDER BY sr.started_at DESC
LIMIT ? OFFSET ?
+7 -2
View File
@@ -13,6 +13,7 @@ import {
ensureDirectoryExists,
} from './file-operations'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH } from '@opencode-manager/shared/utils'
import { getReposPath, ENV } from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import { getOrCreateInternalToken } from './internal-token'
@@ -21,7 +22,7 @@ import { logger } from '../utils/logger'
const ASSISTANT_WARMUP_OPENCODE_TIMEOUT_MS = 90000
const ASSISTANT_MODE_DIR = 'assistant'
const ASSISTANT_MODE_DIR = ASSISTANT_REPO_PATH
const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
@@ -52,7 +53,7 @@ export function getAssistantModeDirectory(): string {
export function buildAssistantRepo(): Repo {
return {
id: 0,
id: ASSISTANT_REPO_ID,
localPath: ASSISTANT_MODE_DIR,
fullPath: getAssistantModeDirectory(),
defaultBranch: 'main',
@@ -339,6 +340,10 @@ Authorization: Bearer <token>
\`${internalBaseUrl}\`
## Assistant Schedules
Use repo ID \`0\` for the built-in Assistant. For example, use \`/repos/0/schedules\` to list or create schedule jobs that run in the Assistant workspace.
## Endpoints
### GET /schedules/all
+2 -1
View File
@@ -39,6 +39,7 @@ import { sseAggregator, type SSEEvent } from './sse-aggregator'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
import { buildAssistantRepo } from './assistant-mode'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
class ScheduleServiceError extends Error {
status: number
@@ -1056,7 +1057,7 @@ export class ScheduleService {
}
private assertRepo(repoId: number) {
if (repoId === 0) {
if (repoId === ASSISTANT_REPO_ID) {
return { ...buildAssistantRepo(), lastAccessedAt: Date.now(), isLocal: true, currentBranch: undefined }
}
const repo = getRepoById(this.db, repoId)
+104
View File
@@ -0,0 +1,104 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import {
listAllScheduleJobsWithRepos,
listAllScheduleRuns,
} from '../../src/db/schedules'
describe('assistant repo (repo_id=0) in global aggregate queries', () => {
let db: Database
beforeEach(() => {
db = new Database(':memory:')
// Disable FK enforcement to match bun:sqlite default behavior (OFF)
db.exec('PRAGMA foreign_keys = OFF')
migrate(db, allMigrations)
const now = Date.now()
// Insert a real repo (id=1)
db.exec(
`INSERT INTO repos (id, repo_url, local_path, branch, default_branch, clone_status, cloned_at)
VALUES (1, 'https://github.com/test/my-repo', 'repos/my-repo', 'main', 'main', 'ready', ${now})`,
)
// Insert a schedule job for the real repo
db.exec(
`INSERT INTO schedule_jobs (id, repo_id, name, enabled, schedule_mode, prompt, created_at, updated_at)
VALUES (1, 1, 'Real repo job', 1, 'interval', 'Run the real repo job', ${now}, ${now})`,
)
// Insert a schedule job for the assistant (repo_id=0)
db.exec(
`INSERT INTO schedule_jobs (id, repo_id, name, enabled, schedule_mode, prompt, created_at, updated_at)
VALUES (2, 0, 'Assistant job', 1, 'interval', 'Run the assistant job', ${now}, ${now})`,
)
// Insert a schedule run for the real repo job
db.exec(
`INSERT INTO schedule_runs (id, job_id, repo_id, trigger_source, status, started_at, created_at)
VALUES (1, 1, 1, 'manual', 'completed', ${now}, ${now})`,
)
// Insert a schedule run for the assistant job
db.exec(
`INSERT INTO schedule_runs (id, job_id, repo_id, trigger_source, status, started_at, created_at)
VALUES (2, 2, 0, 'manual', 'completed', ${now}, ${now})`,
)
})
it('listAllScheduleJobsWithRepos includes assistant jobs with synthetic metadata', () => {
const jobs = listAllScheduleJobsWithRepos(db)
expect(jobs).toHaveLength(2)
const assistantJob = jobs.find(j => j.repoId === 0)
expect(assistantJob).toBeDefined()
if (assistantJob) {
expect(assistantJob.repoName).toBe('Assistant')
expect(assistantJob.repoPath).toBe('assistant')
expect(assistantJob.repoUrl).toBe('')
expect(assistantJob.name).toBe('Assistant job')
}
const realJob = jobs.find(j => j.repoId === 1)
expect(realJob).toBeDefined()
if (realJob) {
expect(realJob.repoName).toBe('my-repo')
expect(realJob.repoPath).toBe('repos/my-repo')
expect(realJob.repoUrl).toBe('https://github.com/test/my-repo')
expect(realJob.name).toBe('Real repo job')
}
})
it('listAllScheduleRuns includes assistant runs with synthetic metadata', () => {
const runs = listAllScheduleRuns(db, {})
expect(runs).toHaveLength(2)
const assistantRun = runs.find(r => r.repoId === 0)
expect(assistantRun).toBeDefined()
if (assistantRun) {
expect(assistantRun.repoName).toBe('Assistant')
expect(assistantRun.repoPath).toBe('assistant')
expect(assistantRun.jobName).toBe('Assistant job')
}
const realRun = runs.find(r => r.repoId === 1)
expect(realRun).toBeDefined()
if (realRun) {
expect(realRun.repoName).toBe('my-repo')
expect(realRun.repoPath).toBe('repos/my-repo')
expect(realRun.jobName).toBe('Real repo job')
}
})
it('listAllScheduleRuns with repoId=0 filter returns only assistant runs', () => {
const runs = listAllScheduleRuns(db, { repoId: 0 })
expect(runs).toHaveLength(1)
const run = runs[0]!
expect(run.repoId).toBe(0)
expect(run.repoName).toBe('Assistant')
expect(run.repoPath).toBe('assistant')
})
})
@@ -18,6 +18,12 @@ describe('buildSchedulesSkill', () => {
expect(skill).toContain(`http://localhost:${ENV.SERVER.PORT}/api/internal`)
expect(skill).not.toContain(':443')
})
it('documents repoId 0 for Assistant schedules', () => {
const skill = buildSchedulesSkill('http://localhost:5003/api/internal')
expect(skill).toContain('Use repo ID `0` for the built-in Assistant')
expect(skill).toContain('/repos/0/schedules')
})
})
describe('buildReposSkill', () => {
@@ -224,6 +230,8 @@ describe('ensureAssistantMode', () => {
const schedulesSkillContent = await readFile(schedulesSkillPath, 'utf8')
expect(schedulesSkillContent).toContain('name: schedule-management')
expect(schedulesSkillContent).toContain('Manage schedule jobs')
expect(schedulesSkillContent).toContain('Use repo ID `0` for the built-in Assistant')
expect(schedulesSkillContent).toContain('/repos/0/schedules')
const notificationsSkillContent = await readFile(notificationsSkillPath, 'utf8')
expect(notificationsSkillContent).toContain('name: notifications')
@@ -33,16 +33,18 @@ describe('buildMoreItems', () => {
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc')
expect(items).toHaveLength(8)
expect(items).toHaveLength(9)
expect(items[0].key).toBe('files')
expect(items[1].key).toBe('mcp')
expect(items[2].key).toBe('skills')
expect(items[3].key).toBe('lsp')
expect(items[3].dialog).toBe('lsp')
expect(items[4].key).toBe('reset-permissions')
expect(items[5].key).toBe('source-control')
expect(items[6].key).toBe('settings')
expect(items[7].key).toBe('logout')
expect(items[5].key).toBe('schedules')
expect(items[5].to).toBe('/repos/42/schedules')
expect(items[6].key).toBe('source-control')
expect(items[7].key).toBe('settings')
expect(items[8].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
@@ -75,6 +75,7 @@ export function buildNavModel(pathname: string): NavModel {
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'lsp', label: 'LSP', icon: Code2, dialog: 'lsp' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${sessionDetailMatch[1]}/schedules` },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
...baseItems,
]
@@ -0,0 +1,148 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ScheduleJobDialog } from './ScheduleJobDialog'
// jsdom does not implement scrollIntoView
Element.prototype.scrollIntoView = vi.fn()
const mocks = vi.hoisted(() => ({
templates: [] as Array<{ id: number; title: string; description: string; category: string; cadenceHint: string; suggestedName: string; suggestedDescription: string; prompt: string }>,
useDeletePromptTemplateMutate: vi.fn(),
}))
vi.mock('@/hooks/usePromptTemplates', () => ({
usePromptTemplates: () => ({ data: mocks.templates, isLoading: false }),
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useDeletePromptTemplate: () => ({ mutate: mocks.useDeletePromptTemplateMutate, isPending: false }),
}))
vi.mock('@/api/providers', () => ({
getProvidersWithModels: () => Promise.resolve([]),
}))
vi.mock('@/api/opencode', () => ({
createOpenCodeClient: () => ({
listAgents: () => Promise.resolve([]),
getConfig: () => Promise.resolve(null),
}),
}))
vi.mock('@/api/settings', () => ({
settingsApi: {
listManagedSkills: () => Promise.resolve([]),
},
}))
vi.mock('@/api/repos', () => ({
listRepos: () => Promise.resolve([]),
}))
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('ScheduleJobDialog — assistant create guard', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renders Assistant as the first repository option', async () => {
const onRepoChange = vi.fn()
const onSubmit = vi.fn()
const onOpenChange = vi.fn()
const user = userEvent.setup()
render(
<ScheduleJobDialog
open
onOpenChange={onOpenChange}
showRepoSelector
repoId={undefined}
onRepoChange={onRepoChange}
onSubmit={onSubmit}
isSaving={false}
/>,
{ wrapper: createWrapper() },
)
// Open the repo combobox by clicking the chevron/input
const repoInput = screen.getByPlaceholderText('Select a repository')
await user.click(repoInput)
// The dropdown should open and show "Assistant" as an option
await waitFor(() => {
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
// Assistant description should also be visible
expect(screen.getByText('Built-in assistant')).toBeInTheDocument()
})
it('disables submit when no repo is selected, enables when Assistant repo is selected', async () => {
const onRepoChange = vi.fn()
const onSubmit = vi.fn()
const user = userEvent.setup()
const { rerender } = render(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
showRepoSelector
repoId={undefined}
onRepoChange={onRepoChange}
onSubmit={onSubmit}
isSaving={false}
/>,
{ wrapper: createWrapper() },
)
// Wait for queries to settle
await waitFor(() => {
expect(screen.getByRole('button', { name: /Create schedule/i })).toBeDisabled()
})
// Fill in required name field
const nameInput = screen.getByLabelText('Name')
await user.type(nameInput, 'Test Assistant Job')
// Switch to Prompt tab to fill prompt
const promptTab = screen.getByRole('tab', { name: 'Prompt' })
await user.click(promptTab)
// Fill in required prompt field
const promptInput = screen.getByRole('textbox', { name: 'Prompt' })
await user.type(promptInput, 'Run a test analysis')
// Submit button should still be disabled (repoId is undefined)
const submitButton = screen.getByRole('button', { name: /Create schedule/i })
expect(submitButton).toBeDisabled()
// Re-render with repoId={0} (Assistant selected) — name and prompt state persists
rerender(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
showRepoSelector
repoId={0}
onRepoChange={onRepoChange}
onSubmit={onSubmit}
isSaving={false}
/>,
)
// Submit button should now be enabled
await waitFor(() => {
expect(screen.getByRole('button', { name: /Create schedule/i })).not.toBeDisabled()
})
})
})
@@ -18,6 +18,7 @@ import {
type SchedulePreset,
} from '@/components/schedules/schedule-utils'
import { getRepoDisplayName } from '@/lib/utils'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME } from '@opencode-manager/shared/utils'
import { Loader2 } from 'lucide-react'
import { usePromptTemplates, useDeletePromptTemplate } from '@/hooks/usePromptTemplates'
import { PromptTemplateDialog } from './PromptTemplateDialog'
@@ -107,16 +108,21 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
staleTime: 5 * 60 * 1000,
})
const repoOptions = useMemo<ComboboxOption[]>(() =>
repos
const repoOptions = useMemo<ComboboxOption[]>(() => {
const assistantOption: ComboboxOption = {
value: ASSISTANT_REPO_ID.toString(),
label: ASSISTANT_REPO_NAME,
description: 'Built-in assistant',
}
const repoEntries = repos
.filter((repo) => repo.cloneStatus === 'ready')
.map((repo) => ({
value: repo.id.toString(),
label: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath),
description: repo.localPath,
})),
[repos]
)
}))
return [assistantOption, ...repoEntries]
}, [repos])
const modelOptions = useMemo<ComboboxOption[]>(() => {
const configuredModels: ComboboxOption[] = []
@@ -335,7 +341,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
<div className="mt-0 shrink-0 border-t border-border px-3 sm:px-6 py-4 flex flex-row gap-2 sm:justify-end">
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving} className="flex-1 sm:flex-none">Cancel</Button>
<Button onClick={handleSubmit} disabled={isSaving || !name.trim() || !prompt.trim() || isScheduleConfigInvalid || (!!showRepoSelector && !job && !selectedRepoId)} className="flex-1 sm:flex-none">
<Button onClick={handleSubmit} disabled={isSaving || !name.trim() || !prompt.trim() || isScheduleConfigInvalid || (!!showRepoSelector && !job && selectedRepoId === undefined)} className="flex-1 sm:flex-none">
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{isSaving ? 'Saving...' : job ? 'Save changes' : 'Create schedule'}
</Button>
@@ -35,6 +35,10 @@ vi.mock('@/components/settings/NotificationSettings', () => ({
NotificationSettings: () => <div data-testid="notification-settings">Notification Settings Content</div>,
}))
vi.mock('@/components/settings/VersionSelectDialog', () => ({
VersionSelectDialog: () => <div data-testid="version-select-dialog">Version Select Dialog</div>,
}))
vi.mock('@/hooks/useMobile', () => ({
useSwipeBack: vi.fn(() => ({
bind: vi.fn(),
@@ -1,7 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useWorkspace } from '../useWorkspace'
import { useScheduleTarget } from '../useScheduleTarget'
import type { AssistantModeStatus, Repo } from '@opencode-manager/shared/types'
const mocks = vi.hoisted(() => ({
@@ -25,13 +25,13 @@ const createWrapper = () => {
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
describe('useWorkspace', () => {
describe('useScheduleTarget', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('repoId === 0 (assistant)', () => {
it('returns assistant workspace with correct properties', async () => {
it('returns assistant schedule target with correct properties', async () => {
const mockStatus: AssistantModeStatus = {
repoId: 0,
directory: '/abs/assistant',
@@ -45,16 +45,16 @@ describe('useWorkspace', () => {
mocks.getAssistantModeStatus.mockResolvedValue(mockStatus)
const { result } = renderHook(() => useWorkspace(0), { wrapper: createWrapper() })
const { result } = renderHook(() => useScheduleTarget(0), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.workspace).toBeDefined()
expect(result.current.scheduleTarget).toBeDefined()
})
expect(result.current.workspace?.kind).toBe('assistant')
expect(result.current.workspace?.fullPath).toBe('/abs/assistant')
expect(result.current.workspace?.repoId).toBe(0)
expect(result.current.workspace?.backHref).toBe('/assistant')
expect(result.current.scheduleTarget?.kind).toBe('assistant')
expect(result.current.scheduleTarget?.fullPath).toBe('/abs/assistant')
expect(result.current.scheduleTarget?.repoId).toBe(0)
expect(result.current.scheduleTarget?.backHref).toBe('/assistant')
expect(result.current.isLoading).toBe(false)
expect(result.current.isError).toBe(false)
})
@@ -68,7 +68,7 @@ describe('useWorkspace', () => {
repoId: 0,
})
renderHook(() => useWorkspace(0), { wrapper: createWrapper() })
renderHook(() => useScheduleTarget(0), { wrapper: createWrapper() })
await vi.waitFor(() => {
expect(mocks.getRepo).not.toHaveBeenCalled()
@@ -77,7 +77,7 @@ describe('useWorkspace', () => {
})
describe('repoId === 5 (real repo)', () => {
it('returns repo workspace with correct properties', async () => {
it('returns repo schedule target with correct properties', async () => {
const mockRepo: Repo = {
id: 5,
repoUrl: 'https://x/my-repo',
@@ -91,16 +91,16 @@ describe('useWorkspace', () => {
mocks.getRepo.mockResolvedValue(mockRepo)
const { result } = renderHook(() => useWorkspace(5), { wrapper: createWrapper() })
const { result } = renderHook(() => useScheduleTarget(5), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.workspace).toBeDefined()
expect(result.current.scheduleTarget).toBeDefined()
})
expect(result.current.workspace?.kind).toBe('repo')
expect(result.current.workspace?.repoId).toBe(5)
expect(result.current.workspace?.fullPath).toBe('/abs/repos/my-repo')
expect(result.current.workspace?.backHref).toBe('/repos/5')
expect(result.current.scheduleTarget?.kind).toBe('repo')
expect(result.current.scheduleTarget?.repoId).toBe(5)
expect(result.current.scheduleTarget?.fullPath).toBe('/abs/repos/my-repo')
expect(result.current.scheduleTarget?.backHref).toBe('/repos/5')
})
it('does not call getAssistantModeStatus for repo', async () => {
@@ -117,7 +117,7 @@ describe('useWorkspace', () => {
mocks.getRepo.mockResolvedValue(mockRepo)
renderHook(() => useWorkspace(5), { wrapper: createWrapper() })
renderHook(() => useScheduleTarget(5), { wrapper: createWrapper() })
await vi.waitFor(() => {
expect(mocks.getAssistantModeStatus).not.toHaveBeenCalled()
@@ -126,10 +126,10 @@ describe('useWorkspace', () => {
})
describe('repoId === undefined', () => {
it('returns undefined workspace', () => {
const { result } = renderHook(() => useWorkspace(undefined), { wrapper: createWrapper() })
it('returns undefined schedule target', () => {
const { result } = renderHook(() => useScheduleTarget(undefined), { wrapper: createWrapper() })
expect(result.current.workspace).toBeUndefined()
expect(result.current.scheduleTarget).toBeUndefined()
expect(result.current.isLoading).toBe(false)
})
})
@@ -1,11 +1,11 @@
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useAssistantMode } from '@/hooks/useAssistantMode'
import { isAssistantRepoId, workspaceFromAssistant, workspaceFromRepo } from '@/lib/schedules/workspace'
import type { Workspace } from '@/lib/schedules/workspace'
import { isAssistantRepoId, scheduleTargetFromAssistant, scheduleTargetFromRepo } from '@/lib/schedules/schedule-target'
import type { ScheduleTarget } from '@/lib/schedules/schedule-target'
export function useWorkspace(repoId: number | undefined): {
workspace: Workspace | undefined
export function useScheduleTarget(repoId: number | undefined): {
scheduleTarget: ScheduleTarget | undefined
isLoading: boolean
isError: boolean
} {
@@ -19,14 +19,14 @@ export function useWorkspace(repoId: number | undefined): {
if (isAssistantRepoId(repoId)) {
return {
workspace: assistantQuery.status ? workspaceFromAssistant(assistantQuery.status) : undefined,
scheduleTarget: assistantQuery.status ? scheduleTargetFromAssistant(assistantQuery.status) : undefined,
isLoading: assistantQuery.isLoading,
isError: assistantQuery.isError,
}
}
return {
workspace: repoQuery.data ? workspaceFromRepo(repoQuery.data) : undefined,
scheduleTarget: repoQuery.data ? scheduleTargetFromRepo(repoQuery.data) : undefined,
isLoading: repoQuery.isLoading,
isError: repoQuery.isError,
}
@@ -1,9 +1,9 @@
import { describe, it, expect } from 'vitest'
import {
isAssistantRepoId,
workspaceFromRepo,
workspaceFromAssistant,
} from './workspace'
scheduleTargetFromRepo,
scheduleTargetFromAssistant,
} from './schedule-target'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
describe('isAssistantRepoId', () => {
@@ -20,8 +20,8 @@ describe('isAssistantRepoId', () => {
})
})
describe('workspaceFromRepo', () => {
it('returns correct workspace for a repo', () => {
describe('scheduleTargetFromRepo', () => {
it('returns correct schedule target for a repo', () => {
const repo = {
id: 5,
repoUrl: 'https://x/y',
@@ -33,9 +33,9 @@ describe('workspaceFromRepo', () => {
clonedAt: 0,
}
const workspace = workspaceFromRepo(repo)
const target = scheduleTargetFromRepo(repo)
expect(workspace).toEqual({
expect(target).toEqual({
repoId: 5,
kind: 'repo',
name: 'y',
@@ -46,8 +46,8 @@ describe('workspaceFromRepo', () => {
})
})
describe('workspaceFromAssistant', () => {
it('returns correct workspace for assistant', () => {
describe('scheduleTargetFromAssistant', () => {
it('returns correct schedule target for assistant', () => {
const status: AssistantModeStatus = {
repoId: 0,
directory: '/abs/assistant',
@@ -59,13 +59,13 @@ describe('workspaceFromAssistant', () => {
schedulesSkill: { path: '', exists: false, created: false },
}
const workspace = workspaceFromAssistant(status)
const target = scheduleTargetFromAssistant(status)
expect(workspace).toEqual({
expect(target).toEqual({
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
subtitle: 'Built-in assistant',
fullPath: '/abs/assistant',
backHref: '/assistant',
})
@@ -1,9 +1,10 @@
import type { Repo } from '@/api/types'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME } from '@opencode-manager/shared/utils'
import { getRepoDisplayName } from '@/lib/utils'
import { getAssistantPath } from '@/lib/navigation'
export interface Workspace {
export interface ScheduleTarget {
repoId: number
kind: 'assistant' | 'repo'
name: string
@@ -12,13 +13,11 @@ export interface Workspace {
backHref: string
}
export const ASSISTANT_REPO_ID = 0
export function isAssistantRepoId(repoId: number | undefined): boolean {
return repoId === ASSISTANT_REPO_ID
}
export function workspaceFromRepo(repo: Repo): Workspace {
export function scheduleTargetFromRepo(repo: Repo): ScheduleTarget {
return {
repoId: repo.id,
kind: 'repo',
@@ -29,12 +28,12 @@ export function workspaceFromRepo(repo: Repo): Workspace {
}
}
export function workspaceFromAssistant(status: AssistantModeStatus): Workspace {
export function scheduleTargetFromAssistant(status: AssistantModeStatus): ScheduleTarget {
return {
repoId: ASSISTANT_REPO_ID,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
name: ASSISTANT_REPO_NAME,
subtitle: 'Built-in assistant',
fullPath: status.directory,
backHref: getAssistantPath(),
}
+5 -4
View File
@@ -16,6 +16,8 @@ import { CalendarClock, Loader2, Plus, ArrowLeft, Play, Pencil, Trash2, Pause, P
import type { ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
import { Combobox } from '@/components/ui/combobox'
import { isAssistantRepoId } from '@/lib/schedules/schedule-target'
import { getAssistantPath } from '@/lib/navigation'
type StatusFilter = 'all' | 'enabled' | 'disabled'
type ScheduleModeFilter = 'all' | 'cron' | 'interval'
@@ -254,7 +256,7 @@ export function GlobalSchedules() {
}
const handleCreate = (data: CreateScheduleJobRequest) => {
if (!selectedRepoId) return
if (selectedRepoId === undefined) return
createMutation.mutate(
{ repoId: selectedRepoId, data },
{
@@ -285,9 +287,8 @@ export function GlobalSchedules() {
const handleNavigateToRepo = (repoPath: string) => {
const repoId = jobs.find((j) => j.repoPath === repoPath)?.repoId
if (repoId) {
navigate(`/repos/${repoId}`)
}
if (repoId === undefined) return
navigate(isAssistantRepoId(repoId) ? getAssistantPath() : `/repos/${repoId}`)
}
if (isLoading) {
+9 -9
View File
@@ -13,7 +13,7 @@ import {
useUpdateRepoSchedule,
} from '@/hooks/useSchedules'
import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useWorkspace } from '@/hooks/useWorkspace'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { useScheduleTab } from '@/hooks/useMobileTabBar'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
@@ -35,9 +35,9 @@ export function Schedules() {
const [deleteJobId, setDeleteJobId] = useState<number | null>(null)
const { scheduleTab: activeTab, setScheduleTab: setActiveTab } = useScheduleTab()
const { workspace, isLoading: workspaceLoading } = useWorkspace(repoId)
const { scheduleTarget, isLoading: scheduleTargetLoading } = useScheduleTarget(repoId)
useRepoActivity(repoId ?? 0, Boolean(workspace) && workspace?.kind === 'repo')
useRepoActivity(repoId ?? 0, Boolean(scheduleTarget) && scheduleTarget?.kind === 'repo')
const { data: jobs, isLoading: jobsLoading } = useRepoSchedules(repoId)
const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, selectedJobId)
@@ -82,7 +82,7 @@ export function Schedules() {
const activeRun = selectedRunDetails ?? activeRunSummary
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
if (workspaceLoading || jobsLoading) {
if (scheduleTargetLoading || jobsLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
@@ -90,11 +90,11 @@ export function Schedules() {
)
}
if (!workspace || repoId === undefined) {
if (!scheduleTarget || repoId === undefined) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">
{repoId === 0 ? 'Workspace not found' : 'Repository not found'}
{repoId === 0 ? 'Assistant not found' : 'Repository not found'}
</p>
</div>
)
@@ -192,10 +192,10 @@ export function Schedules() {
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={workspace.backHref} />
<Header.BackButton to={scheduleTarget.backHref} />
<div className="min-w-0 flex-1 px-3">
<Header.Title className="truncate">{workspace.name}</Header.Title>
<p className="text-xs text-muted-foreground truncate">{workspace.subtitle}</p>
<Header.Title className="truncate">{scheduleTarget.name}</Header.Title>
<p className="text-xs text-muted-foreground truncate">{scheduleTarget.subtitle}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs">{jobs?.length ?? 0} jobs</Badge>
+28 -28
View File
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Schedules } from '../Schedules'
const mocks = vi.hoisted(() => ({
useWorkspace: vi.fn(),
useScheduleTarget: vi.fn(),
useRepoSchedules: vi.fn(),
useRepoSchedule: vi.fn(),
useRepoScheduleRuns: vi.fn(),
@@ -25,8 +25,8 @@ vi.mock('react-router-dom', async (importOriginal) => ({
useNavigate: () => mockNavigate,
}))
vi.mock('@/hooks/useWorkspace', () => ({
useWorkspace: mocks.useWorkspace,
vi.mock('@/hooks/useScheduleTarget', () => ({
useScheduleTarget: mocks.useScheduleTarget,
}))
vi.mock('@/hooks/useSchedules', () => ({
@@ -101,14 +101,14 @@ describe('Schedules', () => {
mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
})
describe('assistant workspace (repoId=0)', () => {
describe('assistant schedule target (repoId=0)', () => {
it('renders assistant title and subtitle', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
subtitle: 'Built-in assistant',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
@@ -123,16 +123,16 @@ describe('Schedules', () => {
renderSchedules('0')
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.getByText('Assistant Workspace')).toBeInTheDocument()
expect(screen.getByText('Built-in assistant')).toBeInTheDocument()
})
it('does not render Repository not found', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
subtitle: 'Built-in assistant',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
@@ -152,12 +152,12 @@ describe('Schedules', () => {
it('renders back button with correct href', () => {
mockNavigate.mockClear()
mocks.useWorkspace.mockReturnValue({
workspace: {
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
subtitle: 'Built-in assistant',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
@@ -179,12 +179,12 @@ describe('Schedules', () => {
it('calls runMutation with repoId=0 when Run Now is clicked', () => {
const mutateMock = vi.fn()
mocks.useWorkspace.mockReturnValue({
workspace: {
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
subtitle: 'Built-in assistant',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
@@ -228,10 +228,10 @@ describe('Schedules', () => {
})
})
describe('repo workspace (repoId=5)', () => {
describe('repo schedule target (repoId=5)', () => {
it('renders repo name and subtitle', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
@@ -256,8 +256,8 @@ describe('Schedules', () => {
it('renders back button with correct href', () => {
mockNavigate.mockClear()
mocks.useWorkspace.mockReturnValue({
workspace: {
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
@@ -282,10 +282,10 @@ describe('Schedules', () => {
})
})
describe('workspace not found', () => {
describe('schedule target not found', () => {
it('renders not found fallback for real repo', () => {
mocks.useWorkspace.mockReturnValue({
workspace: undefined,
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: undefined,
isLoading: false,
isError: true,
})
@@ -300,8 +300,8 @@ describe('Schedules', () => {
})
it('renders not found fallback for assistant', () => {
mocks.useWorkspace.mockReturnValue({
workspace: undefined,
mocks.useScheduleTarget.mockReturnValue({
scheduleTarget: undefined,
isLoading: false,
isError: true,
})
@@ -312,7 +312,7 @@ describe('Schedules', () => {
renderSchedules('0')
expect(screen.getByText('Workspace not found')).toBeInTheDocument()
expect(screen.getByText('Assistant not found')).toBeInTheDocument()
})
})
})
+4
View File
@@ -1,3 +1,7 @@
export const ASSISTANT_REPO_ID = 0
export const ASSISTANT_REPO_NAME = 'Assistant'
export const ASSISTANT_REPO_PATH = 'assistant'
function trimTrailingChar(value: string, char: string): string {
let end = value.length
while (end > 0 && value[end - 1] === char) end--