sessions: Kimi Code sessions open as a transcript (#2056)

infinitr0us: a Kimi Code session on the Sessions page had no transcript
to open. HasTranscript now lists kimi, and kimiTranscript reads the
session's main wire.jsonl:
- protocol 1.4/1.5: turn.prompt and turn.steer (a prompt not from the
  user, a skill's activation or a background task's news, is folded as
  context), and the loop events content.part (text, think), tool.call
  and tool.result, a result named for its call. These are there for
  every session, finished or running; agent.message.appended (1.5, only
  at a turn's end) and the timed context.append_message records say the
  same again and are passed over.
- kimi-cli imports (1.0, and the head of a ses_* session Kimi Code
  reopened): the untimed context.append_message records, with an
  assistant's toolCalls in both shapes (name/arguments and OpenAI's
  function.{name,arguments}).
Search and markdown export read the same parts.

Run:
- TestKimiCodeTranscript on the #1607 reporter's wire files in testdata
  (1.4, a cancelled 1.4, an early 1.5 started by a skill, a failed 1.5,
  a kimi-cli import), and TestKimiCodeTranscriptOrder on a synthetic
  file in the same record shapes, exact part order plus SearchSession.
- Broken by hand: kimi out of HasTranscript fails both tests; reading
  the timed context.append_message records fails both (user/text 9,
  not 3).
- A nogui build's `magpie web` under a sandbox HOME, KIMI_CODE_HOME on
  the reporter's whole zip (8 sessions, the July subagent session and
  a reopened ses_* among them): all 8 listed with a transcript;
  /api/sessions/transcript gave 105, 13 and 205 parts for June, the
  reopened ses_* and July; the markdown export worked.
- gofmt -l clean; go vet darwin, linux -tags nogui, windows;
  go test -tags nogui ./internal/sessions/ ./internal/gui/.

