Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1397,6 +1397,20 @@ moving approvals, or changing token totals. Transcript reads require a
connected shared app-server and omit turns that cannot be attributed to the
child (including inherited parent history).

Codex thread links in replies and transcript previews open **read-only session
previews** without switching the current session. In the terminal, click an
underlined link or press **L** to pick from the links on screen; press **Esc** to
go back. In the browser, activate the link with a click or **Enter**. **Back**
returns to the original reply without discarding a draft. Linked agents use
the same attributable-history rules as `/subagents`. Use **Open session** or
the separate **Resume** action to switch; previewing alone does not mark a
turn read or start work. Resume is unavailable in read-only web mode.

Previews require a connected shared app-server (Codex 0.170.0 or newer), a
ChatGPT account scope, and a target that the current account can verify.
Unverified targets, archived sessions and agents with unknown ownership are
not opened.

Use **`/ps`** from a live session's command browser to list the background
terminals reported by its shared app-server. The read-only panel shows the
command and directory, plus a PID only when Codex provides one. Refresh with
Expand Down
13 changes: 10 additions & 3 deletions internal/codex/daemon_status_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var errDaemonWriteGuardRejected = errors.New("daemon write superseded before sen

type daemonStatusProvider struct {
savedScope string
savedExactIDs bool
savedCatalog *savedMetadataIndex
resumedThreads map[string]resumedThread
names map[string]threadTitle
Expand Down Expand Up @@ -469,6 +470,7 @@ func (p *daemonStatusProvider) ensureConnected(ctx context.Context) error {
p.mu.Lock()
if p.connection == connection && supportsSavedScope(initialized.UserAgent) {
p.savedScope = rand.Text()
p.savedExactIDs = supportsSavedExactIDs(initialized.UserAgent)
}
p.mu.Unlock()
return nil
Expand Down Expand Up @@ -507,12 +509,16 @@ func (p *daemonStatusProvider) isSubscribed(threadID string) bool {
}

func (p *daemonStatusProvider) request(ctx context.Context, method string, params any, target any) error {
p.mu.Lock()
connection := p.connection
p.mu.Unlock()
connection, _ := p.currentTransport()
return p.requestOn(ctx, connection, method, params, target)
}

func (p *daemonStatusProvider) currentTransport() (*websocket.Conn, uint64) {
p.mu.Lock()
defer p.mu.Unlock()
return p.connection, p.commandGeneration
}

func (p *daemonStatusProvider) requestOn(ctx context.Context, connection *websocket.Conn, method string, params any, target any) error {
return p.requestOnChecked(ctx, connection, method, params, target, nil)
}
Expand Down Expand Up @@ -837,6 +843,7 @@ func (p *daemonStatusProvider) disconnect(connection *websocket.Conn) {
p.usageCoverage = nil
p.threadDirectories = nil
p.names, p.savedScope = nil, ""
p.savedExactIDs = false
p.clearSavedCatalogLocked()
p.resumedThreads = nil
p.threadAttachments = nil
Expand Down
11 changes: 8 additions & 3 deletions internal/codex/session_agents.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,20 @@ type agentHistoryProvider interface {
readSessionHistory(context.Context, string, time.Time) ([]SessionContext, bool, error)
}

func (r *LiveUsageReader) linkedAgents(parent, child string) ([]SessionAgent, time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
func (r *LiveUsageReader) sessionAgentRolloutsLocked() map[string]*rolloutCursor {
byID := map[string]*rolloutCursor{}
for _, c := range r.files {
if prev := byID[c.threadID]; c.threadID != "" && (prev == nil || c.activityTime().After(prev.activityTime())) {
byID[c.threadID] = c
}
}
return byID
}

func (r *LiveUsageReader) linkedAgents(parent, child string) ([]SessionAgent, time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
byID := r.sessionAgentRolloutsLocked()
root := byID[parent]
if root == nil || root.nonRoot || root.parentThreadID != "" {
return nil, time.Time{}
Expand Down
18 changes: 14 additions & 4 deletions internal/codex/session_finder_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,17 @@ func (p *daemonStatusProvider) finderNotificationLocked(method string, params js

// Older servers silently ignore unknown thread/list fields.
func supportsSavedScope(userAgent string) bool {
return savedServerAtLeast(userAgent, "go0.170.0")
}

func supportsSavedExactIDs(userAgent string) bool {
return savedServerAtLeast(userAgent, "go0.171.0")
}

func savedServerAtLeast(userAgent, minimum string) bool {
first, _, _ := strings.Cut(userAgent, " ")
_, v, ok := strings.Cut(first, "/")
return ok && version.IsValid("go"+v) && version.Compare("go"+v, "go0.170.0") >= 0
return ok && version.Compare("go"+v, minimum) >= 0
}

func (p *daemonStatusProvider) savedAccount(ctx context.Context, scope string) (string, error) {
Expand Down Expand Up @@ -109,6 +117,10 @@ func (p *daemonStatusProvider) listSaved(ctx context.Context, scope, cursor, sor
if cursor != "" {
params["cursor"] = cursor
}
return p.readSavedPage(ctx, conn, params)
}

func (p *daemonStatusProvider) readSavedPage(ctx context.Context, conn *websocket.Conn, params map[string]any) (SavedPage, error) {
var result struct {
Data []savedWireThread
NextCursor string
Expand All @@ -135,9 +147,7 @@ func (page *SavedPage) addWireThread(t savedWireThread) {
}

func (p *daemonStatusProvider) savedSessionAction(ctx context.Context, scope string) (*websocket.Conn, uint64, string, error) {
p.mu.Lock()
conn, generation := p.connection, p.commandGeneration
p.mu.Unlock()
conn, generation := p.currentTransport()
if conn == nil {
return nil, 0, "", ErrSavedSessions
}
Expand Down
10 changes: 7 additions & 3 deletions internal/codex/session_history_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"context"
"strings"
"time"

"github.com/gorilla/websocket"
)

type historyTurn struct {
Expand All @@ -30,9 +32,11 @@ func (p *daemonStatusProvider) SessionHistory(ctx context.Context, id string) ([
}

func (p *daemonStatusProvider) readSessionHistory(ctx context.Context, id string, ownedSince time.Time) ([]SessionContext, bool, error) {
p.mu.Lock()
conn, generation := p.connection, p.commandGeneration
p.mu.Unlock()
conn, generation := p.currentTransport()
return p.readSessionHistoryOn(ctx, conn, generation, id, ownedSince)
}

func (p *daemonStatusProvider) readSessionHistoryOn(ctx context.Context, conn *websocket.Conn, generation uint64, id string, ownedSince time.Time) ([]SessionContext, bool, error) {
// Bounded, newest-first history reads neither resume nor change a session.
// Do not fall back to an unbounded includeTurns read on older servers.
var response struct{ Data []historyTurn }
Expand Down
53 changes: 53 additions & 0 deletions internal/codex/session_links.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package codex

import (
"context"
"time"

"github.com/merefield/codexometer/internal/prose"
)

type SessionLinkPreview struct {
Root SavedSession `json:"root"`
Agent *SessionAgent `json:"agent,omitempty"`
Turns []SavedTurn `json:"turns,omitempty"`
UnverifiedTurns bool `json:"unverifiedTurns,omitempty"`
}

type SessionLinkClient interface {
PreviewSessionLink(context.Context, string, string) (SessionLinkPreview, error)
}

type sessionLinkProvider interface {
previewSessionLink(context.Context, *LiveUsageReader, string, string) (SessionLinkPreview, error)
}

func (c Client) PreviewSessionLink(ctx context.Context, scope, id string) (SessionLinkPreview, error) {
if c.LiveUsage != nil && scope != "" && len(scope) <= 128 && prose.ThreadID("codex://threads/"+id) != "" {
if p, ok := c.LiveUsage.statusProvider.(sessionLinkProvider); ok {
return p.previewSessionLink(ctx, c.LiveUsage, scope, id)
}
}
return SessionLinkPreview{}, ErrSavedSessions
}

// Only locally attributable agents are eligible; a missing or ambiguous spawn
// must not be treated as an ordinary transcript containing inherited history.
func (r *LiveUsageReader) sessionLinkTarget(id string) (root, name string, since time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
byID := r.sessionAgentRolloutsLocked()
child := byID[id]
if child == nil || child.parentThreadID == "" && !child.nonRoot {
return id, "", time.Time{}
}
root, unlinked := rolloutRoot(child, byID)
if unlinked || child.guardianReviewer || child.startedAt.IsZero() {
return "", "", time.Time{}
}
name = child.agentName
if name == "" {
name = r.sessionNames[id]
}
return root, singleLine(name), child.startedAt
}
67 changes: 67 additions & 0 deletions internal/codex/session_links_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//go:build unix

package codex

import "context"

func (p *daemonStatusProvider) previewSessionLink(ctx context.Context, reader *LiveUsageReader, scope, id string) (SessionLinkPreview, error) {
root, name, since := reader.sessionLinkTarget(id)
if root == "" {
return SessionLinkPreview{}, ErrSavedSessions
}
conn, generation, account, err := p.savedSessionAction(ctx, scope)
if err != nil {
return SessionLinkPreview{}, ErrSavedSessions
}
p.mu.Lock()
exact := p.savedExactIDs
p.mu.Unlock()
current := func() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.connection == conn && p.commandGeneration == generation && p.savedScope == scope
}
if !current() {
return SessionLinkPreview{}, ErrSavedSessions
}
var page SavedPage
if exact {
// The default source filter matches interactive roots only.
page, err = p.readSavedPage(ctx, conn, map[string]any{
"includedThreadIds": []string{root}, "currentAccountOnly": true, "archived": false,
"modelProviders": []string{}, "limit": 1, "useStateDbOnly": true,
})
} else {
// Codex 0.170 has account scoping, but silently ignores includedThreadIds.
page, err = savedPageFor(ctx, p, scope, "", root)
}
if err != nil || exact && len(page.Sessions) != 1 || !current() {
return SessionLinkPreview{}, ErrSavedSessions
}
var row SavedSession
for _, candidate := range page.Sessions {
if candidate.ID == root {
row = candidate
break
}
}
if row.ID == "" {
return SessionLinkPreview{}, ErrSavedSessions
}
turns, unverified, err := p.readSessionHistoryOn(ctx, conn, generation, id, since)
if err != nil {
return SessionLinkPreview{}, ErrSavedSessions
}
if verified, err := p.savedAccount(ctx, scope); err != nil || account != verified || !current() {
return SessionLinkPreview{}, ErrSavedSessions
}
if target, _, at := reader.sessionLinkTarget(id); target != root || at != since {
return SessionLinkPreview{}, ErrSavedSessions
}
reader.protectSessionHistory(id, turns)
preview := SessionLinkPreview{Root: row, Turns: savedTurns(turns), UnverifiedTurns: unverified}
if root != id {
preview.Agent = &SessionAgent{ID: id, Name: name}
}
return preview, nil
}
97 changes: 97 additions & 0 deletions internal/codex/session_links_unix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//go:build unix

package codex

import (
"testing"
"time"
)

func TestLinkedSessionPreviewVerifiesAccountAndAgentHistory(t *testing.T) {
const root = "550e8400-e29b-41d4-a716-446655440000"
const child = "550e8400-e29b-41d4-a716-446655440001"
const missing = "550e8400-e29b-41d4-a716-446655440002"
p, f := newQuotaDaemon(t)
now := time.Now()
turn := func(id string, sec int64, reply string) map[string]any {
return map[string]any{"id": id, "startedAt": sec, "status": "completed", "items": []any{map[string]string{"id": id + "-answer", "type": "agentMessage", "phase": "final_answer", "text": reply}}}
}
f.catalogues = map[string]map[string]any{
"initialize": {"userAgent": "codex/0.172.0 (Linux)"},
"account/read": {"account": map[string]string{"type": "chatgpt", "email": "someone@example.test"}},
"thread/list": {"data": []any{map[string]string{"id": root, "name": "Root"}}},
"thread/turns/list": {"data": []any{turn("two", now.Unix()+1, "Agent-owned result"), turn("one", now.Unix()-1, "Earlier parent context")}},
}
ctx := t.Context()
if err := p.ensureConnected(ctx); err != nil {
t.Fatal(err)
}
p.mu.Lock()
scope := p.savedScope
p.mu.Unlock()
c := Client{LiveUsage: &LiveUsageReader{statusProvider: p, files: map[string]*rolloutCursor{
"root": {threadID: root}, "child": {threadID: child, parentThreadID: root, nonRoot: true, agentName: "Worker", startedAt: now},
}}}
if got, err := c.PreviewSessionLink(ctx, scope, missing); err == nil || len(got.Turns) != 0 {
t.Fatal("unlisted target was exposed", got, err)
}
if got, err := c.PreviewSessionLink(ctx, scope, root); err != nil || got.Root.ID != root || got.Agent != nil || len(got.Turns) != 2 {
t.Fatal("verified root not previewed", got, err)
}
if got, err := c.PreviewSessionLink(ctx, scope, child); err != nil || got.Root.ID != root || got.Agent == nil || got.Agent.Name != "Worker" || len(got.Turns) != 1 || got.Turns[0].Reply != "Agent-owned result" {
t.Fatal("agent preview was not limited to owned history", got, err)
}
f.mu.Lock()
if len(f.historyReads) != 2 || len(f.resumeReads)+len(f.writes)+len(f.readUpdates) != 0 || f.savedReads[1]["currentAccountOnly"] != true || f.savedReads[1]["archived"] != false || f.savedReads[1]["limit"] != float64(1) {
t.Error("unexpected history or write traffic", f.savedReads, f.historyReads, f.resumeReads)
}
if ids, ok := f.savedReads[2]["includedThreadIds"].([]any); !ok || len(ids) != 1 || ids[0] != root {
t.Error("agent lookup was not scoped to owning session", f.savedReads[2])
}
f.historyReadHook = func() { p.mu.Lock(); defer p.mu.Unlock(); p.finderNotificationLocked("account/updated", nil) }
f.mu.Unlock()
if got, err := c.PreviewSessionLink(ctx, scope, root); err == nil || len(got.Turns) != 0 {
t.Fatal("account switched while preview loaded", got, err)
}
}

func TestLinkedSessionPreviewFindsOlderAccountScopedThreadOnCodex170(t *testing.T) {
const id = "550e8400-e29b-41d4-a716-446655440001"
const missing = "550e8400-e29b-41d4-a716-446655440002"
p, f := newQuotaDaemon(t)
f.catalogues = map[string]map[string]any{
"initialize": {"userAgent": "codex/0.170.0 (Linux)"},
"account/read": {"account": map[string]string{"type": "chatgpt", "email": "someone@example.test"}},
"thread/turns/list": {"data": []any{}},
}
newest := map[string]any{"data": []any{map[string]string{"id": "unrelated"}}, "nextCursor": "older"}
f.savedPages = map[[2]string]map[string]any{
{"updated_at", ""}: newest,
{"created_at", ""}: newest,
{"created_at", "older"}: {"data": []any{map[string]string{"id": id, "name": "Earlier work"}}},
}
ctx := t.Context()
if err := p.ensureConnected(ctx); err != nil {
t.Fatal(err)
}
p.mu.Lock()
scope := p.savedScope
p.mu.Unlock()
c := Client{LiveUsage: &LiveUsageReader{statusProvider: p}}
if got, err := c.PreviewSessionLink(ctx, scope, id); err != nil || got.Root.ID != id || got.Root.Name != "Earlier work" {
t.Fatal("could not preview older matching thread", got, err)
}
if got, err := c.PreviewSessionLink(ctx, scope, missing); err == nil || got.Root.ID != "" {
t.Fatal("unlisted target was exposed", got, err)
}
f.mu.Lock()
defer f.mu.Unlock()
if len(f.historyReads) != 1 || f.historyReads[0]["threadId"] != id || len(f.resumeReads)+len(f.writes)+len(f.readUpdates) != 0 {
t.Fatal("unexpected history or write traffic", f.historyReads, f.resumeReads)
}
for _, params := range f.savedReads {
if _, hasExactIDs := params["includedThreadIds"]; hasExactIDs || params["currentAccountOnly"] != true || params["archived"] != false {
t.Fatal("legacy lookup lost account scope or used an unsupported filter", params)
}
}
}
4 changes: 4 additions & 0 deletions internal/i18n/locales/da.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"LINKS": "LINKS",
"SESSION PREVIEW": "FORHÅNDSVISNING AF SESSION",
"OPEN SESSION": "ÅBN SESSION",
"Session unavailable here.": "Sessionen er ikke tilgængelig her.",
"PIE // %d%% USED": "CIRKEL // %d%% BRUGT",
"RING // %d%% ELAPSED": "RING // %d%% FORLØBET",
"RING %d%% ELAPSED": "RING %d%% FORLØBET",
Expand Down
4 changes: 4 additions & 0 deletions internal/i18n/locales/de.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"LINKS": "LINKS",
"SESSION PREVIEW": "SITZUNGSVORSCHAU",
"OPEN SESSION": "SITZUNG ÖFFNEN",
"Session unavailable here.": "Sitzung hier nicht verfügbar.",
"PIE // %d%% USED": "KREIS // %d%% VERBRAUCHT",
"RING // %d%% ELAPSED": "RING // %d%% VERSTRICHEN",
"RING %d%% ELAPSED": "RING %d%% VERSTRICHEN",
Expand Down
Loading
Loading