section 1: Phase 1: One owner for reading a session's latest assistant

This commit is contained in:
Chris Scott committed 2026-10-03 09:01:38 -04:00
1 parent 52b6147ed3
commit a3aaba8515
3 files changed
+148 -33

No files matched your search

+8 -33
View File
@@ -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<SessionMessageInfo[]> {
private async readAssistantReply(sessionId: string): Promise<AssistantReplyState | null> {
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<boolean> {
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)
}
+38
View File
@@ -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<AssistantReplyState | null> {
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<boolean> {
const active = await client.api.session.active()
return sessionId in active
}
+102
View File
@@ -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<string, unknown> = {}): 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)
})
})