Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6840 fix(pi): preserve sessions across workdir changes (#7760)

mrlonely6231962e9840
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 082bc93e43..af10ca7bbf 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5746,16 +5746,22 @@ func providerNeedsInlineSystemPrompt(provider string) bool {
}
}
-// gateResumeToReusedWorkdir clears the task's prior session unless this run
+// gateResumeToReachableSession clears the task's prior session unless this run
// can actually reach the store the session lives in, and reports whether that
-// held. CLI backends key their session stores to the cwd (Claude Code looks
-// sessions up under ~/.claude/projects/<encoded-cwd>/), so a session id from a
-// different workdir can never resolve: the CLI exits within a second and the
-// run fails before doing any work — permanently, because the failed run
-// records no session and the next claim serves the same stale pointer again.
-// This fires whenever the prior workdir no longer exists (GC'd after the issue
-// went done, daemon reinstall, manual cleanup) and execenv.Reuse fell back to a
-// fresh Prepare (GitHub #3854).
+// held. Most CLI backends key their session stores to the cwd (Claude Code
+// looks sessions up under ~/.claude/projects/<encoded-cwd>/), so a session id
+// from a different workdir can never resolve: the CLI exits within a second
+// and the run fails before doing any work — permanently, because the failed
+// run records no session and the next claim serves the same stale pointer
+// again. This fires whenever the prior workdir no longer exists (GC'd after
+// the issue went done, daemon reinstall, manual cleanup) and execenv.Reuse fell
+// back to a fresh Prepare (GitHub #3854).
+//
+// Pi and OMP are the exception. Their opaque session id is an absolute JSONL
+// path under ~/.multica/pi-sessions, and the backend passes that path directly
+// to --session. The transcript remains resumable when only the task workdir
+// changes, so binding it to workdir reuse discards healthy conversation history
+// and forces the model to reconstruct it through `multica chat history`.
//
// A matching workdir is not sufficient on its own. Hermes keys its sessions to
// HERMES_HOME — the per-task overlay under envRoot — not to the cwd, and the
@@ -5770,8 +5776,8 @@ func providerNeedsInlineSystemPrompt(provider string) bool {
// HermesSessionStore) — and false drops the resume with the same disclosure as
// a workdir mismatch.
// sameExistingDir reports whether two paths name the same existing directory.
-// False when either cannot be stat'd, which is the safe answer here: an absent
-// prior workdir means there is nothing to resume from.
+// False when either cannot be stat'd, which is the safe answer for cwd-keyed
+// providers: an absent prior workdir means there is nothing to resume from.
func sameExistingDir(a, b string) bool {
if a == "" || b == "" {
return false
@@ -5787,15 +5793,21 @@ func sameExistingDir(a, b string) bool {
return os.SameFile(ai, bi)
}
-func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, envWorkDir string, sessionHomeReachable bool, taskLog *slog.Logger) bool {
- // Compare the directories, not the spelling. Reuse runs in the canonical
- // path it validated and locked, which need not be character-identical to
- // the PriorWorkDir the server sent — a symlinked workspaces root is enough
- // to make them differ. A string compare would then silently drop the prior
- // session on every follow-up task in that installation.
- reused := task.PriorWorkDir != "" && sameExistingDir(envWorkDir, task.PriorWorkDir) && sessionHomeReachable
- if !reused && task.PriorSessionID != "" {
+func gateResumeToReachableSession(task *Task, taskCtx *execenv.TaskContextForEnv, provider, envWorkDir string, sessionHomeReachable bool, taskLog *slog.Logger) bool {
+ var reachable bool
+ if providerUsesPiSessionFile(provider) {
+ reachable = piSessionFilePresent(task.PriorSessionID)
+ } else {
+ // Compare the directories, not the spelling. Reuse runs in the canonical
+ // path it validated and locked, which need not be character-identical to
+ // the PriorWorkDir the server sent — a symlinked workspaces root is enough
+ // to make them differ. A string compare would then silently drop the prior
+ // session on every follow-up task in that installation.
+ reachable = task.PriorWorkDir != "" && sameExistingDir(envWorkDir, task.PriorWorkDir) && sessionHomeReachable
+ }
+ if !reachable && task.PriorSessionID != "" {
taskLog.Info("dropping prior session: session store not reachable from this run",
+ "provider", provider,
"session_id", task.PriorSessionID,
"prior_workdir", task.PriorWorkDir,
"workdir", envWorkDir,
@@ -5810,7 +5822,27 @@ func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, e
taskCtx.PriorSessionResumeUnavailable = true
task.PriorSessionResumeUnavailable = true
}
- return reused
+ return reachable
+}
+
+func providerUsesPiSessionFile(provider string) bool {
+ if provider == "pi" {
+ return true
+ }
+ desc, ok := agent.BuiltinRuntimeByID(provider)
+ return ok && desc.ProtocolFamily == "pi"
+}
+
+// piSessionFilePresent proves there is persisted history to resume. It does
+// not claim the transcript is idle: the Pi backend takes an exclusive lock for
+// the complete child-process lifetime and reports a busy resume as rejected so
+// runTask falls back to its existing one-shot fresh-session path.
+func piSessionFilePresent(sessionID string) bool {
+ if sessionID == "" {
+ return false
+ }
+ info, err := os.Stat(sessionID)
+ return err == nil && info.Mode().IsRegular() && info.Size() > 0
}
// sessionHomeReachable reports whether a session recorded by a prior task on
@@ -5832,9 +5864,8 @@ func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, e
// - With no store, the transcript is the overlay's own task-local file, which
// survives exactly when this run reused the prior task's env root.
//
-// Every other provider is keyed by cwd (or resolves its own store), so the
-// workdir comparison in gateResumeToReusedWorkdir remains the whole answer and
-// this returns true.
+// Every other provider is keyed by cwd or handles its independently addressed
+// store in gateResumeToReachableSession, so this predicate returns true.
func sessionHomeReachable(provider string, env *execenv.Environment, envReused bool) bool {
if provider != "hermes" {
return true
@@ -5929,7 +5960,7 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
// gateCodexResumeToRolloutPresence drops the prior Codex session when its
// rollout is not actually present in the task's CODEX_HOME sessions. A reused
-// workdir keeps PriorSessionID (gateResumeToReusedWorkdir), but Codex session
+// workdir keeps PriorSessionID (gateResumeToReachableSession), but Codex session
// isolation (MUL-4424) means the rollout may be missing: a migrated legacy home
// that could not locate it, or a local_directory task whose shared history was
// pruned. Codex would then silently thread/start from scratch, so we clear the
@@ -7352,13 +7383,13 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
cancelPrepare()
_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)
- reused := gateResumeToReusedWorkdir(&task, &taskCtx, env.WorkDir, sessionHomeReachable(provider, env, envReused), taskLog)
+ resumeReachable := gateResumeToReachableSession(&task, &taskCtx, provider, env.WorkDir, sessionHomeReachable(provider, env, envReused), taskLog)
// A reused workdir is necessary but not sufficient for a Codex resume: the
// prior thread's rollout must actually be present in this task's CODEX_HOME
// sessions (MUL-4424 isolates them). Drop the resume before the brief is
// generated below if it isn't, so we never tell the agent it is continuing a
// conversation Codex will silently restart from scratch.
- if reused {
+ if resumeReachable {
gateCodexResumeToRolloutPresence(&task, &taskCtx, provider, env.CodexHome, taskLog)
}
@@ -7548,7 +7579,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
"provider", provider,
"workdir", env.WorkDir,
"model", model,
- "reused", reused,
+ "resume_reachable", resumeReachable,
)
if task.PriorSessionID != "" {
taskLog.Info("resuming session", "session_id", task.PriorSessionID)
@@ -7708,7 +7739,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
firstResult := result
firstUsage := result.Usage
firstTools := tools
- retiredSessionID = task.PriorSessionID
+ if !result.ResumeRejectedTransient {
+ retiredSessionID = task.PriorSessionID
+ }
taskLog.Warn("session resume failed, retrying with fresh session", "error", result.Error)
// Rebuild cold-session context before the single retry. The prior
@@ -8008,9 +8041,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// how this went wrong before:
//
// 1. Would a fresh session even fix this? Only if the resume itself was
-// refused — the transcript is gone, or it belongs to another provider
-// account. result.ResumeRejected is the backend's positive evidence of
-// that, and where a backend can produce it, it is the whole answer.
+// refused — permanently because the transcript is gone or belongs to
+// another provider account, or transiently because another live run owns
+// it. result.ResumeRejected and result.ResumeRejectedTransient are the
+// backend's positive evidence of those two cases. Both allow a fresh retry,
+// but only the permanent signal retires the prior session from later
+// lookups.
// Answering by exclusion alone would invert the burden of proof: the
// failures a new session cures are a small enumerable set, while the
// ones it cannot are open-ended. A network drop, a 429, a quota trip or
@@ -8041,7 +8077,7 @@ func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, too
return false
}
// Positive evidence: the backend proved the resume was refused.
- if result.ResumeRejected {
+ if result.ResumeRejected || result.ResumeRejectedTransient {
return true
}
// Positive evidence of a different kind: the resume was NOT refused —
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 10ab55288a..2ffb727c80 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -1954,7 +1954,7 @@ func TestExecuteAndDrain_PinsWhenRolloutAppearsAfterStatus(t *testing.T) {
t.Fatalf("expected the codex session to be pinned once its rollout appeared mid-run, got %+v", rec.snapshot())
}
-func TestGateResumeToReusedWorkdir(t *testing.T) {
+func TestGateResumeToReachableSession(t *testing.T) {
t.Parallel()
tests := []struct {
@@ -2019,7 +2019,7 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- // gateResumeToReusedWorkdir compares directory IDENTITY, not path
+ // gateResumeToReachableSession compares directory IDENTITY, not path
// spelling, so the table's paths have to exist on disk. Mapping
// them under one temp root preserves each case's same/different
// relationship while making them real.
@@ -2039,10 +2039,10 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {
task := Task{PriorSessionID: tt.sessionID, PriorWorkDir: priorDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: tt.sessionID != ""}
- reused := gateResumeToReusedWorkdir(&task, &taskCtx, envDir, !tt.sessionHomeUnreachable, slog.Default())
+ reachable := gateResumeToReachableSession(&task, &taskCtx, "claude", envDir, !tt.sessionHomeUnreachable, slog.Default())
- if reused != tt.wantReused {
- t.Fatalf("reused = %v, want %v", reused, tt.wantReused)
+ if reachable != tt.wantReused {
+ t.Fatalf("reachable = %v, want %v", reachable, tt.wantReused)
}
if task.PriorSessionID != tt.wantSession {
t.Fatalf("PriorSessionID = %q, want %q", task.PriorSessionID, tt.wantSession)
@@ -2060,6 +2060,122 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {
}
}
+func TestGatePiResumeToSessionFile(t *testing.T) {
+ t.Parallel()
+
+ for _, provider := range []string{"pi", "omp"} {
+ t.Run(provider, func(t *testing.T) {
+ t.Parallel()
+
+ base := t.TempDir()
+ priorDir := filepath.Join(base, "prior-workdir")
+ envDir := filepath.Join(base, "fresh-workdir")
+ for _, dir := range []string{priorDir, envDir} {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatalf("create %s: %v", dir, err)
+ }
+ }
+
+ sessionFile := filepath.Join(base, "pi-session.jsonl")
+ if err := os.WriteFile(sessionFile, []byte("{}\n"), 0o644); err != nil {
+ t.Fatalf("create session file: %v", err)
+ }
+
+ task := Task{PriorSessionID: sessionFile, PriorWorkDir: priorDir}
+ taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
+
+ reachable := gateResumeToReachableSession(&task, &taskCtx, provider, envDir, true, slog.Default())
+
+ if !reachable {
+ t.Fatal("Pi-family session file should remain reachable across workdirs")
+ }
+ if task.PriorSessionID != sessionFile {
+ t.Fatalf("PriorSessionID = %q, want %q", task.PriorSessionID, sessionFile)
+ }
+ if !taskCtx.PriorSessionResumed {
+ t.Fatal("PriorSessionResumed was cleared for a reachable Pi-family session")
+ }
+ if taskCtx.PriorSessionResumeUnavailable {
+ t.Fatal("reachable Pi-family session was reported unavailable")
+ }
+ })
+ }
+}
+
+func TestGatePiResumeDropsUnusableSessionFile(t *testing.T) {
+ t.Parallel()
+
+ for _, test := range []struct {
+ name string
+ setup func(t *testing.T, path string)
+ }{
+ {name: "missing"},
+ {
+ name: "empty",
+ setup: func(t *testing.T, path string) {
+ t.Helper()
+ if err := os.WriteFile(path, nil, 0o644); err != nil {
+ t.Fatalf("create empty session: %v", err)
+ }
+ },
+ },
+ {
+ name: "directory",
+ setup: func(t *testing.T, path string) {
+ t.Helper()
+ if err := os.Mkdir(path, 0o755); err != nil {
+ t.Fatalf("create session directory: %v", err)
+ }
+ },
+ },
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ base := t.TempDir()
+ workDir := filepath.Join(base, "workdir")
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ t.Fatalf("create workdir: %v", err)
+ }
+ sessionPath := filepath.Join(base, "session.jsonl")
+ if test.setup != nil {
+ test.setup(t, sessionPath)
+ }
+ task := Task{PriorSessionID: sessionPath, PriorWorkDir: workDir}
+ taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}
+
+ reachable := gateResumeToReachableSession(&task, &taskCtx, "pi", workDir, true, slog.Default())
+
+ if reachable {
+ t.Fatalf("%s Pi session was treated as reachable", test.name)
+ }
+ if task.PriorSessionID != "" {
+ t.Fatalf("PriorSessionID = %q, want empty", task.PriorSessionID)
+ }
+ if taskCtx.PriorSessionResumed {
+ t.Fatalf("PriorSessionResumed stayed true for a %s Pi session", test.name)
+ }
+ if !taskCtx.PriorSessionResumeUnavailable {
+ t.Fatalf("%s Pi session was not reported unavailable", test.name)
+ }
+ })
+ }
+}
+
+func TestProviderUsesPiSessionFileFollowsBuiltinRuntimeDescriptors(t *testing.T) {
+ t.Parallel()
+
+ if !providerUsesPiSessionFile("pi") {
+ t.Fatal("pi protocol family did not use Pi session-file reachability")
+ }
+ for _, desc := range agent.BuiltinRuntimes {
+ want := desc.ProtocolFamily == "pi"
+ if got := providerUsesPiSessionFile(desc.ID); got != want {
+ t.Errorf("providerUsesPiSessionFile(%q) = %v, want %v for protocol family %q", desc.ID, got, want, desc.ProtocolFamily)
+ }
+ }
+}
+
func TestSessionHomeReachable(t *testing.T) {
t.Parallel()
@@ -2619,6 +2735,12 @@ func TestShouldRetryWithFreshSession(t *testing.T) {
priorSessionID: "stale-id",
want: true,
},
+ {
+ name: "temporarily busy resume retries without declaring the session dead",
+ result: agent.Result{Status: "failed", Error: "session already in use", ResumeRejectedTransient: true},
+ priorSessionID: "healthy-id",
+ want: true,
+ },
{
// The reported bug: the session belongs to another provider
// account and the backend echoes the requested id back on the
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 7eca7b2f76..2091f24159 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -336,7 +336,7 @@ type Environment struct {
// GC reclaimed between turns, a switched Hermes profile and an operator's
// `rm` all mount cleanly onto nothing. The daemon reads THIS, not the store
// path, as the answer to "can a prior session id still resolve here?" — see
- // gateResumeToReusedWorkdir.
+ // gateResumeToReachableSession.
HermesSessionHistoryPresent bool
// QwenpawWorkspace is the path to the per-task QwenPaw workspace directory
// (set only for the qwenpaw provider). It is populated with the bound skills
diff --git a/server/internal/daemon/pi_busy_retry_unix_test.go b/server/internal/daemon/pi_busy_retry_unix_test.go
new file mode 100644
index 0000000000..7a9634ed54
--- /dev/null
+++ b/server/internal/daemon/pi_busy_retry_unix_test.go
@@ -0,0 +1,101 @@
+//go:build !windows
+
+package daemon
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// TestRunTaskPiBusyRetryDoesNotRetireHealthySession pins the distinction
+// between a permanently rejected resume and a healthy transcript that another
+// execution owns temporarily. The busy attempt must still fall back to a fresh
+// session for this turn, but that fallback must not remove the original JSONL
+// from every future session lookup.
+func TestRunTaskPiBusyRetryDoesNotRetireHealthySession(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ priorSessionID := filepath.Join(t.TempDir(), "busy-session.jsonl")
+ claim, err := os.OpenFile(priorSessionID, os.O_CREATE|os.O_RDWR, 0o600)
+ if err != nil {
+ t.Fatalf("open prior session: %v", err)
+ }
+ defer claim.Close()
+ if _, err := claim.WriteString("{}\n"); err != nil {
+ t.Fatalf("seed prior session: %v", err)
+ }
+ if err := unix.Flock(int(claim.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
+ t.Fatalf("lock prior session: %v", err)
+ }
+ defer unix.Flock(int(claim.Fd()), unix.LOCK_UN) //nolint:errcheck -- best-effort test cleanup
+
+ fakeBin := filepath.Join(t.TempDir(), "pi")
+ script := `#!/bin/sh
+cat > /dev/null
+printf '%s\n' '{"type":"agent_start"}'
+printf '%s\n' '{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"done"}}'
+printf '%s\n' '{"type":"turn_end","message":{"role":"assistant","model":"test","usage":{"input":1,"output":1}}}'
+`
+ if err := os.WriteFile(fakeBin, []byte(script), 0o755); err != nil {
+ t.Fatalf("write fake pi: %v", err)
+ }
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: logger,
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: map[string]Runtime{"rt-pi": {ID: "rt-pi", Provider: "pi"}},
+ activeEnvRoots: make(map[string]int),
+ cfg: Config{
+ WorkspacesRoot: t.TempDir(),
+ AgentTimeout: 5 * time.Second,
+ ServerBaseURL: srv.URL,
+ Agents: map[string]AgentEntry{
+ "pi": {Path: fakeBin},
+ },
+ },
+ }
+ task := Task{
+ ID: "task-pi-busy",
+ WorkspaceID: "ws-pi",
+ RuntimeID: "rt-pi",
+ IssueID: "issue-pi",
+ AgentID: "agent-pi",
+ AuthToken: "mat_pi_busy",
+ PriorSessionID: priorSessionID,
+ Agent: &AgentData{
+ ID: "agent-pi",
+ Name: "pi-agent",
+ },
+ }
+
+ result, err := d.runTask(context.Background(), task, "pi", 0, logger)
+ if err != nil {
+ t.Fatalf("runTask: %v", err)
+ }
+ if result.Status != "completed" || result.Comment != "done" {
+ t.Fatalf("result = %+v, want successful fresh-session retry", result)
+ }
+ if result.SessionID == "" || result.SessionID == priorSessionID {
+ t.Fatalf("SessionID = %q, want a new session", result.SessionID)
+ }
+ if result.RetiredSessionID != "" {
+ t.Fatalf("RetiredSessionID = %q, want empty for a temporarily busy healthy session", result.RetiredSessionID)
+ }
+}
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index ea8d8dad3f..e3246d4a4c 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -200,7 +200,7 @@ type Result struct {
SessionID string
Usage map[string]TokenUsage // keyed by model name
// ResumeRejected is positive evidence that this run's requested resume
- // was itself refused — the transcript is gone, the session belongs to
+ // was permanently refused — the transcript is gone, the session belongs to
// another provider account, OR the session still exists but its history
// can no longer be replayed to the provider (e.g. GH #5975: a stored
// image now exceeds the provider's max dimensions, so every resumed
@@ -229,6 +229,12 @@ type Result struct {
// shouldRetryWithFreshSession, where "was this run a resume?" is already
// known. Do not encode it here.
ResumeRejected bool
+ // ResumeRejectedTransient is positive evidence that this run's requested
+ // resume cannot proceed right now, but the session itself remains healthy.
+ // The daemon may use a fresh session for this turn, but must not retire the
+ // requested session from future lookups. Backends must not set this together
+ // with ResumeRejected; the latter means the session is permanently unusable.
+ ResumeRejectedTransient bool
// codexInitializeRetrySafe is provider-internal evidence that an
// initialize timeout happened before semantic activity and after the
// process tree was reaped. It is intentionally not part of the public
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.go
index bd80d14346..049c10c700 100644
--- a/server/pkg/agent/pi.go
+++ b/server/pkg/agent/pi.go
@@ -226,6 +226,16 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
if err := ensurePiSessionFile(sessionPath); err != nil {
return nil, fmt.Errorf("%s session file: %w", label, err)
}
+ sessionLock, locked, err := tryLockPiSessionFile(sessionPath)
+ if err != nil {
+ return nil, fmt.Errorf("%s session lock: %w", label, err)
+ }
+ if !locked {
+ if opts.ResumeSessionID != "" {
+ return piSessionBusyResult(label, sessionPath), nil
+ }
+ return nil, fmt.Errorf("%s session file %q is already in use", label, sessionPath)
+ }
runCtx, cancel := runContext(ctx, timeout)
@@ -241,6 +251,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
stdout, err := cmd.StdoutPipe()
if err != nil {
+ releasePiSessionFileLock(sessionLock)
cancel()
return nil, fmt.Errorf("%s stdout pipe: %w", label, err)
}
@@ -251,6 +262,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
// Pi has been observed to wait indefinitely when stdin never reaches EOF.
stdin, err := cmd.StdinPipe()
if err != nil {
+ releasePiSessionFileLock(sessionLock)
cancel()
return nil, fmt.Errorf("%s stdin pipe: %w", label, err)
}
@@ -260,6 +272,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
closeStdin()
+ releasePiSessionFileLock(sessionLock)
cancel()
return nil, fmt.Errorf("start %s: %w", label, err)
}
@@ -289,6 +302,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
}()
go func() {
+ defer func() { releasePiSessionFileLock(sessionLock) }()
defer cancel()
defer close(msgCh)
defer close(resCh)
@@ -457,6 +471,12 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
b.cfg.Logger.Info(label+" finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())
+ // Publish the terminal result only after the transcript is available to
+ // a follow-up run. The result channel is buffered, so relying on a defer
+ // would let the receiver race ahead and spuriously treat the session as
+ // still busy after Pi had already exited.
+ releasePiSessionFileLock(sessionLock)
+ sessionLock = nil
resCh <- Result{
Status: finalStatus,
Output: output.String(),
@@ -470,6 +490,19 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions
return &Session{Messages: msgCh, Result: resCh}, nil
}
+func piSessionBusyResult(label, sessionPath string) *Session {
+ msgCh := make(chan Message)
+ close(msgCh)
+ resCh := make(chan Result, 1)
+ resCh <- Result{
+ Status: "failed",
+ Error: fmt.Sprintf("%s session file %q is already in use by another execution", label, sessionPath),
+ ResumeRejectedTransient: true,
+ }
+ close(resCh)
+ return &Session{Messages: msgCh, Result: resCh}
+}
+
// ── Pi event types ──
// piStreamEvent is the union of fields we consume from Pi's JSON event
diff --git a/server/pkg/agent/pi_session_lock_unix.go b/server/pkg/agent/pi_session_lock_unix.go
new file mode 100644
index 0000000000..b0458f5110
--- /dev/null
+++ b/server/pkg/agent/pi_session_lock_unix.go
@@ -0,0 +1,36 @@
+//go:build !windows
+
+package agent
+
+import (
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// tryLockPiSessionFile takes a non-blocking exclusive lock on the transcript.
+// The daemon can launch more than one task at a time, and Pi appends directly
+// to this JSONL, so the lock must cover the complete child-process lifetime.
+// The kernel releases it if the daemon dies.
+func tryLockPiSessionFile(path string) (*os.File, bool, error) {
+ f, err := os.OpenFile(path, os.O_RDWR, 0)
+ if err != nil {
+ return nil, false, err
+ }
+ if err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
+ _ = f.Close()
+ if err == unix.EWOULDBLOCK {
+ return nil, false, nil
+ }
+ return nil, false, err
+ }
+ return f, true, nil
+}
+
+func releasePiSessionFileLock(f *os.File) {
+ if f == nil {
+ return
+ }
+ _ = unix.Flock(int(f.Fd()), unix.LOCK_UN)
+ _ = f.Close()
+}
diff --git a/server/pkg/agent/pi_session_lock_windows.go b/server/pkg/agent/pi_session_lock_windows.go
new file mode 100644
index 0000000000..ff4e78fa3e
--- /dev/null
+++ b/server/pkg/agent/pi_session_lock_windows.go
@@ -0,0 +1,56 @@
+//go:build windows
+
+package agent
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+// tryLockPiSessionFile is the Windows equivalent of flock(LOCK_EX|LOCK_NB).
+// FILE_SHARE_DELETE keeps a held lock from pinning the session directory when
+// cleanup races a cancelled execution.
+func tryLockPiSessionFile(path string) (*os.File, bool, error) {
+ p, err := windows.UTF16PtrFromString(path)
+ if err != nil {
+ return nil, false, err
+ }
+ h, err := windows.CreateFile(
+ p,
+ windows.GENERIC_READ|windows.GENERIC_WRITE,
+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
+ nil,
+ windows.OPEN_EXISTING,
+ windows.FILE_ATTRIBUTE_NORMAL,
+ 0,
+ )
+ if err != nil {
+ return nil, false, err
+ }
+ f := os.NewFile(uintptr(h), path)
+ overlapped := new(windows.Overlapped)
+ err = windows.LockFileEx(
+ windows.Handle(f.Fd()),
+ windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
+ 0, 1, 0, overlapped,
+ )
+ if err == nil {
+ return f, true, nil
+ }
+ _ = f.Close()
+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
+ return nil, false, nil
+ }
+ return nil, false, err
+}
+
+func releasePiSessionFileLock(f *os.File) {
+ if f == nil {
+ return
+ }
+ overlapped := new(windows.Overlapped)
+ _ = windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, overlapped)
+ _ = f.Close()
+}
diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.go
index 70358bc19c..851a62451f 100644
--- a/server/pkg/agent/pi_test.go
+++ b/server/pkg/agent/pi_test.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
+ "os"
"path/filepath"
"runtime"
"strings"
@@ -161,6 +162,54 @@ func TestPiExecuteRejectsEmptyPrompt(t *testing.T) {
}
}
+func TestPiExecuteRejectsConcurrentSessionWriter(t *testing.T) {
+ t.Parallel()
+
+ sessionPath := filepath.Join(t.TempDir(), "session.jsonl")
+ if err := os.WriteFile(sessionPath, []byte("{}\n"), 0o644); err != nil {
+ t.Fatalf("create session file: %v", err)
+ }
+ claim, locked, err := tryLockPiSessionFile(sessionPath)
+ if err != nil {
+ t.Fatalf("lock session file: %v", err)
+ }
+ if !locked {
+ t.Fatal("first session-file lock was unexpectedly busy")
+ }
+ defer releasePiSessionFileLock(claim)
+
+ executable, err := os.Executable()
+ if err != nil {
+ t.Fatalf("locate test executable: %v", err)
+ }
+ backend, err := New("pi", Config{ExecutablePath: executable, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("New(pi): %v", err)
+ }
+ session, err := backend.Execute(t.Context(), "follow-up", ExecOptions{ResumeSessionID: sessionPath})
+ if err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+ for range session.Messages {
+ }
+ result, ok := <-session.Result
+ if !ok {
+ t.Fatal("result channel closed without a value")
+ }
+ if result.Status != "failed" || !result.ResumeRejectedTransient {
+ t.Fatalf("result = %+v, want failed ResumeRejectedTransient", result)
+ }
+ if result.ResumeRejected {
+ t.Fatal("a busy session is still healthy and must not be permanently rejected")
+ }
+ if result.SessionID != "" {
+ t.Fatalf("SessionID = %q, want empty so the live transcript is not republished", result.SessionID)
+ }
+ if !strings.Contains(result.Error, "already in use") {
+ t.Fatalf("error = %q, want session-in-use diagnostic", result.Error)
+ }
+}
+
// TestPiExecuteAttachesStdinPipe verifies that the Pi backend spawns the child
// with an explicit stdin pipe, writes the task prompt, and closes it. Closing
// delivers both the end-of-prompt signal and the EOF that keeps Pi from
@@ -225,6 +274,14 @@ func TestPiExecuteAttachesStdinPipe(t *testing.T) {
case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for result")
}
+ claim, locked, err := tryLockPiSessionFile(sessionPath)
+ if err != nil {
+ t.Fatalf("lock completed session: %v", err)
+ }
+ if !locked {
+ t.Fatal("Pi backend returned its result before releasing the session-file lock")
+ }
+ releasePiSessionFileLock(claim)
}
// piEventStreamScript builds a sh script that prints each JSON event on