feat: restore and recover agent-local ACP sessions (#30857)
Restore missing or failed agent-local ACP sessions using load or resume, preferring load to replay the latest turn's history. Share concurrent recovery attempts and preserve failed transcripts without automatically retrying messages. Depends on #30903. Generated with Codex, carefully reviewed by Hugo.
This commit is contained in:
1 parent
d2c32e666d
commit
e3068bb4c4
9 files changed
+518
-31
No files matched your search
@@ -47,7 +47,8 @@ func TestACPHarness(t *testing.T) {
|
||||
}
|
||||
|
||||
type fakeNativeSession struct {
|
||||
Value string `json:"value"`
|
||||
History []string `json:"history"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type fakeHarnessMode string
|
||||
@@ -55,6 +56,14 @@ type fakeHarnessMode string
|
||||
const (
|
||||
// fakeHarnessModeBoth advertises load and resume capabilities.
|
||||
fakeHarnessModeBoth fakeHarnessMode = "both"
|
||||
// fakeHarnessModeLoad advertises only load for recovery, testing history
|
||||
// replay and transcript generation resets.
|
||||
fakeHarnessModeLoad fakeHarnessMode = "load"
|
||||
// fakeHarnessModeResume advertises only resume for recovery, testing
|
||||
// restoration without history replay.
|
||||
fakeHarnessModeResume fakeHarnessMode = "resume"
|
||||
// fakeHarnessModeNone disables load and resume to test unavailable recovery.
|
||||
fakeHarnessModeNone fakeHarnessMode = "none"
|
||||
// fakeHarnessModeFail returns an initialization error to test reporting a
|
||||
// failed probe without preventing discovery of other harnesses.
|
||||
fakeHarnessModeFail fakeHarnessMode = "fail"
|
||||
@@ -93,6 +102,16 @@ func (f *fakeHarness) Initialize(ctx context.Context, req acp.InitializeRequest)
|
||||
}
|
||||
var result acp.InitializeResponse
|
||||
_ = json.Unmarshal([]byte(`{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"resume":{}}}}`), &result)
|
||||
if f.mode == fakeHarnessModeLoad {
|
||||
result.AgentCapabilities.SessionCapabilities.Resume = nil
|
||||
}
|
||||
if f.mode == fakeHarnessModeResume {
|
||||
result.AgentCapabilities.LoadSession = false
|
||||
}
|
||||
if f.mode == fakeHarnessModeNone {
|
||||
result.AgentCapabilities.LoadSession = false
|
||||
result.AgentCapabilities.SessionCapabilities.Resume = nil
|
||||
}
|
||||
if f.mode == fakeHarnessModeFail {
|
||||
return result, xerrors.New("probe failed")
|
||||
}
|
||||
@@ -166,6 +185,12 @@ func (f *fakeHarness) Prompt(ctx context.Context, req acp.PromptRequest) (acp.Pr
|
||||
}
|
||||
response := "answer:" + text + ":" + f.value
|
||||
_ = f.update(ctx, req.SessionId, "agent_message_chunk", response)
|
||||
raw, _ := os.ReadFile(string(req.SessionId) + ".json")
|
||||
var saved fakeNativeSession
|
||||
_ = json.Unmarshal(raw, &saved)
|
||||
saved.History = append(saved.History, text, response)
|
||||
raw, _ = json.Marshal(saved)
|
||||
_ = os.WriteFile(string(req.SessionId)+".json", raw, 0o600)
|
||||
return acp.PromptResponse{StopReason: acp.StopReasonEndTurn}, nil
|
||||
}
|
||||
|
||||
@@ -178,6 +203,42 @@ func (f *fakeHarness) Cancel(context.Context, acp.CancelNotification) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHarness) LoadSession(ctx context.Context, req acp.LoadSessionRequest) (acp.LoadSessionResponse, error) {
|
||||
if err := f.check(req.Cwd, req.McpServers); err != nil {
|
||||
return acp.LoadSessionResponse{}, err
|
||||
}
|
||||
raw, err := os.ReadFile(string(req.SessionId) + ".json")
|
||||
if err != nil {
|
||||
return acp.LoadSessionResponse{}, err
|
||||
}
|
||||
var saved fakeNativeSession
|
||||
_ = json.Unmarshal(raw, &saved)
|
||||
f.value = saved.Value
|
||||
if saved.Value == "fail-load" {
|
||||
_ = f.update(ctx, req.SessionId, "agent_message_chunk", "partial replay")
|
||||
return acp.LoadSessionResponse{}, xerrors.New("load failed after partial replay")
|
||||
}
|
||||
for i, text := range saved.History {
|
||||
kind := "user_message_chunk"
|
||||
if i%2 == 1 {
|
||||
kind = "agent_message_chunk"
|
||||
}
|
||||
_ = f.update(ctx, req.SessionId, kind, text)
|
||||
}
|
||||
return acp.LoadSessionResponse{ConfigOptions: f.options()}, nil
|
||||
}
|
||||
|
||||
func (f *fakeHarness) ResumeSession(_ context.Context, req acp.ResumeSessionRequest) (acp.ResumeSessionResponse, error) {
|
||||
if err := f.check(req.Cwd, req.McpServers); err != nil {
|
||||
return acp.ResumeSessionResponse{}, err
|
||||
}
|
||||
raw, err := os.ReadFile(string(req.SessionId) + ".json")
|
||||
var saved fakeNativeSession
|
||||
_ = json.Unmarshal(raw, &saved)
|
||||
f.value = saved.Value
|
||||
return acp.ResumeSessionResponse{ConfigOptions: f.options()}, err
|
||||
}
|
||||
|
||||
func (f *fakeHarness) SetSessionConfigOption(_ context.Context, req acp.SetSessionConfigOptionRequest) (acp.SetSessionConfigOptionResponse, error) {
|
||||
if req.ValueId == nil || req.ValueId.ConfigId != "model" {
|
||||
return acp.SetSessionConfigOptionResponse{}, xerrors.New("unknown config")
|
||||
|
||||
@@ -66,6 +66,7 @@ type Manager struct {
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
sessions map[workspacesdk.ACPSessionID]*SessionFSM
|
||||
initializing map[workspacesdk.ACPSessionID]*initialization
|
||||
configs map[string]harnessConfig
|
||||
configDir string
|
||||
discoveryDir string
|
||||
@@ -94,6 +95,7 @@ func NewManager(ctx context.Context, opts Options) *Manager {
|
||||
workingDir: opts.WorkingDir,
|
||||
sessions: make(map[workspacesdk.ACPSessionID]*SessionFSM),
|
||||
closedDone: make(chan struct{}),
|
||||
initializing: make(map[workspacesdk.ACPSessionID]*initialization),
|
||||
configs: make(map[string]harnessConfig),
|
||||
configHashes: make(map[string][32]byte),
|
||||
}
|
||||
@@ -153,11 +155,12 @@ func (m *Manager) Create(ctx context.Context, req workspacesdk.ACPCreateSessionR
|
||||
}
|
||||
|
||||
// Message submits a prompt to an existing idle session.
|
||||
// If the session failed, Message attempts to recover it before submitting the prompt.
|
||||
func (m *Manager) Message(ctx context.Context, id workspacesdk.ACPSessionID, req workspacesdk.ACPMessageRequest) (workspacesdk.ACPMessageResponse, error) {
|
||||
if strings.TrimSpace(req.Text) == "" {
|
||||
return workspacesdk.ACPMessageResponse{}, ErrInvalid
|
||||
}
|
||||
s, err := m.get(ctx, id)
|
||||
s, err := m.recover(ctx, id)
|
||||
if err != nil {
|
||||
return workspacesdk.ACPMessageResponse{}, err
|
||||
}
|
||||
|
||||
@@ -139,11 +139,7 @@ func TestRequiredDirectoryAndOverrides(t *testing.T) {
|
||||
_, err := m.Create(context.Background(), req)
|
||||
require.ErrorIs(t, err, ErrInvalid)
|
||||
_, err = m.Read(context.Background(), workspacesdk.ACPSessionID{HarnessSlug: req.HarnessSlug, WorkingDirectory: directory, SessionID: "native"}, nil)
|
||||
if filepath.IsAbs(directory) {
|
||||
require.ErrorIs(t, err, ErrNotFound)
|
||||
} else {
|
||||
require.ErrorIs(t, err, ErrInvalid)
|
||||
}
|
||||
require.ErrorIs(t, err, ErrInvalid)
|
||||
}
|
||||
_, err := m.Create(context.Background(), workspacesdk.ACPCreateSessionRequest{HarnessSlug: "fake", WorkingDirectory: dir, Config: map[string]string{"model": "unknown"}})
|
||||
require.ErrorIs(t, err, ErrInvalid)
|
||||
@@ -181,3 +177,19 @@ func holdTestSession(t *testing.T, m *Manager, id workspacesdk.ACPSessionID) *Se
|
||||
}, testutil.IntervalFast)
|
||||
return s
|
||||
}
|
||||
|
||||
func messageTestSession(t *testing.T, m *Manager, id workspacesdk.ACPSessionID, text string) workspacesdk.ACPSessionResponse {
|
||||
t.Helper()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
_, err := m.Message(ctx, id, workspacesdk.ACPMessageRequest{Text: text})
|
||||
require.NoError(t, err)
|
||||
return awaitTestSession(t, m, id)
|
||||
}
|
||||
|
||||
func setTestHarnessCommand(m *Manager, command string) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cfg := m.configs["fake"]
|
||||
cfg.command = command
|
||||
m.configs["fake"] = cfg
|
||||
}
|
||||
@@ -16,6 +16,13 @@ type initialization struct {
|
||||
err error
|
||||
}
|
||||
|
||||
type registrationMode int
|
||||
|
||||
const (
|
||||
registrationCreate registrationMode = iota
|
||||
registrationRestore
|
||||
)
|
||||
|
||||
// createSession returns a new initialized FSM in idle.
|
||||
func (m *Manager) createSession(ctx context.Context, req workspacesdk.ACPCreateSessionRequest) (*SessionFSM, error) {
|
||||
if err := validateSessionRequest(m.fs, req.HarnessSlug, req.WorkingDirectory); err != nil {
|
||||
@@ -73,21 +80,25 @@ func (m *Manager) initializeAndRegisterSession(req sessionInitRequest) (*Session
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := m.registerSession(s); err != nil {
|
||||
mode := registrationCreate
|
||||
if req.nativeID != "" {
|
||||
mode = registrationRestore
|
||||
}
|
||||
if err := m.registerSession(s, mode); err != nil {
|
||||
s.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *Manager) registerSession(s *SessionFSM) error {
|
||||
func (m *Manager) registerSession(s *SessionFSM, mode registrationMode) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if m.closed {
|
||||
return ErrManagerClosed
|
||||
}
|
||||
if m.sessions[s.id] != nil {
|
||||
if mode == registrationCreate && m.sessions[s.id] != nil {
|
||||
return ErrConflict
|
||||
}
|
||||
m.sessions[s.id] = s
|
||||
@@ -118,8 +129,28 @@ func (m *Manager) awaitInitialization(ctx context.Context, attempt *initializati
|
||||
}
|
||||
}
|
||||
|
||||
// get returns an initialized session without creating or restoring one.
|
||||
// get returns the current session, restoring it only if absent.
|
||||
func (m *Manager) get(ctx context.Context, id workspacesdk.ACPSessionID) (*SessionFSM, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.mu.Lock()
|
||||
if m.closed {
|
||||
m.mu.Unlock()
|
||||
return nil, ErrManagerClosed
|
||||
}
|
||||
s := m.sessions[id]
|
||||
m.mu.Unlock()
|
||||
if s != nil {
|
||||
return s, nil
|
||||
}
|
||||
return m.recover(ctx, id)
|
||||
}
|
||||
|
||||
// recover loads absent sessions or replaces failed instances. Concurrent callers
|
||||
// share one manager-owned attempt; cancellation only stops the caller's wait.
|
||||
// Failed instances remain readable until successfully replaced or closed.
|
||||
func (m *Manager) recover(ctx context.Context, id workspacesdk.ACPSessionID) (*SessionFSM, error) {
|
||||
if id.SessionID == "" || id.HarnessSlug == "" || !filepath.IsAbs(id.WorkingDirectory) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
@@ -127,13 +158,55 @@ func (m *Manager) get(ctx context.Context, id workspacesdk.ACPSessionID) (*Sessi
|
||||
return nil, err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.closed {
|
||||
m.mu.Unlock()
|
||||
return nil, ErrManagerClosed
|
||||
}
|
||||
s := m.sessions[id]
|
||||
if s == nil {
|
||||
return nil, ErrNotFound
|
||||
attempt := m.initializing[id]
|
||||
if attempt == nil {
|
||||
s := m.sessions[id]
|
||||
attempt = &initialization{done: make(chan struct{})}
|
||||
m.initializing[id] = attempt
|
||||
m.wg.Go(func() {
|
||||
attempt.fsm, attempt.err = m.restoreSession(id, s)
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.initializing, id)
|
||||
close(attempt.done)
|
||||
})
|
||||
}
|
||||
m.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-attempt.done:
|
||||
return attempt.fsm, attempt.err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// restoreSession runs in the initialization goroutine, which reserves this
|
||||
// session's recovery without holding the manager lock during FSM operations.
|
||||
func (m *Manager) restoreSession(id workspacesdk.ACPSessionID, oldSession *SessionFSM) (*SessionFSM, error) {
|
||||
req := sessionInitRequest{harnessSlug: id.HarnessSlug, workingDirectory: id.WorkingDirectory}
|
||||
if oldSession != nil {
|
||||
unlock, err := oldSession.lock(m.ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
failed := oldSession.info.Status == workspacesdk.ACPSessionStatusError
|
||||
unlock()
|
||||
if !failed {
|
||||
return oldSession, nil
|
||||
}
|
||||
req = oldSession.request
|
||||
}
|
||||
req.nativeID = id.SessionID
|
||||
restored, err := m.initializeAndRegisterSession(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if oldSession != nil {
|
||||
oldSession.Close()
|
||||
}
|
||||
return restored, nil
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package agentacp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/quartz"
|
||||
)
|
||||
|
||||
func restartTestManager(t *testing.T, m *Manager, dir string) *Manager {
|
||||
t.Helper()
|
||||
require.NoError(t, m.Close())
|
||||
fresh := NewManager(context.Background(), Options{
|
||||
Logger: m.logger, Clock: m.clock, Execer: m.execer,
|
||||
Filesystem: afero.NewReadOnlyFs(m.fs), EnvInfo: m.envInfo,
|
||||
WorkingDir: func() string { return dir },
|
||||
})
|
||||
t.Cleanup(func() { require.NoError(t, fresh.Close()) })
|
||||
require.NoError(t, fresh.Reload(testutil.Context(t, testutil.WaitLong)))
|
||||
return fresh
|
||||
}
|
||||
|
||||
func TestRecovery(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, mode := range []fakeHarnessMode{fakeHarnessModeBoth, fakeHarnessModeLoad, fakeHarnessModeResume, fakeHarnessModeNone} {
|
||||
t.Run(string(mode), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, dir, _ := newTestManager(t, mode)
|
||||
info := createTestSession(t, m, dir)
|
||||
messageTestSession(t, m, info.ID, "hello")
|
||||
before := messageTestSession(t, m, info.ID, "latest")
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
if mode == fakeHarnessModeNone {
|
||||
failed := messageTestSession(t, m, info.ID, "exit")
|
||||
require.Equal(t, workspacesdk.ACPSessionStatusError, failed.Session.Status)
|
||||
read, err := m.Read(ctx, info.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, failed, read)
|
||||
_, err = m.Message(ctx, info.ID, workspacesdk.ACPMessageRequest{Text: "unavailable"})
|
||||
require.ErrorIs(t, err, ErrUnavailable)
|
||||
return
|
||||
}
|
||||
// Only native files survive restart. Prefer load to resume.
|
||||
m = restartTestManager(t, m, dir)
|
||||
restored, err := m.Read(ctx, info.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, info.ID, restored.Session.ID)
|
||||
require.NotEqual(t, before.Session.Cursor.GenerationID, restored.Session.Cursor.GenerationID)
|
||||
if mode == fakeHarnessModeResume {
|
||||
require.Empty(t, restored.AssistantResponse)
|
||||
} else {
|
||||
require.Equal(t, before.AssistantResponse, restored.AssistantResponse)
|
||||
require.Len(t, restored.Events, 1)
|
||||
require.Equal(t, workspacesdk.ACPEventKindUpdate, restored.Events[0].Kind)
|
||||
require.Contains(t, string(restored.Events[0].Update), before.AssistantResponse)
|
||||
}
|
||||
_, err = m.Read(ctx, info.ID, &before.Session.Cursor)
|
||||
require.ErrorIs(t, err, ErrConflict)
|
||||
require.Equal(t, "answer:restored:other", messageTestSession(t, m, info.ID, "restored").AssistantResponse)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageRecoveryDoesNotReplayWork(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, dir, _ := newTestManager(t, fakeHarnessModeBoth)
|
||||
info := createTestSession(t, m, dir)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
var history []string
|
||||
for _, failure := range []string{"crash", "write"} {
|
||||
s, err := m.get(ctx, info.ID)
|
||||
require.NoError(t, err)
|
||||
message := workspacesdk.ACPMessageRequest{Text: failure}
|
||||
if failure == "crash" {
|
||||
messageTestSession(t, m, info.ID, "exit")
|
||||
} else {
|
||||
s.proc.stdin = failingWriter{s.proc.stdin}
|
||||
_, err = m.Message(ctx, info.ID, message)
|
||||
require.ErrorContains(t, err, "broken harness input")
|
||||
}
|
||||
failed, err := s.Read(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, workspacesdk.ACPSessionStatusError, failed.Session.Status)
|
||||
_, err = m.Message(ctx, info.ID, message)
|
||||
require.NoError(t, err)
|
||||
result := awaitTestSession(t, m, info.ID)
|
||||
require.Equal(t, "answer:"+failure+":other", result.AssistantResponse)
|
||||
raw, err := os.ReadFile(filepath.Join(dir, info.ID.SessionID+".json"))
|
||||
require.NoError(t, err)
|
||||
var native fakeNativeSession
|
||||
require.NoError(t, json.Unmarshal(raw, &native))
|
||||
history = append(history, failure, result.AssistantResponse)
|
||||
require.Equal(t, history, native.History)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedRecoveryPreservesTranscript(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, failure := range []string{"missing", "partial", "unconfigured"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, dir, configs := newTestManager(t, fakeHarnessModeBoth)
|
||||
info := createTestSession(t, m, dir)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
s := holdTestSession(t, m, info.ID)
|
||||
s.proc.cancel()
|
||||
before := awaitTestSession(t, m, info.ID)
|
||||
require.Equal(t, workspacesdk.ACPSessionStatusError, before.Session.Status)
|
||||
require.Equal(t, "started", before.AssistantResponse)
|
||||
_, events, err := m.Watch(ctx, info.ID, nil)
|
||||
require.NoError(t, err)
|
||||
nativeFile := filepath.Join(dir, info.ID.SessionID+".json")
|
||||
configFile := filepath.Join(configs, "fake.json")
|
||||
switch failure {
|
||||
case "missing":
|
||||
require.NoError(t, os.Remove(nativeFile))
|
||||
case "partial":
|
||||
writeConfig(t, nativeFile, fakeNativeSession{Value: "fail-load"})
|
||||
case "unconfigured":
|
||||
require.NoError(t, os.Remove(configFile))
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
}
|
||||
_, err = m.recover(ctx, info.ID)
|
||||
require.ErrorIs(t, err, ErrUnavailable)
|
||||
after, err := m.Read(ctx, info.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, before, after, "failed restoration must not publish partial replay or reset the generation")
|
||||
select {
|
||||
case event, ok := <-events:
|
||||
t.Fatalf("failed recovery changed the subscription: event=%#v open=%t", event, ok)
|
||||
default:
|
||||
}
|
||||
switch failure {
|
||||
case "missing":
|
||||
require.NoFileExists(t, nativeFile)
|
||||
case "unconfigured":
|
||||
writeConfig(t, configFile, map[string]any{"command": fakeCommand(t, fakeHarnessModeBoth)})
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
require.Equal(t, "answer:retry:other", messageTestSession(t, m, info.ID, "retry").AssistantResponse)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionIdentityTuple(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, dir, configs := newTestManager(t, fakeHarnessModeBoth)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
info := createTestSession(t, m, dir)
|
||||
otherDir := t.TempDir()
|
||||
raw, err := os.ReadFile(filepath.Join(dir, info.ID.SessionID+".json"))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(otherDir, info.ID.SessionID+".json"), raw, 0o600))
|
||||
writeConfig(t, filepath.Join(configs, "other.json"), map[string]any{"command": fakeCommand(t, fakeHarnessModeBoth)})
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
for _, id := range []workspacesdk.ACPSessionID{
|
||||
info.ID,
|
||||
{HarnessSlug: "other", WorkingDirectory: dir, SessionID: info.ID.SessionID},
|
||||
{HarnessSlug: "fake", WorkingDirectory: otherDir, SessionID: info.ID.SessionID},
|
||||
} {
|
||||
read, err := m.Read(ctx, id, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, id, read.Session.ID)
|
||||
}
|
||||
}
|
||||
|
||||
type initializationWaitContext struct {
|
||||
context.Context
|
||||
waiting chan<- struct{}
|
||||
}
|
||||
|
||||
func (c initializationWaitContext) Done() <-chan struct{} {
|
||||
c.waiting <- struct{}{}
|
||||
return c.Context.Done()
|
||||
}
|
||||
|
||||
func TestConcurrentRecovery(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mode fakeHarnessMode
|
||||
existing bool
|
||||
}{
|
||||
{name: "recover", mode: fakeHarnessModeBoth, existing: true},
|
||||
{name: "recover_failure", mode: fakeHarnessModeHang, existing: true},
|
||||
{name: "load", mode: fakeHarnessModeBoth},
|
||||
{name: "load_failure", mode: fakeHarnessModeHang},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, dir, _ := newTestManager(t, fakeHarnessModeBoth)
|
||||
info := createTestSession(t, m, dir)
|
||||
failed := messageTestSession(t, m, info.ID, "exit")
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
old, err := m.get(ctx, info.ID)
|
||||
require.NoError(t, err)
|
||||
if !tc.existing {
|
||||
m = restartTestManager(t, m, dir)
|
||||
}
|
||||
setTestHarnessCommand(m, fakeCommand(t, tc.mode))
|
||||
clock := m.clock.(*quartz.Mock)
|
||||
trap := clock.Trap().AfterFunc("acp-timeout")
|
||||
caller, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
canceled := make(chan error, 1)
|
||||
go func() { _, err := m.recover(caller, info.ID); canceled <- err }()
|
||||
call := trap.MustWait(ctx)
|
||||
get := m.recover
|
||||
var events <-chan workspacesdk.ACPEvent
|
||||
if tc.existing {
|
||||
read, stream, err := m.Watch(ctx, info.ID, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, failed, read)
|
||||
events = stream
|
||||
} else {
|
||||
get = m.get
|
||||
}
|
||||
type result struct {
|
||||
session *SessionFSM
|
||||
err error
|
||||
}
|
||||
results, waiting := make(chan result, 10), make(chan struct{}, 10)
|
||||
waitCtx := initializationWaitContext{Context: ctx, waiting: waiting}
|
||||
for range 10 {
|
||||
go func() { s, err := get(waitCtx, info.ID); results <- result{s, err} }()
|
||||
}
|
||||
for range 10 {
|
||||
testutil.RequireReceive(ctx, t, waiting)
|
||||
}
|
||||
cancel()
|
||||
require.ErrorIs(t, testutil.RequireReceive(ctx, t, canceled), context.Canceled)
|
||||
call.MustRelease(ctx)
|
||||
trap.Close()
|
||||
if tc.mode == fakeHarnessModeHang {
|
||||
clock.Advance(setupTimeout).MustWait(ctx)
|
||||
}
|
||||
first := testutil.RequireReceive(ctx, t, results)
|
||||
for range 9 {
|
||||
other := testutil.RequireReceive(ctx, t, results)
|
||||
if tc.mode == fakeHarnessModeHang {
|
||||
require.Same(t, first.err, other.err)
|
||||
} else {
|
||||
require.NoError(t, other.err)
|
||||
require.Same(t, first.session, other.session)
|
||||
}
|
||||
}
|
||||
if tc.mode == fakeHarnessModeHang {
|
||||
require.ErrorIs(t, first.err, ErrUnavailable)
|
||||
setTestHarnessCommand(m, fakeCommand(t, fakeHarnessModeBoth))
|
||||
first.session, first.err = m.recover(ctx, info.ID)
|
||||
}
|
||||
require.NoError(t, first.err)
|
||||
require.NotSame(t, old, first.session)
|
||||
current, err := m.recover(ctx, info.ID)
|
||||
require.NoError(t, err)
|
||||
require.Same(t, first.session, current, "healthy sessions must not be replaced")
|
||||
if tc.existing {
|
||||
notification := sessionNotification(info.ID, "stale")
|
||||
require.ErrorIs(t, (&sessionClient{session: old}).SessionUpdate(ctx, notification), ErrUnavailable)
|
||||
_, err := old.Read(ctx, nil)
|
||||
require.ErrorIs(t, err, ErrUnavailable)
|
||||
requireClosed(ctx, t, events)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -206,8 +206,8 @@ func (s *SessionFSM) watchProcess(logger slog.Logger) {
|
||||
}
|
||||
}
|
||||
|
||||
// ProcessACPUpdate ignores setup notifications while initializing and applies
|
||||
// live updates while running or interrupting.
|
||||
// ProcessACPUpdate applies replayed notifications while initializing and live
|
||||
// updates while running or interrupting.
|
||||
func (s *SessionFSM) ProcessACPUpdate(ctx context.Context, update ACPUpdate) error {
|
||||
unlock, err := s.lock(ctx)
|
||||
if err != nil {
|
||||
@@ -353,23 +353,34 @@ func (s *SessionFSM) Interrupt(ctx context.Context) (workspacesdk.ACPSession, er
|
||||
}
|
||||
|
||||
func (s *SessionFSM) processUpdateLocked(update ACPUpdate) error {
|
||||
if s.info.Status == workspacesdk.ACPSessionStatusInitializing && update.Notification != nil {
|
||||
return nil
|
||||
}
|
||||
if s.info.Status != workspacesdk.ACPSessionStatusRunning && s.info.Status != workspacesdk.ACPSessionStatusInterrupting {
|
||||
initializing := s.info.Status == workspacesdk.ACPSessionStatusInitializing
|
||||
if !initializing && s.info.Status != workspacesdk.ACPSessionStatusRunning && s.info.Status != workspacesdk.ACPSessionStatusInterrupting {
|
||||
return xerrors.Errorf("%w: ACP update in %s", ErrConflict, s.info.Status)
|
||||
}
|
||||
switch {
|
||||
case update.Notification != nil:
|
||||
req := *update.Notification
|
||||
// Before initialization assigns a new session's identity, its setup
|
||||
// notifications do not represent conversation history.
|
||||
if initializing && s.id.SessionID == "" {
|
||||
return nil
|
||||
}
|
||||
if string(req.SessionId) != s.id.SessionID {
|
||||
return xerrors.Errorf("%w: notification session ID mismatch", ErrInvalid)
|
||||
}
|
||||
if req.Update.UserMessageChunk != nil {
|
||||
if initializing {
|
||||
// Expose only the latest turn from session/load history.
|
||||
s.events, s.assistant = nil, nil
|
||||
s.info.Cursor = workspacesdk.ACPCursor{GenerationID: uuid.New()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return s.appendNotificationLocked(req)
|
||||
case update.Prompt != nil:
|
||||
if initializing {
|
||||
return xerrors.Errorf("%w: prompt result while initializing", ErrConflict)
|
||||
}
|
||||
if update.Turn != s.turn {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -71,6 +71,38 @@ func TestSessionClientUpdates(t *testing.T) {
|
||||
require.Len(t, read.Events, 1)
|
||||
}
|
||||
|
||||
func TestSessionClientHistoryReplay(t *testing.T) {
|
||||
t.Parallel()
|
||||
s, _, _ := newRuntimeSession(t, workspacesdk.ACPSessionStatusInitializing)
|
||||
c := &sessionClient{session: s}
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
require.NoError(t, c.SessionUpdate(ctx, sessionNotification(s.id, "old response")))
|
||||
for _, text := range []string{"first user chunk", "second user chunk"} {
|
||||
require.NoError(t, c.SessionUpdate(ctx, acp.SessionNotification{
|
||||
SessionId: acp.SessionId(s.id.SessionID),
|
||||
Update: acp.SessionUpdate{UserMessageChunk: &acp.SessionUpdateUserMessageChunk{Content: acp.TextBlock(text)}},
|
||||
}))
|
||||
}
|
||||
require.NoError(t, c.SessionUpdate(ctx, sessionNotification(s.id, "history")))
|
||||
wrongID := s.id
|
||||
wrongID.SessionID = "other"
|
||||
require.ErrorIs(t, c.SessionUpdate(ctx, sessionNotification(wrongID, "wrong session")), ErrInvalid)
|
||||
before, err := s.Read(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "history", before.AssistantResponse)
|
||||
require.Len(t, before.Events, 1)
|
||||
require.Equal(t, workspacesdk.ACPSessionStatusInitializing, before.Session.Status)
|
||||
require.NoError(t, s.finishInitialization(s.id.SessionID, before.Session.Harness))
|
||||
after, err := s.Read(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "history", after.AssistantResponse)
|
||||
require.Len(t, after.Events, 1)
|
||||
require.Equal(t, before.Events, after.Events)
|
||||
require.Equal(t, workspacesdk.ACPSessionStatusIdle, after.Session.Status)
|
||||
// Once initialized, idle sessions reject live updates through the FSM.
|
||||
require.ErrorIs(t, c.SessionUpdate(ctx, sessionNotification(s.id, "late")), ErrConflict)
|
||||
}
|
||||
|
||||
func TestSessionClientSetupNotifications(t *testing.T) {
|
||||
t.Parallel()
|
||||
s, _, _ := newRuntimeSession(t, workspacesdk.ACPSessionStatusInitializing)
|
||||
|
||||
@@ -33,6 +33,7 @@ func validateSessionRequest(fs afero.Fs, slug, directory string) error {
|
||||
type sessionInitRequest struct {
|
||||
harnessSlug string
|
||||
workingDirectory string
|
||||
nativeID string // Empty creates a new native session.
|
||||
config map[string]string
|
||||
}
|
||||
|
||||
@@ -43,7 +44,7 @@ type sessionRuntimeOptions struct {
|
||||
}
|
||||
|
||||
// startSessionRuntime creates an initializing FSM before launching the harness.
|
||||
// Setup finishes before the idle FSM is published.
|
||||
// Setup and history replay finish before the idle FSM is published.
|
||||
func startSessionRuntime(ctx context.Context, cfg harnessConfig, req sessionInitRequest, opts sessionRuntimeOptions) (session *SessionFSM, err error) {
|
||||
if err := validateSessionRequest(opts.fs, req.harnessSlug, req.workingDirectory); err != nil {
|
||||
return nil, err
|
||||
@@ -51,6 +52,7 @@ func startSessionRuntime(ctx context.Context, cfg harnessConfig, req sessionInit
|
||||
id := workspacesdk.ACPSessionID{
|
||||
HarnessSlug: req.harnessSlug,
|
||||
WorkingDirectory: req.workingDirectory,
|
||||
SessionID: req.nativeID,
|
||||
}
|
||||
info := workspacesdk.ACPSession{
|
||||
ID: id,
|
||||
@@ -90,15 +92,34 @@ func startSessionRuntime(ctx context.Context, cfg harnessConfig, req sessionInit
|
||||
if init.ProtocolVersion != acp.ProtocolVersionNumber {
|
||||
return nil, xerrors.Errorf("%w: unsupported ACP protocol version", ErrUnavailable)
|
||||
}
|
||||
nativeID := req.nativeID
|
||||
harness := harnessInfo(cfg, init)
|
||||
created, err := p.conn.NewSession(setupCtx, acp.NewSessionRequest{Cwd: req.workingDirectory, McpServers: []acp.McpServer{}})
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("%w: create ACP session: %v", ErrUnavailable, err)
|
||||
var options []acp.SessionConfigOption
|
||||
switch {
|
||||
case nativeID == "":
|
||||
created, err := p.conn.NewSession(setupCtx, acp.NewSessionRequest{Cwd: req.workingDirectory, McpServers: []acp.McpServer{}})
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("%w: create ACP session: %v", ErrUnavailable, err)
|
||||
}
|
||||
if created.SessionId == "" {
|
||||
return nil, xerrors.Errorf("%w: harness returned an empty session id", ErrUnavailable)
|
||||
}
|
||||
nativeID, options = string(created.SessionId), created.ConfigOptions
|
||||
case harness.LoadSession:
|
||||
loaded, err := p.conn.LoadSession(setupCtx, acp.LoadSessionRequest{SessionId: acp.SessionId(nativeID), Cwd: req.workingDirectory, McpServers: []acp.McpServer{}})
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("%w: load ACP session: %v", ErrUnavailable, err)
|
||||
}
|
||||
options = loaded.ConfigOptions
|
||||
case harness.ResumeSession:
|
||||
resumed, err := p.conn.ResumeSession(setupCtx, acp.ResumeSessionRequest{SessionId: acp.SessionId(nativeID), Cwd: req.workingDirectory, McpServers: []acp.McpServer{}})
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("%w: resume ACP session: %v", ErrUnavailable, err)
|
||||
}
|
||||
options = resumed.ConfigOptions
|
||||
default:
|
||||
return nil, xerrors.Errorf("%w: harness does not support restoration", ErrUnavailable)
|
||||
}
|
||||
if created.SessionId == "" {
|
||||
return nil, xerrors.Errorf("%w: harness returned an empty session id", ErrUnavailable)
|
||||
}
|
||||
nativeID, options := string(created.SessionId), created.ConfigOptions
|
||||
for _, id := range slices.Sorted(maps.Keys(req.config)) {
|
||||
value := req.config[id]
|
||||
if !validConfig(options, id, value) {
|
||||
|
||||
@@ -96,7 +96,7 @@ func TestRejectedUserOperationsPreserveTranscript(t *testing.T) {
|
||||
|
||||
func TestSessionFSMUpdateValidation(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, status := range []workspacesdk.ACPSessionStatus{workspacesdk.ACPSessionStatusIdle, workspacesdk.ACPSessionStatusRunning, workspacesdk.ACPSessionStatusInterrupting, workspacesdk.ACPSessionStatusError} {
|
||||
for _, status := range []workspacesdk.ACPSessionStatus{workspacesdk.ACPSessionStatusInitializing, workspacesdk.ACPSessionStatusIdle, workspacesdk.ACPSessionStatusRunning, workspacesdk.ACPSessionStatusInterrupting, workspacesdk.ACPSessionStatusError} {
|
||||
t.Run(string(status), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
s, _, _ := newRuntimeSession(t, status)
|
||||
|
||||
Reference in new issue
Block a user