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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252package acp
import ( "context" "encoding/json" "testing" "time"
"albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol")
func writtenUpdates(t *testing.T, s *session, backend *fakeBackend) []map[string]any { t.Helper() deadline := time.Now().Add(3 * time.Second) for { <-s.adapter.writer.flush() if len(backend.written) > 0 { break } if time.Now().After(deadline) { t.Fatal("no writer output") } time.Sleep(5 * time.Millisecond) } var messages []map[string]any for len(backend.written) > 0 { var message map[string]any if err := json.Unmarshal(<-backend.written, &message); err != nil { t.Fatal(err) } messages = append(messages, message) } return messages}
func updateOf(t *testing.T, message map[string]any) map[string]any { t.Helper() if message["method"] != "session/update" { t.Fatalf("not a session update: %v", message) } params, ok := message["params"].(map[string]any) if !ok { t.Fatalf("no params: %v", message) } update, ok := params["update"].(map[string]any) if !ok { t.Fatalf("no update: %v", message) } return update}
func TestClientCompactionCapability(t *testing.T) { for _, test := range []struct { params string want bool }{ {`{}`, false}, {`{"clientCapabilities":{}}`, false}, {`{"clientCapabilities":{"session":{}}}`, false}, {`{"clientCapabilities":{"session":{"compaction":null}}}`, false}, {`{"clientCapabilities":{"session":{"compaction":{}}}}`, true}, } { if got := decodeClientCapabilities(json.RawMessage(test.params)).compaction; got != test.want { t.Errorf("capability %s = %v, want %v", test.params, got, test.want) } }}
func TestUsageUpdateCarriesTokensWindowAndCost(t *testing.T) { s, backend := testSession(t) s.usage.window.phase = windowKnown s.usage.window.tokens = 200000 prompt, total := 53000, 55000 s.usageLocked(&daemon.Usage{ PromptTokens: &prompt, TotalTokens: &total, Spent: &daemon.Cost{Usd: 0.045, Basis: daemon.BasisCharged}, }) messages := writtenUpdates(t, s, backend) if len(messages) != 1 { t.Fatalf("messages: %d", len(messages)) } update := updateOf(t, messages[0]) if update["sessionUpdate"] != "usage_update" || update["used"] != float64(prompt) || update["size"] != float64(200000) { t.Fatalf("usage update: %v", update) } cost, ok := update["cost"].(map[string]any) if !ok || cost["amount"] != 0.045 || cost["currency"] != "USD" { t.Fatalf("cost: %v", update["cost"]) }}
func TestUsageUpdateUsesCreditsForCountedCost(t *testing.T) { s, backend := testSession(t) s.usage.window.phase = windowKnown s.usage.window.tokens = 4096 s.usageLocked(&daemon.Usage{Spent: &daemon.Cost{Usd: 12, Basis: daemon.BasisCounted}}) update := updateOf(t, writtenUpdates(t, s, backend)[0]) cost, ok := update["cost"].(map[string]any) if !ok || cost["currency"] != "credits" { t.Fatalf("cost: %v", update["cost"]) }}
func TestCompactionUpdateNeedsClientCapability(t *testing.T) { s, backend := testSession(t) s.compacted(daemon.StreamEvent{Type: daemon.EventCompacted, Sequence: 7, Summary: "kept"}) <-s.adapter.writer.flush() if len(backend.written) != 0 || decodeClientCapabilities(json.RawMessage(`{}`)).compaction { t.Fatal("compaction update sent without capability") }
s, backend = testSession(t) s.compactionEnabled = true s.compacted(daemon.StreamEvent{Type: daemon.EventCompacted, Sequence: 9, Summary: " kept "}) update := updateOf(t, writtenUpdates(t, s, backend)[0]) if update["sessionUpdate"] != "compaction_update" || update["status"] != "completed" || update["compactionId"] != "acp-compaction-9" { t.Fatalf("compaction update: %v", update) } summary, ok := update["summary"].([]any) if !ok || len(summary) != 1 { t.Fatalf("summary: %v", update["summary"]) } block, ok := summary[0].(map[string]any) if !ok || block["text"] != "kept" || block["type"] != "text" { t.Fatalf("summary block: %v", summary[0]) }}
func TestLoadReplaysCompactionBoundaryWithADurableID(t *testing.T) { s, backend := testSession(t) s.compactionEnabled = true if err := s.replay(daemon.StreamEvent{ Type: daemon.EventCompacted, EntryID: "compaction-entry", Position: 7, Summary: "kept context", Replayed: true, }); err != nil { t.Fatal(err) } update := updateOf(t, writtenUpdates(t, s, backend)[0]) if update["sessionUpdate"] != "compaction_update" || update["status"] != "completed" { t.Fatalf("replayed compaction update: %v", update) } if update["compactionId"] != "acp-compaction-entry-compaction-entry" { t.Fatalf("replayed compaction id: %v", update["compactionId"]) }}
func TestCompactionIDIncludesDaemonGeneration(t *testing.T) { s, backend := testSession(t) s.compactionEnabled = true s.cursor.Generation = "generation-two" s.compacted(daemon.StreamEvent{Type: daemon.EventCompacted, Sequence: 9, Summary: "kept"}) update := updateOf(t, writtenUpdates(t, s, backend)[0]) if update["compactionId"] != "acp-compaction-generation-two-9" { t.Fatalf("compaction id: %v", update["compactionId"]) }}
type compactBackend struct { *fakeBackend result daemon.CompactionResult called chan string gate chan struct{}}
func (b *compactBackend) Compact(_ context.Context, id string) (daemon.CompactionResult, error) { b.called <- id if b.gate != nil { <-b.gate } return b.result, nil}
func TestUnchangedCompactionAcknowledgesThePrompt(t *testing.T) { s, backend := testSession(t) b := &compactBackend{fakeBackend: backend, result: daemon.CompactionResult{State: "unchanged"}, called: make(chan string, 1)} s.adapter.backend = b s.prompt(request{ID: json.RawMessage("8")}, []json.RawMessage{json.RawMessage(`{"type":"text","text":"/compact"}`)}) <-b.called message := writtenUpdates(t, s, backend)[0] result, ok := message["result"].(map[string]any) if !ok || result["stopReason"] != "end_turn" { t.Fatalf("unchanged compaction should be acknowledged: %v", message) }}
func TestFailedCompactionIsReportedInTheTurn(t *testing.T) { s, backend := testSession(t) s.compactionEnabled = true b := &compactBackend{fakeBackend: backend, result: daemon.CompactionResult{State: "failed", Failure: &protocol.SafeReason{Detail: "no conversation history to compact"}}, called: make(chan string, 1)} s.adapter.backend = b s.prompt(request{ID: json.RawMessage("9")}, []json.RawMessage{json.RawMessage(`{"type":"text","text":"/compact"}`)}) <-b.called messages := writtenUpdates(t, s, backend) // The writer can deliver the failed update before enqueueing the response. if len(messages) == 1 && messages[0]["method"] == "session/update" { messages = append(messages, readResponse(t, backend.written, 9)) } last := messages[len(messages)-1] result, ok := last["result"].(map[string]any) if !ok || result["stopReason"] != "end_turn" { t.Fatalf("failed compaction should still end the turn: %v", last) } found := false for _, message := range messages { if message["method"] != "session/update" { continue } update := updateOf(t, message) if update["sessionUpdate"] == "compaction_update" && update["status"] == "failed" { found = true } } if !found { t.Fatalf("no failed compaction update: %v", messages) }}
func TestFailedCompactionNeedsCapabilityForUpdate(t *testing.T) { s, backend := testSession(t) b := &compactBackend{fakeBackend: backend, result: daemon.CompactionResult{State: "failed", Failure: &protocol.SafeReason{Detail: "no conversation history to compact"}}, called: make(chan string, 1)} s.adapter.backend = b s.prompt(request{ID: json.RawMessage("11")}, []json.RawMessage{json.RawMessage(`{"type":"text","text":"/compact"}`)}) <-b.called messages := writtenUpdates(t, s, backend) for _, message := range messages { if message["method"] != "session/update" { continue } update := updateOf(t, message) if update["sessionUpdate"] == "compaction_update" { t.Fatalf("compaction update sent without capability: %v", update) } }}
func TestCancelAnswersAPendingCompaction(t *testing.T) { s, backend := testSession(t) b := &compactBackend{fakeBackend: backend, result: daemon.CompactionResult{State: "compacted"}, called: make(chan string, 1), gate: make(chan struct{})} s.adapter.backend = b s.prompt(request{ID: json.RawMessage("10")}, []json.RawMessage{json.RawMessage(`{"type":"text","text":"/compact"}`)}) <-b.called s.cancelPrompt() close(b.gate) message := writtenUpdates(t, s, backend)[0] result, ok := message["result"].(map[string]any) if !ok || result["stopReason"] != "cancelled" { t.Fatalf("cancel should answer /compact: %v", message) }}