Skip to content

Commit 0fdc157

Browse files
fix(runtime): detect saved opencode sessions across both storage generations
Revive's resume gate now covers opencode: opencodeHasSession checks the legacy file layout (project/<encoded>/storage/session/info/ses_*.json) and the current SQLite store (opencode.db, root sessions only via parent_id IS NULL, queried through a bounded 3s sqlite3 seam). The gate exists because opencode --continue with no session is not graceful (it hung the TUI upstream, anomalyco/opencode#23437). Everything fails closed to a fresh launch. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <[email protected]>
1 parent f01d114 commit 0fdc157

2 files changed

Lines changed: 262 additions & 7 deletions

File tree

‎internal/runtime/native.go‎

Lines changed: 82 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ import (
2727
"sort"
2828
"strconv"
2929
"strings"
30-
3130
"time"
3231

32+
"os/exec"
33+
3334
"github.com/sushidev-team/lola/internal/agent"
3435
"github.com/sushidev-team/lola/internal/config"
3536
"github.com/sushidev-team/lola/internal/devtab"
@@ -1149,11 +1150,12 @@ func (n *Native) Alive(ctx context.Context, s session.Session) bool {
11491150
// whose worktree survives (dead sessions keep their worktree for inspection).
11501151
// It reuses the existing worktree and its .lola artifacts (prompt, settings,
11511152
// env) exactly as the original spawn left them and relaunches the agent in
1152-
// place: when the agent is Claude AND it wrote a transcript before dying, the
1153-
// pane comes back with `claude --continue` and resumes the prior conversation
1154-
// (launchCommand resume=true); otherwise it launches fresh on the same worktree
1155-
// — the case for a session that died so fast it never recorded a transcript
1156-
// (an empty --continue would just error and re-kill the pane).
1153+
// place: when the agent is Claude and it wrote a transcript before dying, or
1154+
// opencode and it saved a session, the pane comes back with `--continue` and
1155+
// resumes the prior conversation (launchCommand resume=true); otherwise it
1156+
// launches fresh on the same worktree — the case for a session that died so
1157+
// fast it never recorded anything (an empty --continue would just error and
1158+
// re-kill the pane).
11571159
//
11581160
// The caller (daemon.handleRevive) is responsible for the checks Revive does
11591161
// not do: that the session is not already alive, and re-establishing the
@@ -1166,7 +1168,8 @@ func (n *Native) Revive(ctx context.Context, s session.Session) (session.Session
11661168
return session.Session{}, fmt.Errorf("runtime: revive %s: worktree %s is gone — let the issue re-dispatch instead", id, dir)
11671169
}
11681170
kind := agent.Parse(s.Agent)
1169-
resume := kind == agent.Claude && claudeHasTranscript(dir)
1171+
resume := (kind == agent.Claude && claudeHasTranscript(dir)) ||
1172+
(kind == agent.OpenCode && opencodeHasSession(ctx, dir))
11701173
if err := n.Tmux.NewSession(ctx, id, dir, n.launchCommand(id, kind, resume)); err != nil {
11711174
return session.Session{}, fmt.Errorf("runtime: revive %s: %w", id, err)
11721175
}
@@ -1202,6 +1205,78 @@ func claudeHasTranscript(dir string) bool {
12021205
return len(matches) > 0
12031206
}
12041207

1208+
// opencodeHasSession reports whether opencode has a saved session for the
1209+
// worktree at dir — i.e. whether `opencode --continue` has anything to resume.
1210+
// The gate exists because `--continue` with no prior session is not graceful
1211+
// (it hung the TUI upstream, anomalyco/opencode#23437, later made a clean
1212+
// error-exit), so Revive must know a session exists before passing it.
1213+
// opencode has used TWO storage generations, and either may hold the session:
1214+
//
1215+
// - Legacy (pre-SQLite): sessions live under
1216+
// <data-root>/opencode/project/<encoded-dir>/storage/session/info/ses_*.json,
1217+
// where <encoded-dir> is the worktree's absolute path with the leading "/"
1218+
// stripped and the remaining "/" replaced by "-".
1219+
// - Current (SQLite): sessions live in <data-root>/opencode/opencode.db,
1220+
// table `session`, column `directory` holding the worktree path verbatim.
1221+
// Only ROOT sessions count (`parent_id IS NULL`) — that mirrors what
1222+
// `--continue` actually picks (the most recent root session; child/subagent
1223+
// sessions don't).
1224+
//
1225+
// `--continue` resumes the last session of the CURRENT directory, and each lola
1226+
// session owns its worktree, so that resolves to the right conversation. The
1227+
// data root is $XDG_DATA_HOME (read at call time) or ~/.local/share. Best-effort
1228+
// and fail-closed: an unresolvable data root, a glob error, a missing sqlite3,
1229+
// a locked db or any query failure means "no session", so Revive launches fresh.
1230+
func opencodeHasSession(ctx context.Context, dir string) bool {
1231+
root := opencodeDataRoot()
1232+
if root == "" {
1233+
return false
1234+
}
1235+
// Legacy generation.
1236+
encoded := strings.ReplaceAll(strings.TrimPrefix(dir, "/"), "/", "-")
1237+
matches, _ := filepath.Glob(filepath.Join(root, "opencode", "project", encoded, "storage", "session", "info", "ses_*.json"))
1238+
if len(matches) > 0 {
1239+
return true
1240+
}
1241+
// Current generation: the SQLite store, when it exists.
1242+
db := filepath.Join(root, "opencode", "opencode.db")
1243+
if fi, err := os.Stat(db); err != nil || fi.IsDir() {
1244+
return false
1245+
}
1246+
return opencodeSessionInDB(ctx, db, dir)
1247+
}
1248+
1249+
// opencodeDataRoot resolves opencode's data directory: $XDG_DATA_HOME when set
1250+
// (read at call time so tests can override it), else ~/.local/share. Returns ""
1251+
// when neither resolves, which callers treat as "no session".
1252+
func opencodeDataRoot() string {
1253+
if root := os.Getenv("XDG_DATA_HOME"); root != "" {
1254+
return root
1255+
}
1256+
home, err := os.UserHomeDir()
1257+
if err != nil || home == "" {
1258+
return ""
1259+
}
1260+
return filepath.Join(home, ".local", "share")
1261+
}
1262+
1263+
// opencodeSessionInDB reports whether opencode's SQLite session store at db
1264+
// holds a root session for dir. Seam: overridden in tests; the default shells
1265+
// the sqlite3 CLI (ships with macOS), bounded and fail-closed — a missing
1266+
// binary, a locked db, a timeout or a schema mismatch all answer false.
1267+
var opencodeSessionInDB = func(ctx context.Context, db, dir string) bool {
1268+
qctx, cancel := context.WithTimeout(ctx, 3*time.Second)
1269+
defer cancel()
1270+
// SQLite string-literal escaping: double the single quotes.
1271+
esc := strings.ReplaceAll(dir, "'", "''")
1272+
query := "SELECT 1 FROM session WHERE directory = '" + esc + "' AND parent_id IS NULL LIMIT 1;"
1273+
out, err := exec.CommandContext(qctx, "sqlite3", db, query).Output()
1274+
if err != nil {
1275+
return false
1276+
}
1277+
return strings.TrimSpace(string(out)) == "1"
1278+
}
1279+
12051280
// issueFromSessionID recovers the Linear identifier from a session ID built
12061281
// by SessionID for the given project (retry suffixes like "-r2" are
12071282
// stripped), or "" when the ID has another shape.

‎internal/runtime/native_test.go‎

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1525,6 +1525,186 @@ func TestReviveResumesWhenTranscriptExists(t *testing.T) {
15251525
}
15261526
}
15271527

1528+
// TestReviveResumesOpenCodeWhenSessionExists: when opencode saved a session for
1529+
// the worktree, revive relaunches with --continue --auto (and no --prompt) so
1530+
// the agent resumes its prior conversation instead of starting over.
1531+
func TestReviveResumesOpenCodeWhenSessionExists(t *testing.T) {
1532+
f := newFixture(t, "", "")
1533+
xdg := t.TempDir()
1534+
t.Setenv("XDG_DATA_HOME", xdg)
1535+
t.Setenv("HOME", t.TempDir()) // no claude transcript either
1536+
id := "lola-nori-eng-78"
1537+
dir := filepath.Join(f.root, "nori", id)
1538+
if err := os.MkdirAll(filepath.Join(dir, lolaDir), 0o700); err != nil {
1539+
t.Fatal(err)
1540+
}
1541+
// opencode's project dir is the worktree path with the leading "/" stripped
1542+
// and the remaining "/" replaced by "-".
1543+
encoded := strings.ReplaceAll(strings.TrimPrefix(dir, "/"), "/", "-")
1544+
info := filepath.Join(xdg, "opencode", "project", encoded, "storage", "session", "info")
1545+
if err := os.MkdirAll(info, 0o755); err != nil {
1546+
t.Fatal(err)
1547+
}
1548+
if err := os.WriteFile(filepath.Join(info, "ses_test.json"), []byte("{}\n"), 0o644); err != nil {
1549+
t.Fatal(err)
1550+
}
1551+
s := session.Session{ID: id, Source: "native", Project: "nori", Issue: "ENG-78", Agent: "opencode", Status: "dead"}
1552+
if _, err := f.n.Revive(context.Background(), s); err != nil {
1553+
t.Fatalf("Revive: %v", err)
1554+
}
1555+
tmuxCalls := loggedArgs(t, f.tmuxLog)
1556+
if !strings.Contains(tmuxCalls, "--continue") || !strings.Contains(tmuxCalls, "--auto") {
1557+
t.Errorf("saved opencode session → revive must resume via --continue --auto:\n%s", tmuxCalls)
1558+
}
1559+
if strings.Contains(tmuxCalls, "--prompt") {
1560+
t.Errorf("opencode resume must not pass --prompt (broken with --continue upstream):\n%s", tmuxCalls)
1561+
}
1562+
}
1563+
1564+
// TestReviveOpenCodeFreshWithoutSession: an opencode session with no saved
1565+
// opencode session launches fresh (the --prompt briefing, no --continue).
1566+
func TestReviveOpenCodeFreshWithoutSession(t *testing.T) {
1567+
f := newFixture(t, "", "")
1568+
t.Setenv("XDG_DATA_HOME", t.TempDir())
1569+
t.Setenv("HOME", t.TempDir())
1570+
id := "lola-nori-eng-79"
1571+
if err := os.MkdirAll(filepath.Join(f.root, "nori", id, lolaDir), 0o700); err != nil {
1572+
t.Fatal(err)
1573+
}
1574+
s := session.Session{ID: id, Source: "native", Project: "nori", Issue: "ENG-79", Agent: "opencode", Status: "dead"}
1575+
if _, err := f.n.Revive(context.Background(), s); err != nil {
1576+
t.Fatalf("Revive: %v", err)
1577+
}
1578+
tmuxCalls := loggedArgs(t, f.tmuxLog)
1579+
if !strings.Contains(tmuxCalls, "--prompt") {
1580+
t.Errorf("no saved opencode session → revive must launch fresh with --prompt:\n%s", tmuxCalls)
1581+
}
1582+
if strings.Contains(tmuxCalls, "--continue") {
1583+
t.Errorf("no saved opencode session → must not resume:\n%s", tmuxCalls)
1584+
}
1585+
}
1586+
1587+
// plantOpencodeDB creates a real minimal opencode SQLite session store at
1588+
// <xdg>/opencode/opencode.db with the given rows (directory, parent_id).
1589+
func plantOpencodeDB(t *testing.T, xdg string, rows []struct{ dir, parent string }) {
1590+
t.Helper()
1591+
if _, err := exec.LookPath("sqlite3"); err != nil {
1592+
t.Skip("sqlite3 not on PATH")
1593+
}
1594+
dir := filepath.Join(xdg, "opencode")
1595+
if err := os.MkdirAll(dir, 0o755); err != nil {
1596+
t.Fatal(err)
1597+
}
1598+
db := filepath.Join(dir, "opencode.db")
1599+
args := []string{db, "CREATE TABLE session (id text PRIMARY KEY, parent_id text, directory text NOT NULL);"}
1600+
for i, r := range rows {
1601+
args = append(args, fmt.Sprintf("INSERT INTO session (id, parent_id, directory) VALUES ('ses_%d', %s, '%s');",
1602+
i, sqlNull(r.parent), r.dir))
1603+
}
1604+
if out, err := exec.Command("sqlite3", args...).CombinedOutput(); err != nil {
1605+
t.Fatalf("plant opencode db: %v\n%s", err, out)
1606+
}
1607+
}
1608+
1609+
// sqlNull renders s as a SQL literal, NULL for the empty string.
1610+
func sqlNull(s string) string {
1611+
if s == "" {
1612+
return "NULL"
1613+
}
1614+
return "'" + s + "'"
1615+
}
1616+
1617+
// TestReviveResumesOpenCodeFromSQLite: current opencode builds store sessions
1618+
// in SQLite (<data-root>/opencode/opencode.db, table session, column
1619+
// directory); a root session (parent_id NULL) for the worktree makes revive
1620+
// resume via --continue --auto.
1621+
func TestReviveResumesOpenCodeFromSQLite(t *testing.T) {
1622+
f := newFixture(t, "", "")
1623+
xdg := t.TempDir()
1624+
t.Setenv("XDG_DATA_HOME", xdg)
1625+
t.Setenv("HOME", t.TempDir())
1626+
id := "lola-nori-eng-80"
1627+
dir := filepath.Join(f.root, "nori", id)
1628+
if err := os.MkdirAll(filepath.Join(dir, lolaDir), 0o700); err != nil {
1629+
t.Fatal(err)
1630+
}
1631+
plantOpencodeDB(t, xdg, []struct{ dir, parent string }{{dir, ""}})
1632+
s := session.Session{ID: id, Source: "native", Project: "nori", Issue: "ENG-80", Agent: "opencode", Status: "dead"}
1633+
if _, err := f.n.Revive(context.Background(), s); err != nil {
1634+
t.Fatalf("Revive: %v", err)
1635+
}
1636+
tmuxCalls := loggedArgs(t, f.tmuxLog)
1637+
if !strings.Contains(tmuxCalls, "--continue") || !strings.Contains(tmuxCalls, "--auto") {
1638+
t.Errorf("root session in the SQLite store → revive must resume via --continue --auto:\n%s", tmuxCalls)
1639+
}
1640+
if strings.Contains(tmuxCalls, "--prompt") {
1641+
t.Errorf("opencode resume must not pass --prompt:\n%s", tmuxCalls)
1642+
}
1643+
}
1644+
1645+
// TestReviveOpenCodeFreshWhenDBHasNoRootSession: the SQLite store exists but
1646+
// holds only a child session (parent_id set) for the worktree — --continue
1647+
// picks root sessions only, so revive launches fresh.
1648+
func TestReviveOpenCodeFreshWhenDBHasNoRootSession(t *testing.T) {
1649+
f := newFixture(t, "", "")
1650+
xdg := t.TempDir()
1651+
t.Setenv("XDG_DATA_HOME", xdg)
1652+
t.Setenv("HOME", t.TempDir())
1653+
id := "lola-nori-eng-81"
1654+
dir := filepath.Join(f.root, "nori", id)
1655+
if err := os.MkdirAll(filepath.Join(dir, lolaDir), 0o700); err != nil {
1656+
t.Fatal(err)
1657+
}
1658+
plantOpencodeDB(t, xdg, []struct{ dir, parent string }{{dir, "ses_0"}})
1659+
s := session.Session{ID: id, Source: "native", Project: "nori", Issue: "ENG-81", Agent: "opencode", Status: "dead"}
1660+
if _, err := f.n.Revive(context.Background(), s); err != nil {
1661+
t.Fatalf("Revive: %v", err)
1662+
}
1663+
tmuxCalls := loggedArgs(t, f.tmuxLog)
1664+
if !strings.Contains(tmuxCalls, "--prompt") {
1665+
t.Errorf("no root session in the SQLite store → revive must launch fresh with --prompt:\n%s", tmuxCalls)
1666+
}
1667+
if strings.Contains(tmuxCalls, "--continue") {
1668+
t.Errorf("no root session in the SQLite store → must not resume:\n%s", tmuxCalls)
1669+
}
1670+
}
1671+
1672+
// TestReviveOpenCodeSeamConsulted: the SQLite seam is what answers the resume
1673+
// gate — an empty db file (no tables, so the real query would fail) plus a
1674+
// seam override returning true makes revive resume. Proves the wiring without
1675+
// sqlite3.
1676+
func TestReviveOpenCodeSeamConsulted(t *testing.T) {
1677+
f := newFixture(t, "", "")
1678+
xdg := t.TempDir()
1679+
t.Setenv("XDG_DATA_HOME", xdg)
1680+
t.Setenv("HOME", t.TempDir())
1681+
id := "lola-nori-eng-82"
1682+
dir := filepath.Join(f.root, "nori", id)
1683+
if err := os.MkdirAll(filepath.Join(dir, lolaDir), 0o700); err != nil {
1684+
t.Fatal(err)
1685+
}
1686+
if err := os.MkdirAll(filepath.Join(xdg, "opencode"), 0o755); err != nil {
1687+
t.Fatal(err)
1688+
}
1689+
if err := os.WriteFile(filepath.Join(xdg, "opencode", "opencode.db"), nil, 0o644); err != nil {
1690+
t.Fatal(err)
1691+
}
1692+
orig := opencodeSessionInDB
1693+
opencodeSessionInDB = func(ctx context.Context, db, dir string) bool { return true }
1694+
defer func() { opencodeSessionInDB = orig }()
1695+
s := session.Session{ID: id, Source: "native", Project: "nori", Issue: "ENG-82", Agent: "opencode", Status: "dead"}
1696+
if _, err := f.n.Revive(context.Background(), s); err != nil {
1697+
t.Fatalf("Revive: %v", err)
1698+
}
1699+
tmuxCalls := loggedArgs(t, f.tmuxLog)
1700+
if !strings.Contains(tmuxCalls, "--continue") || !strings.Contains(tmuxCalls, "--auto") {
1701+
t.Errorf("seam says a session exists → revive must resume via --continue --auto:\n%s", tmuxCalls)
1702+
}
1703+
if strings.Contains(tmuxCalls, "--prompt") {
1704+
t.Errorf("opencode resume must not pass --prompt:\n%s", tmuxCalls)
1705+
}
1706+
}
1707+
15281708
// TestReviveWorktreeGoneErrors: with the worktree removed there is nothing to
15291709
// resume, so Revive errors (and never touches tmux) rather than launching into
15301710
// a missing directory.

0 commit comments

Comments
 (0)