Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237package acp
import ( "bytes" "context" "encoding/json" "errors" "io" "testing" "time"
"albedo/cli/internal/app" "albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol")
const lifecycleSession = "01a0fcea-2b00-7000-8000-000000000001"
// lifecycleBackend answers the requests that attach, release and delete a// session, and records what each one did.type lifecycleBackend struct { *fakeBackend onResume func(context.Context) error releases chan string deletes chan string releaseErr error deleteErr error}
func (b *lifecycleBackend) Catalog(context.Context) (app.ACPSettings, error) { return app.ACPSettings{Efforts: map[string][]string{}, Windows: map[string][]int{}}, nil}
func (b *lifecycleBackend) Refresh(_ context.Context, _ string, settings app.ACPSettings) (app.ACPSettings, error) { return settings, nil}
func (b *lifecycleBackend) Resume(ctx context.Context, id, _ string, _ []protocol.ACPMCPServer) (protocol.ACPAttachment, error) { if b.onResume != nil { if err := b.onResume(ctx); err != nil { return protocol.ACPAttachment{}, err } } return protocol.ACPAttachment{SessionID: id, Lease: protocol.ACPLease{HeartbeatMs: 60_000, LeaseMs: 120_000}}, nil}
func (b *lifecycleBackend) Release(_ context.Context, id string) error { b.releases <- id return b.releaseErr}
func (b *lifecycleBackend) Delete(_ context.Context, id string) error { b.deletes <- id return b.deleteErr}
// Observer is never streamed here: the adapter's watch seam replaces the stream.func (b *lifecycleBackend) Observer(string, protocol.Cursor) *daemon.ChatClient { return &daemon.ChatClient{}}
func testAdapter(t *testing.T) (*adapter, *lifecycleBackend) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) backend := &lifecycleBackend{ fakeBackend: &fakeBackend{written: make(chan []byte, 64)}, releases: make(chan string, 8), deletes: make(chan string, 8), } a := &adapter{initialized: true, ctx: ctx, cancel: cancel, backend: backend, sessions: map[string]*session{}, diagnostics: io.Discard, writer: newWriter(capturedWriter{backend.written})} a.watch = func(ctx context.Context, _ func(daemon.StreamEvent) error, _ func()) error { <-ctx.Done() return ctx.Err() } go a.writer.run(ctx) return a, backend}
func lifecycleParams(sessionID string) json.RawMessage { params, err := json.Marshal(map[string]any{"sessionId": sessionID, "cwd": "/workspace", "mcpServers": []any{}}) if err != nil { panic(err) } return params}
func readResponse(t *testing.T, written <-chan []byte, id float64) map[string]any { t.Helper() deadline := time.After(30 * time.Second) for { select { case data := <-written: var message map[string]any if json.Unmarshal(bytes.TrimSpace(data), &message) != nil { t.Fatalf("unreadable message: %s", data) } if message["id"] == id { return message } case <-deadline: t.Fatalf("no response for %v", id) } }}
func attachSession(t *testing.T, a *adapter, backend *lifecycleBackend) { t.Helper() a.handle(request{ID: json.RawMessage(`1`), Method: methodResume, Params: lifecycleParams(lifecycleSession)}, "test") if response := readResponse(t, backend.written, 1); response["error"] != nil { t.Fatalf("resume failed: %v", response["error"]) } if a.attached(lifecycleSession) == nil { t.Fatal("resume did not attach the session") }}
func TestAFailedDeleteKeepsTheSessionAttached(t *testing.T) { a, backend := testAdapter(t) attachSession(t, a, backend) backend.deleteErr = errors.New("deletion is incomplete") a.handle(request{ID: json.RawMessage(`2`), Method: methodDelete, Params: lifecycleParams(lifecycleSession)}, "test") if response := readResponse(t, backend.written, 2); response["error"] == nil { t.Fatalf("a refused delete answered success: %v", response) } if id := receive(t, backend.deletes); id != lifecycleSession { t.Fatalf("deleted %q", id) } if a.attached(lifecycleSession) == nil { t.Fatal("a refused delete detached the session anyway") }}
func TestASuccessfulDeleteDetachesTheSession(t *testing.T) { a, backend := testAdapter(t) attachSession(t, a, backend) a.handle(request{ID: json.RawMessage(`2`), Method: methodDelete, Params: lifecycleParams(lifecycleSession)}, "test") if response := readResponse(t, backend.written, 2); response["error"] != nil { t.Fatalf("delete failed: %v", response["error"]) } if id := receive(t, backend.deletes); id != lifecycleSession { t.Fatalf("deleted %q", id) } if a.attached(lifecycleSession) != nil { t.Fatal("a deleted session stayed attached") }}
func TestCloseWaitsForAnInFlightResume(t *testing.T) { a, backend := testAdapter(t) entered, release := make(chan struct{}), make(chan struct{}) backend.onResume = func(context.Context) error { close(entered) <-release return nil } a.handle(request{ID: json.RawMessage(`1`), Method: methodResume, Params: lifecycleParams(lifecycleSession)}, "test") <-entered a.handle(request{ID: json.RawMessage(`2`), Method: methodClose, Params: lifecycleParams(lifecycleSession)}, "test") select { case id := <-backend.releases: t.Fatalf("close released %q while its resume was still running", id) case <-time.After(150 * time.Millisecond): } close(release) readResponse(t, backend.written, 1) readResponse(t, backend.written, 2) if id := receive(t, backend.releases); id != lifecycleSession { t.Fatalf("released %q", id) } if a.attached(lifecycleSession) != nil { t.Fatal("a closed session stayed attached") }}
func TestLoadFailsWhenTheStreamNeverSubscribes(t *testing.T) { a, _ := testAdapter(t) a.watch = func(context.Context, func(daemon.StreamEvent) error, func()) error { return errors.New("connection refused") } current := &session{adapter: a, ctx: a.ctx, stop: func() {}, id: lifecycleSession, watch: a.watch, reconciler: newReconciler()} current.observation = buffering current.start() err := current.load(request{ID: json.RawMessage(`1`)}) failure, ok := errors.AsType[*rpcError](err) if !ok || failure.Data["reason"] != "observation_uncertain" { t.Fatalf("load without a stream: %v", err) }}
func TestCancelDuringReconnectAndRetryAfterStreamFailure(t *testing.T) { a, backend := testAdapter(t) ctx, cancel := context.WithCancel(a.ctx) cancel() a.sessions[lifecycleSession] = &session{ sessionState: sessionState{observation: disconnected}, adapter: a, id: lifecycleSession, cwd: "/workspace", ctx: ctx, stop: cancel, } entered := make(chan struct{}, 1) fail := make(chan struct{}) a.watch = func(ctx context.Context, _ func(daemon.StreamEvent) error, _ func()) error { entered <- struct{}{} select { case <-fail: return errors.New("stream rejected") case <-ctx.Done(): return ctx.Err() } } params, err := json.Marshal(map[string]any{"sessionId": lifecycleSession, "prompt": []map[string]string{{"type": "text", "text": "hello"}}}) if err != nil { t.Fatal(err) } prompt := request{ID: json.RawMessage("1"), Method: methodPrompt, Params: params} a.handle(prompt, "") select { case <-entered: case <-time.After(30 * time.Second): t.Fatal("reconnect did not start") } a.handle(request{Method: methodCancel, Params: lifecycleParams(lifecycleSession)}, "") result := readResponse(t, backend.written, 1)["result"] if result == nil || result.(map[string]any)["stopReason"] != "cancelled" { t.Fatalf("cancelled prompt returned %v", result) } close(fail) a.workers.Wait() receive(t, backend.releases) prompt.ID = json.RawMessage("2") a.handle(prompt, "") a.workers.Wait() receive(t, backend.releases) if failure := readResponse(t, backend.written, 2)["error"]; failure == nil { t.Fatal("admitted prompt without a working stream") }}