diff --git a/README.md b/README.md index 219d4e5..4b3c150 100644 --- a/README.md +++ b/README.md @@ -1481,10 +1481,14 @@ This does not build a separate on-disk index or change the live Filter box. In write-enabled web mode, choose **New session** beside **Saved sessions**. With the same shared server, this opens a blank composer without creating a Codex thread. Check the working directory, then send the first message to -start it using Codex's normal defaults. The selected directory must already -be explicitly trusted in Codex's user configuration; use the same directory -where you approved folder trust in Codex (usually the repository root). -Codexometer does not grant trust. Type **`/resume`** or choose **Resume** +start it using Codex's normal defaults. In the terminal, if Codex has no trust +decision for the directory, **Trust & send** shows the exact path and asks +you to save trust before starting. **Esc** goes back without losing the draft. +Trusted folder settings and hooks can run before the first message; this +confirmation is required even with `--confirmation none`. Codexometer never overrides +an untrusted decision or grants trust to a broader path. If Codex expects a +Git repository root, select that root. The browser still requires a directory +already explicitly trusted in Codex. Type **`/resume`** or choose **Resume** (**Saved sessions** in web mode) in the draft to open an existing conversation instead. Closing the picker returns to your draft. Closing the draft before sending creates nothing. Strict confirmation mode reviews the exact folder and first @@ -2041,22 +2045,23 @@ usage and does not change token totals, quota learning or API-EQ calculations. | `/model` | Advertised models, their descriptions and supported reasoning levels. Save the next-turn setting in Codex immediately, even while a turn is running. Choosing a model resets its explicit speed override to the server default. | | Advertised speed commands, such as `/fast` | Show the default speed and every advertised tier in one list, initially highlighting the current speed. Up/Down highlights; **Enter APPLY** or clicking a choice applies it without a second confirmation by default. IDs and descriptions come from the current model's catalogue; no tier IDs are guessed. The changed speed is verified before success is reported. | | `/plan` | Advertised collaboration modes, using Codex's built-in mode instructions. | -| `/permissions` | Native permission profiles, approval policies and reviewer selection, subject to Codex's managed requirements. Also accepts `/permissions [--approval-policy=] [--reviewer=user\|auto_review]`. Changes are verified against the running session. | +| `/permissions` | The same starter choices as Codex CLI: **Ask for approval**, **Approve for me**, **Full Access**, **Read Only**, then any custom profiles. Availability follows Codex's requirements. Also accepts `/permissions [--approval-policy=] [--reviewer=user\|auto_review]`. Changes are verified against the running session. | | `/approve` | Review a recently observed native Auto-review denial and record consent for **one retry of that exact action**. It does not run the action directly; the retry still passes through Auto-review. | | `/skills`, `/apps`, `/mcp`, `/hooks`, `/experimental` | **Browse-only** live inventories and supplied help, including MCP tool descriptions. Invoke/configure these through Codex. | | `/help` | Available command families. Unsupported or empty catalogues are omitted. | -**Native Auto-review:** use `/permissions` → **Reviewer** to choose **Human** -or **Auto-review** for the selected session. This does not change its sandbox. -The server must expose reviewer settings, enable `guardian_approval`, and permit -the choice under its managed requirements. For example: +**Native Auto-review:** choose **Approve for me** in `/permissions` to use +workspace permissions with Codex's native reviewer, or **Ask for approval** +to use workspace permissions with human review. Like the Codex CLI, the picker +only shows **Approve for me** when `guardian_approval` is enabled. Managed +requirements can make a displayed choice unavailable. To apply a specific +profile, policy and reviewer, use inline arguments, for example: ```text /permissions :workspace --approval-policy=on-request --reviewer=auto_review ``` -Profile IDs come from the live catalogue; `:workspace` is an example, not a -hard-coded fallback. Quoted arguments and native granular policy JSON are +Profile IDs are checked against the live catalogue. Quoted arguments and native granular policy JSON are accepted. The menu spells out which kinds of approval **prompts** a managed policy enables or disables; enabling a prompt does not grant permission. Profile, policy and reviewer changes target subsequent turns. An @@ -2274,7 +2279,7 @@ and speed choices can affect quota consumption or API cost. | Setting | Behaviour | |---|---| | Omitted | Balanced default: confirm higher-impact actions. | -| `--confirmation none` | Skip extra confirmations, except quota-reset redemption. Native denial inspection still precedes an explicit Apply action. | +| `--confirmation none` | Skip extra confirmations, except quota-reset redemption and granting folder trust. Native denial inspection still precedes an explicit Apply action. | | `--confirmation require` | Confirm every substantive action; navigation and viewing stay immediate. | ```sh @@ -2282,7 +2287,7 @@ codexometer --confirmation none codexometer --web --web-control --confirmation require ``` -**Quota-reset redemption always requires confirmation, in every mode.** Strict +**Quota-reset redemption and granting folder trust always require confirmation.** Strict mode also reviews ordinary terminal replies, active-turn steer/queue/interrupt actions, queued-message edits and trigger deletion. Reviews bind the exact target, payload and live capability, expire, and can be cancelled without discarding the diff --git a/SECURITY.md b/SECURITY.md index 2978c26..a9c7e8b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -61,8 +61,8 @@ reset redemption still have no routes. Reversible session-local slash changes (name, model/reasoning, advertised speed, and collaboration mode) apply on explicit selection without a second UI click. Permissions, directories and unknown actions remain guarded by default. -`--no-confirm` is a launch-only opt-out from other Codexometer confirmation clicks; -quota-reset redemption remains guarded even with this option. It does not select +`--confirmation none` is a launch-only opt-out from other Codexometer confirmation clicks; +quota-reset redemption and terminal folder trust remain guarded. It does not select approvals automatically, change Codex sandbox policies, enable read-only web control routes or bypass server-side preparation/commit, source freshness, revision, one-use capability or replay validation. Browser preparation and commit @@ -70,7 +70,13 @@ remain distinct protected requests even when one user action runs both phases. Never infer an action's risk from its display label: the shared adapter marks only an explicit allowlist of reversible RPC methods/fields. Unknown metadata requires confirmation by default. Test both policies, including unavailable -actions, failed preparation, stale/replaced requests and the reset exception. +actions, failed preparation, stale/replaced requests and the mandatory confirmations. + +Folder trust can only be granted in the terminal's New Session draft. Confirmation +must show the full canonical path and the warning about project settings and hooks. +Never grant trust implicitly, expand it to a parent path, override an untrusted +decision, or expose the write in web mode. Use Codex's version-checked user config +RPC and verify effective trust before sending `thread/start` or the first prompt. Prepared bodies are limited to 64 KiB and each answer to 4,096 characters. At most one prepared action is retained for 30 seconds per server; replacement invalidates diff --git a/docs/slash-command-support.md b/docs/slash-command-support.md index 1b9cef3..173a19f 100644 --- a/docs/slash-command-support.md +++ b/docs/slash-command-support.md @@ -36,7 +36,7 @@ Aliases on one row share the rating and implementation. Lifecycle commands share - Provider-aware model/speed discovery and threshold validation on Codex 0.169+, plus thread/environment-aware `/hooks` discovery on 0.166+. - In the terminal and writable web composer, a space after a supported command opens its parameter list. Type `/goal resume` to narrow it to **Resume goal**, or type through the model and reasoning choices. Browsing does not run a command. - Reversible settings normally need no extra confirmation. Choose `/model` during work to set the model for the next turn without interrupting the current one. The launch confirmation policy does not override Codex's permissions or mandatory human checkpoints. -- The Sessions list now has a **New session** draft (terminal **N**) and a separate saved-session picker (terminal **R** or `/resume`). The first send starts a thread in an already trusted working directory. Read-only web can browse saved sessions; write-enabled web can also start or resume them. +- The Sessions list now has a **New session** draft (terminal **N**) and a separate saved-session picker (terminal **R** or `/resume`). The first send starts a thread in a trusted working directory. In the terminal, the draft can ask you to trust an undecided folder before sending. Read-only web can browse saved sessions; write-enabled web can also start (in an already trusted folder) or resume them. - `/subagents` inspects linked agents without retargeting the parent composer. `/ps` lists and refreshes background terminals without stopping them. Both are read-only. Local display commands remain daemon-independent. Server-backed menus use a bounded, memory-only catalogue tree; execution always revalidates fresh server options. These delivered items are not future roadmap work. @@ -51,7 +51,7 @@ Local display commands remain daemon-independent. Server-backed menus use a boun | `/pwd`, `/cwd` | Implemented aliases | Done | — | Read-only `thread/resume` **without overrides** reports the running directory, including during active turns. Captured `thread/read.cwd` metadata is not used as the answer. The session directory/footer also follows live directory reads and settings notifications. | | `/model` | Session adapter | Done | — | Live model/reasoning catalogue; send one verified `thread/settings/update` immediately on idle or working sessions, for subsequent turns only. No Codexometer-side queue or automatic retry. Fresh provider/settings/catalogue checks precede the write. The balanced default needs no extra confirmation. Selecting a model clears its explicit speed override. Session-only scope is intentional; no native persistent-default editor is proposed. | | `/plan` | Partial | P2 | Medium | Advertised collaboration-mode selection; no native optional prompt argument. Proposed next increment: explicit review of an inline plan prompt and confirmed mode/prompt submission without losing the draft. | -| `/permissions` | Session adapter | Done | — | Native allowed profiles, approval policies and Human/Auto-review reviewer selection. Supports `/permissions [--approval-policy=] [--reviewer=user\|auto_review]`, shell-style quoting and native granular policy JSON. May update subsequent-turn settings during work, but retained/overflowed human requests and native approval/input waits block writes. Managed requirements and the `guardian_approval` feature govern availability. Requested settings are read back; uncertain writes are not retried. Browser edits invalidate prepared/in-flight inline reviews. Older servers without reviewer metadata retain profile-only controls; no global configuration editor is implied. | +| `/permissions` | Session adapter | Done | — | Native preset order: Ask for approval, Approve for me, Full Access, Read Only, then custom profiles. Supports `/permissions [--approval-policy=] [--reviewer=user\|auto_review]`, shell-style quoting and native granular policy JSON. May update subsequent-turn settings during work, but retained/overflowed human requests and native approval/input waits block writes. Managed requirements and the `guardian_approval` feature govern availability. Requested settings are read back; uncertain writes are not retried. Browser edits invalidate prepared/in-flight inline reviews. Older servers without reviewer metadata retain profile-only controls; no global configuration editor is implied. | | `/approve` | Session adapter | Done | — | `thread/approveGuardianDeniedAction` records consent for one exact recent native denial, not direct execution. The retry still passes through Auto-review; critical-risk and mandatory human checks are not bypassed. Full action/rationale inspection precedes consent even with `--confirmation none`. Inventories and assessment display are root-thread-scoped, memory-only and connection-local: up to ten denials per thread and 256 tracked threads, with spent-consent replay protection. Unknown/incomplete actions stay in Codex. Read-only web displays assessments but cannot send consent. | | `/skills` | Browse only | P2 | Medium | `skills/list` inventory/help. No invocation or configuration flow; `skills/config/write` exists but needs scope/review UI. Proposed next increment: invoke an advertised skill through structured input after review. Configuration/enablement writes are a separate High-complexity extension. | | `/apps` | Browse only | P3 | High | `app/list` inventory/help. Installation, linking and authentication workflows are absent. Proposed next increment: a guided linking/authentication workflow with return/cancellation handling; reuse upstream flows rather than inventing installation semantics. | diff --git a/internal/codex/session_auto_review_unix_test.go b/internal/codex/session_auto_review_unix_test.go index dc422e8..cb23cd8 100644 --- a/internal/codex/session_auto_review_unix_test.go +++ b/internal/codex/session_auto_review_unix_test.go @@ -303,12 +303,87 @@ func configureNativePermissions(f *quotaDaemonFixture) { f.reviewers = map[string]string{"one": "user"} f.approvalPolicies = map[string]any{"one": "on-request"} f.catalogues = map[string]map[string]any{ - "permissionProfile/list": {"data": []any{map[string]any{"id": ":workspace", "description": "Write inside the project.", "allowed": true}}}, + "permissionProfile/list": {"data": []any{ + map[string]any{"id": ":read-only", "description": nil, "allowed": true}, + map[string]any{"id": ":workspace", "allowed": true}, + map[string]any{"id": ":danger-full-access", "description": nil, "allowed": true}, + }}, "configRequirements/read": {"requirements": nil}, "experimentalFeature/list": {"data": []any{map[string]any{"name": "guardian_approval", "enabled": true}}}, } } +func TestNativePermissionPickerUsesCLIOrderAndUpdatesCompletePreset(t *testing.T) { + p, f := newQuotaDaemon(t) + configureNativePermissions(f) + ctx := t.Context() + want := []struct{ label, profile, policy, reviewer string }{ + {"Ask for approval", ":workspace", "on-request", "user"}, + {"Approve for me", ":workspace", "on-request", "auto_review"}, + {"Full Access", ":danger-full-access", "never", "user"}, + {"Read Only", ":read-only", "on-request", "user"}, + } + for selected, apply := range []int{1, 2, 3, 0} { + menu, err := p.SessionCommands(ctx, "one", "permissions") + if err != nil || len(menu.Choices) != len(want) { + t.Fatalf("expected four native options: %+v %v", menu.Choices, err) + } + for i, choice := range menu.Choices { + if choice.Label != want[i].label || choice.Selected != (i == selected) || !choice.Action || choice.Reversible || choice.Next != "" { + t.Fatalf("unexpected preset at %d: %+v", i, choice) + } + } + if err := p.ExecuteSessionCommand(ctx, "one", menu.Path, menu.Revision, menu.Choices[apply].ID); err != nil { + t.Fatal(err) + } + f.mu.Lock() + got, count := f.writes[len(f.writes)-1], len(f.writes) + f.mu.Unlock() + preset := want[apply] + if count != selected+1 || len(got) != 4 || got["threadId"] != "one" || got["permissions"] != preset.profile || got["approvalPolicy"] != preset.policy || got["approvalsReviewer"] != preset.reviewer { + t.Fatalf("wrong complete update for %s: %v", preset.label, got) + } + } +} + +func TestNativePermissionPickerHonoursRestrictions(t *testing.T) { + p, f := newQuotaDaemon(t) + configureNativePermissions(f) + ctx := t.Context() + menu, err := p.SessionCommands(ctx, "one", "permissions") + if err != nil || len(menu.Choices) != 4 { + t.Fatal(menu, err) + } + f.mu.Lock() + profiles := f.catalogues["permissionProfile/list"] + profiles["data"] = append(profiles["data"].([]any), map[string]any{"id": "custom", "allowed": true}) + f.catalogues["configRequirements/read"]["requirements"] = map[string]any{ + "allowedPermissionProfiles": map[string]bool{":workspace": true, ":read-only": true, "custom": true}, + "allowedApprovalsReviewers": []string{"user"}, + } + f.mu.Unlock() + if err := p.ExecuteSessionCommand(ctx, "one", menu.Path, menu.Revision, menu.Choices[2].ID); err == nil { + t.Fatal("stale Full Access selection ignored managed requirements") + } + menu, err = p.SessionCommands(ctx, "one", "permissions") + if err != nil || len(menu.Choices) != 5 || menu.Choices[4].Label != "custom" || !menu.Choices[4].Action { + t.Fatal(menu, err) + } + for _, i := range []int{1, 2} { + if o := menu.Choices[i]; o.Action || o.Unavailable == "" { + t.Fatalf("blocked preset should be visible but not actionable: %+v", o) + } + } + f.mu.Lock() + f.catalogues["experimentalFeature/list"] = map[string]any{"data": []any{map[string]any{"name": "guardian_approval", "enabled": false}}} + writes := len(f.writes) + f.mu.Unlock() + menu, err = p.SessionCommands(ctx, "one", "permissions") + if err != nil || len(menu.Choices) != 4 || menu.Choices[1].Label != "Full Access" || writes != 0 { + t.Fatal("Guardian disabled should hide Approve for me and no settings should be written", menu, err) + } +} + func TestNativePermissionsInlineAndVerification(t *testing.T) { p, f := newQuotaDaemon(t) configureNativePermissions(f) diff --git a/internal/codex/session_permissions_menu_unix.go b/internal/codex/session_permissions_menu_unix.go index 4c62275..0a72bcb 100644 --- a/internal/codex/session_permissions_menu_unix.go +++ b/internal/codex/session_permissions_menu_unix.go @@ -200,6 +200,66 @@ func reviewerName(reviewer string) string { return reviewer } +type permissionProfileOption struct { + ID, Description string + Allowed bool +} + +func (v permissionProfileOption) help() string { + if strings.TrimSpace(v.Description) == "" { + return "Configured permission profile." + } + return v.Description +} + +func (v permissionProfileOption) choice(thread string, active *sessionPermissions) SessionCommandChoice { + choice := SessionCommandChoice{Label: v.ID, Help: v.help(), Selected: active.Profile != nil && active.Profile.ID == v.ID} + if v.Allowed { + choice.method = "thread/settings/update" + choice.params = map[string]any{"threadId": thread, "permissions": v.ID} + } else { + choice.Unavailable = "Disabled by Codex requirements." + } + return choice +} + +// Codex CLI builds these presets from the server's profile catalogue. Each +// selectable preset applies all three settings together, not just the profile. +var nativePermissionPresets = [...]struct { + label, help, profile, policy, reviewer string +}{ + {"Ask for approval", "Read and edit workspace files and run commands. Codex asks before accessing the internet or editing files outside the workspace.", ":workspace", "on-request", "user"}, + {"Approve for me", "Use the same workspace access with Codex's native reviewer. Mandatory human checkpoints still go to you.", ":workspace", "on-request", "auto_review"}, + {"Full Access", "Use with caution: Codex can edit files outside this workspace and access the internet without asking for approval.", ":danger-full-access", "never", "user"}, + {"Read Only", "Read workspace files. Codex asks you before allowing edits or internet access.", ":read-only", "on-request", "user"}, +} + +func nativePermissionChoices(threadID string, active *sessionPermissions, profiles map[string]permissionProfileOption, auto bool, allowed func(map[string]any) bool) []SessionCommandChoice { + choices := make([]SessionCommandChoice, 0, len(nativePermissionPresets)) + if len(profiles) == 0 { + return choices + } + for _, preset := range nativePermissionPresets { + if preset.reviewer == "auto_review" && !auto { + continue // The native CLI hides this preset when Guardian is off. + } + policy, _ := permissionPolicy(preset.policy) + params := map[string]any{"threadId": threadID, "permissions": preset.profile, "approvalPolicy": policy, "approvalsReviewer": preset.reviewer} + choice := SessionCommandChoice{Label: preset.label, Help: preset.help, + Selected: active.Profile != nil && active.Profile.ID == preset.profile && equalPermissionPolicy(policy, active.Policy) && active.Reviewer == preset.reviewer} + switch { + case profiles[preset.profile].ID == "": + choice.Unavailable = "Not available on this Codex server." + case !allowed(params): + choice.Unavailable = "Disabled by Codex requirements." + default: + choice.method, choice.params = "thread/settings/update", params + } + choices = append(choices, choice) + } + return choices +} + func (p *daemonStatusProvider) permissionMenu(ctx context.Context, t commandThread, path string) (SessionCommandMenu, error) { p.mu.Lock() conn := p.connection @@ -224,23 +284,28 @@ func (p *daemonStatusProvider) permissionMenu(ctx context.Context, t commandThre if err != nil { return m, err } - profiles := map[string]string{} + profiles := make(map[string]permissionProfileOption, len(rows)) + ordered := make([]permissionProfileOption, 0, len(rows)) for _, raw := range rows { - var v struct { - ID, Description string - Allowed bool - } - if json.Unmarshal(raw, &v) == nil && v.Allowed && commandSafe(v.ID) && strings.TrimSpace(v.Description) != "" { - profiles[v.ID] = v.Description - if path == "permissions" { - m.Choices = append(m.Choices, SessionCommandChoice{Label: v.ID, Help: v.Description, method: "thread/settings/update", params: map[string]any{"threadId": t.ID, "permissions": v.ID}, Selected: s.Profile != nil && s.Profile.ID == v.ID}) - } + var v permissionProfileOption + if json.Unmarshal(raw, &v) != nil || !commandSafe(v.ID) { + continue } + if _, duplicate := profiles[v.ID]; duplicate { + return m, ErrSessionCommand + } + profiles[v.ID] = v + ordered = append(ordered, v) } if s.Reviewer == "" || len(s.Policy) == 0 { if path != "permissions" { return m, fmt.Errorf("native reviewer settings unavailable; update the shared Codex app-server") } + for _, v := range ordered { + if v.Allowed { + m.Choices = append(m.Choices, v.choice(t.ID, &s)) + } + } return m, nil } var response struct{ Requirements json.RawMessage } @@ -253,6 +318,7 @@ func (p *daemonStatusProvider) permissionMenu(ctx context.Context, t commandThre var requirements struct { Policies *[]json.RawMessage `json:"allowedApprovalPolicies"` Reviewers *[]string `json:"allowedApprovalsReviewers"` + Profiles *map[string]bool `json:"allowedPermissionProfiles"` } if string(response.Requirements) != "null" { if err := json.Unmarshal(response.Requirements, &requirements); err != nil { @@ -274,6 +340,9 @@ func (p *daemonStatusProvider) permissionMenu(ctx context.Context, t commandThre } } allowed := func(params map[string]any) bool { + if id, ok := params["permissions"].(string); ok && (!profiles[id].Allowed || requirements.Profiles != nil && !(*requirements.Profiles)[id]) { + return false + } if r, ok := params["approvalsReviewer"].(string); ok { if r != "user" && r != "auto_review" || r == "auto_review" && !auto { return false @@ -307,7 +376,13 @@ func (p *daemonStatusProvider) permissionMenu(ctx context.Context, t commandThre } switch path { case "permissions": - m.Choices = append(m.Choices, SessionCommandChoice{Label: "Approval policy", Help: "When native Codex asks for approval.", Next: "permissions/policy"}, SessionCommandChoice{Label: "Reviewer", Help: "Who reviews eligible escalations. Does not change the sandbox.", Next: "permissions/reviewer"}) + m.Choices = nativePermissionChoices(t.ID, &s, profiles, auto, allowed) + for _, v := range ordered { + if !strings.HasPrefix(v.ID, ":") { + v.Allowed = allowed(map[string]any{"permissions": v.ID}) + m.Choices = append(m.Choices, v.choice(t.ID, &s)) + } + } case "permissions/policy": for _, v := range []string{"untrusted", "on-request", "never"} { policy, _ := permissionPolicy(v) @@ -343,14 +418,11 @@ func (p *daemonStatusProvider) permissionMenu(ctx context.Context, t commandThre if err != nil { return m, err } - profile, ok := params["permissions"].(string) - if !ok || profiles[profile] == "" { - return m, ErrSessionCommand - } if !allowed(params) { return m, ErrSessionCommand } - detail := "Profile: " + profile + "\n" + profiles[profile] + profile := profiles[params["permissions"].(string)] // parsePermissionArgs requires this field. + detail := "Profile: " + profile.ID + "\n" + profile.help() if policy, ok := params["approvalPolicy"].(json.RawMessage); ok { detail += "\nApproval policy: " + policySummary(policy) } diff --git a/internal/codex/session_settings_unix_test.go b/internal/codex/session_settings_unix_test.go index bd1fdcc..0130a9d 100644 --- a/internal/codex/session_settings_unix_test.go +++ b/internal/codex/session_settings_unix_test.go @@ -24,6 +24,8 @@ type quotaDaemonFixture struct { turnStarts []map[string]any startDelay time.Duration turnStartError map[string]any + trustWrites []map[string]any + trustAfterWrite map[string]any savedPages map[[2]string]map[string]any // keyed by sort order and cursor approvalPolicies map[string]any reviewers map[string]string @@ -182,6 +184,13 @@ func newQuotaDaemonTransport(t *testing.T, compressed bool) (*daemonStatusProvid ids = append(ids, id) } result["data"] = ids + case "config/batchWrite": + fixture.trustWrites = append(fixture.trustWrites, req.Params) + result = fixture.catalogues[req.Method] + failure = result == nil + if !failure && fixture.trustAfterWrite != nil { + fixture.catalogues["config/read"] = fixture.trustAfterWrite + } case "thread/start", "turn/start": if req.Method == "thread/start" { fixture.starts = append(fixture.starts, req.Params) diff --git a/internal/codex/session_start.go b/internal/codex/session_start.go index 30b0509..bfa088a 100644 --- a/internal/codex/session_start.go +++ b/internal/codex/session_start.go @@ -14,6 +14,31 @@ type SessionStartClient interface { StartSession(ctx context.Context, scope, directory, prompt string) (string, error) } +// SessionTrustClient is deliberately separate: ordinary starts (including the +// browser) cannot grant folder trust. +type SessionTrustClient interface { + TrustAndStartSession(ctx context.Context, scope, directory, prompt string, review SessionTrustRequired) (string, error) +} + +type SessionTrustRequired struct { + Directory string + sessionScope string + configFile string + configRevision string +} + +// Folder-trust errors are separate from validation and submission errors: no +// thread or turn has been started when one of these is returned. +var ( + ErrSessionStartTrust = errors.New("Codex has not verified this folder as trusted; choose an already-trusted folder or open it in Codex to review folder trust") + ErrSessionTrustCheck = errors.New("Could not read Codex folder trust. Check the shared connection and retry.") + ErrSessionTrustRestricted = errors.New("Codex marks this folder as untrusted. Choose another folder.") + ErrSessionTrustNotSaved = errors.New("Could not verify saved folder trust. No session was started.") +) + +func (SessionTrustRequired) Error() string { return ErrSessionStartTrust.Error() } +func (SessionTrustRequired) Unwrap() error { return ErrSessionStartTrust } + // A new thread may load project configuration and warm up model connections. // This is the total action budget, not the timeout for routine discovery RPCs. const SessionStartTimeout = 12 * time.Second @@ -21,7 +46,6 @@ const SessionStartTimeout = 12 * time.Second var ( ErrSessionStartUnavailable = errors.New("new session unavailable; check the shared Codex connection") ErrSessionStartDirectory = errors.New("choose an existing absolute working directory") - ErrSessionStartTrust = errors.New("Codex has not verified this folder as trusted; choose an already-trusted folder or open it in Codex to review folder trust") ErrSessionStartPrompt = errors.New("enter a first message with at most 4096 characters and no unsupported control characters") ErrSessionStartCommand = errors.New("this slash command is not available before starting a session") ) @@ -35,6 +59,14 @@ var ( ) func (c Client) StartSession(ctx context.Context, scope, directory, prompt string) (string, error) { + return c.startSession(ctx, scope, directory, prompt, nil) +} + +func (c Client) TrustAndStartSession(ctx context.Context, scope, directory, prompt string, review SessionTrustRequired) (string, error) { + return c.startSession(ctx, scope, directory, prompt, &review) +} + +func (c Client) startSession(ctx context.Context, scope, directory, prompt string, review *SessionTrustRequired) (string, error) { if c.LiveUsage == nil || scope == "" || len(scope) > 128 { return "", ErrSessionStartUnavailable } @@ -50,16 +82,27 @@ func (c Client) StartSession(ctx context.Context, scope, directory, prompt strin if strings.TrimSpace(prompt) == "" || utf8.RuneCountInString(prompt) > sessionContextLimit || !safePatchText(prompt) { return "", ErrSessionStartPrompt } - if !filepath.IsAbs(directory) || len(directory) > 4096 || SanitizeSessionContext(directory) != directory { + if !validSessionStartDirectory(directory) { return "", ErrSessionStartDirectory } directory, err := filepath.EvalSymlinks(directory) - if err != nil || SanitizeSessionContext(directory) != directory { + if err != nil || !validSessionStartDirectory(directory) { return "", ErrSessionStartDirectory } info, err := os.Stat(directory) if err != nil || !info.IsDir() { return "", ErrSessionStartDirectory } + if review != nil { + trust, ok := p.(SessionTrustClient) + if !ok || review.sessionScope != scope || review.Directory != directory || review.configRevision == "" || review.configFile == "" { + return "", ErrSessionTrustNotSaved + } + return trust.TrustAndStartSession(ctx, scope, directory, prompt, *review) + } return p.StartSession(ctx, scope, directory, prompt) } + +func validSessionStartDirectory(directory string) bool { + return filepath.IsAbs(directory) && len(directory) <= 4096 && !strings.ContainsAny(directory, "\n\u2028\u2029") && SanitizeSessionContext(directory) == directory +} diff --git a/internal/codex/session_start_unix.go b/internal/codex/session_start_unix.go index ff15080..4c91328 100644 --- a/internal/codex/session_start_unix.go +++ b/internal/codex/session_start_unix.go @@ -6,7 +6,9 @@ import ( "context" "encoding/json" "errors" + "os" "path/filepath" + "strings" "time" "github.com/gorilla/websocket" @@ -18,12 +20,15 @@ type projectTrustConfig struct { } } -func (p *daemonStatusProvider) newSessionTrust(ctx context.Context, conn *websocket.Conn, cwd string) bool { +// A nil result means the exact directory is already trusted. A review offer +// is issued only for an undecided directory and carries the user config revision. +func (p *daemonStatusProvider) newSessionTrust(ctx context.Context, conn *websocket.Conn, generation uint64, scope, cwd string) error { var result struct { - Config projectTrustConfig + Config *projectTrustConfig Layers []struct { - Name struct{ Type string } + Name struct{ Type, File string } Config projectTrustConfig + Version string DisabledReason *string } } @@ -31,35 +36,108 @@ func (p *daemonStatusProvider) newSessionTrust(ctx context.Context, conn *websoc // folder as trusted. Require an exact, effective decision from Codex's // user configuration. Never infer trust from a parent or a project layer. params := map[string]any{"cwd": cwd, "includeLayers": true} - if p.requestOn(ctx, conn, "config/read", params, &result) != nil || result.Config.Projects[cwd].TrustLevel != "trusted" { - return false + if p.requestOnChecked(ctx, conn, "config/read", params, &result, &generation) != nil || result.Config == nil { + return ErrSessionTrustCheck + } + // An explicit untrusted decision on an enclosing path is never silently + // overridden by writing a narrower entry. Fail closed on ambiguous layers. + for path, project := range result.Config.Projects { + if project.TrustLevel == "untrusted" && sessionTrustPathContains(path, cwd) { + return ErrSessionTrustRestricted + } } - trusted := false + effective := result.Config.Projects[cwd].TrustLevel + userTrust, file, revision := "", "", "" + userSeen, disabledProject := false, false for _, layer := range result.Layers { if layer.Name.Type == "project" && layer.DisabledReason != nil { - return false + disabledProject = true + // Recognise Codex's undecided-layer reason only when it names this + // exact directory. Never turn a repo-wide decision into a write. + const prefix = "To load project-local config, hooks, and exec policies, add " + if !strings.HasPrefix(*layer.DisabledReason, prefix+cwd+" as a trusted project in ") { + return ErrSessionStartTrust + } } - if layer.Name.Type == "user" && layer.DisabledReason == nil && layer.Config.Projects[cwd].TrustLevel == "trusted" { - trusted = true + if layer.Name.Type == "user" { + if layer.DisabledReason != nil { + return ErrSessionStartTrust + } + // config/read orders layers high to low, so the first user layer + // is the writable profile when one is selected, otherwise the base. + if !userSeen { + userSeen, file, revision = true, layer.Name.File, layer.Version + } + if userTrust == "" { + userTrust = layer.Config.Projects[cwd].TrustLevel + } + } + } + if userTrust == "untrusted" { + return ErrSessionTrustRestricted + } + if effective == "trusted" && userTrust == "trusted" && !disabledProject { + return nil + } + if effective == "" && userTrust == "" && revision != "" && filepath.IsAbs(file) { + return SessionTrustRequired{Directory: cwd, sessionScope: scope, configFile: file, configRevision: revision} + } + return ErrSessionStartTrust +} + +// Check saved restrictions under alternate names for the same local directory +// (e.g. a symlink or a case-insensitive filesystem), not just exact map keys. +func sessionTrustPathContains(path, cwd string) bool { + if !filepath.IsAbs(path) { + return false + } + if rel, err := filepath.Rel(path, cwd); err == nil && filepath.IsLocal(rel) { + return true + } + target, err := os.Stat(path) + if err != nil || !target.IsDir() { + return false + } + for parent := cwd; ; parent = filepath.Dir(parent) { + if info, err := os.Stat(parent); err == nil && os.SameFile(info, target) { + return true + } + if parent == filepath.Dir(parent) { + return false } } - return trusted } func (p *daemonStatusProvider) StartSession(ctx context.Context, scope, cwd, prompt string) (string, error) { + return p.startSession(ctx, scope, cwd, prompt, nil) +} + +func (p *daemonStatusProvider) TrustAndStartSession(ctx context.Context, scope, cwd, prompt string, review SessionTrustRequired) (string, error) { + return p.startSession(ctx, scope, cwd, prompt, &review) +} + +func (p *daemonStatusProvider) startSession(ctx context.Context, scope, cwd, prompt string, review *SessionTrustRequired) (string, error) { conn, generation, account, err := p.savedSessionAction(ctx, scope) if err != nil { return "", ErrSessionStartUnavailable } - if !p.newSessionTrust(ctx, conn, cwd) { - return "", ErrSessionStartTrust + err = p.newSessionTrust(ctx, conn, generation, scope, cwd) + if review == nil { + if err != nil { + return "", err + } + } else if err != nil { + if !p.writeSessionTrust(ctx, conn, generation, account, *review, err) || p.newSessionTrust(ctx, conn, generation, scope, cwd) != nil { + return "", ErrSessionTrustNotSaved + } } var result struct { Cwd, ApprovalsReviewer string Thread struct{ ID string } } // The outer action deadline still bounds all preflights and both writes. - err = p.requestOnWithin(ctx, conn, "thread/start", map[string]string{"cwd": cwd}, &result, &generation, 9*time.Second) + err = p.requestOnWithin(ctx, conn, "thread/start", map[string]string{"cwd": cwd}, &result, &generation, 9*time.Second, + func() bool { return p.savedScope == scope }) var rejected *daemonResponseError switch { case errors.Is(err, errDaemonWriteGuardRejected): @@ -101,3 +179,22 @@ func (p *daemonStatusProvider) StartSession(ctx context.Context, scope, cwd, pro } return id, nil } + +func (p *daemonStatusProvider) writeSessionTrust(ctx context.Context, conn *websocket.Conn, generation uint64, account string, review SessionTrustRequired, fresh error) bool { + offer, ok := fresh.(SessionTrustRequired) + if !ok || offer != review { + return false + } + if current, err := p.savedAccount(ctx, offer.sessionScope); err != nil || current != account { + return false + } + // Follow the native TUI's quoted config key syntax: dots in a path stay + // literal and backslashes and quotes are escaped for the key parser. + key := strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(offer.Directory) + params := map[string]any{ + "edits": []map[string]string{{"keyPath": `projects."` + key + `".trust_level`, "value": "trusted", "mergeStrategy": "replace"}}, + "filePath": offer.configFile, "expectedVersion": offer.configRevision, "reloadUserConfig": true, + } + return p.requestOnChecked(ctx, conn, "config/batchWrite", params, nil, &generation, + func() bool { return p.savedScope == offer.sessionScope }) == nil +} diff --git a/internal/codex/session_start_unix_test.go b/internal/codex/session_start_unix_test.go index fb8d322..84d281a 100644 --- a/internal/codex/session_start_unix_test.go +++ b/internal/codex/session_start_unix_test.go @@ -46,6 +46,7 @@ func TestNewSessionUsesNativeDefaultsAndTargetsFirstTurn(t *testing.T) { }{ {"wrong", cwd, "first", ErrSessionStartUnavailable}, {scope, "relative", "first", ErrSessionStartDirectory}, + {scope, cwd + "/folder\nname", "first", ErrSessionStartDirectory}, {scope, cwd, "/resume", ErrSessionStartCommand}, {scope, cwd, " ", ErrSessionStartPrompt}, {scope, cwd, "hidden\x1b[0m", ErrSessionStartPrompt}, @@ -97,7 +98,13 @@ func TestNewSessionRequiresExplicitEffectiveTrust(t *testing.T) { reply["layers"] = []any{map[string]any{"name": map[string]string{"type": "project"}, "config": reply["config"]}} } f.mu.Unlock() - if id, err := c.StartSession(t.Context(), scope, cwd, "first"); id != "" || !errors.Is(err, ErrSessionStartTrust) { + want := ErrSessionStartTrust + if mode == "missing" { + want = ErrSessionTrustCheck + } else if mode == "overridden" { + want = ErrSessionTrustRestricted + } + if id, err := c.StartSession(t.Context(), scope, cwd, "first"); id != "" || !errors.Is(err, want) { t.Fatal("unverified folder accepted", id, err) } f.mu.Lock() @@ -109,6 +116,125 @@ func TestNewSessionRequiresExplicitEffectiveTrust(t *testing.T) { } } +const trustTestConfigFile = "/some/config.toml" + +func sessionTrustConfig(cwd, level, revision string, disabled ...string) map[string]any { + projects := map[string]any{} + if level != "" { + projects[cwd] = map[string]string{"trust_level": level} + } + config := map[string]any{"projects": projects} + layers := []any{map[string]any{"name": map[string]string{"type": "user", "file": trustTestConfigFile}, "version": revision, "config": config}} + for _, reason := range disabled { + layers = append(layers, map[string]any{"name": map[string]string{"type": "project"}, "disabledReason": reason}) + } + return map[string]any{"config": config, "layers": layers} +} + +func TestNewSessionTrustAndSend(t *testing.T) { + c, f, parent, scope := startFixture(t) + cwd := filepath.Join(parent, `new.repo "quoted"\path`) + alias := filepath.Join(parent, "alias") + if err := os.Mkdir(cwd, 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(cwd, alias); err != nil { + t.Fatal(err) + } + const prefix = "To load project-local config, hooks, and exec policies, add " + f.mu.Lock() + f.catalogues["config/read"] = sessionTrustConfig(cwd, "", "rev-before", prefix+cwd+" as a trusted project in /some/config.toml.") + f.catalogues["config/batchWrite"] = map[string]any{"status": "ok"} + f.catalogues["thread/start"]["cwd"] = cwd + f.trustAfterWrite = sessionTrustConfig(cwd, "trusted", "rev-after") + f.mu.Unlock() + const prompt = "first message" + id, err := c.StartSession(t.Context(), scope, alias, prompt) + var review SessionTrustRequired + if id != "" || !errors.As(err, &review) || review.Directory != cwd { + t.Fatalf("ordinary send must offer to review the canonical path: %q %+v %v", id, review, err) + } + f.mu.Lock() + if len(f.trustWrites)+len(f.starts)+len(f.turnStarts) != 0 { + t.Error("unconfirmed start made a write") + } + f.mu.Unlock() + if id, err = c.TrustAndStartSession(t.Context(), scope, alias, prompt, review); id != "created" || err != nil { + t.Fatal(id, err) + } + f.mu.Lock() + defer f.mu.Unlock() + want := []map[string]any{{"edits": []any{map[string]any{"keyPath": `projects."` + parent + `/new.repo \"quoted\"\\path".trust_level`, "value": "trusted", "mergeStrategy": "replace"}}, "filePath": trustTestConfigFile, "expectedVersion": "rev-before", "reloadUserConfig": true}} + if !reflect.DeepEqual(f.trustWrites, want) || !reflect.DeepEqual(f.starts, []map[string]any{{"cwd": cwd}}) || len(f.turnStarts) != 1 { + t.Fatal(f.trustWrites, f.starts, f.turnStarts) + } +} + +func TestNewSessionTrustFailsClosed(t *testing.T) { + for _, tc := range []struct { + mode string + writes int + }{ + {"changed directory", 0}, {"changed symlink target", 0}, {"changed revision", 0}, {"untrusted parent", 0}, + {"changed profile", 0}, {"untrusted alias", 0}, {"different root", 0}, {"write rejected", 1}, {"unverified write", 1}, + } { + t.Run(tc.mode, func(t *testing.T) { + c, f, cwd, scope := startFixture(t) + directory := cwd + other := t.TempDir() + if tc.mode == "changed symlink target" || tc.mode == "untrusted alias" { + directory = filepath.Join(other, "alias") + if err := os.Symlink(cwd, directory); err != nil { + t.Fatal(err) + } + } + f.mu.Lock() + f.catalogues["config/read"] = sessionTrustConfig(cwd, "", "rev-before") + f.mu.Unlock() + var review SessionTrustRequired + if _, err := c.StartSession(t.Context(), scope, directory, "hello"); !errors.As(err, &review) { + t.Fatal(err) + } + if tc.mode == "changed symlink target" { + if err := os.Remove(directory); err != nil { + t.Fatal(err) + } + if err := os.Symlink(other, directory); err != nil { + t.Fatal(err) + } + } + f.mu.Lock() + switch tc.mode { + case "changed directory": + directory = other + case "changed revision": + f.catalogues["config/read"] = sessionTrustConfig(cwd, "", "rev-concurrent") + case "changed profile": + config := f.catalogues["config/read"] + profile := map[string]any{"name": map[string]string{"type": "user", "file": "/some/work.config.toml"}, "version": "rev-before", "config": map[string]any{}} + config["layers"] = append([]any{profile}, config["layers"].([]any)...) + case "untrusted parent": + f.catalogues["config/read"] = sessionTrustConfig(filepath.Dir(cwd), "untrusted", "rev-before") + case "untrusted alias": + f.catalogues["config/read"] = sessionTrustConfig(directory, "untrusted", "rev-before") + case "different root": + f.catalogues["config/read"] = sessionTrustConfig(cwd, "", "rev-before", "To load project-local config, hooks, and exec policies, add "+filepath.Dir(cwd)+" as a trusted project in /config.toml.") + case "unverified write": + f.catalogues["config/batchWrite"] = map[string]any{"status": "ok"} + } + f.mu.Unlock() + if id, err := c.TrustAndStartSession(t.Context(), scope, directory, "hello", review); id != "" || !errors.Is(err, ErrSessionTrustNotSaved) { + t.Fatal(id, err) + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.trustWrites) != tc.writes || len(f.starts)+len(f.turnStarts) != 0 { + t.Fatal(f.trustWrites, f.starts, f.turnStarts) + } + }) + } +} + func TestNewSessionKnownNativeRejection(t *testing.T) { c, f, cwd, scope := startFixture(t) f.mu.Lock() diff --git a/internal/i18n/locales/da.json b/internal/i18n/locales/da.json index 9230288..8e434a3 100644 --- a/internal/i18n/locales/da.json +++ b/internal/i18n/locales/da.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "VIL DU STOLE PÅ DENNE MAPPE?", + "[ (T) Trust & send ]": "[ (T) Stol på og send ]", + "[ Esc Back ]": "[ Esc Tilbage ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Tilliden gemmes. Mappeindstillinger og hooks kan køre kode før den første besked.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Gør terminalen større for at se tillidsvalget, eller tryk på Esc for at gå tilbage.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex anser ikke denne mappe for betroet. Vælg en anden mappe.", + "Could not verify saved folder trust. No session was started.": "Kunne ikke bekræfte den gemte mappetillid. Ingen session blev startet.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Kunne ikke læse Codex' mappetillid. Kontrollér den delte forbindelse, og prøv igen.", "CLEAR CHEC(K)": "RYD TJEK (K)", "CONFIRM (K)": "BEKRÆFT (K)", "Copied %d chars": "Kopierede %d tegn", diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 32d6baf..e504ae5 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "DIESEM ORDNER VERTRAUEN?", + "[ (T) Trust & send ]": "[ (T) Vertrauen & senden ]", + "[ Esc Back ]": "[ Esc Zurück ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Das Vertrauen wird gespeichert. Ordnereinstellungen und Hooks können vor der ersten Nachricht Code ausführen.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Terminal vergrössern, um das Vertrauen zu prüfen, oder mit Esc zurückgehen.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex stuft diesen Ordner als nicht vertrauenswürdig ein. Wähle einen anderen Ordner.", + "Could not verify saved folder trust. No session was started.": "Das gespeicherte Ordnervertrauen konnte nicht überprüft werden. Es wurde keine Sitzung gestartet.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Das Ordnervertrauen konnte nicht aus Codex gelesen werden. Prüfe die gemeinsame Verbindung und versuche es erneut.", "CLEAR CHEC(K)": "PRÜFFÄLLE AUSBLENDEN (K)", "CONFIRM (K)": "BESTÄTIGEN (K)", "Copied %d chars": "%d Zeichen kopiert", diff --git a/internal/i18n/locales/en-GB.json b/internal/i18n/locales/en-GB.json index 2addf24..e9b4760 100644 --- a/internal/i18n/locales/en-GB.json +++ b/internal/i18n/locales/en-GB.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "TRUST THIS FOLDER?", + "[ (T) Trust & send ]": "[ (T) Trust & send ]", + "[ Esc Back ]": "[ Esc Back ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Trust is saved. Folder settings and hooks may run code before the first message.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Enlarge the terminal to review folder trust, or press Esc to go back.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex marks this folder as untrusted. Choose another folder.", + "Could not verify saved folder trust. No session was started.": "Could not verify saved folder trust. No session was started.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Could not read Codex folder trust. Check the shared connection and retry.", "CLEAR CHEC(K)": "CLEAR CHEC(K)", "CONFIRM (K)": "CONFIRM (K)", "Copied %d chars": "Copied %d chars", diff --git a/internal/i18n/locales/es.json b/internal/i18n/locales/es.json index 7de74b7..ffddd5c 100644 --- a/internal/i18n/locales/es.json +++ b/internal/i18n/locales/es.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "¿CONFIAR EN ESTA CARPETA?", + "[ (T) Trust & send ]": "[ (T) Confiar y enviar ]", + "[ Esc Back ]": "[ Esc Volver ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "La confianza se guarda. La configuración y los hooks de la carpeta pueden ejecutar código antes del primer mensaje.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Amplía la terminal para revisar la confianza de la carpeta, o pulsa Esc para volver.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex marca esta carpeta como no confiable. Elige otra carpeta.", + "Could not verify saved folder trust. No session was started.": "No se pudo verificar la confianza guardada. No se inició ninguna sesión.", + "Could not read Codex folder trust. Check the shared connection and retry.": "No se pudo leer la confianza de la carpeta en Codex. Comprueba la conexión compartida y vuelve a intentarlo.", "CLEAR CHEC(K)": "OCULTAR REVISIÓN (K)", "CONFIRM (K)": "CONFIRMAR (K)", "Copied %d chars": "%d caracteres copiados", diff --git a/internal/i18n/locales/et.json b/internal/i18n/locales/et.json index 3522bed..c020fda 100644 --- a/internal/i18n/locales/et.json +++ b/internal/i18n/locales/et.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "KAS USALDADA SEDA KAUSTA?", + "[ (T) Trust & send ]": "[ (T) Usalda ja saada ]", + "[ Esc Back ]": "[ Esc Tagasi ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Usaldus salvestatakse. Kausta sätted ja haagid võivad käivitada koodi enne esimest sõnumit.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Kausta usalduse ülevaatamiseks suurenda terminali või vajuta naasmiseks Esc.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex on märkinud selle kausta ebausaldusväärseks. Vali teine kaust.", + "Could not verify saved folder trust. No session was started.": "Salvestatud kausta usaldust ei saanud kontrollida. Seanssi ei käivitatud.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Codexi kausta usaldust ei saanud lugeda. Kontrolli jagatud ühendust ja proovi uuesti.", "CLEAR CHEC(K)": "PEIDA KONTROLL (K)", "CONFIRM (K)": "KINNITA (K)", "Copied %d chars": "Kopeeriti %d märki", diff --git a/internal/i18n/locales/fi.json b/internal/i18n/locales/fi.json index 9ebf47e..dd1644b 100644 --- a/internal/i18n/locales/fi.json +++ b/internal/i18n/locales/fi.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "LUOTETAANKO TÄHÄN KANSIOON?", + "[ (T) Trust & send ]": "[ (T) Luota ja lähetä ]", + "[ Esc Back ]": "[ Esc Takaisin ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Luottamus tallennetaan. Kansion asetukset ja koukut voivat suorittaa koodia ennen ensimmäistä viestiä.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Suurenna päätettä tarkistaaksesi kansion luottamuksen tai palaa takaisin painamalla Esc.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex on merkinnyt kansion epäluotettavaksi. Valitse toinen kansio.", + "Could not verify saved folder trust. No session was started.": "Tallennettua kansion luottamusta ei voitu vahvistaa. Istuntoa ei aloitettu.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Kansion luottamusta ei voitu lukea Codexista. Tarkista jaettu yhteys ja yritä uudelleen.", "CLEAR CHEC(K)": "PIILOTA TARKISTA (K)", "CONFIRM (K)": "VAHVISTA (K)", "Copied %d chars": "Kopioitu %d merkkiä", diff --git a/internal/i18n/locales/fr.json b/internal/i18n/locales/fr.json index d63c8a5..88d050a 100644 --- a/internal/i18n/locales/fr.json +++ b/internal/i18n/locales/fr.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "FAIRE CONFIANCE À CE DOSSIER ?", + "[ (T) Trust & send ]": "[ (T) Se fier et envoyer ]", + "[ Esc Back ]": "[ Esc Retour ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Ce choix est enregistré. Les paramètres et les hooks du dossier peuvent exécuter du code avant le premier message.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Agrandissez le terminal pour vérifier ce choix ou appuyez sur Esc pour revenir.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex considère ce dossier comme non fiable. Choisissez un autre dossier.", + "Could not verify saved folder trust. No session was started.": "Impossible de vérifier le choix enregistré. Aucune session n’a été démarrée.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Impossible de lire l’état de confiance du dossier dans Codex. Vérifiez la connexion partagée, puis réessayez.", "CLEAR CHEC(K)": "MASQUER À VÉRIFIER (K)", "CONFIRM (K)": "CONFIRMER (K)", "Copied %d chars": "%d caractères copiés", diff --git a/internal/i18n/locales/it.json b/internal/i18n/locales/it.json index 3773a54..ba8fa10 100644 --- a/internal/i18n/locales/it.json +++ b/internal/i18n/locales/it.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "CONSIDERARE ATTENDIBILE QUESTA CARTELLA?", + "[ (T) Trust & send ]": "[ (T) Accetta e invia ]", + "[ Esc Back ]": "[ Esc Indietro ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "La scelta viene salvata. Le impostazioni e gli hook della cartella possono eseguire codice prima del primo messaggio.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Ingrandisci il terminale per esaminare la scelta o premi Esc per tornare indietro.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex indica che questa cartella non è attendibile. Scegline un’altra.", + "Could not verify saved folder trust. No session was started.": "Impossibile verificare la scelta salvata. Nessuna sessione è stata avviata.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Impossibile leggere lo stato di attendibilità della cartella in Codex. Controlla la connessione condivisa e riprova.", "CLEAR CHEC(K)": "NASCONDI VERIFICA (K)", "CONFIRM (K)": "CONFERMA (K)", "Copied %d chars": "%d caratteri copiati", diff --git a/internal/i18n/locales/ja.json b/internal/i18n/locales/ja.json index 21f6347..0c47a92 100644 --- a/internal/i18n/locales/ja.json +++ b/internal/i18n/locales/ja.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "このフォルダーを信頼しますか?", + "[ (T) Trust & send ]": "[ (T) 信頼して送信 ]", + "[ Esc Back ]": "[ Esc 戻る ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "信頼の設定は保存されます。フォルダーの設定やフックは、最初のメッセージの前にコードを実行することがあります。", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "フォルダーの信頼設定を確認するには端末を広げてください。Esc キーで戻れます。", + "Codex marks this folder as untrusted. Choose another folder.": "Codex はこのフォルダーを信頼しない設定です。別のフォルダーを選んでください。", + "Could not verify saved folder trust. No session was started.": "保存されたフォルダーの信頼設定を確認できませんでした。セッションは開始していません。", + "Could not read Codex folder trust. Check the shared connection and retry.": "Codex のフォルダー信頼設定を読み取れませんでした。共有接続を確認して再試行してください。", "CLEAR CHEC(K)": "要確認を非表示 (K)", "CONFIRM (K)": "確認 (K)", "Copied %d chars": "%d 文字をコピーしました", diff --git a/internal/i18n/locales/nb.json b/internal/i18n/locales/nb.json index 561fd52..8049bf1 100644 --- a/internal/i18n/locales/nb.json +++ b/internal/i18n/locales/nb.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "STOLE PÅ DENNE MAPPEN?", + "[ (T) Trust & send ]": "[ (T) Stol på og send ]", + "[ Esc Back ]": "[ Esc Tilbake ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Tilliten lagres. Mappeinnstillinger og kroker kan kjøre kode før den første meldingen.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Gjør terminalen større for å se tillitsvalget, eller trykk Esc for å gå tilbake.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex regner ikke denne mappen som klarert. Velg en annen mappe.", + "Could not verify saved folder trust. No session was started.": "Kunne ikke bekrefte den lagrede mappetilliten. Ingen økt ble startet.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Kunne ikke lese mappetilliten fra Codex. Kontroller den delte tilkoblingen og prøv igjen.", "CLEAR CHEC(K)": "SKJUL SJEKK (K)", "CONFIRM (K)": "BEKREFT (K)", "Copied %d chars": "Kopierte %d tegn", diff --git a/internal/i18n/locales/nl.json b/internal/i18n/locales/nl.json index e5d974c..b20205f 100644 --- a/internal/i18n/locales/nl.json +++ b/internal/i18n/locales/nl.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "DEZE MAP VERTROUWEN?", + "[ (T) Trust & send ]": "[ (T) Vertrouw en verstuur ]", + "[ Esc Back ]": "[ Esc Terug ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Het vertrouwen wordt opgeslagen. Mapinstellingen en hooks kunnen vóór het eerste bericht code uitvoeren.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Vergroot de terminal om de vertrouwenskeuze te bekijken of druk op Esc om terug te gaan.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex beschouwt deze map als niet-vertrouwd. Kies een andere map.", + "Could not verify saved folder trust. No session was started.": "Kan de opgeslagen vertrouwenskeuze niet verifiëren. Er is geen sessie gestart.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Kan de vertrouwensstatus niet uitlezen in Codex. Controleer de gedeelde verbinding en probeer het opnieuw.", "CLEAR CHEC(K)": "CONTROLE VERBERGEN (K)", "CONFIRM (K)": "BEVESTIGEN (K)", "Copied %d chars": "%d tekens gekopieerd", diff --git a/internal/i18n/locales/pt-BR.json b/internal/i18n/locales/pt-BR.json index a35186d..69df8ab 100644 --- a/internal/i18n/locales/pt-BR.json +++ b/internal/i18n/locales/pt-BR.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "CONFIAR NESTA PASTA?", + "[ (T) Trust & send ]": "[ (T) Confiar e enviar ]", + "[ Esc Back ]": "[ Esc Voltar ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "A confiança é salva. As configurações e os hooks da pasta podem executar código antes da primeira mensagem.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Amplie o terminal para revisar a confiança da pasta ou pressione Esc para voltar.", + "Codex marks this folder as untrusted. Choose another folder.": "O Codex marcou esta pasta como não confiável. Escolha outra pasta.", + "Could not verify saved folder trust. No session was started.": "Não foi possível verificar a confiança salva. Nenhuma sessão foi iniciada.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Não foi possível ler a confiança da pasta no Codex. Verifique a conexão compartilhada e tente novamente.", "CLEAR CHEC(K)": "OCULTAR VERIFICAR (K)", "CONFIRM (K)": "CONFIRMAR (K)", "Copied %d chars": "%d caracteres copiados", diff --git a/internal/i18n/locales/pt-PT.json b/internal/i18n/locales/pt-PT.json index 4a37afd..6e0eaa4 100644 --- a/internal/i18n/locales/pt-PT.json +++ b/internal/i18n/locales/pt-PT.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "CONFIAR NESTA PASTA?", + "[ (T) Trust & send ]": "[ (T) Confiar e enviar ]", + "[ Esc Back ]": "[ Esc Voltar ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "A decisão de confiança é guardada. As definições e os hooks da pasta podem executar código antes da primeira mensagem.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Aumente o terminal para rever a confiança da pasta ou prima Esc para voltar.", + "Codex marks this folder as untrusted. Choose another folder.": "O Codex marcou esta pasta como não fidedigna. Escolha outra pasta.", + "Could not verify saved folder trust. No session was started.": "Não foi possível verificar a confiança guardada. Não foi iniciada nenhuma sessão.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Não foi possível ler a confiança da pasta no Codex. Verifique a ligação partilhada e tente novamente.", "CLEAR CHEC(K)": "OCULTAR VERIFICAR (K)", "CONFIRM (K)": "CONFIRMAR (K)", "Copied %d chars": "%d caracteres copiados", diff --git a/internal/i18n/locales/ru.json b/internal/i18n/locales/ru.json index bb88bf9..376d2b5 100644 --- a/internal/i18n/locales/ru.json +++ b/internal/i18n/locales/ru.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "ДОВЕРЯТЬ ЭТОЙ ПАПКЕ?", + "[ (T) Trust & send ]": "[ (T) Доверять и отправить ]", + "[ Esc Back ]": "[ Esc Назад ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Решение сохранится. Настройки и хуки папки могут выполнять код до первого сообщения.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Увеличьте окно терминала, чтобы проверить решение о доверии, или нажмите Esc для возврата.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex считает эту папку недоверенной. Выберите другую папку.", + "Could not verify saved folder trust. No session was started.": "Не удалось проверить сохранённое решение о доверии. Сеанс не запущен.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Не удалось прочитать настройки доверия к папке в Codex. Проверьте общее подключение и повторите попытку.", "CLEAR CHEC(K)": "СКРЫТЬ ПРОВЕРКУ (K)", "CONFIRM (K)": "ПОДТВЕРДИТЬ (K)", "Copied %d chars": "Скопировано символов: %d", diff --git a/internal/i18n/locales/sv.json b/internal/i18n/locales/sv.json index 45a4bf7..10af43e 100644 --- a/internal/i18n/locales/sv.json +++ b/internal/i18n/locales/sv.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "LITA PÅ DEN HÄR MAPPEN?", + "[ (T) Trust & send ]": "[ (T) Lita på och skicka ]", + "[ Esc Back ]": "[ Esc Tillbaka ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Förtroendet sparas. Mappinställningar och hooks kan köra kod före det första meddelandet.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Förstora terminalen för att granska förtroendet, eller tryck på Esc för att gå tillbaka.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex betraktar inte den här mappen som betrodd. Välj en annan mapp.", + "Could not verify saved folder trust. No session was started.": "Det gick inte att verifiera det sparade förtroendet. Ingen session startades.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Det gick inte att läsa mappens förtroendestatus från Codex. Kontrollera den delade anslutningen och försök igen.", "CLEAR CHEC(K)": "DÖLJ KOLLA (K)", "CONFIRM (K)": "BEKRÄFTA (K)", "Copied %d chars": "Kopierade %d tecken", diff --git a/internal/i18n/locales/tr.json b/internal/i18n/locales/tr.json index 265384c..ce61efc 100644 --- a/internal/i18n/locales/tr.json +++ b/internal/i18n/locales/tr.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "BU KLASÖRE GÜVENİLSİN Mİ?", + "[ (T) Trust & send ]": "[ (T) Güven ve gönder ]", + "[ Esc Back ]": "[ Esc Geri ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "Güven kararı kaydedilir. Klasör ayarları ve kancaları ilk mesajdan önce kod çalıştırabilir.", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "Klasör güvenini incelemek için terminali büyütün veya geri dönmek için Esc tuşuna basın.", + "Codex marks this folder as untrusted. Choose another folder.": "Codex bu klasörü güvenilmez olarak işaretliyor. Başka bir klasör seçin.", + "Could not verify saved folder trust. No session was started.": "Kaydedilen klasör güveni doğrulanamadı. Oturum başlatılmadı.", + "Could not read Codex folder trust. Check the shared connection and retry.": "Codex klasör güveni okunamadı. Paylaşılan bağlantıyı kontrol edip yeniden deneyin.", "CLEAR CHEC(K)": "KONTROL GİZLE (K)", "CONFIRM (K)": "ONAYLA (K)", "Copied %d chars": "%d karakter kopyalandı", diff --git a/internal/i18n/locales/zh-Hans.json b/internal/i18n/locales/zh-Hans.json index 837c0fb..0d9a999 100644 --- a/internal/i18n/locales/zh-Hans.json +++ b/internal/i18n/locales/zh-Hans.json @@ -1,4 +1,12 @@ { + "TRUST THIS FOLDER?": "信任此文件夹吗?", + "[ (T) Trust & send ]": "[ (T) 信任并发送 ]", + "[ Esc Back ]": "[ Esc 返回 ]", + "Trust is saved. Folder settings and hooks may run code before the first message.": "信任决定会被保存。文件夹设置和钩子可能在发送首条消息前运行代码。", + "Enlarge the terminal to review folder trust, or press Esc to go back.": "请扩大终端窗口以查看文件夹信任提示,或按 Esc 返回。", + "Codex marks this folder as untrusted. Choose another folder.": "Codex 已将此文件夹标为不受信任。请选择其他文件夹。", + "Could not verify saved folder trust. No session was started.": "无法验证已保存的文件夹信任。未启动会话。", + "Could not read Codex folder trust. Check the shared connection and retry.": "无法从 Codex 读取文件夹信任状态。请检查共享连接后重试。", "CLEAR CHEC(K)": "隐藏待检查 (K)", "CONFIRM (K)": "确认 (K)", "Copied %d chars": "已复制 %d 个字符", diff --git a/internal/ui/monitor_auto_review_test.go b/internal/ui/monitor_auto_review_test.go index 6687085..572ee46 100644 --- a/internal/ui/monitor_auto_review_test.go +++ b/internal/ui/monitor_auto_review_test.go @@ -167,13 +167,13 @@ func TestNativeDenialNoConfirmStillRequiresInspectThenApply(t *testing.T) { } func TestInlinePermissionsQuotedProfileUsesNativeParser(t *testing.T) { - for _, query := range []string{"':workspace'", ":workspace", "Reviewer"} { + for _, query := range []string{"':workspace'", ":workspace", "Approve for me"} { m, _ := commandTestModel(t) p := &m.monitorCommands p.inline = true p.prefix = "/permissions " p.menu.Path = "permissions" - p.menu.Choices = []codex.SessionCommandChoice{{Label: ":workspace", Action: true}, {Label: "Reviewer", Next: "permissions/reviewer"}} + p.menu.Choices = []codex.SessionCommandChoice{{Label: "Ask for approval", Action: true}, {Label: "Approve for me", Action: true}} m.monitorPrompt.input.SetValue(p.prefix + query) m.monitorPrompt.input.Focus() indices := m.commandChoiceIndices() @@ -182,16 +182,12 @@ func TestInlinePermissionsQuotedProfileUsesNativeParser(t *testing.T) { p.selected = indices[0] } next, cmd, _ := m.updateMonitorCommands(tea.KeyPressMsg{Code: tea.KeyEnter}) - if query == "':workspace'" { + if query != "Approve for me" { if cmd == nil || next.monitorCommands.menu.Path != "permissions "+query { t.Fatal("quoted profile did not reach native parser") } - } else if query == ":workspace" { - if cmd != nil || !next.monitorCommands.detail { - t.Fatal("matching profile selection changed") - } - } else if cmd == nil || next.monitorCommands.menu.Path != "permissions/reviewer" { - t.Fatal("matching submenu selection changed") + } else if cmd != nil || !next.monitorCommands.detail || next.monitorCommands.selected != 1 { + t.Fatal("matching native preset should open its review") } } } diff --git a/internal/ui/session_start.go b/internal/ui/session_start.go index 8a82b10..a1b4a80 100644 --- a/internal/ui/session_start.go +++ b/internal/ui/session_start.go @@ -25,6 +25,7 @@ type newSessionDraft struct { sending bool uncertain bool rejected bool + trust *codex.SessionTrustRequired } type newSessionResult struct { @@ -66,7 +67,7 @@ func (m *Model) closeNewSession() { func (m *Model) startDraftSession() tea.Cmd { d := &m.newSession - if !d.open() || d.sending || d.pendingID != "" || d.uncertain { + if !d.open() || d.sending || d.pendingID != "" || d.uncertain || d.trust != nil { return nil } if !m.canStartNewSession() || d.scope != m.finder.scope { @@ -81,16 +82,22 @@ func (m *Model) startDraftSession() tea.Cmd { d.notice = i18n.Text("Type a first message, or use /resume to open a saved session.") return nil } - cwd, scope, generation := d.directory.Value(), d.scope, d.generation + cwd, scope := d.directory.Value(), d.scope if m.reviewMonitorAction("new-session", cwd, i18n.Text("START NEW SESSION"), value, []string{scope, cwd, value}) { return nil } - d.sending, d.notice = true, i18n.Text("Starting session…") starter := m.fetcher.(codex.SessionStartClient) + return m.sendNewSession(starter.StartSession) +} + +func (m *Model) sendNewSession(start func(context.Context, string, string, string) (string, error)) tea.Cmd { + d := &m.newSession + cwd, scope, value, generation := d.directory.Value(), d.scope, d.prompt.Value(), d.generation + d.sending, d.notice, d.trust = true, i18n.Text("Starting session…"), nil return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), codex.SessionStartTimeout) defer cancel() - id, err := starter.StartSession(ctx, scope, cwd, value) + id, err := start(ctx, scope, cwd, value) return newSessionResult{generation, id, err} } } @@ -163,6 +170,9 @@ func layoutNewSession(width, height int, folderFocused, hasNotice bool) newSessi func (m Model) renderNewSession(width, height int, colors palette) string { d := m.newSession + if d.trust != nil { + return m.renderNewSessionTrust(m.layoutNewSessionTrust(width, height), width, height, colors) + } g := layoutNewSession(width, height, d.directory.Focused(), d.notice != "") innerWidth := max(width-4, 1) label := colors.label() @@ -187,8 +197,16 @@ func (m Model) renderNewSession(width, height int, colors palette) string { if !g.labels && height > 3 { folder.Prompt = i18n.Text("DIR") + " " } + tint := monitorComposerBackground(colors) + styles := folder.Styles() + styles.Focused.Text = label.Background(tint) + styles.Blurred.Text = styles.Focused.Text + styles.Cursor.Color = colors.primary + folder.SetStyles(styles) folder.SetWidth(max(innerWidth-ansi.StringWidth(folder.Prompt)-1, 1)) - rows[g.folder] = folder.View() + folder.SetCursor(folder.Position()) + line := ansi.Truncate(folder.View(), innerWidth, "") + rows[g.folder] = withDefaultBackground(line+strings.Repeat(" ", innerWidth-ansi.StringWidth(line)), tint) } for _, button := range g.buttons { style := colors.label() @@ -226,6 +244,9 @@ var newSessionKnownErrors = [...]error{ codex.ErrSessionStartUnavailable, codex.ErrSessionStartDirectory, codex.ErrSessionStartTrust, + codex.ErrSessionTrustCheck, + codex.ErrSessionTrustRestricted, + codex.ErrSessionTrustNotSaved, codex.ErrSessionStartPrompt, codex.ErrSessionStartCommand, codex.ErrSessionStartRejected, @@ -250,6 +271,11 @@ func (m Model) updateNewSession(message tea.Msg) (Model, tea.Cmd, bool) { return m, nil, true } d.sending = false + var review codex.SessionTrustRequired + if _, ok := m.fetcher.(codex.SessionTrustClient); ok && errors.As(event.err, &review) && d.scope == m.finder.scope { + d.trust, d.notice = &review, "" + return m, nil, true + } d.rejected = errors.Is(event.err, codex.ErrSessionFirstPrompt) && event.id != "" if event.err != nil && !d.rejected { d.notice = newSessionErrorText(event.err) @@ -279,7 +305,18 @@ func (m Model) updateNewSession(message tea.Msg) (Model, tea.Cmd, bool) { return m, nil, false } g := m.dashboardLayout() + if d.trust != nil { + return m.updateNewSessionTrust(message, g.contentWidth, g.meterHeight, g.meterY) + } draftGeometry := layoutNewSession(g.contentWidth, g.meterHeight, d.directory.Focused(), d.notice != "") + // The submitted directory and prompt must not change while obtaining a + // result that can offer to trust them, including via Tab or the mouse. + if d.sending { + if key, ok := message.(tea.KeyPressMsg); ok && key.String() == "ctrl+c" { + return m, nil, false + } + return m, nil, newSessionEditMessage(message) || isNewSessionClick(message, g.meterY, g.meterHeight) + } if key, ok := message.(tea.KeyPressMsg); ok { switch key.String() { case "ctrl+c": @@ -339,8 +376,9 @@ func (m Model) updateNewSession(message tea.Msg) (Model, tea.Cmd, bool) { } default: local := event.Y - g.meterY - if local == draftGeometry.folder || draftGeometry.prompt >= 0 && local >= draftGeometry.prompt && local < draftGeometry.prompt+draftGeometry.promptRows { - cmd := m.focusNewSessionFolder(local == draftGeometry.folder) + folderHit := local == draftGeometry.folder || draftGeometry.labels && local == draftGeometry.folder-1 + if folderHit || draftGeometry.prompt >= 0 && local >= draftGeometry.prompt && local < draftGeometry.prompt+draftGeometry.promptRows { + cmd := m.focusNewSessionFolder(folderHit) return m, cmd, true } } @@ -361,6 +399,11 @@ func (m Model) updateNewSession(message tea.Msg) (Model, tea.Cmd, bool) { return m, cmd, newSessionEditMessage(message) } +func isNewSessionClick(message tea.Msg, y, height int) bool { + event, ok := message.(tea.MouseClickMsg) + return ok && event.Y >= y && event.Y < y+height +} + func newSessionEditMessage(message tea.Msg) bool { switch message.(type) { case tea.KeyPressMsg, tea.PasteMsg: diff --git a/internal/ui/session_start_test.go b/internal/ui/session_start_test.go index 94565ad..419e139 100644 --- a/internal/ui/session_start_test.go +++ b/internal/ui/session_start_test.go @@ -16,10 +16,21 @@ import ( type newSessionProbe struct { resumeFinderProbe - prompts []string + prompts []string + startErr error + trustedSends int } func (p *newSessionProbe) StartSession(_ context.Context, _, _, prompt string) (string, error) { + p.prompts = append(p.prompts, prompt) + if p.startErr != nil { + return "", p.startErr + } + return "created", nil +} + +func (p *newSessionProbe) TrustAndStartSession(_ context.Context, _, _, prompt string, _ codex.SessionTrustRequired) (string, error) { + p.trustedSends++ p.prompts = append(p.prompts, prompt) return "created", nil } @@ -60,6 +71,60 @@ func TestNewSessionClickAndCancelResumePreservesDraft(t *testing.T) { } } +func TestNewSessionDirectoryUsesComposerBackground(t *testing.T) { + const width, height = 80, 16 + m := contextTestModel() + m.fetcher = &newSessionProbe{} + m.finder.setScope("account") + m.openNewSession() + m.newSession.directory.SetValue("/tmp/project") + for _, focused := range []bool{false, true} { + m.focusNewSessionFolder(focused) + g := layoutNewSession(width, height, focused, false) + for theme := themeHacker; theme < themeCount; theme++ { + colors := paletteFor(theme) + lines := backgroundTestLines(m.renderNewSession(width, height, colors)) + folder := lines[g.folder] + want := monitorComposerBackground(colors) + for _, x := range []int{2, 5, width - 3} { + assertBackground(t, folder[x].Style.Bg, want) + } + assertBackground(t, folder[1].Style.Bg, colors.background) + assertBackground(t, lines[g.folder-1][2].Style.Bg, colors.background) + assertBackground(t, lines[g.prompt][5].Style.Bg, want) + } + } +} + +func TestNewSessionDirectoryClickFocusesAndEdits(t *testing.T) { + for _, clickLabel := range []bool{false, true} { + m := contextTestModel() + m.width, m.height = 96, 28 + m.fetcher = &newSessionProbe{} + m.finder.setScope("account") + m.openNewSession() + const path, prompt = "/tmp/project", "unsent text" + m.newSession.directory.SetValue(path) + m.newSession.prompt.SetValue(prompt) + d := m.dashboardLayout() + g := layoutNewSession(d.contentWidth, d.meterHeight, false, false) + x, y := d.contentWidth-3, d.meterY+g.folder + if clickLabel { + x, y = 2, y-1 + } + next, _ := m.Update(tea.MouseClickMsg{Button: tea.MouseLeft, X: x + 2, Y: y}) + m = next.(Model) + if !m.newSession.directory.Focused() || m.newSession.prompt.Focused() { + t.Fatal("clicking the directory did not transfer focus from the composer") + } + next, _ = m.Update(tea.PasteMsg{Content: "-test"}) + m = next.(Model) + if m.newSession.directory.Value() != path+"-test" || m.newSession.prompt.Value() != prompt { + t.Fatal("click did not direct editing to the directory", m.newSession.directory.Value(), m.newSession.prompt.Value()) + } + } +} + func TestNewSessionFirstSendUsesStrictReview(t *testing.T) { m := contextTestModel() probe := &newSessionProbe{} @@ -112,6 +177,81 @@ func TestNewSessionLateObservationKeepsAcknowledgedID(t *testing.T) { } } +func TestNewSessionTrustReviewPreservesDraftAndRequiresExplicitConsent(t *testing.T) { + const prompt, dir = "Unsent first message", "/some/long/folder.abs" + for _, useMouse := range []bool{false, true} { + m := contextTestModel() + m.width, m.height = 120, 30 + m.confirmations.Mode = confirmation.None + probe := &newSessionProbe{startErr: codex.SessionTrustRequired{Directory: dir}} + m.fetcher = probe + m.finder.setScope("account") + m.openNewSession() + m.newSession.directory.SetValue(dir) + m.newSession.prompt.SetValue(prompt) + + for attempt := 0; attempt < 2; attempt++ { + next, cmd := m.Update(specialKey(tea.KeyEnter)) + m = next.(Model) + if cmd == nil { + t.Fatal("first send should check trust") + } + next, _ = m.Update(cmd()) + m = next.(Model) + if m.newSession.trust == nil || probe.trustedSends != 0 { + t.Fatal("must wait for explicit consent, even with confirmations disabled") + } + g := m.dashboardLayout() + view := ansi.Strip(m.renderNewSession(g.contentWidth, g.meterHeight, paletteFor(m.theme))) + for _, text := range []string{dir, i18n.Text("TRUST THIS FOLDER?"), i18n.Text("[ (T) Trust & send ]")} { + if !strings.Contains(view, text) { + t.Fatalf("trust review missing %q: %s", text, view) + } + } + for _, input := range []tea.Msg{specialKey(tea.KeyEnter), key('c'), tea.PasteMsg{Content: "replacement prompt"}} { + next, noAction := m.Update(input) + m = next.(Model) + if noAction != nil || m.newSession.trust == nil || m.newSession.prompt.Value() != prompt { + t.Fatal("ordinary input changed or authorised the pending review") + } + } + if attempt == 0 { + next, _ = m.Update(specialKey(tea.KeyEscape)) + m = next.(Model) + if m.newSession.trust != nil || !m.newSession.open() || m.newSession.prompt.Value() != prompt || m.newSession.directory.Value() != dir { + t.Fatal("back should restore the original draft") + } + } + } + var input tea.Msg = key('t') + if useMouse { + g := m.dashboardLayout() + trust := m.layoutNewSessionTrust(g.contentWidth, g.meterHeight).buttons[0] + input = tea.MouseClickMsg{Button: tea.MouseLeft, X: trust.rect.x + 2, Y: g.meterY + trust.rect.y} + } + next, cmd := m.Update(input) + if cmd == nil || !next.(Model).newSession.sending { + t.Fatal("explicit trust confirmation did not send") + } + if result := cmd().(newSessionResult); result.id != "created" || result.err != nil || probe.trustedSends != 1 || probe.prompts[2] != prompt { + t.Fatal(result, probe) + } + } +} + +func TestNewSessionCannotConfirmTrustWhenPathIsClipped(t *testing.T) { + m := contextTestModel() + m.fetcher = &newSessionProbe{} + m.finder.setScope("account") + m.openNewSession() + m.newSession.trust = &codex.SessionTrustRequired{Directory: "/" + strings.Repeat("long/", 300)} + m.width, m.height = 80, 15 + next, cmd := m.Update(key('t')) + if cmd != nil || next.(Model).newSession.trust == nil { + t.Fatal("cannot authorise trust if the user cannot read the full path") + } +} + func TestNewSessionFitsShortTerminalsAndSharesHitTargets(t *testing.T) { m := contextTestModel() m.fetcher = &newSessionProbe{} diff --git a/internal/ui/session_start_trust.go b/internal/ui/session_start_trust.go new file mode 100644 index 0000000..ec42165 --- /dev/null +++ b/internal/ui/session_start_trust.go @@ -0,0 +1,105 @@ +package ui + +import ( + "context" + "strings" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + "github.com/merefield/codexometer/internal/codex" + "github.com/merefield/codexometer/internal/i18n" +) + +type newSessionTrustLayout struct { + path, warning []string + buttons []monitorNavigationButton + ready bool +} + +func (m Model) layoutNewSessionTrust(width, height int) newSessionTrustLayout { + inner := max(width-4, 1) + g := newSessionTrustLayout{ + path: wrapProse(m.newSession.trust.Directory, inner), + warning: wrapProse(i18n.Text("Trust is saved. Folder settings and hooks may run code before the first message."), inner), + } + trust := monitorNavigationButton{label: i18n.Text("[ (T) Trust & send ]"), action: "new:trust", enabled: true} + back := monitorNavigationButton{label: i18n.Text("[ Esc Back ]"), action: "new:back", enabled: true} + row := 1 + len(g.path) + len(g.warning) + if width-4 >= ansi.StringWidth(trust.label)+1+ansi.StringWidth(back.label) && row < height-1 { + g.buttons = []monitorNavigationButton{trust, back} + layoutNavigationButtons(g.buttons, 2, row) + g.ready = true + } + return g +} + +func (m Model) renderNewSessionTrust(g newSessionTrustLayout, width, height int, colors palette) string { + title := i18n.Text("TRUST THIS FOLDER?") + if height <= 2 { + return renderFrameTitle(width, title, colors.warning, colors) + strings.Repeat("\n", max(height-1, 0)) + } + var body []string + if g.ready { + for _, line := range g.path { + body = append(body, colors.label().Bold(true).Render(line)) + } + for _, line := range g.warning { + body = append(body, colors.label().Foreground(colors.warning).Render(line)) + } + body = append(body, m.renderMonitorNavigationButtons(g.buttons, colors.label(), colors)) + } else { + body = wrapProse(i18n.Text("Enlarge the terminal to review folder trust, or press Esc to go back."), max(width-4, 1)) + } + return frameSized(width, height-2, title, strings.Join(body[:min(len(body), height-2)], "\n"), colors.warning, colors) +} + +func (m Model) updateNewSessionTrust(message tea.Msg, width, height, y int) (Model, tea.Cmd, bool) { + g := m.layoutNewSessionTrust(width, height) + action := "" + switch event := message.(type) { + case tea.KeyPressMsg: + switch event.String() { + case "ctrl+c": + return m, nil, false + case "esc": + action = "new:back" + case "t": + if !event.IsRepeat && g.ready { + action = "new:trust" + } + } + case tea.MouseClickMsg: + if event.Button == tea.MouseLeft { + action = monitorNavigationButtonsHit(g.buttons, event.X-2, event.Y-y) + } + case tea.MouseMotionMsg: + hover := monitorNavigationButtonsHit(g.buttons, event.X-2, event.Y-y) + if hover != "" || strings.HasPrefix(m.monitorContextHover, "new:") { + m.monitorContextHover = hover + return m, nil, true + } + return m, nil, false + case tea.PasteMsg: + default: + return m, nil, false + } + d := &m.newSession + switch action { + case "new:back": + d.trust, m.monitorContextHover = nil, "" + case "new:trust": + starter, ok := m.fetcher.(codex.SessionTrustClient) + if !ok || d.scope != m.finder.scope { + d.trust = nil + d.notice = i18n.Text("Codex connection changed. Close this draft and open a new one.") + return m, nil, true + } + review := *d.trust + m.monitorContextHover = "" + cmd := m.sendNewSession(func(ctx context.Context, scope, directory, value string) (string, error) { + return starter.TrustAndStartSession(ctx, scope, directory, value, review) + }) + return m, cmd, true + } + return m, nil, true +} diff --git a/internal/web/session_mutation.go b/internal/web/session_mutation.go index 2db017f..9fba66f 100644 --- a/internal/web/session_mutation.go +++ b/internal/web/session_mutation.go @@ -113,8 +113,12 @@ func (s *server) startSession(w http.ResponseWriter, r *http.Request, target ses status := http.StatusBadGateway switch err { case codex.ErrSessionStartDirectory, codex.ErrSessionStartPrompt, codex.ErrSessionStartCommand, - codex.ErrSessionStartUnavailable, codex.ErrSessionStartTrust, codex.ErrSessionStartRejected: + codex.ErrSessionStartUnavailable, codex.ErrSessionTrustRestricted, codex.ErrSessionStartRejected: status = http.StatusBadRequest + default: + if errors.Is(err, codex.ErrSessionStartTrust) { + status = http.StatusBadRequest + } } http.Error(w, err.Error(), status) return diff --git a/internal/web/session_mutation_test.go b/internal/web/session_mutation_test.go index 514212d..8e31361 100644 --- a/internal/web/session_mutation_test.go +++ b/internal/web/session_mutation_test.go @@ -71,6 +71,8 @@ func TestNewSessionRouteRequiresWriteModePairingAndExactConsent(t *testing.T) { firstMessageOnly bool }{ {codex.ErrSessionStartTrust, 400, false}, + {codex.SessionTrustRequired{Directory: "/other"}, 400, false}, + {codex.ErrSessionTrustRestricted, 400, false}, {codex.ErrSessionStartRejected, 400, false}, {codex.ErrSessionStartUncertain, 502, false}, {codex.ErrSessionFirstPrompt, 200, true}, diff --git a/main.go b/main.go index 1a2e3b0..0054955 100644 --- a/main.go +++ b/main.go @@ -390,7 +390,7 @@ func run(args []string, stdout, stderr io.Writer, deps dependencies) int { codexPath = flags.String("codex", "codex", "path to the Codex CLI") errorLog = flags.String("error-log", "", "write bounded operational diagnostics to this file (off by default)") verbose = flags.Bool("verbose", false, "include diagnostic context in --error-log (never raw payloads)") - confirmationOption = flags.String("confirmation", "balanced", "confirmation policy: balanced, none or require (quota resets always require confirmation)") + confirmationOption = flags.String("confirmation", "balanced", "confirmation policy: balanced, none or require (quota resets and folder trust always require confirmation)") refresh = flags.Duration("refresh", time.Minute, "quota refresh interval") demo = flags.Bool("demo", false, "show the UI with simulated quota data") inline = flags.Bool("inline", false, "render inline instead of using the alternate screen")