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
63 changes: 62 additions & 1 deletion agent/x/agentacp/fake_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,23 @@ func TestACPHarness(t *testing.T) {
}

type fakeNativeSession struct {
Value string `json:"value"`
History []string `json:"history"`
Value string `json:"value"`
}

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"
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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
}

Expand All @@ -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")
Expand Down
5 changes: 4 additions & 1 deletion agent/x/agentacp/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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),
}
Expand Down Expand Up @@ -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
}
Expand Down
22 changes: 17 additions & 5 deletions agent/x/agentacp/manager_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
91 changes: 82 additions & 9 deletions agent/x/agentacp/manager_sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -118,22 +129,84 @@ 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
}
if err := ctx.Err(); err != nil {
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)
})
}
return s, nil
m.mu.Unlock()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-attempt.done:
return attempt.fsm, attempt.err
}
}

// 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
}
Loading
Loading