diff --git a/.github/workflows/go-ci.yml b/.github/workflows/go-ci.yml index eef37b5e72..d19657ac29 100644 --- a/.github/workflows/go-ci.yml +++ b/.github/workflows/go-ci.yml @@ -209,7 +209,7 @@ jobs: TEST_POSTGRES_BOOTSTRAP_SCHEMA=0 go test -v -race -count=1 -timeout 90s \ ./internal/agent/runtime/session/ledger TEST_POSTGRES_BOOTSTRAP_SCHEMA=0 go test -v -race -count=1 -timeout 90s \ - -run '^TestPostgres(ResumeScopes|WSStepHistory|ProviderUsage|RedisDecision|NativeDecisionAcceptance|HistoryReset|RedisHistoryReset)' ./internal/agent/application + -run '^TestPostgres(ResumeScopes|ShutdownResume|WSStepHistory|ProviderUsage|RedisDecision|NativeDecisionAcceptance|HistoryReset|RedisHistoryReset)' ./internal/agent/application TEST_POSTGRES_BOOTSTRAP_SCHEMA=0 go test -v -race -count=1 -timeout 90s \ -run '^TestPostgresBotCreate' ./internal/bots TEST_POSTGRES_BOOTSTRAP_SCHEMA=0 go test -v -race -count=1 -timeout 90s \ diff --git a/apps/web/src/composables/api/useChat.types.ts b/apps/web/src/composables/api/useChat.types.ts index 6c9f132105..2dafa04c93 100644 --- a/apps/web/src/composables/api/useChat.types.ts +++ b/apps/web/src/composables/api/useChat.types.ts @@ -465,6 +465,9 @@ export interface RuntimeRunOperation { } export interface RuntimeCurrentRunView { + // A shutdown continuation answers this historical turn; run/turn_id still + // identify its execution and remain the target of runtime commands. + resume_turn?: UIAssistantTurn configuration_only?: boolean run_id: string turn_id: string diff --git a/apps/web/src/store/chat/runtime-projection.ts b/apps/web/src/store/chat/runtime-projection.ts index 4d668bce08..a95190d56e 100644 --- a/apps/web/src/store/chat/runtime-projection.ts +++ b/apps/web/src/store/chat/runtime-projection.ts @@ -83,7 +83,7 @@ export function runOwnsTurn( ): boolean { const target = turnId.trim() if (!run || !target) return false - if (run.turn_id.trim() === target) return true + if (run.turn_id.trim() === target || run.resume_turn?.turn_id.trim() === target) return true // userTurnsForRun owns the whole wire-shape chain — user_turns, the legacy // request_user_turn, and an edit's replacement turn. Re-deriving it here // duplicated two thirds of it and dropped the third, so a retry or edit whose @@ -174,7 +174,9 @@ function emptyTranscript(): RuntimeTranscriptSlice { function transcriptForRun(run: RuntimeCurrentRunView | null): RuntimeTranscriptSlice { if (!run || run.configuration_only) return emptyTranscript() - const turnId = run.turn_id.trim() + const turnId = run.resume_turn?.turn_id.trim() || run.turn_id.trim() + const turnPosition = run.resume_turn?.turn_position ?? run.turn_position + const prefix = run.resume_turn?.messages ?? [] const turns: UITurn[] = [] const userTurns = userTurnsForRun(run) // A run spans several turns once a steer opens one (SR-TURN-001), so a @@ -186,7 +188,7 @@ function transcriptForRun(run: RuntimeCurrentRunView | null): RuntimeTranscriptS if (!id) return undefined const owner = userTurns.find(turn => turn.turn_id.trim() === id) if (owner?.turn_position !== undefined) return owner.turn_position - if (id === turnId) return run.turn_position + if (id === turnId) return turnPosition // A claimed steer knows its slot before its row exists. return (run.steer_turns ?? []).find(steer => steer.turn_id?.trim() === id)?.turn_position } @@ -215,8 +217,14 @@ function transcriptForRun(run: RuntimeCurrentRunView | null): RuntimeTranscriptS // streamed blocks). // Runtime activity belongs to the current run, even when a steer splits its // transcript. Keep it out of the historical segments defined by message IDs. - const runtimeStatus = active ? run.messages.find(message => message.type === 'status') : undefined - const assistantMessages = run.messages.filter(message => message.type !== 'status') + // Keep the committed prefix separate on the wire so a provider retry only + // replaces this run's output. Offset live block IDs within the displayed turn. + const liveMessages = run.messages.map(message => ({ ...message, id: message.id + prefix.length })) + const runtimeStatus = active ? liveMessages.find(message => message.type === 'status') : undefined + const assistantMessages = [ + ...prefix.map((message, id) => ({ ...message, id })), + ...liveMessages.filter(message => message.type !== 'status'), + ] const projectsAssistantContent = active || assistantMessages.length > 0 || Boolean(run.error_code) @@ -224,7 +232,7 @@ function transcriptForRun(run: RuntimeCurrentRunView | null): RuntimeTranscriptS // The block is rendered from the code; the run carries no error text. if (run.error_code && !assistantMessages.some(message => message.type === 'error')) { assistantMessages.push({ - id: nextMessageId(run.messages), + id: nextMessageId([...assistantMessages, ...liveMessages]), type: 'error', code: run.error_code, content: '', @@ -232,11 +240,11 @@ function transcriptForRun(run: RuntimeCurrentRunView | null): RuntimeTranscriptS } let segmentStart = 0 let segmentTurnId = turnId - let segmentTimestamp = run.started_at + let segmentTimestamp = run.resume_turn?.timestamp || run.started_at for (const steer of steerTurns) { let segmentEnd = segmentStart while (segmentEnd < assistantMessages.length - && assistantMessages[segmentEnd]!.id <= steer.after_message_id) { + && assistantMessages[segmentEnd]!.id <= steer.after_message_id + prefix.length) { segmentEnd += 1 } const segment = assistantMessages.slice(segmentStart, segmentEnd) @@ -292,7 +300,7 @@ function transcriptForRun(run: RuntimeCurrentRunView | null): RuntimeTranscriptS return { runId: run.run_id, turnId, - turnPosition: run.turn_position, + turnPosition, invocationId: run.invocation_id?.trim() ?? '', continuation: false, steerTurnIds, diff --git a/apps/web/src/store/chat/transcript-race.test.ts b/apps/web/src/store/chat/transcript-race.test.ts index 83244e9aef..e4ea5aa873 100644 --- a/apps/web/src/store/chat/transcript-race.test.ts +++ b/apps/web/src/store/chat/transcript-race.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import { ref } from 'vue' -import type { UIMessage, UITurn } from '@/composables/api/useChat.types' +import type { RuntimeCurrentRunView, UIAssistantTurn, UIMessage, UITurn } from '@/composables/api/useChat.types' import { createBackgroundTaskTracker } from './background-tasks' import { createTranscriptController } from './transcript' -import type { RuntimeTranscriptSlice } from './runtime-projection' +import { projectRuntimeTranscript, type RuntimeTranscriptSlice } from './runtime-projection' vi.mock('@/store/user', () => ({ useUserStore: () => ({ userInfo: { id: 'user-1' } }), @@ -13,7 +13,7 @@ function rawUser(id: string, text = 'hello', timestamp = '2026-01-01T00:00:00.00 return { id, turn_id: `turn-${id}`, role: 'user', text, timestamp, platform: 'local' } } -function rawAssistant(id: string, messages: UIMessage[] = [], timestamp = '2026-01-01T00:00:01.000Z'): UITurn { +function rawAssistant(id: string, messages: UIMessage[] = [], timestamp = '2026-01-01T00:00:01.000Z'): UIAssistantTurn { return { id, turn_id: `turn-${id}`, role: 'assistant', messages, timestamp } } @@ -226,3 +226,28 @@ describe('chat transcript projection identity', () => { expect(transcript.messages.every(turn => turn.turnId === 'turn-1')).toBe(true) }) }) + +// A continuation has a new execution ID, but answers the original history turn. +it('merges resumed output and errors into the original turn without losing its prefix', () => { + for (const status of ['completed', 'errored'] as const) { + const { transcript } = makeTranscript() + const prefix: UIMessage[] = [{ id: 0, type: 'text', content: 'before restart' }] + const history = { ...rawAssistant('saved-answer', prefix), turn_id: 'original-turn', turn_position: 2 } + transcript.appendToView(...transcript.normalizeTurns([history])) + const run: RuntimeCurrentRunView = { + run_id: 'resumed-run', turn_id: 'new-admission-turn', turn_position: 3, + generation: 'new-owner', status: 'running', started_at: history.timestamp, updated_at: history.timestamp, + resume_turn: history, messages: [{ id: 0, type: 'text', content: 'continued' }], + } + transcript.applyRuntimeTranscript(projectRuntimeTranscript(run)) + transcript.applyRuntimeTranscript(projectRuntimeTranscript({ + ...run, status, ...(status === 'errored' ? { error_code: 'workspace.unreachable' } : {}), + })) + expect(transcript.messages).toHaveLength(1) + expect(transcript.messages[0]).toMatchObject({ turnId: 'original-turn', turnPosition: 2, messages: [ + { id: 0, type: 'text', content: 'before restart' }, + { id: 1, type: 'text', content: 'continued' }, + ...(status === 'errored' ? [{ id: 2, type: 'error', code: 'workspace.unreachable' }] : []), + ] }) + } +}) diff --git a/db/postgres/queries/messages.sql b/db/postgres/queries/messages.sql index 925109e471..72e6d858b0 100644 --- a/db/postgres/queries/messages.sql +++ b/db/postgres/queries/messages.sql @@ -1233,6 +1233,16 @@ WHERE request.team_id = public.memoh_current_team_id() ORDER BY request.turn_position DESC LIMIT 1; +-- name: RunWroteHistoryMessages :one +-- Distinguish an input never persisted from history whose request was removed. +SELECT EXISTS ( + SELECT 1 + FROM bot_history_messages m + WHERE m.team_id = public.memoh_current_team_id() + AND m.session_id = sqlc.arg(session_id) + AND (m.run_id = sqlc.arg(run_id) OR m.turn_id = sqlc.arg(root_turn_id)) +)::boolean; + -- name: ReplaceHistoryTurn :one WITH owner_session AS MATERIALIZED ( SELECT session.id diff --git a/docs/agent-runtime.md b/docs/agent-runtime.md index 5a95136903..b5ab07d348 100644 --- a/docs/agent-runtime.md +++ b/docs/agent-runtime.md @@ -625,8 +625,15 @@ Uncommitted streaming tokens can be lost. Background command handles from the ol process are not reattached; workspace output and external job receipts must be checked. Subagent sessions can continue, but old in-memory parent waiters are gone. SIGKILL, OOM, host failure and a shutdown unable to write PostgreSQL cannot reliably -record a marker and therefore retain the existing `lost` behavior. Once a resumed -run is admitted, ordinary failures are reported rather than automatically replayed. +record a marker and therefore retain the existing `lost` behavior. A continuation records its resolved request in its own intent. On another +restart it first checks its own applied inputs, then validates that saved +request, so image feedback and subsequent output remain in the same history turn. The runtime +view carries that turn and its committed prefix separately from the new run's +admission identity; Web extends the prefix rather than showing a second reply. +Once admitted, a continuation retries temporary workspace unavailability during +initial target/config preparation for up to 30 seconds per stage, within the +original context deadline. Model and tool execution are not replayed by this +startup retry. Other failures are reported normally. The server has a 30-second graceful shutdown budget. Compose allows 45 seconds, and the entrypoint waits for Server exit before terminating embedded containerd. diff --git a/internal/agent/application/history_reset_resume_postgres_test.go b/internal/agent/application/history_reset_resume_postgres_test.go index 4a63fc08d0..aedfea715f 100644 --- a/internal/agent/application/history_reset_resume_postgres_test.go +++ b/internal/agent/application/history_reset_resume_postgres_test.go @@ -10,6 +10,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" sessionruntime "github.com/felinics/memoh/internal/agent/runtime/session" + messagepkg "github.com/felinics/memoh/internal/chat/message" dbsqlc "github.com/felinics/memoh/internal/db/postgres/sqlc" postgresstore "github.com/felinics/memoh/internal/db/postgres/store" "github.com/felinics/memoh/internal/runtimefence" @@ -39,6 +40,14 @@ func (q resumeLedgerQueries) RetireInterruptedSessionRun(ctx context.Context, ru return q.db.RetireInterruptedSessionRun(ctx, runID) } +func (q resumeLedgerQueries) GetSessionRun(ctx context.Context, runID pgtype.UUID) (dbsqlc.SessionRun, error) { + return q.db.GetSessionRun(ctx, runID) +} + +func (q resumeLedgerQueries) ListRunHistoryTurnRequestMessageIDs(ctx context.Context, arg dbsqlc.ListRunHistoryTurnRequestMessageIDsParams) ([]pgtype.UUID, error) { + return q.db.ListRunHistoryTurnRequestMessageIDs(ctx, arg) +} + // resumeProcess is one server process: its runtime and its application // service, with resume enabled the way the server configures it. type resumeProcess struct { @@ -74,6 +83,20 @@ func (h wsStepHistoryHarness) interruptedTurn(t *testing.T, p resumeProcess, tas t.Fatalf("admit turn = (%+v, %v)", admission, err) } fenced := runtimefence.WithContext(ctx, runtimefence.Fence{BotID: h.botID, SessionID: h.sessionID, Token: admission.Handle.FencingToken}) + request, err := h.messages.Persist(fenced, messagepkg.PersistInput{ + BotID: h.botID, SessionID: h.sessionID, RunID: admission.RunID, Role: "user", + Content: []byte(`{"role":"user","content":"` + task + `"}`), + TurnID: admission.TurnID, TurnPosition: &admission.TurnPosition, + }) + if err != nil { + t.Fatal(err) + } + if _, err := h.messages.Persist(fenced, messagepkg.PersistInput{ + BotID: h.botID, SessionID: h.sessionID, RunID: admission.RunID, Role: "assistant", + TurnRequestMessageID: request.ID, Content: []byte(`{"role":"assistant","content":"before restart"}`), + }); err != nil { + t.Fatal(err) + } if err := p.service.recordRunResumeContext(fenced, ChatRequest{RunID: admission.RunID, ChatID: h.botID, Query: task}); err != nil { t.Fatalf("record resume intent: %v", err) } diff --git a/internal/agent/application/service.go b/internal/agent/application/service.go index aec8553108..558786d20b 100644 --- a/internal/agent/application/service.go +++ b/internal/agent/application/service.go @@ -458,6 +458,7 @@ func (s *Service) resolveWithHTTPClient(ctx context.Context, req ChatRequest, mo req = s.applySubagentThreadDefaults(ctx, req, sessionPrefModelID != "") runCfg, chatModel, provider, err := s.buildBaseRunConfig(ctx, baseRunConfigParams{ + ShutdownResume: req.ShutdownResume, BotID: req.BotID, ChatID: req.ChatID, SessionID: req.ThreadID, @@ -755,6 +756,7 @@ func (s *Service) Chat(ctx context.Context, req ChatRequest) (ChatResponse, erro // baseRunConfigParams holds parameters for buildBaseRunConfig that differ // between chat and discuss callers. type baseRunConfigParams struct { + ShutdownResume bool BotID string ChatID string SessionID string @@ -913,7 +915,7 @@ func (s *Service) buildBaseRunConfig(ctx context.Context, p baseRunConfigParams) ctx = workspace.WithWorkspaceTarget(ctx, bound.TargetID) } if s.workspaceTargets != nil { - if target, targetErr := s.workspaceTargets.ResolveWorkspaceTarget(ctx, p.BotID, ""); targetErr == nil { + if target, targetErr := s.resolveStartupWorkspace(ctx, p.BotID, "", p.ShutdownResume); targetErr == nil { cfg.Identity.WorkspaceTargetID = strings.TrimSpace(target.TargetID) cfg.Identity.WorkspaceTargetKind = strings.TrimSpace(target.Kind) cfg.Identity.WorkspaceTargetName = strings.TrimSpace(target.Name) diff --git a/internal/agent/application/service_continuation.go b/internal/agent/application/service_continuation.go index 085142f459..84f6e504b6 100644 --- a/internal/agent/application/service_continuation.go +++ b/internal/agent/application/service_continuation.go @@ -6,6 +6,8 @@ import ( "fmt" "strings" + "github.com/jackc/pgx/v5" + contextfrag "github.com/felinics/memoh/internal/agent/context/fragment" historyfrag "github.com/felinics/memoh/internal/agent/context/history" "github.com/felinics/memoh/internal/agent/runtime/native" @@ -56,7 +58,29 @@ func (s *Service) continuationTurnRequestMessageID(ctx context.Context, sessionI // An applied steer opens a later turn within this run. Its next tool // result and resumed model output belong there, even though admission's // run handle still names the original request turn. - return resolver.GetRunTurnRequestMessageID(ctx, sessionID, strings.TrimSpace(runHandle.RunID), turnID) + runID := strings.TrimSpace(runHandle.RunID) + id, err := resolver.GetRunTurnRequestMessageID(ctx, sessionID, runID, turnID) + if !errors.Is(err, pgx.ErrNoRows) { + return id, err + } + // A continuation that has applied no new input carries its request in its + // own intent. Validate that the request is still visible in this session. + if s.queries == nil { + return "", err + } + row, loadErr := s.queries.GetSessionRun(ctx, db.ParseUUIDOrEmpty(runID)) + if loadErr != nil { + return "", loadErr + } + admitted, decodeErr := decodeRunAdmission(row.InputJson) + if decodeErr != nil { + return "", decodeErr + } + if admitted.Resume == nil || strings.TrimSpace(admitted.Resume.RequestMessageID) == "" { + return "", err + } + request, requestErr := s.recordedResumeRequest(ctx, sessionID, admitted.Resume.RequestMessageID) + return request.messageID, requestErr } func (s *Service) prepareContinuationRunConfig( diff --git a/internal/agent/application/service_workspace_target.go b/internal/agent/application/service_workspace_target.go index 8816657d68..94091b157a 100644 --- a/internal/agent/application/service_workspace_target.go +++ b/internal/agent/application/service_workspace_target.go @@ -5,11 +5,14 @@ import ( "errors" "fmt" "strings" + "time" "github.com/felinics/memoh/internal/agent/runtime/native" "github.com/felinics/memoh/internal/bots" + ctr "github.com/felinics/memoh/internal/container" "github.com/felinics/memoh/internal/workdir" "github.com/felinics/memoh/internal/workspace" + "github.com/felinics/memoh/internal/workspace/bridge" ) var ErrExternalAgentWorkspaceTargetUnsupported = errors.New("workspace_target_id is not supported for external agent sessions") @@ -73,7 +76,7 @@ func (s *Service) prepareWorkspaceRequest(ctx context.Context, req ChatRequest) } return ctx, req, nil } - resolved, err := s.workspaceTargets.ResolveWorkspaceTarget(ctx, req.BotID, requestedTargetID) + resolved, err := s.resolveStartupWorkspace(ctx, req.BotID, requestedTargetID, req.ShutdownResume) if err != nil { return ctx, req, err } @@ -122,3 +125,24 @@ func rejectExternalAgentWorkspaceTarget(req ChatRequest) error { } return ErrExternalAgentWorkspaceTargetUnsupported } + +// A readiness probe can succeed just before the workspace transport rolls. +// Retry only target/config lookup, before any model or tool executes. +func (s *Service) resolveStartupWorkspace(ctx context.Context, botID, targetID string, resume bool) (workspace.ResolvedWorkspaceTarget, error) { + until := time.Now().Add(30 * time.Second) + for { + if err := ctx.Err(); err != nil { + return workspace.ResolvedWorkspaceTarget{}, err + } + target, err := s.workspaceTargets.ResolveWorkspaceTarget(ctx, botID, targetID) + unavailable := errors.Is(err, bridge.ErrUnavailable) || errors.Is(err, ctr.ErrUnavailable) + if err == nil || !resume || !unavailable || !time.Now().Before(until) { + return target, err + } + select { + case <-ctx.Done(): + return workspace.ResolvedWorkspaceTarget{}, ctx.Err() + case <-time.After(time.Second): + } + } +} diff --git a/internal/agent/application/session_resume.go b/internal/agent/application/session_resume.go index 9c243930f3..849146c796 100644 --- a/internal/agent/application/session_resume.go +++ b/internal/agent/application/session_resume.go @@ -44,6 +44,7 @@ type resumeContext struct { TokenClaims map[string]string `json:"token_claims,omitempty"` ChatClaims map[string]string `json:"chat_claims,omitempty"` DeadlineAt *time.Time `json:"deadline_at,omitempty"` + RequestMessageID string `json:"request_message_id,omitempty"` // Version 2 carries an External Discuss batch instead of a query: the // resume admits it again behind its instructions. DiscussMessages []turn.DiscussMessage `json:"discuss_messages,omitempty"` @@ -91,6 +92,9 @@ func (s *Service) recordRunResumeContext(ctx context.Context, req ChatRequest) e ConversationType: req.ConversationType, Model: req.Model, ReasoningEffort: req.ReasoningEffort, WorkspaceTargetID: req.WorkspaceTargetID, SessionType: req.SessionType, ToolHTTPURL: req.ToolHTTPURL, } + if req.UserMessagePersisted || req.ReusePersistedUserMessage { + data.RequestMessageID = strings.TrimSpace(req.PersistedUserMessageID) + } var err error if data.TokenClaims, err = s.resumeClaims(req.Token); err != nil { return err @@ -370,6 +374,14 @@ func (s *Service) resumeInterruptedSession(ctx context.Context, row sqlc.Session if err != nil { return nil, err } + request, err := s.interruptedRunRequest(ctx, row, data) + if err != nil { + return nil, err + } + resumeTurn, err := s.resumedHistoryTurn(ctx, row.SessionID.String(), request.messageID) + if err != nil { + return nil, err + } if s.resumeReady != nil { probeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) err := s.resumeReady(probeCtx, row.BotID.String(), data.WorkspaceTargetID) @@ -396,12 +408,15 @@ func (s *Service) resumeInterruptedSession(ctx context.Context, row sqlc.Session oldCancel := cancel cancel = func() { cancelDeadline(); oldCancel() } } + data.RequestMessageID = request.messageID payload, err := json.Marshal(map[string]any{"kind": "resume", "interrupted_run_id": row.RunID.String(), "resume": data}) if err != nil { cancel() return nil, err } - runCtx, admission, _, err := s.admitTriggeredRun(runBase, data.SessionType, row.BotID.String(), row.SessionID.String(), "resume:"+row.RunID.String(), payload, nil, row.RunID.String()) + runCtx, admission, _, err := s.admitTriggeredRun(runBase, data.SessionType, row.BotID.String(), row.SessionID.String(), "resume:"+row.RunID.String(), payload, func(sessionruntime.RunHandle) *sessionruntime.RunAdmissionView { + return &sessionruntime.RunAdmissionView{ResumeTurn: resumeTurn} + }, row.RunID.String()) if err != nil { cancel() if errors.Is(err, ledger.ErrResumeSuperseded) || errors.Is(err, sessionruntime.ErrInvocationConflict) { @@ -429,7 +444,7 @@ func (s *Service) resumeInterruptedSession(ctx context.Context, row sqlc.Session req.discussPromptPrefix = resumeInstruction req.Query = resumeInstruction + discussAgentFullContextPrompt(data.DiscussMessages) + req.discussPromptSuffix } - chunks, errs := s.streamTurnChat(runCtx, req) + chunks, errs := s.streamResumedTurn(runCtx, req, data, request) h := &runHandle{ id: admission.RunID, ctx: runCtx, cancel: cancel, events: make(chan turn.Event, 16), errs: make(chan error, 1), inject: make(chan turn.InjectMessage), finishRun: s.turnRunFinisher(runCtx, admission, data.SessionType), diff --git a/internal/agent/application/session_resume_request.go b/internal/agent/application/session_resume_request.go new file mode 100644 index 0000000000..7b3d019d80 --- /dev/null +++ b/internal/agent/application/session_resume_request.go @@ -0,0 +1,150 @@ +package application + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/jackc/pgx/v5" + + "github.com/felinics/memoh/internal/agent/turn" + chatview "github.com/felinics/memoh/internal/agent/view" + messagepkg "github.com/felinics/memoh/internal/chat/message" + "github.com/felinics/memoh/internal/db/postgres/sqlc" +) + +// runRequestResolver reads only the interrupted run's own inputs and history. +type runRequestResolver interface { + continuationTurnRequestMessageResolver + RunWroteHistory(ctx context.Context, sessionID, runID, turnID string) (bool, error) +} + +type visibleTurnReader interface { + GetVisibleTurnByMessage(ctx context.Context, sessionID, messageID string) (messagepkg.HistoryTurn, error) +} + +// resumeRequest is the request row a shutdown continuation answers. +type resumeRequest struct { + // messageID is the request the interrupted run was answering. + messageID string + // restore means the interrupted run stopped before it wrote its request: + // the continuation writes it under its own turn before running. + restore bool +} + +// Prefer input the run applied itself (including a steer or restored request), +// then its recorded request. Each continuation carries that anchor forward. +func (s *Service) interruptedRunRequest(ctx context.Context, row sqlc.SessionRun, data *resumeContext) (resumeRequest, error) { + // A Discuss run answers rows its ingress already wrote; it never has a + // request row of its own to resolve or restore. + if data.SessionType == string(turn.ModeDiscuss) { + return resumeRequest{}, nil + } + resolver, ok := s.messageService.(runRequestResolver) + if !ok { + return resumeRequest{}, nil + } + sessionID := row.SessionID.String() + id, err := resolver.GetRunTurnRequestMessageID(ctx, sessionID, row.RunID.String(), row.TurnID.String()) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return resumeRequest{}, fmt.Errorf("resolve interrupted request: %w", err) + } + if id != "" { + return resumeRequest{messageID: id}, nil + } + if recorded := strings.TrimSpace(data.RequestMessageID); recorded != "" { + return s.recordedResumeRequest(ctx, sessionID, recorded) + } + wrote, err := resolver.RunWroteHistory(ctx, sessionID, row.RunID.String(), row.TurnID.String()) + if err != nil { + return resumeRequest{}, fmt.Errorf("inspect interrupted history: %w", err) + } + if wrote { + // The run wrote history whose request is no longer visible. Answering + // it would file the continuation under some other turn. + return resumeRequest{}, fmt.Errorf("%w: interrupted request is no longer in history", errResumeUnrecoverable) + } + return resumeRequest{restore: true}, nil +} + +// recordedResumeRequest accepts the request an intent recorded only while it +// is still the request of a visible turn in the session. +func (s *Service) recordedResumeRequest(ctx context.Context, sessionID, messageID string) (resumeRequest, error) { + reader, ok := s.messageService.(visibleTurnReader) + if !ok { + return resumeRequest{}, nil + } + historyTurn, err := reader.GetVisibleTurnByMessage(ctx, sessionID, messageID) + if errors.Is(err, pgx.ErrNoRows) || err == nil && historyTurn.RequestMessageID != messageID { + return resumeRequest{}, fmt.Errorf("%w: interrupted request is no longer in history", errResumeUnrecoverable) + } + if err != nil { + return resumeRequest{}, fmt.Errorf("resolve recorded request: %w", err) + } + return resumeRequest{messageID: messageID}, nil +} + +// streamResumedTurn starts the continuation bound to the request it answers. +// A request that cannot be restored fails the admitted run before any model +// call, rather than running it with rows that belong to no turn. +func (s *Service) streamResumedTurn(ctx context.Context, req ChatRequest, data *resumeContext, request resumeRequest) (<-chan StreamChunk, <-chan error) { + req.PersistedUserMessageID = request.messageID + if request.restore { + id, err := s.restoreInterruptedRequest(ctx, req, data) + if err != nil { + chunks, errs := make(chan StreamChunk), make(chan error, 1) + close(chunks) + errs <- err + close(errs) + return chunks, errs + } + req.PersistedUserMessageID = id + } + return s.streamTurnChat(ctx, req) +} + +// restoreInterruptedRequest writes the request an interrupted run never +// persisted, under the continuation's admitted turn. It holds the original +// task, not the resume instruction the model is given around it. +func (s *Service) restoreInterruptedRequest(ctx context.Context, req ChatRequest, data *resumeContext) (string, error) { + restored := ChatRequest{ + BotID: req.BotID, ChatID: req.ChatID, ThreadID: req.ThreadID, + RunID: req.RunID, TurnID: req.TurnID, TurnPosition: req.TurnPosition, + Query: data.Query, UserVisibleText: turn.UnwrapUserMessageEnvelope(data.Query), + UserID: req.UserID, SourceChannelIdentityID: req.SourceChannelIdentityID, + CurrentChannel: req.CurrentChannel, ReplyTarget: req.ReplyTarget, ConversationType: req.ConversationType, + SessionType: req.SessionType, WorkspaceTargetID: req.WorkspaceTargetID, + } + persisted, err := s.persistUserTurn(ctx, restored) + if err != nil { + return "", fmt.Errorf("restore interrupted request: %w", err) + } + return persisted.ID, nil +} + +// resumedHistoryTurn publishes the same response identity and prefix as REST +// history. Loading it before admission leaves the old intent retryable on errors. +func (s *Service) resumedHistoryTurn(ctx context.Context, sessionID, requestID string) (*chatview.UITurn, error) { + if requestID == "" { + return nil, nil + } + reader, ok := s.messageService.(visibleTurnReader) + if !ok { + return nil, nil + } + historyTurn, err := reader.GetVisibleTurnByMessage(ctx, sessionID, requestID) + if err != nil { + return nil, err + } + rows, err := s.messageService.ListVisibleFromBySession(ctx, sessionID, requestID) + if err != nil { + return nil, err + } + for _, t := range chatview.ConvertMessagesToUITurns(rows) { + if t.Role == "assistant" && t.TurnID == historyTurn.ID { + return &t, nil + } + } + return &chatview.UITurn{TurnID: historyTurn.ID, TurnPosition: &historyTurn.Position, Role: "assistant", Timestamp: historyTurn.CreatedAt}, nil +} diff --git a/internal/agent/application/session_resume_request_postgres_test.go b/internal/agent/application/session_resume_request_postgres_test.go new file mode 100644 index 0000000000..a2d460bfef --- /dev/null +++ b/internal/agent/application/session_resume_request_postgres_test.go @@ -0,0 +1,106 @@ +package application + +import ( + "context" + "encoding/base64" + "fmt" + "testing" + + sdk "github.com/felinics/twilight/sdk" + + sessionruntime "github.com/felinics/memoh/internal/agent/runtime/session" + tools "github.com/felinics/memoh/internal/agent/tool" + "github.com/felinics/memoh/internal/agent/toolexec" + "github.com/felinics/memoh/internal/db" + "github.com/felinics/memoh/internal/workspace" + "github.com/felinics/memoh/internal/workspace/bridge" +) + +type readImageTools struct{} + +func (readImageTools) Tools(context.Context, tools.SessionContext) ([]toolexec.Tool, error) { + type readArgs struct { + Path string `json:"path"` + } + return []toolexec.Tool{toolexec.Define(tools.ReadMediaToolName().String(), "Read a workspace file.", + func(_ *toolexec.ToolExecContext, args readArgs) (sdk.ToolOutput, error) { + return toolexec.OutputFromValue(tools.ReadMediaToolOutput{ + Public: tools.ReadMediaToolResult{OK: true, Path: args.Path, Mime: "image/png"}, + ImageBase64: base64.StdEncoding.EncodeToString([]byte("\x89PNG\r\n\x1a\n\x00screenshot")), + ImageMediaType: "image/png", + }), nil + })}, nil +} + +type resumeUnavailableWorkspace struct{ calls int } + +func (w *resumeUnavailableWorkspace) ResolveWorkspaceTarget(context.Context, string, string) (workspace.ResolvedWorkspaceTarget, error) { + w.calls++ + // Both initial target selection and the later run-config lookup can fail + // after the readiness check. No model/tool has executed at either boundary. + if w.calls == 1 || w.calls == 3 { + return workspace.ResolvedWorkspaceTarget{}, fmt.Errorf("restart window: %w", bridge.ErrUnavailable) + } + return workspace.ResolvedWorkspaceTarget{TargetID: "native", Kind: "native"}, nil +} + +func TestPostgresShutdownResumeReadsImageAfterWorkspaceRecovery(t *testing.T) { + h := newWSStepHistoryHarness(t, wsStepHistorySuccess) + runID := h.interruptedTurn(t, h.startProcess(t), "inspect the desktop") + next := h.startProcess(t) + next.service.streamHTTPClient.Transport.(*wsStepHistoryTransport).mode = wsStepHistoryReadImage + config := next.service.queries.(resumeLedgerQueries).directLifecycleQueries + model := config.models["direct-lifecycle-model"] + model.Config = []byte(`{"context_window":128000,"compatibilities":["tool-call","vision"]}`) + config.models["direct-lifecycle-model"] = model + next.service.agent.SetToolProviders([]tools.ToolProvider{readImageTools{}}) + target := &resumeUnavailableWorkspace{} + next.service.SetWorkspaceTargetResolver(target) + next.service.SetResumeReadiness(func(context.Context, string, string) error { return nil }) + if !h.resumeScan(t, next, runID) { + t.Fatal("continuation was not admitted") + } + var resumed, state, originalTurn string + err := h.pool.QueryRow(t.Context(), `SELECT run_id::text,state FROM session_runs WHERE invocation_id=$1`, "resume:"+runID).Scan(&resumed, &state) + if err != nil || state != "completed" { + t.Fatalf("resume: state=%s err=%v", state, err) + } + if err := h.pool.QueryRow(t.Context(), `SELECT turn_id::text FROM session_runs WHERE run_id=$1`, runID).Scan(&originalTurn); err != nil { + t.Fatal(err) + } + var feedback, foreign, requests int + err = h.pool.QueryRow(t.Context(), `SELECT count(*) FILTER(WHERE metadata->>'message_source'='internal_feedback'),count(*) FILTER(WHERE turn_id<>$2::uuid),count(*) FILTER(WHERE role='user' AND COALESCE(metadata->>'message_source','')<>'internal_feedback') FROM bot_history_messages WHERE run_id=$1`, resumed, originalTurn).Scan(&feedback, &foreign, &requests) + if err != nil || feedback != 1 || foreign != 0 || requests != 0 { + t.Fatalf("history: feedback=%d foreign=%d requests=%d err=%v", feedback, foreign, requests, err) + } + snapshot, err := next.manager.Snapshot(t.Context(), h.botID, h.sessionID) + if err != nil { + t.Fatal(err) + } + view := snapshot.CurrentRunView + if view == nil || view.ResumeTurn == nil || view.ResumeTurn.TurnID != originalTurn || view.TurnID == originalTurn || len(view.ResumeTurn.Messages) == 0 { + t.Fatalf("resume projection: %+v", view) + } + // A subsequent shutdown and a decision continuation use this run's intent, + // even though it wrote output but no request of its own. + row, err := next.service.queries.GetSessionRun(t.Context(), db.ParseUUIDOrEmpty(resumed)) + if err != nil { + t.Fatal(err) + } + admitted, err := decodeRunAdmission(row.InputJson) + if err != nil || admitted.Resume == nil || admitted.Resume.RequestMessageID == "" { + t.Fatalf("saved request: %+v, %v", admitted.Resume, err) + } + request, err := next.service.interruptedRunRequest(t.Context(), row, admitted.Resume) + if err != nil || request.restore || request.messageID != admitted.Resume.RequestMessageID { + t.Fatalf("next shutdown request: %+v, %v", request, err) + } + decisionRequest, err := next.service.continuationTurnRequestMessageID(t.Context(), h.sessionID, sessionruntime.RunHandle{RunID: resumed, TurnID: row.TurnID.String()}) + if err != nil || decisionRequest != request.messageID { + t.Fatalf("decision request: %q, %v", decisionRequest, err) + } + + if target.calls < 4 { + t.Fatalf("setup was not retried: %d calls", target.calls) + } +} diff --git a/internal/agent/application/session_resume_test.go b/internal/agent/application/session_resume_test.go index 63ee617f46..21418be2e8 100644 --- a/internal/agent/application/session_resume_test.go +++ b/internal/agent/application/session_resume_test.go @@ -260,3 +260,17 @@ func TestResumeScanRetiresIntentsThatCannotContinue(t *testing.T) { t.Fatalf("admission=%+v, want only the resumable run", inputs) } } + +func TestResumeWorkspaceRetryStopsOnCancellationAndDoesNotRetryNormalTurns(t *testing.T) { + target := &resumeUnavailableWorkspace{} + s := &Service{workspaceTargets: target} + if _, err := s.resolveStartupWorkspace(t.Context(), "bot", "native", false); err == nil || target.calls != 1 { + t.Fatalf("normal turn: calls=%d err=%v", target.calls, err) + } + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) + defer cancel() + target.calls = 0 + if _, err := s.resolveStartupWorkspace(ctx, "bot", "native", true); !errors.Is(err, context.DeadlineExceeded) || target.calls != 1 { + t.Fatalf("resume deadline: calls=%d err=%v", target.calls, err) + } +} diff --git a/internal/agent/application/ws_step_history_postgres_test.go b/internal/agent/application/ws_step_history_postgres_test.go index 7f8b92344f..fa0eaac143 100644 --- a/internal/agent/application/ws_step_history_postgres_test.go +++ b/internal/agent/application/ws_step_history_postgres_test.go @@ -75,6 +75,10 @@ const ( // detection aborts the run. The abort follows no error event, and its // cause carries no catalogued code. wsStepHistoryTextLoop wsStepHistoryModel = "text_loop" + // wsStepHistoryReadImage answers the first call with a call to the read + // tool and every later call with text. The image the tool reads reaches + // the second call as internal feedback. + wsStepHistoryReadImage wsStepHistoryModel = "read_image" ) // wsStepHistoryTransport answers streaming model requests with the scripted @@ -113,6 +117,19 @@ func (t *wsStepHistoryTransport) RoundTrip(r *http.Request) (*http.Response, err } } switch t.mode { + case wsStepHistoryReadImage: + if call == 1 { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"id\":\"chatcmpl-ws-step\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_read_image\",\"type\":\"function\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"/data/screenshot.png\\\"}\"}}]},\"finish_reason\":null}]}\n\n" + + "data: {\"id\":\"chatcmpl-ws-step\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\ndata: [DONE]\n\n")), + Request: r, + }, nil + } + return stream(strings.NewReader("data: {\"id\":\"chatcmpl-ws-step\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")), nil case wsStepHistoryToolThenBrokenStream, wsStepHistoryToolThenAuthFailure: if call == 1 { return &http.Response{ diff --git a/internal/agent/runtime/session/manager.go b/internal/agent/runtime/session/manager.go index 8bdf1137ee..b9cc620999 100644 --- a/internal/agent/runtime/session/manager.go +++ b/internal/agent/runtime/session/manager.go @@ -1299,6 +1299,7 @@ func (m *Manager) startRun(ctx context.Context, start runStart) (RunHandle, Curs snapshot.UpdatedAt = now run.Status = RunStatusRunning run.Operation = admission.Operation + run.ResumeTurn = admission.ResumeTurn switch { case admission.RequestUserTurn != nil: run.UserTurns = []chatview.UITurn{*admission.RequestUserTurn} diff --git a/internal/agent/runtime/session/state.go b/internal/agent/runtime/session/state.go index 60f63e8be9..3131ea7549 100644 --- a/internal/agent/runtime/session/state.go +++ b/internal/agent/runtime/session/state.go @@ -260,6 +260,7 @@ func normalizeRunAdmission(admission RunAdmissionView) (RunAdmissionView, error) } return RunAdmissionView{ RequestUserTurn: requestUserTurn, + ResumeTurn: admission.ResumeTurn, Operation: operation, }, nil } diff --git a/internal/agent/runtime/session/types.go b/internal/agent/runtime/session/types.go index 02631d0739..1a10434e63 100644 --- a/internal/agent/runtime/session/types.go +++ b/internal/agent/runtime/session/types.go @@ -263,10 +263,14 @@ func (s Snapshot) cursor() Cursor { } type CurrentRunView struct { + // ResumeTurn is the original response turn and its committed prefix. The run + // keeps its own admission identity for ownership and decision commands. + ResumeTurn *chatview.UITurn `json:"resume_turn,omitempty"` // ConfigurationOnly holds the session lock but does not generate a reply. ConfigurationOnly bool `json:"configuration_only,omitempty"` RunID string `json:"run_id" validate:"required" format:"uuid"` - // TurnID is the durable turn this run writes into, allocated at admission. + // TurnID is this run's durable admission slot. A shutdown continuation + // answers ResumeTurn instead, while commands still target this admission. // It is part of the observable view because SR-OBS-003 requires every // subscriber to agree on the run's turn, and a subscriber that only learns // the run id cannot line the run up against persisted history. @@ -347,6 +351,7 @@ type SteerTurnView struct { // a durable history row; ordinary sends still persist user + assistant // together when the run reaches a terminal result. type RunAdmissionView struct { + ResumeTurn *chatview.UITurn RequestUserTurn *chatview.UITurn Operation *RunOperationView } diff --git a/internal/chat/message/replacement.go b/internal/chat/message/replacement.go index 17f86bc53a..fc2a5f7b48 100644 --- a/internal/chat/message/replacement.go +++ b/internal/chat/message/replacement.go @@ -189,3 +189,26 @@ func (s *DBService) GetRunTurnRequestMessageID(ctx context.Context, sessionID, r }) return id.String(), err } + +// RunWroteHistory includes hidden rows so a removed request is not restored. +func (s *DBService) RunWroteHistory(ctx context.Context, sessionID, runID, rootTurnID string) (bool, error) { + reader, ok := s.queries.(interface { + RunWroteHistoryMessages(context.Context, sqlc.RunWroteHistoryMessagesParams) (bool, error) + }) + if !ok { + return false, errors.New("message store does not support run history lookup") + } + session, err := dbpkg.ParseUUID(sessionID) + if err != nil { + return false, err + } + run, err := dbpkg.ParseUUID(runID) + if err != nil { + return false, err + } + turn, err := dbpkg.ParseUUID(rootTurnID) + if err != nil { + return false, err + } + return reader.RunWroteHistoryMessages(ctx, sqlc.RunWroteHistoryMessagesParams{SessionID: session, RunID: run, RootTurnID: turn}) +} diff --git a/internal/db/postgres/sqlc/messages.sql.go b/internal/db/postgres/sqlc/messages.sql.go index cb5163c29d..738e0101df 100644 --- a/internal/db/postgres/sqlc/messages.sql.go +++ b/internal/db/postgres/sqlc/messages.sql.go @@ -5419,6 +5419,30 @@ func (q *Queries) ReplaceHistoryTurn(ctx context.Context, arg ReplaceHistoryTurn return i, err } +const runWroteHistoryMessages = `-- name: RunWroteHistoryMessages :one +SELECT EXISTS ( + SELECT 1 + FROM bot_history_messages m + WHERE m.team_id = public.memoh_current_team_id() + AND m.session_id = $1 + AND (m.run_id = $2 OR m.turn_id = $3) +)::boolean +` + +type RunWroteHistoryMessagesParams struct { + SessionID pgtype.UUID `json:"session_id"` + RunID pgtype.UUID `json:"run_id"` + RootTurnID pgtype.UUID `json:"root_turn_id"` +} + +// Distinguish an input never persisted from history whose request was removed. +func (q *Queries) RunWroteHistoryMessages(ctx context.Context, arg RunWroteHistoryMessagesParams) (bool, error) { + row := q.db.QueryRow(ctx, runWroteHistoryMessages, arg.SessionID, arg.RunID, arg.RootTurnID) + var column_1 bool + err := row.Scan(&column_1) + return column_1, err +} + const searchMessages = `-- name: SearchMessages :many SELECT m.id,