mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Merge pull request #370 from chriswritescode-dev/fix/schedule-report-links
fix(schedules): open report links in place and route schedule notifications to the run report
This commit is contained in:
18 files changed
+280
-86
No files matched your search
@@ -460,6 +460,12 @@ export function getScheduleRunById(db: Database, repoId: number, jobId: number,
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function getScheduleRunBySessionId(db: Database, sessionId: string): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1')
|
||||
const row = stmt.get(sessionId) as ScheduleRunRow | undefined
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number, jobId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare(`
|
||||
SELECT * FROM schedule_runs
|
||||
|
||||
@@ -40,7 +40,7 @@ export function createInternalNotificationRoutes(notificationService: Notificati
|
||||
timestamp: Date.now(),
|
||||
data: {
|
||||
eventType: 'assistant.message',
|
||||
url: parsed.data.url ?? '/',
|
||||
url: notificationService.getScheduleRunReportUrl(parsed.data.sessionId) ?? parsed.data.url ?? '/',
|
||||
priority: parsed.data.priority,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -569,6 +569,7 @@ Sending is rate limited to **10 notifications per minute**. Beyond that the tool
|
||||
- Notifications are only sent if the user has registered devices (browser push subscriptions)
|
||||
- If VAPID is not configured on the server, the tool fails with a \`503\` status
|
||||
- Use \`priority: 'high'\` for urgent notifications that should interrupt the user
|
||||
- In a scheduled run, the notification always opens that run's report, so \`url\` is not needed
|
||||
- Do not call the internal HTTP API with \`curl\` for notifications; the tool is the supported path
|
||||
`
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
getRepoName,
|
||||
listRepos,
|
||||
} from "../db/queries";
|
||||
import { getScheduleRunBySessionId } from "../db/schedules";
|
||||
import type { Repo } from "../types/repo";
|
||||
import { getReposPath } from "@opencode-manager/shared/config/env";
|
||||
import { ASSISTANT_REPO_ID } from "@opencode-manager/shared/utils";
|
||||
@@ -71,6 +72,11 @@ const EVENT_CONFIG: Record<
|
||||
|
||||
const MAX_BODY_LENGTH = 140;
|
||||
|
||||
const RUN_OUTCOME_EVENTS = new Set<string>([
|
||||
NotificationEventType.SESSION_IDLE,
|
||||
NotificationEventType.SESSION_FAILED,
|
||||
]);
|
||||
|
||||
function resolveEventSessionId(event: SSEEvent): string | undefined {
|
||||
if (event.type === NotificationEventType.FORM_CREATED) {
|
||||
return event.data.form.sessionID;
|
||||
@@ -78,6 +84,10 @@ function resolveEventSessionId(event: SSEEvent): string | undefined {
|
||||
return sessionIDFromEvent(event);
|
||||
}
|
||||
|
||||
export function buildScheduleRunReportUrl(runId: number): string {
|
||||
return `/schedules?scheduleTab=runs&runId=${runId}`;
|
||||
}
|
||||
|
||||
export function buildNotificationUrl(
|
||||
repo: Pick<Repo, "id"> | null,
|
||||
sessionId: string | undefined
|
||||
@@ -272,6 +282,13 @@ export class NotificationService {
|
||||
return rows.map((r) => r.user_id);
|
||||
}
|
||||
|
||||
/** Returns the run report URL when the session was started by a scheduled run. */
|
||||
getScheduleRunReportUrl(sessionId: string | undefined): string | null {
|
||||
if (!sessionId) return null;
|
||||
const run = getScheduleRunBySessionId(this.db, sessionId);
|
||||
return run ? buildScheduleRunReportUrl(run.id) : null;
|
||||
}
|
||||
|
||||
private async resolveRepoForDirectory(directory: string): Promise<Repo | null> {
|
||||
const repo =
|
||||
getRepoBySourcePath(this.db, path.resolve(directory)) ??
|
||||
@@ -312,7 +329,8 @@ export class NotificationService {
|
||||
const repo = directory ? await this.resolveRepoForDirectory(directory) : null;
|
||||
const repoId = repo?.id;
|
||||
const repoName = repo ? getRepoName(repo) : undefined;
|
||||
const url = buildNotificationUrl(repo, sessionId);
|
||||
const reportUrl = RUN_OUTCOME_EVENTS.has(event.type) ? this.getScheduleRunReportUrl(sessionId) : null;
|
||||
const url = reportUrl ?? buildNotificationUrl(repo, sessionId);
|
||||
|
||||
const payload = buildEventNotificationPayload(event, {
|
||||
repoName,
|
||||
|
||||
@@ -198,8 +198,9 @@ async function postInternalApi(routePath, body, signal) {
|
||||
|
||||
var ACTIONS = {
|
||||
send_notification: {
|
||||
run: async function (params, signal) {
|
||||
var result = await postInternalApi('/notifications/send', params, signal)
|
||||
run: async function (params, context) {
|
||||
var body = Object.assign({}, params, { sessionId: context.sessionID })
|
||||
var result = await postInternalApi('/notifications/send', body, context.signal)
|
||||
if (result.noSubscriptions === true) {
|
||||
return 'No devices are registered for push notifications, so nothing was delivered.'
|
||||
}
|
||||
@@ -207,9 +208,9 @@ var ACTIONS = {
|
||||
},
|
||||
},
|
||||
request: {
|
||||
run: async function (params, signal) {
|
||||
run: async function (params, context) {
|
||||
assertAllowedRoute(params.method, params.path)
|
||||
var text = await requestInternalApi(params.method, params.path, params.body, signal)
|
||||
var text = await requestInternalApi(params.method, params.path, params.body, context.signal)
|
||||
return text || 'The request succeeded with an empty response body.'
|
||||
},
|
||||
},
|
||||
@@ -229,14 +230,14 @@ function assertParams(actionName, params) {
|
||||
}
|
||||
}
|
||||
|
||||
async function runAction(input, signal) {
|
||||
async function runAction(input, context) {
|
||||
var actionName = input !== null && typeof input === 'object' ? input.action : undefined
|
||||
if (!Object.prototype.hasOwnProperty.call(ACTIONS, actionName)) {
|
||||
throw new Error('Unknown OpenCode Manager action: ' + String(actionName) + '. Supported actions: ' + ACTION_NAMES.join(', ') + '.')
|
||||
}
|
||||
var params = input.params
|
||||
assertParams(actionName, params)
|
||||
return await ACTIONS[actionName].run(params, signal)
|
||||
return await ACTIONS[actionName].run(params, context)
|
||||
}
|
||||
|
||||
export default {
|
||||
@@ -249,7 +250,7 @@ export default {
|
||||
input: INPUT_SCHEMA,
|
||||
options: { codemode: false },
|
||||
execute: async function (input, context) {
|
||||
return { content: await runAction(input, context.signal) }
|
||||
return { content: await runAction(input, context) }
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createOpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/schedules'
|
||||
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
|
||||
|
||||
describe('internal/notifications routes', () => {
|
||||
@@ -142,6 +143,42 @@ describe('internal/notifications routes', () => {
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
describe('notification url', () => {
|
||||
const send = (payload: Record<string, unknown>) =>
|
||||
app.request('/api/internal/notifications/send', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ title: 'Test', body: 'Body', ...payload }),
|
||||
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
|
||||
})
|
||||
|
||||
const sentUrl = (sendToUser: ReturnType<typeof vi.spyOn>) =>
|
||||
(sendToUser.mock.calls[0]?.[1] as { data: { url: string } }).data.url
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(notificationService, 'isConfigured').mockReturnValue(true)
|
||||
})
|
||||
|
||||
it('links a scheduled run session to its run report, even when the agent passes a url', async () => {
|
||||
db.exec('PRAGMA foreign_keys = OFF')
|
||||
const run = createScheduleRun(db, { jobId: 7, repoId: 0, triggerSource: 'schedule', status: 'running', startedAt: 1, createdAt: 1 })
|
||||
updateScheduleRunMetadata(db, 0, 7, run.id, { sessionId: 'ses_scheduled' })
|
||||
const sendToUser = vi.spyOn(notificationService, 'sendToUser').mockResolvedValue({ delivered: 1, expired: 0, failed: 0, total: 1 })
|
||||
|
||||
const res = await send({ sessionId: 'ses_scheduled', url: '/repos/my-repo' })
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(sentUrl(sendToUser)).toBe(`/schedules?scheduleTab=runs&runId=${run.id}`)
|
||||
})
|
||||
|
||||
it('keeps the agent url for sessions that are not scheduled runs', async () => {
|
||||
const sendToUser = vi.spyOn(notificationService, 'sendToUser').mockResolvedValue({ delivered: 1, expired: 0, failed: 0, total: 1 })
|
||||
|
||||
await send({ sessionId: 'ses_manual', url: '/repos/3' })
|
||||
|
||||
expect(sentUrl(sendToUser)).toBe('/repos/3')
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /api/internal/notifications/send returns 429 after 10 calls within rate window', async () => {
|
||||
vi.spyOn(notificationService, 'isConfigured').mockReturnValue(true)
|
||||
vi.spyOn(notificationService, 'sendToUser').mockResolvedValue({ delivered: 0, expired: 0, failed: 0, total: 0 })
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { createRepo } from '../../src/db/queries'
|
||||
import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/schedules'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { sseAggregator, type SSEEvent } from '../../src/services/sse-aggregator'
|
||||
@@ -45,8 +46,7 @@ function permissionAskedEvent(sessionID: string): SSEEvent {
|
||||
}
|
||||
}
|
||||
|
||||
function createService(): NotificationService {
|
||||
const db = new Database(':memory:')
|
||||
function createService(db = new Database(':memory:')): NotificationService {
|
||||
migrate(db, allMigrations)
|
||||
createRepo(db, {
|
||||
localPath: 'repo-one',
|
||||
@@ -128,6 +128,27 @@ describe('NotificationService.handleSSEEvent session routing', () => {
|
||||
expect(payload.data?.url).toBe('/repos/1/sessions/ses_perm')
|
||||
})
|
||||
|
||||
it('opens the run report for a scheduled session that finishes, but the session for its permission prompts', async () => {
|
||||
const db = new Database(':memory:')
|
||||
const service = createService(db)
|
||||
db.exec('PRAGMA foreign_keys = OFF')
|
||||
const run = createScheduleRun(db, { jobId: 5, repoId: 1, triggerSource: 'schedule', status: 'running', startedAt: 1, createdAt: 1 })
|
||||
updateScheduleRunMetadata(db, 1, 5, run.id, { sessionId: 'ses_sched' })
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, {
|
||||
id: 'evt_idle_1',
|
||||
created: 1700000000000,
|
||||
type: 'session.idle',
|
||||
location: { directory: DIRECTORY },
|
||||
data: { sessionID: 'ses_sched' },
|
||||
} as SSEEvent)
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_sched'))
|
||||
|
||||
const urls = send.mock.calls.map((call) => (call[1] as PushNotificationPayload).data?.url)
|
||||
expect(urls).toEqual([`/schedules?scheduleTab=runs&runId=${run.id}`, '/repos/1/sessions/ses_sched'])
|
||||
})
|
||||
|
||||
it('suppresses a permission for a session the user is viewing', async () => {
|
||||
const service = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
@@ -506,7 +506,12 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
|
||||
expect(apiRequests).toHaveLength(1)
|
||||
const request = JSON.parse(apiRequests[0] as string) as { auth: string; body: string }
|
||||
expect(request.auth).toBe('Bearer test-token')
|
||||
expect(JSON.parse(request.body)).toEqual({ title: 'Storm watch', body: 'Formation odds crossed 40%', priority: 'high' })
|
||||
expect(JSON.parse(request.body)).toEqual({
|
||||
title: 'Storm watch',
|
||||
body: 'Formation odds crossed 40%',
|
||||
priority: 'high',
|
||||
sessionId: expect.stringMatching(/^ses_/),
|
||||
})
|
||||
expect(toolResults.some((output) => output.includes('Notification sent: 1 delivered, 0 failed.'))).toBe(true)
|
||||
} finally {
|
||||
api.server.close()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState, memo, useCallback, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { FileBrowser, type FileBrowserHandle } from './FileBrowser'
|
||||
import { getRepoRelativeDisplayPath } from './display-path'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -116,7 +117,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
|
||||
|
||||
if (!isOpen && !shouldRender) return null
|
||||
|
||||
return (
|
||||
return createPortal(
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="fixed inset-0 z-50"
|
||||
@@ -200,6 +201,7 @@ export const FileBrowserSheet = memo(function FileBrowserSheet({ isOpen, onClose
|
||||
itemName={downloadDialog?.type === 'directory' ? currentPath.split('/').pop() || 'Directory' : repoName || 'Repository'}
|
||||
targetPath={downloadDialog?.type === 'directory' ? currentPath : basePath}
|
||||
/>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
})
|
||||
@@ -1,7 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
|
||||
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
|
||||
import { getRepo } from '@/api/repos'
|
||||
import { getWorkspaceFilePath } from '@/lib/markdownLinks'
|
||||
import { getSessionPath } from '@/lib/navigation'
|
||||
import { getRepoDisplayName } from '@/lib/utils'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import type { ScheduleRun } from '@opencode-manager/shared/types'
|
||||
|
||||
@@ -15,6 +22,21 @@ interface RunDetailPanelProps {
|
||||
|
||||
export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) {
|
||||
const navigate = useNavigate()
|
||||
const [selectedFilePath, setSelectedFilePath] = useState<string | null>(null)
|
||||
const { data: repo } = useQuery({
|
||||
queryKey: ['repo', repoId],
|
||||
queryFn: () => getRepo(repoId),
|
||||
})
|
||||
|
||||
const handleOpenLocalPath = repo
|
||||
? (linkPath: string) => {
|
||||
setSelectedFilePath(getWorkspaceFilePath(linkPath, {
|
||||
directory: activeRun?.worktreePath ?? repo.fullPath,
|
||||
repoFullPath: repo.fullPath,
|
||||
repoLocalPath: repo.localPath,
|
||||
}))
|
||||
}
|
||||
: undefined
|
||||
|
||||
if (selectedRunLoading && !activeRun) {
|
||||
return (
|
||||
@@ -28,55 +50,67 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
|
||||
return <div className="flex h-full items-center justify-center text-sm text-muted-foreground">Select a run to inspect logs and output.</div>
|
||||
}
|
||||
|
||||
const { sessionId } = activeRun
|
||||
|
||||
return (
|
||||
<Tabs key={`${activeRun.id}-${String(activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log')}`} defaultValue={activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log'} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-center gap-2 px-2 py-1.5">
|
||||
<TabsList className="h-auto gap-0 rounded-none border-0 bg-transparent p-0">
|
||||
<TabsTrigger value="log" className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Log</TabsTrigger>
|
||||
<TabsTrigger value="response" disabled={!activeRun.responseText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Assistant Output</TabsTrigger>
|
||||
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
{(activeRun.status === 'running' || activeRun.sessionId || activeRun.responseText) && (
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{activeRun.sessionId && (
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(`/repos/${repoId}/sessions/${activeRun.sessionId}`)}>
|
||||
Open session
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending || activeRun.status !== 'running'}>
|
||||
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
Cancel run
|
||||
</Button>
|
||||
<>
|
||||
<Tabs key={`${activeRun.id}-${String(activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log')}`} defaultValue={activeRun.responseText ? 'response' : activeRun.errorText ? 'error' : 'log'} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div className="flex items-center justify-center gap-2 px-2 py-1.5">
|
||||
<TabsList className="h-auto gap-0 rounded-none border-0 bg-transparent p-0">
|
||||
<TabsTrigger value="log" className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Log</TabsTrigger>
|
||||
<TabsTrigger value="response" disabled={!activeRun.responseText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">Assistant Output</TabsTrigger>
|
||||
<TabsTrigger value="error" disabled={!activeRun.errorText} className="rounded-none border-b-2 border-transparent px-3 py-1.5 text-xs data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none">{activeRun.status === 'cancelled' ? 'Details' : 'Error'}</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
)}
|
||||
<TabsContent value="log" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : (
|
||||
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">{activeRun.logText ?? 'No log text captured.'}</pre>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="response" className="mt-0 min-h-0 flex-1 flex flex-col overflow-hidden">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : activeRun.responseText ? (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-0 py-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<ScheduleRunMarkdown content={activeRun.responseText} />
|
||||
{(activeRun.status === 'running' || activeRun.sessionId || activeRun.responseText) && (
|
||||
<div className="flex items-center justify-between gap-2 px-3 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{sessionId && (
|
||||
<Button variant="outline" size="sm" onClick={() => navigate(getSessionPath(repoId, sessionId))}>
|
||||
Open session
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={onCancelRun} disabled={cancelRunPending || activeRun.status !== 'running'}>
|
||||
{cancelRunPending ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
Cancel run
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-3"><pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">No assistant output captured.</pre></div>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="error" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : (
|
||||
<pre className={`whitespace-pre-wrap break-words text-sm font-mono leading-6 ${activeRun.status === 'cancelled' ? 'text-muted-foreground' : 'text-destructive'}`}>{activeRun.errorText ?? 'No error recorded.'}</pre>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<TabsContent value="log" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : (
|
||||
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">{activeRun.logText ?? 'No log text captured.'}</pre>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="response" className="mt-0 min-h-0 flex-1 flex flex-col overflow-hidden">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : activeRun.responseText ? (
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-0 py-2 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<ScheduleRunMarkdown content={activeRun.responseText} onOpenLocalPath={handleOpenLocalPath} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-3"><pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6">No assistant output captured.</pre></div>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="error" className="mt-0 min-h-0 flex-1 overflow-y-auto px-0 py-3 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{selectedRunLoading && !activeRun ? (
|
||||
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
|
||||
) : (
|
||||
<pre className={`whitespace-pre-wrap break-words text-sm font-mono leading-6 ${activeRun.status === 'cancelled' ? 'text-muted-foreground' : 'text-destructive'}`}>{activeRun.errorText ?? 'No error recorded.'}</pre>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<FileBrowserSheet
|
||||
isOpen={selectedFilePath !== null}
|
||||
onClose={() => setSelectedFilePath(null)}
|
||||
basePath={repo?.localPath}
|
||||
repoName={repo ? getRepoDisplayName(repo) : undefined}
|
||||
repoId={repoId}
|
||||
initialSelectedFile={selectedFilePath ?? undefined}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useRepoScheduleRun } from '@/hooks/useSchedules'
|
||||
interface RunHistoryCardsProps {
|
||||
runs: ScheduleRun[] | undefined
|
||||
runsLoading: boolean
|
||||
selectedRunId?: number | null
|
||||
onSelectRun: (id: number) => void
|
||||
onCancelRun: () => void
|
||||
cancelRunPending: boolean
|
||||
@@ -19,20 +20,25 @@ interface RunHistoryCardsProps {
|
||||
export function RunHistoryCards({
|
||||
runs,
|
||||
runsLoading,
|
||||
selectedRunId = null,
|
||||
onSelectRun,
|
||||
onCancelRun,
|
||||
cancelRunPending,
|
||||
onDeleteRun,
|
||||
deleteRunPending,
|
||||
}: RunHistoryCardsProps) {
|
||||
const [expandedRunId, setExpandedRunId] = useState<number | null>(null)
|
||||
const [expandedRunRepoId, setExpandedRunRepoId] = useState<number | null>(null)
|
||||
const [expandedRunJobId, setExpandedRunJobId] = useState<number | null>(null)
|
||||
const [expandedRunId, setExpandedRunId] = useState<number | null>(selectedRunId)
|
||||
const [syncedSelectedRunId, setSyncedSelectedRunId] = useState<number | null>(selectedRunId)
|
||||
if (selectedRunId !== syncedSelectedRunId) {
|
||||
setSyncedSelectedRunId(selectedRunId)
|
||||
setExpandedRunId(selectedRunId)
|
||||
}
|
||||
const expandedRun = runs?.find((run) => run.id === expandedRunId)
|
||||
|
||||
const { data: runDetail, isLoading } = useRepoScheduleRun(
|
||||
expandedRunRepoId ?? undefined,
|
||||
expandedRunJobId,
|
||||
expandedRunId
|
||||
expandedRun?.repoId,
|
||||
expandedRun?.jobId ?? null,
|
||||
expandedRun?.id ?? null
|
||||
)
|
||||
|
||||
function getRunStatusIcon(status: ScheduleRun['status']) {
|
||||
@@ -42,15 +48,11 @@ export function RunHistoryCards({
|
||||
return <Ban className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
}
|
||||
|
||||
function handleCardClick(runId: number, repoId: number, jobId: number) {
|
||||
function handleCardClick(runId: number) {
|
||||
if (expandedRunId === runId) {
|
||||
setExpandedRunId(null)
|
||||
setExpandedRunRepoId(null)
|
||||
setExpandedRunJobId(null)
|
||||
} else {
|
||||
setExpandedRunId(runId)
|
||||
setExpandedRunRepoId(repoId)
|
||||
setExpandedRunJobId(jobId)
|
||||
onSelectRun(runId)
|
||||
}
|
||||
}
|
||||
@@ -92,7 +94,7 @@ export function RunHistoryCards({
|
||||
<div className="flex items-stretch">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCardClick(run.id, run.repoId, run.jobId)}
|
||||
onClick={() => handleCardClick(run.id)}
|
||||
className="min-w-0 flex-1 px-3 py-2 text-left flex items-center justify-between gap-2"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { ScheduleRunMarkdown } from './ScheduleRunMarkdown'
|
||||
|
||||
describe('ScheduleRunMarkdown links', () => {
|
||||
it('opens local file links through the callback instead of navigating', () => {
|
||||
const onOpenLocalPath = vi.fn()
|
||||
render(<ScheduleRunMarkdown content="[Report](recaps/daily.html)" onOpenLocalPath={onOpenLocalPath} />)
|
||||
|
||||
const link = screen.getByRole('link', { name: 'Report' })
|
||||
const event = new MouseEvent('click', { bubbles: true, cancelable: true })
|
||||
fireEvent(link, event)
|
||||
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
expect(onOpenLocalPath).toHaveBeenCalledWith('recaps/daily.html')
|
||||
})
|
||||
|
||||
it('opens external links in a new tab', () => {
|
||||
render(<ScheduleRunMarkdown content="[Docs](https://example.com)" onOpenLocalPath={vi.fn()} />)
|
||||
|
||||
const link = screen.getByRole('link', { name: 'Docs' })
|
||||
expect(link.getAttribute('target')).toBe('_blank')
|
||||
expect(link.getAttribute('rel')).toBe('noopener noreferrer')
|
||||
})
|
||||
})
|
||||
@@ -1,21 +1,30 @@
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import ReactMarkdown, { type Components } from 'react-markdown'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { markdownComponents } from '@/components/file-browser/MarkdownComponents'
|
||||
import { MarkdownLink } from '@/components/ui/markdown-link'
|
||||
|
||||
type ScheduleRunMarkdownProps = {
|
||||
content: string
|
||||
onOpenLocalPath?: (linkPath: string) => void
|
||||
}
|
||||
|
||||
export function ScheduleRunMarkdown({ content }: ScheduleRunMarkdownProps) {
|
||||
export function ScheduleRunMarkdown({ content, onOpenLocalPath }: ScheduleRunMarkdownProps) {
|
||||
const components: Components = {
|
||||
...markdownComponents,
|
||||
a(props) {
|
||||
return <MarkdownLink {...props} onOpenLocalPath={onOpenLocalPath} />
|
||||
},
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden">
|
||||
<div className="prose prose-invert prose-enhanced max-w-none break-words text-foreground leading-snug">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight, rehypeRaw]}
|
||||
components={markdownComponents}
|
||||
components={components}
|
||||
>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getLocalLinkPath, resolvePathFromFile, isExternalLink } from './markdownLinks'
|
||||
import { getLocalLinkPath, getWorkspaceFilePath, resolvePathFromFile, isExternalLink } from './markdownLinks'
|
||||
|
||||
const FROM = 'opencode-manager/ocm-link-test/index.md'
|
||||
|
||||
@@ -44,6 +44,22 @@ describe('resolvePathFromFile', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getWorkspaceFilePath', () => {
|
||||
const workspace = { directory: '/workspace/repos/assistant', repoFullPath: '/workspace/repos/assistant', repoLocalPath: 'assistant' }
|
||||
|
||||
it('maps relative and repo-absolute paths to repo-local workspace paths', () => {
|
||||
expect(getWorkspaceFilePath('recaps/daily.html', workspace)).toBe('assistant/recaps/daily.html')
|
||||
expect(getWorkspaceFilePath('./recaps/daily.html', workspace)).toBe('assistant/recaps/daily.html')
|
||||
expect(getWorkspaceFilePath('/workspace/repos/assistant/recaps/daily.html', workspace)).toBe('assistant/recaps/daily.html')
|
||||
})
|
||||
|
||||
it('resolves against a separate working directory and leaves outside paths absolute', () => {
|
||||
const worktree = { ...workspace, directory: '/workspace/worktrees/job-1-run-2' }
|
||||
expect(getWorkspaceFilePath('out.md', worktree)).toBe('/workspace/worktrees/job-1-run-2/out.md')
|
||||
expect(getWorkspaceFilePath('/etc/hosts', workspace)).toBe('/etc/hosts')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isExternalLink', () => {
|
||||
it('detects http and https links only', () => {
|
||||
expect(isExternalLink('https://example.com')).toBe(true)
|
||||
|
||||
@@ -39,6 +39,23 @@ export function resolvePathFromFile(fromFilePath: string, linkPath: string): str
|
||||
return segments.join('/') || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a file path referenced from a working directory to the path the file browser opens.
|
||||
* Relative paths resolve against the directory, and paths inside the repo root become repo-local workspace paths.
|
||||
*/
|
||||
export function getWorkspaceFilePath(
|
||||
filePath: string,
|
||||
workspace: { directory?: string; repoFullPath?: string; repoLocalPath?: string },
|
||||
): string {
|
||||
const { directory, repoFullPath, repoLocalPath } = workspace
|
||||
const absolutePath = filePath.startsWith('/') || !directory
|
||||
? filePath
|
||||
: `${directory}/${filePath.replace(/^\.\//, '')}`
|
||||
return repoFullPath && repoLocalPath && absolutePath.startsWith(`${repoFullPath}/`)
|
||||
? `${repoLocalPath}/${absolutePath.slice(repoFullPath.length + 1)}`
|
||||
: absolutePath
|
||||
}
|
||||
|
||||
/** Returns whether a link targets an external http(s) page. */
|
||||
export function isExternalLink(href: string | undefined): boolean {
|
||||
return !!href && /^https?:\/\//i.test(href)
|
||||
|
||||
@@ -816,13 +816,13 @@ export function GlobalSchedules() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto py-4 pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-4 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
{runsLoading && allRuns.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : allRuns.length === 0 ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="flex items-center justify-center px-4 py-12">
|
||||
<Card className="max-w-md border-dashed border-border/70">
|
||||
<CardContent className="flex flex-col items-center gap-4 p-8 text-center">
|
||||
<div className="rounded-full border border-border bg-muted/40 p-4">
|
||||
@@ -856,6 +856,7 @@ export function GlobalSchedules() {
|
||||
<RunHistoryCards
|
||||
runs={sortedRuns}
|
||||
runsLoading={runsLoading}
|
||||
selectedRunId={runId}
|
||||
onSelectRun={selectRun}
|
||||
onCancelRun={() => {
|
||||
if (runId) {
|
||||
|
||||
@@ -34,6 +34,7 @@ import { MessageSkeleton } from "@/components/message/MessageSkeleton";
|
||||
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
|
||||
import { getMessagesContentVersion } from "./sessionContentVersion";
|
||||
import { showToast } from "@/lib/toast";
|
||||
import { getWorkspaceFilePath } from "@/lib/markdownLinks";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
||||
@@ -400,14 +401,11 @@ export function SessionDetail() {
|
||||
|
||||
|
||||
const handleFileClick = useCallback((filePath: string) => {
|
||||
const absolutePath = filePath.startsWith('/') || !sessionDirectory
|
||||
? filePath
|
||||
: `${sessionDirectory}/${filePath.replace(/^\.\//, '')}`
|
||||
const repoRoot = repo?.fullPath
|
||||
const pathToOpen = repoRoot && repo?.localPath && absolutePath.startsWith(`${repoRoot}/`)
|
||||
? `${repo.localPath}/${absolutePath.slice(repoRoot.length + 1)}`
|
||||
: absolutePath
|
||||
setSelectedFilePath(pathToOpen)
|
||||
setSelectedFilePath(getWorkspaceFilePath(filePath, {
|
||||
directory: sessionDirectory,
|
||||
repoFullPath: repo?.fullPath,
|
||||
repoLocalPath: repo?.localPath,
|
||||
}))
|
||||
setFileBrowserOpen(true)
|
||||
}, [repo?.fullPath, repo?.localPath, sessionDirectory, setFileBrowserOpen]);
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ export const AssistantNotificationRequestSchema = z.object({
|
||||
url: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.URL_MAX).optional(),
|
||||
tag: z.string().max(ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX).optional(),
|
||||
priority: AssistantNotificationPrioritySchema.default('normal'),
|
||||
sessionId: z.string().min(1).optional(),
|
||||
})
|
||||
|
||||
export const AssistantNotificationResponseSchema = z.object({
|
||||
|
||||
Reference in new issue
Block a user