Merge: Claude Code chats survive server restarts via a detachable host

This commit is contained in:
2026-11-04 16:15:06 +00:00
21 changed files with 2400 additions and 40 deletions
+5
View File
@@ -325,6 +325,7 @@ func (s *session) ensureProcess(ctx context.Context) (*process, error) {
p := s.proc
s.lastUsed = time.Now()
s.mu.Unlock()
s.awaitReady(ctx)
return p, nil
}
if s.starting != nil {
@@ -408,6 +409,7 @@ func (c *Chat) Interrupt(ctx context.Context, id string) error {
if s == nil {
return nil
}
s.awaitReady(ctx)
s.mu.Lock()
proc := s.proc
running := s.running
@@ -489,6 +491,7 @@ func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermi
if s == nil {
return []protocol.ChatPermissionFrame{}, nil
}
s.awaitReady(ctx)
s.mu.Lock()
defer s.mu.Unlock()
frames := make([]protocol.ChatPermissionFrame, 0, len(s.approvals))
@@ -505,6 +508,7 @@ func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error
if s == nil {
return []protocol.ChatForm{}, nil
}
s.awaitReady(ctx)
s.mu.Lock()
defer s.mu.Unlock()
forms := make([]protocol.ChatForm, 0, len(s.forms))
@@ -629,6 +633,7 @@ func (c *Chat) Shells(ctx context.Context, id string) ([]protocol.ChatShell, err
if s == nil {
return []protocol.ChatShell{}, nil
}
s.awaitReady(ctx)
s.mu.Lock()
defer s.mu.Unlock()
result := []protocol.ChatShell{}
+38 -6
View File
@@ -4,9 +4,11 @@
// mode: stream-json input carries user turns, stream-json output carries
// assistant/tool events, and control requests carry interactive prompts
// (can_use_tool) and session queries. This adapter owns one CLI process per
// active session and mirrors that protocol into Pipelines chat frames. It never
// changes the operator's Claude configuration, starts a daemon, or invents a
// transcript: history is read back from the CLI's own session files.
// active session and mirrors that protocol into Pipelines chat frames. In the
// installed server each CLI runs inside a per-session pipelines-claude-host so
// it survives a server restart (hosted.go). It never changes the operator's
// Claude configuration or invents a transcript: history is read back from the
// CLI's own session files.
package claude
import (
@@ -14,6 +16,7 @@ import (
"crypto/rand"
"encoding/hex"
"errors"
"log"
"os"
"os/exec"
"path/filepath"
@@ -22,6 +25,7 @@ import (
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
@@ -96,6 +100,9 @@ type Chat struct {
auth authEnv
// dirEnv supplies each chat directory's own environment (direnv, mise).
dirEnv *workenv.Resolver
// hostDir is the private directory of detachable CLI hosts, "" when the
// CLI is this server's child (see hosted.go).
hostDir string
// hinted records sessions whose registry directory has been resolved.
hinted sync.Map
@@ -115,13 +122,30 @@ func New(ctx context.Context) *Chat {
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
c := &Chat{ctx: ctx, cancel: cancel, binary: BinaryPath(), dirEnv: workenv.Default, sessions: map[string]*session{}}
c := newChat(ctx)
if c.hostDir != "" {
if err := claudehost.EnsureDir(c.hostDir); err != nil {
log.Printf("claude chat: host directory %s: %v; Claude Code chats stop on a server restart", c.hostDir, err)
c.hostDir = ""
}
}
c.reattachHosts()
go c.reapIdle()
return c
}
// Close stops every owned CLI process. Session transcripts stay on disk.
// newChat is New without the reattach pass and the reaper (tests).
func newChat(ctx context.Context) *Chat {
ctx, cancel := context.WithCancel(ctx)
c := &Chat{ctx: ctx, cancel: cancel, binary: BinaryPath(), dirEnv: workenv.Default, sessions: map[string]*session{}}
hostConfig.Lock()
c.hostDir = hostConfig.dir
hostConfig.Unlock()
return c
}
// Close stops every owned CLI process, hosted ones included. Session
// transcripts stay on disk. A server shutdown uses Detach instead.
func (c *Chat) Close() {
c.cancel()
c.mu.Lock()
@@ -321,6 +345,10 @@ type session struct {
// injectedSeen holds the identities of agent reports and notices already
// published live, so a delivery the stream repeats is shown once.
injectedSeen map[string]bool
// silent is set while a reattached host replays output an earlier server
// already published: state is rebuilt, nothing is broadcast.
silent bool
}
type promptRecord struct {
@@ -355,6 +383,10 @@ func (s *session) emit(frame protocol.ChatEventFrame) {
s.compaction = nil
}
}
if s.silent {
s.mu.Unlock()
return
}
targets := make([]chan protocol.ChatEventFrame, 0, len(s.subs))
for ch := range s.subs {
targets = append(targets, ch)
+591
View File
@@ -0,0 +1,591 @@
package claude
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Detachable hosts. With hosting configured, a session's CLI is owned by a
// pipelines-claude-host process (internal/claudehost) instead of this server,
// so a server restart does not end the conversation: the next server finds
// the host's registry file, reconnects, rebuilds the session's state from the
// spooled output and continues from its last acknowledged offset. Without
// hosting (tests, a missing host binary) the CLI is this server's child, as
// before, and a restart resumes it with --resume.
const hostAttachTimeout = 3 * time.Second
var hostConfig struct {
sync.Mutex
dir string
binary string
args []string
}
// ConfigureHosts makes Chats created afterwards run their CLIs in detachable
// hosts kept in dir. An empty dir turns hosting off. PIPELINES_CLAUDE_HOST
// names the host executable ("off" disables hosting); otherwise
// pipelines-claude-host is looked up next to this executable, then on PATH.
func ConfigureHosts(dir string) {
hostConfig.Lock()
defer hostConfig.Unlock()
hostConfig.dir = strings.TrimSpace(dir)
hostConfig.binary = ""
hostConfig.args = nil
if hostConfig.dir == "" {
return
}
binary := hostBinaryPath()
if binary == "" {
log.Printf("claude chat: pipelines-claude-host was not found; Claude Code chats stop on a server restart")
hostConfig.dir = ""
return
}
hostConfig.binary = binary
}
// DefaultHostDir is the private host directory for one server instance,
// scoped by its database path so two servers of one user never adopt each
// other's chats.
func DefaultHostDir(scope string) string {
base, err := os.UserCacheDir()
if err != nil || base == "" {
return ""
}
if absolute, err := filepath.Abs(scope); err == nil {
scope = absolute
}
sum := sha256.Sum256([]byte(scope))
return filepath.Join(base, "pipelines", "claude-hosts", hex.EncodeToString(sum[:6]))
}
func hostBinaryPath() string {
if value := strings.TrimSpace(os.Getenv("PIPELINES_CLAUDE_HOST")); value != "" {
if value == "off" {
return ""
}
return value
}
if executable, err := os.Executable(); err == nil {
candidate := filepath.Join(filepath.Dir(executable), "pipelines-claude-host")
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate
}
}
if path, err := exec.LookPath("pipelines-claude-host"); err == nil {
return path
}
return ""
}
// hostLink is a process's connection to its host.
type hostLink struct {
dir string
record claudehost.Record
mu sync.Mutex
conn *claudehost.Conn
committed int64
detached atomic.Bool
closing atomic.Bool
}
func (l *hostLink) current() *claudehost.Conn {
l.mu.Lock()
defer l.mu.Unlock()
return l.conn
}
func (l *hostLink) send(frame claudehost.Frame) error {
conn := l.current()
if conn == nil {
return errProcessClosed
}
if err := conn.Send(frame); err != nil {
return fmt.Errorf("write to the Claude Code host: %w", err)
}
return nil
}
// replayPlan says how a freshly attached reader treats output it has seen
// before: lines below silentUntil were processed by an earlier server and only
// rebuild state; control requests below catchUpEnd are applied only when the
// host still has them pending (answered ones must not reappear).
type replayPlan struct {
base int64
silentUntil int64
catchUpEnd int64
pending map[string]bool
busyAtAcked bool
restore bool
}
// startHosted starts a host for args and attaches to it.
func (s *session) startHosted(ctx context.Context, args []string, mode string, env []string) (*process, error) {
c := s.chat
hostConfig.Lock()
binary, hostArgs := hostConfig.binary, append([]string(nil), hostConfig.args...)
hostConfig.Unlock()
cmd, err := claudehost.Spawn(ctx, claudehost.SpawnOptions{
HostBinary: binary, HostArgs: hostArgs, Dir: c.hostDir, SessionID: s.id,
Claude: c.binary, Args: args, Env: env, Cwd: s.directory, Idle: idleProcessExpiry,
})
if err != nil {
return nil, err
}
// Reap the host if it ends while this server is still its parent.
go func() { _ = cmd.Wait() }()
paths := claudehost.PathsFor(c.hostDir, s.id)
conn, status, err := claudehost.Attach(paths.Socket, 0, hostAttachTimeout)
if err != nil {
claudehost.KillStale(c.hostDir, claudehost.Record{SessionID: s.id, HostPID: cmd.Process.Pid})
return nil, fmt.Errorf("attach to the Claude Code host: %w", err)
}
link := &hostLink{dir: c.hostDir, conn: conn, record: claudehost.Record{
SessionID: s.id, HostPID: status.HostPID, ClaudePID: status.ClaudePID, Socket: paths.Socket,
}}
p := newProcess(s, mode)
p.link = link
p.markReady()
go p.readHost(conn, replayPlan{})
return p, nil
}
// connectHost attaches to a host found in the registry and prepares a
// process for s without registering it. A host that is unreachable, belongs
// to another session or never finished initializing is stopped and its files
// removed; nil is returned and the next prompt starts a fresh CLI with
// --resume.
func (c *Chat) connectHost(record claudehost.Record) (*process, *claudehost.Conn, replayPlan) {
conn, status, err := claudehost.Attach(record.Socket, 0, hostAttachTimeout)
if err != nil {
log.Printf("claude chat %s: host unreachable (%v); the next prompt resumes the session", record.SessionID, err)
claudehost.KillStale(c.hostDir, record)
return nil, nil, replayPlan{}
}
var models []protocol.ChatModel
var account accountIdentity
if len(status.Init) > 0 {
models, account, err = parseInitialize(status.Init)
} else {
err = errors.New("the host's CLI never finished initializing")
}
if status.SessionID != record.SessionID || err != nil {
_ = conn.Close()
claudehost.KillStale(c.hostDir, record)
return nil, nil, replayPlan{}
}
directory := status.Directory
if directory == "" {
directory = record.Directory
}
s := c.sessionFor(record.SessionID, directory)
p := newProcess(s, status.Mode)
p.link = &hostLink{dir: c.hostDir, conn: conn, committed: status.Acked, record: claudehost.Record{
SessionID: record.SessionID, HostPID: status.HostPID, ClaudePID: status.ClaudePID, Socket: record.Socket,
}}
p.stderr.WriteString(status.Stderr)
p.models, p.account, p.appliedModel = models, account, status.Model
plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true}
for _, pending := range status.Pending {
plan.pending[pending.ID] = true
}
if status.Acked < status.Base {
// Output the previous server never processed was dropped by the spool
// bound; watchers reload the transcript.
log.Printf("claude chat %s: %d bytes of unread output exceeded the host spool", record.SessionID, status.Base-status.Acked)
plan.silentUntil = status.Base
}
return p, conn, plan
}
// adoptLocked applies an attached host's model and account to the session.
// Callers hold s.mu.
func (s *session) adoptLocked(p *process) {
s.models, s.account = p.models, p.account
s.appliedModel = p.appliedModel
if s.model == "" {
s.model = p.appliedModel
}
s.lastUsed = time.Now()
}
// attachHost adopts a live host found in the registry at server start.
func (c *Chat) attachHost(record claudehost.Record) bool {
p, conn, plan := c.connectHost(record)
if p == nil {
return false
}
s := p.session
s.mu.Lock()
if s.proc != nil || s.starting != nil {
s.mu.Unlock()
_ = conn.Close()
return false
}
s.proc = p
s.adoptLocked(p)
s.mu.Unlock()
go p.readHost(conn, plan)
return true
}
// reattachHosts adopts every live host of this server's directory. The
// registration is synchronous, so a prompt never races a second host for the
// same session; the replay that rebuilds each session runs in the background
// (see process.ready).
func (c *Chat) reattachHosts() {
if c.hostDir == "" {
return
}
var wg sync.WaitGroup
for _, record := range claudehost.Records(c.hostDir) {
wg.Add(1)
go func(record claudehost.Record) {
defer wg.Done()
if c.attachHost(record) {
log.Printf("claude chat %s: reattached to its running Claude Code host", record.SessionID)
}
}(record)
}
wg.Wait()
}
// existingHost adopts a host left for this session (one that started after
// this server's reattach pass) instead of starting a second one. The caller
// holds the session's starting slot and registers the process.
func (s *session) existingHost() *process {
c := s.chat
if c.hostDir == "" {
return nil
}
data, err := os.ReadFile(claudehost.PathsFor(c.hostDir, s.id).Record)
if err != nil {
return nil
}
var record claudehost.Record
if json.Unmarshal(data, &record) != nil || record.SessionID != s.id {
claudehost.Remove(c.hostDir, s.id)
return nil
}
p, conn, plan := c.connectHost(record)
if p == nil {
return nil
}
s.mu.Lock()
s.adoptLocked(p)
s.mu.Unlock()
go p.readHost(conn, plan)
return p
}
// readHost is the hosted counterpart of readStdout + wait.
func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
s := p.session
live := false
goLive := func() {
if live {
return
}
live = true
s.mu.Lock()
s.silent = false
turn := ""
if plan.restore {
if plan.busyAtAcked && !s.running {
turn = fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.turnID = turn
s.running = true
s.steered = 0
} else if !plan.busyAtAcked {
// Output that starts a turn after the reconnect (a follow-up of
// messages written before it) is adopted as a running turn.
s.awaitFollowUp = true
}
}
s.mu.Unlock()
if turn != "" {
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
}
if plan.restore {
// Watchers already attached reload the transcript.
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventResync})
}
}
if plan.silentUntil > plan.base {
s.mu.Lock()
s.silent = true
s.mu.Unlock()
} else {
goLive()
}
if plan.catchUpEnd <= plan.base {
p.markReady()
}
sinceAck := 0
for {
frame, err := conn.Recv()
if err != nil {
goLive()
p.markReady()
if next := p.hostLost(conn, err); next != nil {
conn = next
plan = replayPlan{}
continue
}
return
}
switch frame.Op {
case claudehost.OpOut:
if frame.Offset >= plan.silentUntil {
goLive()
}
if !(frame.Offset < plan.catchUpEnd && answeredRequest(frame.Data, plan.pending)) {
s.handleLine(p, frame.Data)
}
p.link.mu.Lock()
p.link.committed = frame.End
p.link.mu.Unlock()
sinceAck++
if sinceAck >= 64 || !conn.Buffered() {
_ = conn.Send(claudehost.Frame{Op: claudehost.OpAck, Offset: frame.End})
sinceAck = 0
}
if frame.End >= plan.silentUntil {
goLive()
}
if frame.End >= plan.catchUpEnd {
p.markReady()
}
case claudehost.OpExit:
goLive()
p.markReady()
if frame.Status != nil && frame.Status.Stderr != "" {
p.mu.Lock()
if p.stderr.Len() == 0 {
p.stderr.WriteString(frame.Status.Stderr)
}
p.mu.Unlock()
}
var exitErr error
if frame.Error != "" {
exitErr = errors.New(frame.Error)
}
p.link.closing.Store(true)
_ = conn.Close()
p.finish(exitErr)
return
case claudehost.OpClosed:
p.link.closing.Store(true)
}
}
}
// answeredRequest reports a replayed CLI control request that is no longer
// pending, so an approval already answered is not shown again.
func answeredRequest(line []byte, pending map[string]bool) bool {
var envelope struct {
Type string `json:"type"`
RequestID string `json:"request_id"`
}
if json.Unmarshal(line, &envelope) != nil || envelope.Type != "control_request" {
return false
}
return !pending[envelope.RequestID]
}
func (p *process) markReady() {
p.readyOnce.Do(func() { close(p.ready) })
}
// hostLost handles an ended host connection. A deliberate detach or close just
// ends the reader; an unexpected loss is retried once (the host may only have
// dropped the connection), and otherwise the host is treated as crashed: what
// it left is stopped and the turn is settled with a notice, and the next prompt
// resumes the session with --resume as after any release.
func (p *process) hostLost(conn *claudehost.Conn, cause error) *claudehost.Conn {
link := p.link
_ = conn.Close()
if link.detached.Load() {
p.finishDetached()
return nil
}
if link.closing.Load() {
p.finish(nil)
return nil
}
link.mu.Lock()
committed := link.committed
link.mu.Unlock()
for attempt := 0; attempt < 2; attempt++ {
time.Sleep(150 * time.Millisecond)
if link.detached.Load() || link.closing.Load() {
break
}
next, _, err := claudehost.Attach(link.record.Socket, committed, hostAttachTimeout)
if err == nil {
link.mu.Lock()
link.conn = next
link.mu.Unlock()
return next
}
}
if link.detached.Load() {
p.finishDetached()
return nil
}
if link.closing.Load() {
p.finish(nil)
return nil
}
log.Printf("claude chat %s: host connection lost (%v); falling back to --resume", p.session.id, cause)
claudehost.KillStale(link.dir, link.record)
p.mu.Lock()
p.stderr.Reset()
p.mu.Unlock()
p.finish(errors.New("the Claude Code host stopped unexpectedly; the next prompt resumes this session with --resume"))
return nil
}
// finishDetached ends a process this server let go of on shutdown. The CLI
// keeps running in its host; nothing is reported to watchers.
func (p *process) finishDetached() {
p.mu.Lock()
if p.exited {
p.mu.Unlock()
return
}
p.exited = true
pending := p.pending
p.pending = map[string]chan controlReply{}
close(p.done)
p.mu.Unlock()
for _, ch := range pending {
select {
case ch <- controlReply{err: "the server is shutting down"}:
default:
}
}
}
// closeHosted stops the host and its CLI (an explicit release).
func (p *process) closeHosted() {
link := p.link
link.closing.Store(true)
if err := link.send(claudehost.Frame{Op: claudehost.OpClose}); err != nil {
claudehost.KillStale(link.dir, link.record)
}
select {
case <-p.done:
case <-time.After(8 * time.Second):
claudehost.KillStale(link.dir, link.record)
if conn := link.current(); conn != nil {
_ = conn.Close()
}
}
}
// detach lets the host keep running while this server stops.
func (p *process) detach() {
link := p.link
if link == nil {
p.close()
return
}
link.detached.Store(true)
if conn := link.current(); conn != nil {
_ = conn.Close()
}
select {
case <-p.done:
case <-time.After(2 * time.Second):
}
}
// Detach disconnects from every hosted CLI without stopping it, for a server
// shutdown: the next server reattaches. CLIs this server owns directly (no
// host) are stopped as Close does.
func (c *Chat) Detach() {
c.cancel()
c.mu.Lock()
c.closed = true
sessions := make([]*session, 0, len(c.sessions))
for _, s := range c.sessions {
sessions = append(sessions, s)
}
c.sessions = map[string]*session{}
c.mu.Unlock()
var wg sync.WaitGroup
for _, s := range sessions {
s.mu.Lock()
p := s.proc
s.proc = nil
s.mu.Unlock()
if p == nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
p.detach()
}()
}
wg.Wait()
}
// ReleaseSession stops a session's CLI (and its host) for an explicit operator
// close. The transcript stays; a later prompt resumes it.
func (c *Chat) ReleaseSession(_ context.Context, id string) error {
if s := c.session(id); s != nil {
s.closeProcess()
}
return nil
}
// ProbeTurn reports whether a turn is in flight, after a reattached host's
// replay has rebuilt the session, so a turn that survived a restart is
// observed and notifies.
func (c *Chat) ProbeTurn(ctx context.Context, id string) (bool, error) {
s := c.session(id)
if s == nil {
return false, nil
}
s.awaitReady(ctx)
s.mu.Lock()
defer s.mu.Unlock()
return s.running, nil
}
// awaitReady waits, bounded, until a reattached process has replayed what it
// missed, so approvals and the running turn are known before they are read.
func (s *session) awaitReady(ctx context.Context) {
s.mu.Lock()
p := s.proc
s.mu.Unlock()
if p == nil {
return
}
timer := time.NewTimer(10 * time.Second)
defer timer.Stop()
select {
case <-p.ready:
case <-ctx.Done():
case <-timer.C:
}
}
+385
View File
@@ -0,0 +1,385 @@
package claude
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// The test binary doubles as pipelines-claude-host: a host spawned by a test
// re-executes it with this variable set.
const hostSelfTest = "PIPELINES_CLAUDE_HOST_SELFTEST"
func TestMain(m *testing.M) {
if os.Getenv(hostSelfTest) == "1" {
os.Exit(claudehost.Main(os.Args[1:]))
}
os.Exit(m.Run())
}
type hostedFixture struct {
hostDir string
gate string
logPath string
}
// hostedSetup configures the fake CLI and detachable hosts in a short private
// directory (Unix socket paths are length-limited).
func hostedSetup(t *testing.T) hostedFixture {
t.Helper()
base, err := os.MkdirTemp("/tmp", "pch")
if err != nil {
t.Fatal(err)
}
source, err := os.ReadFile(filepath.Join("testdata", "fake-claude.py"))
if err != nil {
t.Fatal(err)
}
script := filepath.Join(base, "claude")
if err := os.WriteFile(script, source, 0o700); err != nil {
t.Fatal(err)
}
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
fixture := hostedFixture{hostDir: filepath.Join(base, "h"), gate: filepath.Join(base, "gate"), logPath: filepath.Join(base, "args.log")}
t.Setenv("PIPELINES_CLAUDE", script)
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(base, "config"))
t.Setenv("FAKE_CLAUDE_LOG", fixture.logPath)
t.Setenv("FAKE_CLAUDE_GATE", fixture.gate)
t.Setenv("PIPELINES_CLAUDE_HOST", executable)
t.Setenv(hostSelfTest, "1")
ConfigureHosts(fixture.hostDir)
t.Cleanup(func() {
ConfigureHosts("")
for _, record := range claudehost.Records(fixture.hostDir) {
claudehost.KillStale(fixture.hostDir, record)
}
_ = os.RemoveAll(base)
})
return fixture
}
func hostedChat(t *testing.T) *Chat {
t.Helper()
chat := New(context.Background())
if chat.hostDir == "" {
t.Fatal("hosting is not configured")
}
t.Cleanup(chat.Close)
return chat
}
func onlyRecord(t *testing.T, fixture hostedFixture) claudehost.Record {
t.Helper()
var records []claudehost.Record
eventually(t, "a host registry record", func() bool {
records = claudehost.Records(fixture.hostDir)
return len(records) == 1
})
return records[0]
}
func alive(pid int) bool { return pid > 0 && syscall.Kill(pid, 0) == nil }
func textFrame(contains string) func(protocol.ChatEventFrame) bool {
return func(frame protocol.ChatEventFrame) bool {
return strings.Contains(frame.Delta, contains) || (frame.Part != nil && strings.Contains(frame.Part.Text, contains))
}
}
func stepStarted(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepStarted
}
// restart stands in for a server restart: the old Chat detaches (its host
// keeps running) and a new one is built over the same host directory.
func restart(t *testing.T, old *Chat) *Chat {
t.Helper()
old.Detach()
return hostedChat(t)
}
func TestHostedTurnSurvivesRestartAndReplaysMissedOutput(t *testing.T) {
fixture := hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
frames := subscribe(t, first, session.ID)
if err := first.Prompt(context.Background(), session.ID, "gate please"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "text before the restart", textFrame("Working"))
record := onlyRecord(t, fixture)
first.Detach()
if !alive(record.HostPID) || !alive(record.ClaudePID) {
t.Fatal("detaching must leave the host and its CLI running")
}
// The CLI finishes its turn while no server is attached.
if err := os.WriteFile(fixture.gate, nil, 0o600); err != nil {
t.Fatal(err)
}
eventually(t, "the turn result in the spool", func() bool {
data, _ := os.ReadFile(record.Spool)
return strings.Contains(string(data), `"type":"result"`)
})
second := newChat(context.Background())
t.Cleanup(second.Close)
second.sessionFor(session.ID, session.Directory)
frames = subscribe(t, second, session.ID)
second.reattachHosts()
waitFrame(t, frames, "the restored running turn", stepStarted)
waitFrame(t, frames, "text produced while disconnected", textFrame("after the restart"))
waitStepEnded(t, frames)
if second.TurnRunning(session.ID) {
t.Fatal("the replayed result must settle the turn")
}
if spawns := readArgs(t, fixture.logPath); len(spawns) != 1 {
t.Fatalf("the CLI must not be restarted, spawns: %+v", spawns)
}
// The same CLI keeps serving turns.
if err := second.Prompt(context.Background(), session.ID, "hello again"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "the next turn's text", textFrame("Hello"))
waitStepEnded(t, frames)
}
func TestPendingApprovalIsAnsweredAfterRestart(t *testing.T) {
hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
if err := first.Prompt(context.Background(), session.ID, "permission please"); err != nil {
t.Fatal(err)
}
var before []protocol.ChatPermissionFrame
eventually(t, "the approval before the restart", func() bool {
before, _ = first.Permissions(context.Background(), session.ID)
return len(before) == 1
})
second := restart(t, first)
running, err := second.ProbeTurn(context.Background(), session.ID)
if err != nil || !running {
t.Fatalf("the restored turn must be running: %v %v", running, err)
}
after, err := second.Permissions(context.Background(), session.ID)
if err != nil || len(after) != 1 || after[0].RequestID != before[0].RequestID {
t.Fatalf("the pending approval must survive the restart: %+v %v", after, err)
}
frames := subscribe(t, second, session.ID)
if err := second.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: session.ID, RequestID: after[0].RequestID, Decision: protocol.ChatDecisionOnce}); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "the approved tool result", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.State != nil &&
frame.Part.State.Status == protocol.ChatToolCompleted && len(frame.Part.State.Content) == 1 &&
strings.Contains(frame.Part.State.Content[0].Text, "File created")
})
waitStepEnded(t, frames)
// An answered approval is not shown again by a later restart's replay.
third := restart(t, second)
if pending, _ := third.Permissions(context.Background(), session.ID); len(pending) != 0 {
t.Fatalf("an answered approval reappeared: %+v", pending)
}
if third.TurnRunning(session.ID) {
t.Fatal("a finished turn must not be restored as running")
}
}
func TestQuestionSurvivesRestart(t *testing.T) {
hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
if err := first.Prompt(context.Background(), session.ID, "question please"); err != nil {
t.Fatal(err)
}
eventually(t, "the question before the restart", func() bool {
forms, _ := first.Forms(context.Background(), session.ID)
return len(forms) == 1
})
second := restart(t, first)
forms, err := second.Forms(context.Background(), session.ID)
if err != nil || len(forms) != 1 {
t.Fatalf("the question must survive the restart: %+v %v", forms, err)
}
frames := subscribe(t, second, session.ID)
if err := second.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: session.ID, FormID: forms[0].ID, Answers: map[string]any{"q0": "Beta"}}); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "the answered question", func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.State != nil &&
len(frame.Part.State.Content) == 1 && strings.Contains(frame.Part.State.Content[0].Text, "Beta")
})
waitStepEnded(t, frames)
}
func TestInterruptAfterRestart(t *testing.T) {
hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
frames := subscribe(t, first, session.ID)
if err := first.Prompt(context.Background(), session.ID, "long task"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "the long turn's text", textFrame("Hello"))
second := restart(t, first)
if running, _ := second.ProbeTurn(context.Background(), session.ID); !running {
t.Fatal("the long turn must still be running after the restart")
}
frames = subscribe(t, second, session.ID)
if err := second.Interrupt(context.Background(), session.ID); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if second.TurnRunning(session.ID) {
t.Fatal("the interrupted turn must settle")
}
}
func TestModelAndBackgroundTaskSurviveRestart(t *testing.T) {
fixture := hostedSetup(t)
first := hostedChat(t)
session := newCreatedChat(t, first)
if _, err := first.Models(context.Background(), session.ID); err != nil {
t.Fatal(err)
}
if err := first.SwitchModel(context.Background(), session.ID, Backend, "haiku"); err != nil {
t.Fatal(err)
}
frames := subscribe(t, first, session.ID)
if err := first.Prompt(context.Background(), session.ID, "background please"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if shells, _ := first.Shells(context.Background(), session.ID); len(shells) != 1 {
t.Fatalf("the background command must be running: %+v", shells)
}
second := restart(t, first)
shells, err := second.Shells(context.Background(), session.ID)
if err != nil || len(shells) != 1 || shells[0].Command != "sleep 600" {
t.Fatalf("the background command must still be listed after the restart: %+v %v", shells, err)
}
s := second.session(session.ID)
s.mu.Lock()
applied, models := s.appliedModel, len(s.models)
s.mu.Unlock()
if applied != "haiku" || models != 3 {
t.Fatalf("the live model and catalog must be restored: %q %d", applied, models)
}
frames = subscribe(t, second, session.ID)
if err := second.PromptWithMessageIDModel(context.Background(), session.ID, "notify me", "", "haiku"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
if shells, _ := second.Shells(context.Background(), session.ID); len(shells) != 0 {
t.Fatalf("the notification must finish the restored command: %+v", shells)
}
if spawns := readArgs(t, fixture.logPath); len(spawns) != 1 {
t.Fatalf("the CLI must not be restarted, spawns: %d", len(spawns))
}
}
func TestHostCrashFallsBackToResume(t *testing.T) {
fixture := hostedSetup(t)
chat := hostedChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "long task"); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "the long turn's text", textFrame("Hello"))
record := onlyRecord(t, fixture)
if err := syscall.Kill(record.HostPID, syscall.SIGKILL); err != nil {
t.Fatal(err)
}
waitFrame(t, frames, "the host crash notice", func(frame protocol.ChatEventFrame) bool {
return frame.Part != nil && frame.Part.State != nil && frame.Part.State.Error != nil &&
strings.Contains(frame.Part.State.Error.Message, "--resume")
})
waitStepEnded(t, frames)
eventually(t, "the orphaned CLI to stop", func() bool { return !alive(record.ClaudePID) || isZombie(record.ClaudePID) })
if _, err := os.Stat(record.Socket); !os.IsNotExist(err) {
t.Fatalf("the crashed host's files must be removed: %v", err)
}
if err := chat.Prompt(context.Background(), session.ID, "hello again"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
spawns := readArgs(t, fixture.logPath)
if len(spawns) != 2 || argValue(spawns[1].Args, "--resume") != session.ID {
t.Fatalf("the next prompt must resume the session: %+v", spawns)
}
}
func isZombie(pid int) bool {
var status syscall.WaitStatus
got, _ := syscall.Wait4(pid, &status, syscall.WNOHANG, nil)
return got == pid
}
func TestReleasingAHostedChatStopsItsHost(t *testing.T) {
fixture := hostedSetup(t)
chat := hostedChat(t)
session := newCreatedChat(t, chat)
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
record := onlyRecord(t, fixture)
if err := chat.ReleaseSession(context.Background(), session.ID); err != nil {
t.Fatal(err)
}
eventually(t, "the host to exit", func() bool { return !alive(record.HostPID) })
eventually(t, "the CLI to exit", func() bool { return !alive(record.ClaudePID) || isZombie(record.ClaudePID) })
if records := claudehost.Records(fixture.hostDir); len(records) != 0 {
t.Fatalf("a released host must remove its registry record: %+v", records)
}
// A restarted server finds nothing to reattach; the next prompt resumes.
next := hostedChat(t)
if next.session(session.ID) != nil {
t.Fatal("a released session must not be reattached")
}
}
func TestHostStatusReportsRegistryAndPrivateSocket(t *testing.T) {
fixture := hostedSetup(t)
chat := hostedChat(t)
session := newCreatedChat(t, chat)
if _, err := chat.Models(context.Background(), session.ID); err != nil {
t.Fatal(err)
}
record := onlyRecord(t, fixture)
info, err := os.Stat(record.Socket)
if err != nil || info.Mode().Perm()&0o077 != 0 {
t.Fatalf("the socket must be private: %v %v", info.Mode(), err)
}
dir, err := os.Stat(fixture.hostDir)
if err != nil || dir.Mode().Perm() != 0o700 {
t.Fatalf("the host directory must be private: %v %v", dir.Mode(), err)
}
conn, err := claudehost.Dial(record.Socket, time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := conn.Send(claudehost.Frame{Op: claudehost.OpStatus}); err != nil {
t.Fatal(err)
}
frame, err := conn.Recv()
if err != nil || frame.Status == nil || frame.Status.SessionID != session.ID || len(frame.Status.Init) == 0 {
raw, _ := json.Marshal(frame)
t.Fatalf("status: %s %v", raw, err)
}
}
+76 -22
View File
@@ -14,6 +14,7 @@ import (
"sync/atomic"
"time"
"git.a-wan.net/alan/pipelines/internal/claudehost"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -48,6 +49,23 @@ type process struct {
// mode is the permission mode this process runs in, guarded by the
// session's mu: set at spawn and after a confirmed set_permission_mode.
mode string
// link is set when a detachable host owns the CLI (hosted.go); cmd and
// stdin are then unused.
link *hostLink
// ready closes once a reattached process has replayed the output it
// missed; a process this server started is ready at once.
ready chan struct{}
readyOnce sync.Once
// models, account and appliedModel carry an attached host's
// initialize state until the session adopts it.
models []protocol.ChatModel
account accountIdentity
appliedModel string
}
func newProcess(s *session, mode string) *process {
return &process{session: s, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), ready: make(chan struct{}), mode: mode}
}
type controlReply struct {
@@ -97,6 +115,7 @@ func sessionDisplayName(title string) string {
// spawn starts the CLI in the session directory. A session whose transcript
// already exists resumes it; a new one pins the id we recorded at create time.
// With hosting configured the CLI runs in a detachable host (hosted.go).
func (s *session) spawn(ctx context.Context) (*process, error) {
if err := s.requireBinary(); err != nil {
return nil, err
@@ -107,34 +126,24 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
if info, err := os.Stat(s.directory); err != nil || !info.IsDir() {
return nil, fmt.Errorf("Claude session directory is not available: %s", s.directory)
}
if p := s.existingHost(); p != nil {
return p, nil
}
args, mode := s.cliArgs(findTranscriptFile(s.id) != "")
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
env, notices := s.chat.processEnv(ctx, s.directory)
cmd.Env = env
s.mu.Lock()
s.envNotices = notices
s.mu.Unlock()
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
var p *process
var err error
if s.chat.hostDir != "" {
p, err = s.startHosted(ctx, args, mode, env)
} else {
p, err = s.startDirect(args, mode, env)
}
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), mode: mode}
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
// The CLI holds can_use_tool requests until the host has initialized. Do that
// before any user turn so an approval is never silently denied.
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
@@ -152,11 +161,47 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
return p, nil
}
// startDirect runs the CLI as this server's own child.
func (s *session) startDirect(args []string, mode string, env []string) (*process, error) {
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
cmd.Dir = s.directory
cmd.Env = env
cmd.WaitDelay = 5 * time.Second
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start Claude Code: %w", err)
}
p := newProcess(s, mode)
p.cmd, p.stdin = cmd, stdin
p.markReady()
go p.readStderr(stderr)
go p.readStdout(stdout)
go p.wait()
return p, nil
}
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
raw, err := p.request(ctx, "initialize", map[string]any{"subtype": "initialize"})
if err != nil {
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
}
return parseInitialize(raw)
}
// parseInitialize reads the CLI's initialize response: its model catalog and
// signed-in account.
func parseInitialize(raw json.RawMessage) ([]protocol.ChatModel, accountIdentity, error) {
var reply struct {
Models []struct {
Value string `json:"value"`
@@ -237,7 +282,6 @@ func (p *process) write(value any) error {
if err != nil {
return err
}
data = append(data, '\n')
p.writeMu.Lock()
defer p.writeMu.Unlock()
p.mu.Lock()
@@ -246,6 +290,10 @@ func (p *process) write(value any) error {
if exited {
return errProcessClosed
}
if p.link != nil {
return p.link.send(claudehost.Frame{Op: claudehost.OpIn, Data: data})
}
data = append(data, '\n')
if _, err := p.stdin.Write(data); err != nil {
return fmt.Errorf("write to Claude Code: %w", err)
}
@@ -314,7 +362,9 @@ func (p *process) finish(err error) {
default:
}
}
_ = p.stdin.Close()
if p.stdin != nil {
_ = p.stdin.Close()
}
p.session.processExit(p, err)
}
@@ -325,6 +375,10 @@ func (p *process) close() {
if exited {
return
}
if p.link != nil {
p.closeHosted()
return
}
_ = p.stdin.Close()
if p.cmd.Process != nil {
_ = p.cmd.Process.Signal(os.Interrupt)
+49
View File
@@ -72,6 +72,15 @@ def user_message(text):
send({"type": "system", "subtype": "init", "session_id": state["session"],
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd()})
message_id = "msg_fake_%d" % state["turn"]
if "gate" in text:
gated(message_id)
return
if "background" in text:
background(message_id)
return
if "notify" in text:
send({"type": "system", "subtype": "task_notification", "task_id": "b1",
"tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"})
send({"type": "stream_event", "event": {"type": "message_start", "message": {"id": message_id}}})
send({"type": "stream_event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}}})
for delta in ("Hello ", "world"):
@@ -125,6 +134,46 @@ def user_message(text):
finish(message_id)
def wait_for(path):
import time
while not os.path.exists(path):
time.sleep(0.02)
def gated(message_id):
"""A turn that streams, then waits for FAKE_CLAUDE_GATE to exist before it
streams the rest and finishes: the test restarts the server in between."""
gate = os.environ["FAKE_CLAUDE_GATE"]
send({"type": "stream_event", "event": {"type": "message_start", "message": {"id": message_id}}})
send({"type": "stream_event", "event": {"type": "content_block_start", "index": 0, "content_block": {"type": "text"}}})
send({"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": "Working"}}})
wait_for(gate)
send({"type": "stream_event", "event": {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": " after the restart"}}})
send({"type": "stream_event", "event": {"type": "content_block_stop", "index": 0}})
send({"type": "stream_event", "event": {"type": "message_stop"}})
text = "Working after the restart"
append({"type": "assistant", "uuid": "asst-%d" % state["turn"], "timestamp": stamp(),
"message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": text}]}})
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test",
"content": [{"type": "text", "text": text}]}})
finish(message_id)
def background(message_id):
"""Starts a background Bash command that a later "notify" turn finishes."""
tool_id = "toolu_bg_fake"
use = {"type": "tool_use", "id": tool_id, "name": "Bash",
"input": {"command": "sleep 600", "run_in_background": True}}
send({"type": "assistant", "message": {"id": message_id, "role": "assistant", "model": "claude-test", "content": [use]}})
block = {"type": "tool_result", "tool_use_id": tool_id,
"content": "Command running in background with ID: b1. Output is being written to: /tmp/b1.output"}
send({"type": "user", "message": {"role": "user", "content": [block]}})
finish(message_id)
def finish(message_id):
# Shape of SDKRateLimitEvent in Claude Code 2.1.316 (synthetic numbers).
if os.environ.get("FAKE_CLAUDE_RATE_LIMIT"):
+6
View File
@@ -348,6 +348,9 @@ func (s *session) claimStreamedLocked(kind, full string, local int) (blockState,
// broadcastLocked emits while the session lock is already held: the caller is a
// stream-delta path that owns state it just updated.
func (s *session) broadcastLocked(frame protocol.ChatEventFrame) {
if s.silent {
return
}
targets := make([]chan protocol.ChatEventFrame, 0, len(s.subs))
for ch := range s.subs {
targets = append(targets, ch)
@@ -568,6 +571,9 @@ func (s *session) handleResult(envelope lineEnvelope) {
turn := s.turnID
running := s.running
proc := s.proc
if s.silent {
proc = nil // replayed: the live usage query is made once caught up
}
s.running = false
s.turnID = ""
// Messages written mid-turn that the CLI did not fold into this turn run