Not tried: a live Kimi Code session on this machine (none here; the kimi
installed is kimi-cli 1.52.0), the GUI's look of the transcript, WSL.
A subagent's own wire file isn't shown; the main agent's is.
This commit is contained in:
yetone
2026-10-14 08:28:52 +08:00
parent 75cbc7e1e5
commit 2d8f2a86a5
4 changed files with 336 additions and 3 deletions
+7 -1
View File
@@ -328,7 +328,13 @@ in [`cursor_editor_test.go`](../../internal/sessions/cursor_editor_test.go).
Messages without tokens or an active-time estimate still count as sessions
in the overview. Cursor and OpenCode conversations can be opened through
the existing transcript API, including CLI reasoning and tool calls. When the selected date range is empty but
the existing transcript API, including CLI reasoning and tool calls. So can
Kimi Code's main agent, from its `wire.jsonl`: a turn's `turn.prompt` and
loop events from protocol 1.4 on (so a turn still running shows), and the
untimed `context.append_message` records of a session imported from
kimi-cli; Kimi Code's own timed messages repeat those and are skipped
([`transcript_kimi.go`](../../internal/sessions/transcript_kimi.go),
`TestKimiCodeTranscript`). When the selected date range is empty but
matching history exists, Usage offers **All sessions**, preserving the agent,
model, folder and search filters. See `sessions-empty-range.test.cjs`.
+4 -2
View File
@@ -30,7 +30,7 @@ var ErrNoTranscript = errors.New("this agent's conversations can't be shown")
// transcript.
func HasTranscript(agent string) bool {
switch agent {
case "claude", "qoder", "qoder-cn", "codex", "pi", "omp", "cursor", "opencode":
case "claude", "qoder", "qoder-cn", "codex", "pi", "omp", "cursor", "opencode", "kimi":
return true
}
return false
@@ -67,7 +67,7 @@ func readTranscript(s Session, add func(bool, Part) bool) error {
}
// readTranscriptOf is readTranscript decoding only the lines keep says yes
// to, where a line stands alone (Claude's, Codex's); Pi's lines are a tree,
// to, where a line stands alone (Claude's, Codex's, Kimi's); Pi's lines are a tree,
// read whole.
func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bool) error {
whole := Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}
@@ -80,6 +80,8 @@ func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bo
return codexContentOf(whole, keep, add)
case "pi", "omp":
return piTranscript(s.Path, add)
case "kimi":
return kimiTranscript(s.Path, keep, add)
default:
return claudeContentOf(whole, keep, add)
}
+195
View File
@@ -0,0 +1,195 @@
package sessions
import (
"bytes"
"cmp"
"encoding/json"
)
// Kimi Code's conversation, read from a session's main wire.jsonl (#2056,
// infinitr0us). From protocol 1.4 on a turn is its turn.prompt (the user's
// input; one whose origin isn't the user, a skill's activation or a
// subagent's system_trigger, is shown folded) and the loop events written as it
// runs: content.part (text or think), tool.call (name, args, toolCallId)
// and tool.result (toolCallId, result.output). These alone are read, since
// they are there for every 1.4 and 1.5 session, finished or still running:
// Kimi Code 2.1.1 writes a turn's agent.message.appended only as it ends,
// and older 1.5 sessions have none. A turn.steer is what came in during a
// turn: the user's words, or a background task's news.
//
// What a session imported from the Python kimi-cli said is in
// context.append_message records with no time (protocol 1.0, and the head
// of a ses_* session Kimi Code opened again): role user, assistant or tool,
// text and think blocks, an assistant's toolCalls ({id, name, arguments} or
// OpenAI's {id, function: {name, arguments}}) and a tool message's
// toolCallId. Kimi Code's own context.append_message records carry a time
// and say again what the prompt and loop events said, so they are passed
// over.
//
// A fork's file starts with its source's records, copied up to its forked
// marker; they are read too, as the conversation the fork goes on from.
type kimiLine struct {
Type string `json:"type"`
Time int64 `json:"time"`
Input []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"input"`
Origin struct {
Kind string `json:"kind"`
} `json:"origin"`
Event struct {
Type string `json:"type"`
Name string `json:"name"`
ToolCallID string `json:"toolCallId"`
Args json.RawMessage `json:"args"`
Part struct {
Type string `json:"type"`
Text string `json:"text"`
Think string `json:"think"`
} `json:"part"`
Result struct {
Output json.RawMessage `json:"output"`
} `json:"result"`
} `json:"event"`
Message struct {
Role string `json:"role"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
Think string `json:"think"`
} `json:"content"`
ToolCalls []struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
Function struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
} `json:"function"`
} `json:"toolCalls"`
ToolCallID string `json:"toolCallId"`
} `json:"message"`
}
var kimiSaid = [][]byte{[]byte(`"turn.prompt"`), []byte(`"turn.steer"`), []byte(`"content.part"`), []byte(`"tool.call"`), []byte(`"tool.result"`), []byte(`"context.append_message"`)}
// kimiTranscript tells add what a Kimi Code session said, in the order of
// its main wire file, decoding only the lines keep says yes to.
func kimiTranscript(path string, keep func([]byte) bool, add func(bool, Part) bool) error {
names := map[string]string{} // a tool call's name, by its id
_, err := scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
said := false
for _, k := range kimiSaid {
if bytes.Contains(b, k) {
said = true
break
}
}
if !said || (keep != nil && !keep(b)) {
return true
}
var l kimiLine
if json.Unmarshal(b, &l) != nil {
return true
}
for _, p := range kimiParts(l, names) {
if !add(p.Role != "assistant", p) {
return false
}
}
return true
})
return err
}
// kimiParts are what one line of a wire file said.
func kimiParts(l kimiLine, names map[string]string) []Part {
switch l.Type {
case "turn.prompt", "turn.steer":
var parts []Part
for _, p := range l.Input {
if p.Type != "text" {
continue
}
if l.Origin.Kind == "user" {
parts = append(parts, textPart("user", p.Text))
} else {
// a skill's activation, a background task's news: folded
parts = append(parts, Part{Role: "user", Kind: "context", Text: p.Text})
}
}
return parts
case "context.append_loop_event":
e := l.Event
switch e.Type {
case "content.part":
switch e.Part.Type {
case "text":
return []Part{textPart("assistant", e.Part.Text)}
case "think":
return []Part{{Role: "assistant", Kind: "thinking", Text: e.Part.Think}}
}
case "tool.call":
names[e.ToolCallID] = e.Name
return []Part{{Role: "assistant", Kind: "tool_use", Name: e.Name, Text: pretty(e.Args)}}
case "tool.result":
return []Part{{Role: "tool", Kind: "tool_result", Name: names[e.ToolCallID], Text: resultText(e.Result.Output)}}
}
case "context.append_message":
if l.Time != 0 {
return nil
}
return kimiMessageParts(l, names)
}
return nil
}
// kimiMessageParts are what a message imported from kimi-cli said.
func kimiMessageParts(l kimiLine, names map[string]string) []Part {
m := l.Message
var parts []Part
switch m.Role {
case "user", "assistant":
for _, c := range m.Content {
switch c.Type {
case "text":
parts = append(parts, textPart(m.Role, c.Text))
case "think":
parts = append(parts, Part{Role: m.Role, Kind: "thinking", Text: c.Think})
}
}
for _, c := range m.ToolCalls {
name := cmp.Or(c.Name, c.Function.Name)
names[c.ID] = name
args := c.Arguments
if len(args) == 0 {
args = c.Function.Arguments
}
parts = append(parts, Part{Role: "assistant", Kind: "tool_use", Name: name, Text: kimiArgs(args)})
}
case "tool":
var text []byte
for _, c := range m.Content {
if c.Type == "text" {
if len(text) > 0 {
text = append(text, '\n')
}
text = append(text, c.Text...)
}
}
parts = append(parts, Part{Role: "tool", Kind: "tool_result", Name: names[m.ToolCallID], Text: string(text)})
}
return parts
}
// kimiArgs is a call's arguments: an OpenAI-style call has them as a string
// of JSON.
func kimiArgs(raw json.RawMessage) string {
var s string
if json.Unmarshal(raw, &s) == nil {
return pretty(json.RawMessage(s))
}
return pretty(raw)
}
+130
View File
@@ -0,0 +1,130 @@
package sessions
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
)
// kindsOf counts a transcript's parts by role and kind.
func kindsOf(tr Transcript) map[string]int {
n := map[string]int{}
for _, p := range tr.Parts {
n[p.Role+"/"+p.Kind]++
}
return n
}
// #2056 (infinitr0us): a Kimi Code session opens as a transcript, read from
// the #1607 reporter's whole wire files (text redacted by them, every
// record's shape as Kimi Code wrote it). The counts are the files' own: the
// prompts and loop events of 1.4 and 1.5, the untimed messages of 1.0, and
// nothing from the timed context.append_message or agent.message.appended
// records, which say again what those said.
func TestKimiCodeTranscript(t *testing.T) {
inZone(t, 0)
claude, _ := setup(t)
kimiSessionsIn(t, filepath.Join(filepath.Dir(claude), "home", ".kimi-code"))
ss := List(0)
for _, c := range []struct {
id string
first string
want map[string]int
}{
// 1.4, three prompts typed and a background task's steer
{kimiJune, "user/text", map[string]int{"user/text": 3, "user/context": 1, "assistant/thinking": 25, "assistant/text": 6, "assistant/tool_use": 35, "tool/tool_result": 35}},
// 1.4, cut off mid-request
{kimiCancel, "user/text", map[string]int{"user/text": 1, "assistant/thinking": 6, "assistant/text": 1, "assistant/tool_use": 9, "tool/tool_result": 9}},
// 1.5 with no agent.message.appended, started by a skill
{kimiEarly, "user/context", map[string]int{"user/context": 1, "assistant/thinking": 8, "assistant/text": 5, "assistant/tool_use": 10, "tool/tool_result": 10}},
// 1.5 whose one call failed: its prompt, once
{"session_0f2d1067-903e-4a6a-9f1f-df1f0b0e606c", "user/text", map[string]int{"user/text": 1}},
// imported from kimi-cli: context.append_message alone
{kimiOld, "user/text", map[string]int{"user/text": 1, "assistant/thinking": 1, "assistant/text": 1}},
} {
s := find(t, ss, "kimi", c.id)
if !s.Transcript {
t.Fatalf("%s: listed as having no transcript", c.id)
}
tr, err := TranscriptOf(s)
if err != nil {
t.Fatalf("%s: %v", c.id, err)
}
got := kindsOf(tr)
if len(got) != len(c.want) {
t.Fatalf("%s: parts %v, want %v", c.id, got, c.want)
}
for k, n := range c.want {
if got[k] != n {
t.Fatalf("%s: parts %v, want %v", c.id, got, c.want)
}
}
if p := tr.Parts[0]; p.Role+"/"+p.Kind != c.first {
t.Fatalf("%s: starts with %+v", c.id, p)
}
}
}
// A ses_* session Kimi Code opened again: kimi-cli's messages (an
// assistant's tool calls as Kimi Code imports them, and OpenAI's shape),
// then Kimi Code's own turn, each record in the shape the reporter's files
// have. Each part comes once, in order, a result named for its call.
func TestKimiCodeTranscriptOrder(t *testing.T) {
dir := t.TempDir()
wire := filepath.Join(dir, "wire.jsonl")
lines := []string{
`{"type":"metadata","protocol_version":"1.4","created_at":1772085117694}`,
`{"type":"context.append_message","message":{"role":"user","content":[{"type":"text","text":"old ask"}],"toolCalls":[]}}`,
`{"type":"context.append_message","message":{"role":"assistant","content":[{"type":"think","think":"old think"},{"type":"text","text":"old reply"}],"toolCalls":[{"type":"function","id":"tool_A","name":"Shell","arguments":"{\"command\":\"ls\"}"},{"type":"function","id":"tool_B","function":{"name":"ReadFile","arguments":"{\"path\":\"a.go\"}"}}]}}`,
`{"type":"context.append_message","message":{"role":"tool","content":[{"type":"text","text":"a.go"},{"type":"text","text":"b.go"}],"toolCalls":[],"toolCallId":"tool_A"}}`,
`{"type":"context.append_message","message":{"role":"tool","content":[{"type":"text","text":"package a"}],"toolCalls":[],"toolCallId":"tool_B"}}`,
`{"type":"config.update","modelAlias":"kimi-code/k3","thinkingEffort":"max","time":1784436245384}`,
`{"type":"turn.prompt","input":[{"type":"text","text":"new ask"}],"origin":{"kind":"user"},"time":1784436249636}`,
`{"type":"context.append_message","agentId":"main","message":{"role":"user","content":[{"type":"text","text":"new ask"}],"toolCalls":[],"origin":{"kind":"user"}},"time":1784436249636}`,
`{"type":"context.append_message","agentId":"main","message":{"role":"user","content":[{"type":"text","text":"<system-reminder>date</system-reminder>"}],"toolCalls":[],"origin":{"kind":"injection"}},"time":1784436249637}`,
`{"type":"context.append_loop_event","event":{"type":"step.begin","uuid":"u1","turnId":"0","step":1},"time":1784436249640}`,
`{"type":"context.append_loop_event","event":{"type":"content.part","uuid":"u2","turnId":"0","step":1,"part":{"type":"think","think":"new think"}},"time":1784436254379}`,
`{"type":"context.append_loop_event","event":{"type":"tool.call","uuid":"tool_C","turnId":"0","step":1,"toolCallId":"tool_C","name":"Grep","args":{"pattern":"needle"},"description":"x"},"time":1784436254398}`,
`{"type":"context.append_loop_event","event":{"type":"tool.result","parentUuid":"p","toolCallId":"tool_C","result":{"output":"found the haystack","isError":true}},"time":1784436254401}`,
`{"type":"context.append_loop_event","event":{"type":"content.part","uuid":"u3","turnId":"0","step":2,"part":{"type":"text","text":"new reply"}},"time":1784436255379}`,
`{"message":{"message":{"role":"assistant","content":[{"type":"text","text":"new reply"}],"toolCalls":[{"id":"tool_C","name":"Grep","arguments":"{}"}]}},"type":"agent.message.appended","time":1784436255400,"kind":"event"}`,
`{"type":"context.append_loop_event","event":{"type":"step.end","uuid":"u1","turnId":"0","step":2,"finishReason":"end_turn"},"time":1784436255406}`,
}
if err := os.WriteFile(wire, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
s := Session{Agent: "kimi", ID: "ses_x", Path: wire}
tr, err := TranscriptOf(s)
if err != nil {
t.Fatal(err)
}
var got []string
for _, p := range tr.Parts {
got = append(got, p.Role+"/"+p.Kind+"/"+p.Name+"/"+strings.Join(strings.Fields(p.Text), " "))
}
want := []string{
"user/text//old ask",
"assistant/thinking//old think",
"assistant/text//old reply",
`assistant/tool_use/Shell/{ "command": "ls" }`,
`assistant/tool_use/ReadFile/{ "path": "a.go" }`,
"tool/tool_result/Shell/a.go b.go",
"tool/tool_result/ReadFile/package a",
"user/text//new ask",
"assistant/thinking//new think",
`assistant/tool_use/Grep/{ "pattern": "needle" }`,
"tool/tool_result/Grep/found the haystack",
"assistant/text//new reply",
}
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Fatalf("parts:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
// search reads the same parts
h, found, err := SearchSession(context.Background(), s, NeedleOf("haystack"))
if err != nil || !found || h.Kind != "tool_result" || !strings.Contains(strings.ToLower(h.Match), "haystack") {
t.Fatalf("search: %+v %v %v", h, found, err)
}
}