Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/go-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down
3 changes: 3 additions & 0 deletions apps/web/src/composables/api/useChat.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 17 additions & 9 deletions apps/web/src/store/chat/runtime-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -215,28 +217,34 @@ 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)
if (projectsAssistantContent) {
// 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: '',
})
}
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)
Expand Down Expand Up @@ -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,
Expand Down
31 changes: 28 additions & 3 deletions apps/web/src/store/chat/transcript-race.test.ts
Original file line number Diff line number Diff line change
@@ -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' } }),
Expand All @@ -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 }
}

Expand Down Expand Up @@ -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' }] : []),
] })
}
})
10 changes: 10 additions & 0 deletions db/postgres/queries/messages.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions docs/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions internal/agent/application/history_reset_resume_postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 3 additions & 1 deletion internal/agent/application/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
26 changes: 25 additions & 1 deletion internal/agent/application/service_continuation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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(
Expand Down
26 changes: 25 additions & 1 deletion internal/agent/application/service_workspace_target.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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):
}
}
}
Loading
Loading