d27c682c19
Add a Kagi source that indexes Assistant conversations with the subscriber
session token, one entry per thread.
- Read the token from KAGI_SESSION_TOKEN, KAGI_SESSION_TOKEN_FILE, or the
kagi-cli config ([auth] session_token); accept full session-link URLs.
- List conversations through /api/conversations, load each thread via
/api/v2/conversations/{id}/init, and walk older turn pages through the
branch turns endpoint.
- Render one markdown document per thread (stable fingerprint by conversation
UUID, content hash for versioning), keeping the newest turns when a thread
exceeds the body budget.
- Skip re-fetching threads whose updated_at has not moved during this process.
- Wire the 30-minute watcher ticker + sync status, the `knox kagi` command,
the full ingest sweep, MCP scope filtering, thread anchoring, and web links.
309 lines
8.6 KiB
Go
309 lines
8.6 KiB
Go
package ingest
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// kagiServer stands in for the Assistant v2 API: a paged conversation list and
|
|
// an init call whose oldest page is behind a branch-pagination cursor.
|
|
type kagiServer struct {
|
|
mu sync.Mutex
|
|
baseURL string
|
|
token string
|
|
updatedAt string
|
|
listCalls int
|
|
afterIDs []string
|
|
initCalls int
|
|
}
|
|
|
|
func newKagiServer(t *testing.T, token string) *kagiServer {
|
|
t.Helper()
|
|
// The updated_at cache is process-wide; isolate each test's fixture.
|
|
kagiSeen.Lock()
|
|
kagiSeen.m = map[string]string{}
|
|
kagiSeen.Unlock()
|
|
ks := &kagiServer{token: token, updatedAt: "2026-11-01T10:00:00Z"}
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/api/conversations", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Cookie") != "kagi_session="+ks.token {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
ks.mu.Lock()
|
|
ks.listCalls++
|
|
ks.afterIDs = append(ks.afterIDs, r.URL.Query().Get("after_id"))
|
|
updated := ks.updatedAt
|
|
ks.mu.Unlock()
|
|
|
|
if r.URL.Query().Get("after_id") == "" {
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"items": []any{map[string]any{
|
|
"conversation": map[string]any{
|
|
"uuid": "conv-1", "title": "ESP32 clocks", "created_at": "2026-10-30T09:00:00Z",
|
|
"updated_at": updated, "is_saved": true, "model_name": "claude",
|
|
},
|
|
"snippet": "a stable list snippet",
|
|
}},
|
|
"has_more": true,
|
|
})
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"items": []any{map[string]any{
|
|
"uuid": "conv-2", "title": "Idle thought", "created_at": "2026-10-31T09:00:00Z",
|
|
"updated_at": "2026-10-31T09:00:00Z",
|
|
}},
|
|
"has_more": false,
|
|
})
|
|
})
|
|
|
|
mux.HandleFunc("/api/v2/conversations/conv-1/init", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Cookie") != "kagi_session="+ks.token {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
ks.mu.Lock()
|
|
ks.initCalls++
|
|
ks.mu.Unlock()
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"conversation": map[string]any{
|
|
"uuid": "conv-1", "title": "ESP32 clocks", "created_at": "2026-10-30T09:00:00Z",
|
|
"updated_at": ks.updatedAt, "is_saved": true, "model_name": "claude",
|
|
},
|
|
"active_branch": map[string]any{"uuid": "branch-1", "is_default": true},
|
|
"turns": []any{
|
|
map[string]any{"uuid": "turn-2", "role": "assistant", "content": "Use the GT911 stub.", "created_at": "2026-10-30T09:01:00Z"},
|
|
},
|
|
"turns_has_more": true,
|
|
})
|
|
})
|
|
|
|
mux.HandleFunc("/api/v2/conversations/conv-2/init", func(w http.ResponseWriter, r *http.Request) {
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"conversation": map[string]any{
|
|
"uuid": "conv-2", "title": "Idle thought", "created_at": "2026-10-31T09:00:00Z",
|
|
"updated_at": "2026-10-31T09:00:00Z",
|
|
},
|
|
"turns": []any{
|
|
map[string]any{"uuid": "turn-3", "role": "user", "content": "a half-formed idea"},
|
|
},
|
|
})
|
|
})
|
|
|
|
mux.HandleFunc("/api/v2/branches/branch-1/turns", func(w http.ResponseWriter, r *http.Request) {
|
|
ks.mu.Lock()
|
|
ks.afterIDs = append(ks.afterIDs, "before="+r.URL.Query().Get("before"))
|
|
ks.mu.Unlock()
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"turns": []any{
|
|
map[string]any{"uuid": "turn-1", "role": "user", "content": "How do I initialize the touch panel?", "created_at": "2026-10-30T09:00:00Z"},
|
|
},
|
|
"has_more": false,
|
|
})
|
|
})
|
|
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
|
|
ks.baseURL = srv.URL
|
|
return ks
|
|
}
|
|
|
|
func (ks *kagiServer) ingester() *KagiIngester {
|
|
return &KagiIngester{
|
|
Version: "kagi/v1",
|
|
BaseURL: ks.baseURL,
|
|
Token: ks.token,
|
|
MaxThreads: 500,
|
|
client: &http.Client{},
|
|
}
|
|
}
|
|
|
|
func TestKagiIngestsThreadsWithOlderTurns(t *testing.T) {
|
|
ks := newKagiServer(t, "token-1")
|
|
results, err := ks.ingester().IngestAll()
|
|
if err != nil {
|
|
t.Fatalf("IngestAll: %v", err)
|
|
}
|
|
if len(results) != 2 {
|
|
t.Fatalf("want 2 threads, got %d", len(results))
|
|
}
|
|
|
|
var conv1 *IngestResult
|
|
for _, r := range results {
|
|
if r.Provenance["conversation_id"] == "conv-1" {
|
|
conv1 = r
|
|
}
|
|
}
|
|
if conv1 == nil {
|
|
t.Fatal("conv-1 not ingested")
|
|
}
|
|
if !strings.Contains(conv1.Content, "## User") || !strings.Contains(conv1.Content, "How do I initialize the touch panel?") {
|
|
t.Fatalf("older user turn missing from body:\n%s", conv1.Content)
|
|
}
|
|
if !strings.Contains(conv1.Content, "## Assistant") || !strings.Contains(conv1.Content, "GT911 stub") {
|
|
t.Fatalf("assistant turn missing from body:\n%s", conv1.Content)
|
|
}
|
|
if conv1.Title != "ESP32 clocks" {
|
|
t.Fatalf("title = %q", conv1.Title)
|
|
}
|
|
if conv1.Summary != "a stable list snippet" {
|
|
t.Fatalf("summary = %q", conv1.Summary)
|
|
}
|
|
if conv1.Confidence != 0.9 {
|
|
t.Fatalf("saved thread confidence = %v", conv1.Confidence)
|
|
}
|
|
if conv1.SourceID != "kagi" || conv1.ContentType != "assistant/thread" {
|
|
t.Fatalf("source = %s/%s", conv1.SourceID, conv1.ContentType)
|
|
}
|
|
if !strings.HasSuffix(conv1.SourcePath, "/chat/conv-1") {
|
|
t.Fatalf("source path = %q", conv1.SourcePath)
|
|
}
|
|
if conv1.SourceUpdated == 0 {
|
|
t.Fatal("updated_at was not parsed")
|
|
}
|
|
|
|
// The list must have followed after_id once, and turns pagination once.
|
|
if len(ks.afterIDs) < 3 {
|
|
t.Fatalf("expected list pagination and turn pagination, got %v", ks.afterIDs)
|
|
}
|
|
if ks.afterIDs[1] != "conv-1" {
|
|
t.Fatalf("after_id = %q", ks.afterIDs[1])
|
|
}
|
|
}
|
|
|
|
func TestKagiSkipsUnchangedButFollowsEdits(t *testing.T) {
|
|
ks := newKagiServer(t, "token-2")
|
|
ing := ks.ingester()
|
|
|
|
first, err := ing.IngestAll()
|
|
if err != nil {
|
|
t.Fatalf("first sweep: %v", err)
|
|
}
|
|
if len(first) != 2 {
|
|
t.Fatalf("first sweep: want 2, got %d", len(first))
|
|
}
|
|
before := ks.initCalls
|
|
|
|
second, err := ing.IngestAll()
|
|
if err != nil {
|
|
t.Fatalf("second sweep: %v", err)
|
|
}
|
|
if len(second) != 0 {
|
|
t.Fatalf("second sweep: everything was cached, got %d", len(second))
|
|
}
|
|
if ks.initCalls != before {
|
|
t.Fatalf("unchanged thread was re-fetched (%d -> %d)", before, ks.initCalls)
|
|
}
|
|
|
|
// A new turn bumps updated_at: the thread must be re-read and versioned.
|
|
ks.mu.Lock()
|
|
ks.updatedAt = "2026-11-02T12:00:00Z"
|
|
ks.mu.Unlock()
|
|
third, err := ing.IngestAll()
|
|
if err != nil {
|
|
t.Fatalf("third sweep: %v", err)
|
|
}
|
|
var edited *IngestResult
|
|
for _, r := range third {
|
|
if r.Provenance["conversation_id"] == "conv-1" {
|
|
edited = r
|
|
}
|
|
}
|
|
if edited == nil {
|
|
t.Fatal("edited thread was skipped")
|
|
}
|
|
if edited.Fingerprint != first[0].Fingerprint && edited.Fingerprint != first[1].Fingerprint {
|
|
t.Fatal("fingerprint changed for the same conversation")
|
|
}
|
|
var sameFP bool
|
|
for _, r := range first {
|
|
if r.Fingerprint == edited.Fingerprint && r.ContentHash == edited.ContentHash {
|
|
sameFP = true
|
|
}
|
|
}
|
|
if sameFP {
|
|
t.Fatal("content hash did not change after an edit")
|
|
}
|
|
}
|
|
|
|
func TestKagiAuthFailureIsExplicit(t *testing.T) {
|
|
ks := newKagiServer(t, "token-3")
|
|
ing := ks.ingester()
|
|
ing.Token = "expired"
|
|
_, err := ing.IngestAll()
|
|
if err == nil || !strings.Contains(err.Error(), "session token") {
|
|
t.Fatalf("want session-token error, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestKagiLongThreadKeepsNewestTurns(t *testing.T) {
|
|
turns := make([]kagiTurn, 0, 16)
|
|
for i := 0; i < 16; i++ {
|
|
role := "user"
|
|
marker := ""
|
|
if i == 0 {
|
|
marker = "OLDEST-MARKER "
|
|
}
|
|
if i%2 == 1 {
|
|
role = "assistant"
|
|
}
|
|
turns = append(turns, kagiTurn{UUID: "t", Role: role, Content: marker + strings.Repeat("x", 9000)})
|
|
}
|
|
turns[len(turns)-1].Content = "NEWEST-MARKER " + strings.Repeat("y", 9000)
|
|
|
|
out := renderKagiThread(kagiConversation{Title: "long thread"}, turns)
|
|
if !strings.Contains(out, "NEWEST-MARKER") {
|
|
t.Fatal("newest turn was dropped")
|
|
}
|
|
if strings.Contains(out, "OLDEST-MARKER") {
|
|
t.Fatal("oldest turn survived truncation")
|
|
}
|
|
if !strings.Contains(out, "older turns truncated") {
|
|
t.Fatal("truncation marker missing")
|
|
}
|
|
if n := len([]rune(out)); n > kagiMaxBodyRunes+200 {
|
|
t.Fatalf("body not bounded: %d runes", n)
|
|
}
|
|
}
|
|
|
|
func TestKagiNormalizesSessionLink(t *testing.T) {
|
|
cases := map[string]string{
|
|
"abc123": "abc123",
|
|
"https://kagi.com/search?token=abc123": "abc123",
|
|
"https://kagi.com/search?token=abc%2F123&x=1": "abc/123",
|
|
" wrapped ": "wrapped",
|
|
}
|
|
for in, want := range cases {
|
|
if got := normalizeKagiToken(in); got != want {
|
|
t.Errorf("normalizeKagiToken(%q) = %q, want %q", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestKagiTokenFromCLIConfig(t *testing.T) {
|
|
body := `# kagi-cli config
|
|
[mail]
|
|
session_token = "not-this"
|
|
|
|
[auth]
|
|
api_key = "key"
|
|
session_token = "the-session"
|
|
|
|
[profiles.work.auth]
|
|
session_token = "profile-session"
|
|
`
|
|
if got := kagiTokenFromTOML(body); got != "the-session" {
|
|
t.Fatalf("token = %q", got)
|
|
}
|
|
if got := kagiTokenFromTOML("[profiles.work.auth]\nsession_token = \"x\"\n"); got != "" {
|
|
t.Fatalf("profile token leaked: %q", got)
|
|
}
|
|
}
|