diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index e97294ff..06db18c0 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -7,7 +7,7 @@ import { type ScheduleRunTriggerSource, type UpdateScheduleJobRequest, } from '@opencode-manager/shared/types' -import { assistantText, mcpStatusByName, openCodeLocation, sessionIDFromEvent, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode' +import { mcpStatusByName, openCodeLocation, sessionIDFromEvent } from '@opencode-manager/shared/opencode' import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas' import { getRepoById } from '../db/queries' import type { ScheduleJobWithRepo } from '../db/schedules' @@ -46,6 +46,7 @@ import { computeNextRunAtForJob, } from './schedule-config' import { resolveOpenCodeModel } from './opencode-models' +import { isSessionBusy, readLatestAssistantReply, type AssistantReplyState } from './session-reply' import type { OpenCodeClient } from './opencode/client' import type { ScheduleWorktreeManager } from './schedule-worktree' import type { Repo } from '../types/repo' @@ -165,26 +166,6 @@ function buildRunStartedLog(input: { ].join('\n') } -function getAssistantMessageState(messages: SessionMessageInfo[]): { - responseText: string | null - errorText: string | null - completed: boolean -} | null { - const assistantMessage = messages.find( - (message): message is SessionMessageAssistant => message.type === 'assistant', - ) - - if (!assistantMessage) { - return null - } - - return { - responseText: assistantText(assistantMessage.content, { stripThink: true }) || null, - errorText: assistantMessage.error?.message ?? null, - completed: Boolean(assistantMessage.time.completed), - } -} - function getSessionErrorText(event: SSEEvent): string | null { if (event.type !== 'session.execution.failed') { return null @@ -1184,7 +1165,7 @@ export class ScheduleService { return { kind: 'busy' } } - const assistantState = getAssistantMessageState(await this.listSessionMessages(sessionId)) + const assistantState = await this.readAssistantReply(sessionId) if (assistantState?.completed || assistantState?.errorText) { return { kind: 'settled', responseText: assistantState.responseText, errorText: assistantState.errorText } } @@ -1209,9 +1190,9 @@ export class ScheduleService { const signal = await sessionMonitor.nextSignal() if (signal.errorText || signal.disposed) { - const messages = await this.listSessionMessages(sessionId) + const assistantState = await this.readAssistantReply(sessionId) return { - responseText: getAssistantMessageState(messages)?.responseText ?? null, + responseText: assistantState?.responseText ?? null, errorText: signal.errorText ?? SESSION_STOPPED_ERROR, } } @@ -1230,14 +1211,9 @@ export class ScheduleService { } } - private async listSessionMessages(sessionId: string): Promise { + private async readAssistantReply(sessionId: string): Promise { try { - const response = await this.openCodeClient.api.message.list({ - sessionID: sessionId, - order: 'desc', - limit: 20, - }) - return response.data + return await readLatestAssistantReply(this.openCodeClient, sessionId) } catch (error) { throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to fetch session messages', 502) } @@ -1245,8 +1221,7 @@ export class ScheduleService { private async isSessionActive(sessionId: string): Promise { try { - const active = await this.openCodeClient.api.session.active() - return sessionId in active + return await isSessionBusy(this.openCodeClient, sessionId) } catch (error) { throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to fetch active sessions', 502) } diff --git a/backend/src/services/session-reply.ts b/backend/src/services/session-reply.ts new file mode 100644 index 00000000..12d47aa6 --- /dev/null +++ b/backend/src/services/session-reply.ts @@ -0,0 +1,38 @@ +import { assistantText, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode' +import type { OpenCodeClient } from './opencode/client' + +export interface AssistantReplyState { + responseText: string | null + errorText: string | null + completed: boolean +} + +export function getLatestAssistantReplyState(messages: SessionMessageInfo[]): AssistantReplyState | null { + const assistantMessage = messages.find( + (message): message is SessionMessageAssistant => message.type === 'assistant', + ) + + if (!assistantMessage) { + return null + } + + return { + responseText: assistantText(assistantMessage.content, { stripThink: true }) || null, + errorText: assistantMessage.error?.message ?? null, + completed: Boolean(assistantMessage.time.completed), + } +} + +export async function readLatestAssistantReply(client: OpenCodeClient, sessionId: string): Promise { + const response = await client.api.message.list({ + sessionID: sessionId, + order: 'desc', + limit: 20, + }) + return getLatestAssistantReplyState(response.data) +} + +export async function isSessionBusy(client: OpenCodeClient, sessionId: string): Promise { + const active = await client.api.session.active() + return sessionId in active +} diff --git a/backend/test/services/session-reply.test.ts b/backend/test/services/session-reply.test.ts new file mode 100644 index 00000000..252b40dd --- /dev/null +++ b/backend/test/services/session-reply.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it, vi } from 'vitest' +import type { SessionMessageInfo } from '@opencode-manager/shared/opencode' +import type { OpenCodeClient } from '../../src/services/opencode/client' +import { + getLatestAssistantReplyState, + isSessionBusy, + readLatestAssistantReply, +} from '../../src/services/session-reply' +import { assistantMessage } from '../helpers/stub-schedule-api' + +function createFakeClient(messages: SessionMessageInfo[], active: Record = {}): OpenCodeClient { + return { + api: { + message: { + list: vi.fn(async () => ({ data: messages, cursor: {} })), + }, + session: { + active: vi.fn(async () => active), + }, + }, + forwardRaw: vi.fn(), + } as unknown as OpenCodeClient +} + +describe('getLatestAssistantReplyState', () => { + it('returns the newest assistant text with think blocks stripped', () => { + const state = getLatestAssistantReplyState([ + assistantMessage('', { + completed: true, + content: [ + { type: 'text', text: '\u003cthink\u003eprivate reasoning\u003c/think\u003e\nFinal answer' }, + { type: 'text', text: 'Second paragraph.' }, + ], + }), + ]) + + expect(state).toEqual({ + responseText: 'Final answer\n\nSecond paragraph.', + errorText: null, + completed: true, + }) + }) + + it('surfaces the assistant error message', () => { + const state = getLatestAssistantReplyState([ + assistantMessage('', { error: 'Provider exploded' }), + ]) + + expect(state).toEqual({ + responseText: null, + errorText: 'Provider exploded', + completed: false, + }) + }) + + it('reports an incomplete assistant message as not completed', () => { + const state = getLatestAssistantReplyState([assistantMessage('Partial output')]) + + expect(state).toEqual({ + responseText: 'Partial output', + errorText: null, + completed: false, + }) + }) + + it('returns null when no assistant message is present', () => { + expect(getLatestAssistantReplyState([])).toBeNull() + }) +}) + +describe('readLatestAssistantReply', () => { + it('reads the newest assistant reply through the client', async () => { + const client = createFakeClient([assistantMessage('From the client.', { completed: true })]) + + await expect(readLatestAssistantReply(client, 'ses-1')).resolves.toEqual({ + responseText: 'From the client.', + errorText: null, + completed: true, + }) + expect(client.api.message.list).toHaveBeenCalledWith({ + sessionID: 'ses-1', + order: 'desc', + limit: 20, + }) + }) + + it('returns null when the session has no assistant message', async () => { + await expect(readLatestAssistantReply(createFakeClient([]), 'ses-1')).resolves.toBeNull() + }) +}) + +describe('isSessionBusy', () => { + it('is true when the session appears in the active set', async () => { + const client = createFakeClient([], { 'ses-1': { type: 'running' } }) + + await expect(isSessionBusy(client, 'ses-1')).resolves.toBe(true) + }) + + it('is false when the session is absent from the active set', async () => { + await expect(isSessionBusy(createFakeClient([], {}), 'ses-1')).resolves.toBe(false) + }) +})