Merge remote-tracking branch 'origin/main' into places-slice-1
29 files changed,
+1,313
−74
.rastrillo/budgets.txt+4 −4docs/superpowers/plans/CONTROLLER-REPORT-native-composer.md+91 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+2 −0internal/equipo/copy.go+2 −0internal/plan3test/plan3_release_test.go+3 −1internal/runner/forge/branch.go+4 −0internal/runner/forge/credential_file.go+40 −5internal/runner/forge/credential_file_test.go+27 −0internal/runner/forge/merge.go+84 −5internal/runner/forge/merge_notsent_test.go+208 −0internal/runner/forge/repositories.go+4 −0internal/runner/thin/forge.go+168 −24internal/runner/thin/forges.go+20 −1internal/runner/thin/forges_review_test.go+3 −1internal/runner/thin/merge_credential_test.go+440 −0internal/runner/thin/mergestep.go+29 −1internal/runner/thin/run.go+3 −0internal/runner/workspace/workspace.go+5 −0internal/wire/tasks.go+19 −0native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift+2 −1native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift+5 −1native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift+32 −21native/apple/Sources/EquipoKit/UI/Screens/NeedsScreen.swift+1 −0native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift+1 −0native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift+1 −1native/apple/Sources/EquipoMac/MacComposer.swift+32 −6native/apple/Sources/EquipoMac/MacStyle.swift+4 −2native/apple/Tests/EquipoKitTests/ComposerPolishTests.swift+39 −0native/ios/UITests/AttachmentSourceUITests.swift+40 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index bf6f0876..12bbad0a 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 22598 - Stuck tasks: the task page Retry on a failed preview and the coordinator's retried attempt on the timeline (2026-11-25); measured 22598 source lines. |
| -size internal/wire 7069 - Native task evidence hosted names and Today done_at, additive device fields; measured 7069 source lines (2026-11-26). |
| +size internal/equipo 22600 - Stuck tasks' Retry and timeline (2026-11-25), merge_credential and amadan_unreachable copy (2026-11-26); measured 22600 source lines. |
| +size internal/wire 7088 - Native task evidence fields, merge_credential and amadan_unreachable reasons (2026-11-26); measured 7088 source lines. |
| size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -30,7 +30,7 @@ size internal/runner/provider 5731 - Fable follow-up: base and diagnostic gates, |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| -size internal/plan3test - 11911 Paused-work strings, the Assistant routes and Paul's approved stuck-task strings in the release inventory and API contract (2026-11-25); measured 11911 test lines. |
| +size internal/plan3test - 11913 Paused-work, Assistant, stuck-task and merge credential strings in the release inventory (2026-11-26); measured 11913 test lines. |
| time internal/runner/forge 20s Plan 3 CI repair measured 10.527s for the full package (controller CI 10.407s). |
| time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full package (controller CI 10.709s); |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 28530 22894 Protocol 30: the preview scanner's health in the capability report, the stuck-task tools refused on an older link (2026-11-25); measured 28530/22894. |
| +size internal/runner/thin 28724 23336 Protocol 30 scanner health and stuck-task tools, merge credential fallback and write scope (2026-11-26); measured 28724/23336. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-native-composer.md b/docs/superpowers/plans/CONTROLLER-REPORT-native-composer.md| new file mode 100644 |
| index 00000000..09752708 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-native-composer.md |
| @@ -0,0 +1,91 @@ |
| +# Native composer polish |
| + |
| +Branch: `native/composer`, based on main `c74fd0ac`. |
| + |
| +## Reference and changes |
| + |
| +Read Base's `origin/main:native/apple/Sources/BaseKit/Ask/Composer.swift` |
| +and `origin/main:native/apple/Sources/BaseKit/Phone/PhoneAskScreen.swift` |
| +with `git show`. The composer uses the screen background, a tinted field |
| +with a 10-point corner and a focus edge in Equipo's accent. No new copy. |
| + |
| +Conversation, task detail (including its thread), and Needs you (which can |
| +contain a reply field) dismiss the keyboard interactively. The attachment |
| +menu is a separate round 44-point target to the field's left, with thumbnails |
| +above. Photos continues to present from the picker owner outside the Menu. |
| +Mac keeps paste and drop and adds a file panel via the same round add button. |
| + |
| +## Verification |
| + |
| +Test-first: `swift test --package-path native/apple --filter ComposerPolishTests` |
| +failed on the original production code: three missing scroll-dismissal |
| +modifiers and no separate Mac attachment button. There is no ViewInspector |
| +in this package; source contracts follow ProjectsReviewTests. Actual phone |
| +dragging, menu and Photos presentation are exercised by AttachmentSourceUITests. |
| + |
| +Results, mutation commands, screenshot manifest and final gates follow below. |
| + |
| +Mutation command for each: `swift test --package-path native/apple --filter ComposerPolishTests`. |
| +All six compiled and were killed by assertions, then restored: |
| + |
| +1. Conversation `.interactively` replaced with `.never`. |
| +2. Task detail `.interactively` replaced with `.never`. |
| +3. Needs you `.interactively` replaced with `.never`. |
| +4. Mac attachment button moved inside the field view. |
| +5. Mac attachment target reduced from 44 to 32 points. |
| +6. Mac field's 52-point attachment offset removed (overlap). |
| + |
| +Simulator baseline: `xcodebuild -project native/ios/EquipoPhone.xcodeproj |
| +-scheme AttachmentSources -configuration Debug -destination |
| +'platform=iOS Simulator,id=9B363AD0-4B74-46BD-AEEC-24241419BF65' |
| +-derivedDataPath native/build/Phone -resultBundlePath "$TMPDIR/composer-before-fixed.xcresult" |
| +CODE_SIGNING_ALLOWED=NO test`. |
| +The original production code failed `testConversationDragDismissesKeyboard` |
| +at the keyboard-disappeared assertion; the appearance and Photos-menu tests |
| +passed. The fixture uses production ConversationScreen with a fake transport. |
| +An initial harness attempt used `textViews`; the current simulator exposes |
| +SwiftUI's vertical field as `textFields`, so the query was corrected before |
| +collecting the baseline. No production workaround was needed. |
| + |
| +The definitive simulator regression uses a swipe beginning on a rendered |
| +message. It passed with interactive dismissal, and replacing it with `.never` |
| +failed at the keyboard-disappeared assertion (`composer-ui-mutation.xcresult`). |
| +This is the seventh killed mutation, in addition to the six native checks. |
| +The modifier lives on the containing screen, as in Base, covering the scroll |
| +and the composer in its bottom inset. The test also verifies the typed draft |
| +survives dismissal. |
| + |
| +An isolated AppKit probe clicked the real add button, observed its file panel, |
| +and cancelled without changing the draft. Presenting a modal panel in the |
| +concurrent full test process caused an early clean process exit, so the gate |
| +tests the production panel factory without presenting it: files allowed, |
| +directories excluded and multiple selection allowed. The existing paste/drop |
| +tests also run in the native gate. |
| + |
| +The extra empty-padding gesture initially queried `app.scrollViews.firstMatch`, |
| +which is ambiguous while the keyboard's prediction scroller is present. A |
| +stable `conversation-scroll` identifier fixes that test target. Both the message |
| +swipe and padding swipe pass (`composer-scroller-id.xcresult`); no gesture |
| +workaround or content-shape change is shipped. Temporary runtime diagnostics |
| +confirmed the UIKit scroller had interactive dismissal and vertical bouncing, |
| +and were removed. |
| + |
| +Three further panel mutations also compiled and failed assertions using the |
| +same filtered test command: files disabled, folders enabled, and multiple |
| +selection disabled. All ten mutations were restored; the filtered suite |
| +passes again. |
| + |
| +Final native gate: `native/scripts/check-native.sh` passed: 346 tests in 46 |
| +suites (one existing known issue), 330 parity strings, schema/markdown checks, |
| +reference scan, Mac build and iPhone Simulator build. No server changes. |
| + |
| +Screenshots are under `site/build/composer/` in the daily-driver audit: |
| +`iphone-{before,after}-{light,dark}-keyboard-{up,down}.png`, |
| +`mac-{before,after}-{light,dark}.png`, and menu/Photos-picker captures. |
| +They are actual simulator/AppKit captures from production views with the |
| +existing attachment fake server. No new strings or copy questions. |
| + |
| +Final simulator command is the same AttachmentSources invocation above with |
| +`-resultBundlePath "$TMPDIR/composer-final.xcresult"`. All three UI tests passed: |
| +light/dark captures, message and padding dismissal with draft preservation, |
| +and the 44-point attachment menu opening the private Photos picker. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index d6e36d8f..ae2e6956 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6908,6 +6908,8 @@ records remain unchanged. |
| | `chat.activity.offer_retry` | Offering to try the merge again… | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6haczxo74hoyyuf7xkojgqd27e, unchanged) | |
| | `chat.activity.retry_step` | Trying it again… | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6haczxo74hoyyuf7xkojgqd27e, unchanged) | |
| | `work.tl.coordinator_retried` | The coordinator started %s again. | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6haczxo74hoyyuf7xkojgqd27e, unchanged) | |
| +| `work.reason.merge_credential` | the runner has no Amadan credential for this repository | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) | |
| +| `work.reason.amadan_unreachable` | Amadan could not be reached to confirm Equipo may merge here | Copy specialist | Runtime; COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) | |
| ## Task 21 |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 088dba28..70c8347e 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -1057,6 +1057,8 @@ var pageCopy = map[string]string{ |
| "work.reason.merge_forbidden": "Equipo may not merge in this repository", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "work.reason.merge_failed": "Amadan did not merge it", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "work.reason.merge_unborn_default": "the first merge into this empty repository needs an Amadan update", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| + "work.reason.merge_credential": "the runner has no Amadan credential for this repository", // COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) |
| + "work.reason.amadan_unreachable": "Amadan could not be reached to confirm Equipo may merge here", // COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged) |
| "chat.card.merge_question": "Merge %s without checks?", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.card.merge": "Merge", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "chat.card.wait": "Wait for checks", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go| index eaf16089..5cefd80c 100644 |
| --- a/internal/plan3test/plan3_release_test.go |
| +++ b/internal/plan3test/plan3_release_test.go |
| @@ -183,6 +183,8 @@ func plan3CopyInventory(t *testing.T) { |
| approvedFailedReplies := strings.HasPrefix(key, "chat.failed.") && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-22, copy-review ipgtz3lqoo3rj6rpiodpekh6vu, unchanged)") || key == "signin.refused" && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-22, copy-review smart-door-copy-5, unchanged)") |
| // Paul's own review of the Engineering stop reasons. |
| approvedStopReasons := slices.Contains([]string{"work.reason.no_further_changes", "work.reason.tools_refused"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-23, copy-review eavqvil43jg2zs3wxx3kxp3bpm, unchanged)") |
| + // Paul's own review of the merge step's credential and hub reasons. |
| + approvedMergeCredential := slices.Contains([]string{"work.reason.merge_credential", "work.reason.amadan_unreachable"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-25, copy-review 6wxwi7zo3fph5nu4nm6eipptfq, unchanged)") |
| // Paul's own review of the coordinator's stuck-task strings. |
| approvedStuckTasks := slices.Contains([]string{"chat.merge.retry_offer", "chat.activity.offer_retry", "chat.activity.retry_step", "work.tl.coordinator_retried"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY APPROVED (Paul, 2026-11-25, copy-review 6haczxo74hoyyuf7xkojgqd27e, unchanged)") |
| acceptedRoster := strings.HasPrefix(key, "roster.") && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Astra, 2026-11-14)") |
| @@ -210,7 +212,7 @@ func plan3CopyInventory(t *testing.T) { |
| acceptedProjects := slices.Contains([]string{"projects.amadan", "projects.yours", "projects.can_add", "projects.add_reachable", "projects.names", "projects.names_hint", "projects.details", "projects.title", "projects.description", "projects.save", "projects.context", "projects.found", "projects.selected", "projects.owner_add", "projects.selection_lost", "projects.other", "projects.name_question", "projects.personal_names", "projects.forget_name", "docs/api/equipo-v1.md / Projects and starting a request"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-22)") |
| acceptedAgentAccess := slices.Contains([]string{"copyAgentConfig", "copyAgentForbidden", "copyAgentNotFound", "copyAgentUnavailable", "copyAgentTooLarge", "copyAgentInvalid", "copyAgentMedia", "copyAgentUnauthenticated", "agent.equipo_projects_list", "agent.equipo_tasks_list", "agent.equipo_task_get", "agent.equipo_needs_you", "docs/api/equipo-v1.md / Delegated read-only operations"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)") |
| acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key]) |
| - if !approvedStuckTasks && !acceptedPaused && !acceptedNewTeamCard && !acceptedGitHubEgress && !acceptedForgeSeam && !acceptedAPIErrors && !acceptedNativeProjects && !acceptedInjection && !acceptedMail && !acceptedPush && !acceptedAgentAccess && !acceptedProjects && !acceptedCardNames && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina && !approvedFailedReplies && !approvedStopReasons { |
| + if !approvedMergeCredential && !approvedStuckTasks && !acceptedPaused && !acceptedNewTeamCard && !acceptedGitHubEgress && !acceptedForgeSeam && !acceptedAPIErrors && !acceptedNativeProjects && !acceptedInjection && !acceptedMail && !acceptedPush && !acceptedAgentAccess && !acceptedProjects && !acceptedCardNames && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina && !approvedFailedReplies && !approvedStopReasons { |
| t.Fatal("entry has no copy review status or applicable acceptance", key) |
| } |
| } |
diff --git a/internal/runner/forge/branch.go b/internal/runner/forge/branch.go| index c6f46358..0314b22a 100644 |
| --- a/internal/runner/forge/branch.go |
| +++ b/internal/runner/forge/branch.go |
| @@ -200,6 +200,10 @@ func (b BranchPush) head(ctx context.Context, remote workspace.Remote) (string, |
| // remote resolves the repository's remote and checks it is that one. |
| func (b BranchPush) remote(ctx context.Context) (workspace.Remote, error) { |
| remote, err := b.Remote(ctx) |
| + if errors.Is(err, workspace.ErrHubUnavailable) { |
| + // Write access could not be confirmed: worth trying again. |
| + return workspace.Remote{}, fmt.Errorf("resolving the remote: %w", err) |
| + } |
| if err != nil { |
| return workspace.Remote{}, fmt.Errorf("%w: resolving the remote: %v", ErrPushRefused, err) |
| } |
diff --git a/internal/runner/forge/credential_file.go b/internal/runner/forge/credential_file.go| index 309eff08..66a01621 100644 |
| --- a/internal/runner/forge/credential_file.go |
| +++ b/internal/runner/forge/credential_file.go |
| @@ -23,9 +23,12 @@ type forgeCredentialFile struct { |
| Repositories map[string]json.RawMessage `json:"repositories"` |
| } |
| -// Agent is the agent-wide credential: the file's own api and git, or, |
| -// in a file with per-repository entries only, the first of them (one |
| -// agent account serves them all). |
| +// Agent is the agent-wide credential: the file's own api and git. In a |
| +// legacy file, with per-repository entries only, one agent account serves |
| +// them all, so it is the one bearer every usable entry shares (with the |
| +// one git password they give); entries that disagree name no agent |
| +// credential, never whichever sorts first. A fallback write with it still |
| +// needs the hub's list, fetched with that bearer, to name the repository. |
| func (f FileCredentials) Agent(ctx context.Context) (Credential, error) { |
| var file forgeCredentialFile |
| if err := readCredentialFile(f.Path, &file); err != nil { |
| @@ -34,11 +37,37 @@ func (f FileCredentials) Agent(ctx context.Context) (Credential, error) { |
| if file.API != "" { |
| return agentCredential(file, "", file.API, file.Git) |
| } |
| - names, err := f.RepositoryNames() |
| + names, err := repositoryNames(file) |
| if err != nil || len(names) == 0 { |
| return Credential{}, provider.ErrIdentity |
| } |
| - return f.Credential(ctx, names[0]) |
| + var out Credential |
| + for _, name := range names { |
| + c, err := entryCredential(file, name) |
| + switch { |
| + case err != nil: |
| + case out.Bearer == "": |
| + out = c |
| + case c.Bearer != out.Bearer: |
| + return Credential{}, provider.ErrIdentity |
| + case c.GitPassword != "" && out.GitPassword == "": |
| + out.GitPassword = c.GitPassword |
| + case c.GitPassword != "" && c.GitPassword != out.GitPassword: |
| + return Credential{}, provider.ErrIdentity |
| + } |
| + } |
| + if out.Bearer == "" { |
| + return Credential{}, provider.ErrIdentity |
| + } |
| + out.Remote = "" |
| + return out, nil |
| +} |
| + |
| +// Legacy reports a file with per-repository entries and no agent-wide |
| +// api: its agent credential comes from Agent's legacy rule. |
| +func (f FileCredentials) Legacy() bool { |
| + var file forgeCredentialFile |
| + return readCredentialFile(f.Path, &file) == nil && file.API == "" && len(file.Repositories) > 0 |
| } |
| func agentCredential(file forgeCredentialFile, repo, api, git string) (Credential, error) { |
| @@ -57,6 +86,12 @@ func (f FileCredentials) Credential(_ context.Context, repo string) (Credential, |
| if err := readCredentialFile(f.Path, &file); err != nil { |
| return Credential{}, err |
| } |
| + return entryCredential(file, repo) |
| +} |
| + |
| +// entryCredential is repo's credential in a read file: its own entry, or |
| +// the agent-wide api when the file has one. |
| +func entryCredential(file forgeCredentialFile, repo string) (Credential, error) { |
| var entry struct { |
| API string `json:"api"` |
| Git string `json:"git"` |
diff --git a/internal/runner/forge/credential_file_test.go b/internal/runner/forge/credential_file_test.go| index 59e6edc6..6b5fdcb4 100644 |
| --- a/internal/runner/forge/credential_file_test.go |
| +++ b/internal/runner/forge/credential_file_test.go |
| @@ -112,3 +112,30 @@ func TestForgeCredentialAgentWide(t *testing.T) { |
| t.Fatal("a per-repository file crossed repositories") |
| } |
| } |
| + |
| +// TestForgeCredentialLegacyAgentRule: in a file without an agent-wide api |
| +// the agent credential is the one bearer all usable entries share, never |
| +// whichever entry sorts first; entries with different bearers give none. |
| +func TestForgeCredentialLegacyAgentRule(t *testing.T) { |
| + ctx := context.Background() |
| + write := func(raw string) FileCredentials { |
| + path := filepath.Join(t.TempDir(), "amadan.json") |
| + must(t, os.WriteFile(path, []byte(raw), 0600)) |
| + return FileCredentials{Path: path} |
| + } |
| + shared := write(`{"agent":"equipo~owner@example.test","repositories":{"amadan.net/ns/a":{"git":"git-broken"},"amadan.net/ns/b":{"api":"api-one","git":"git-one"},"amadan.net/ns/c":"api-one"}}`) |
| + if c, err := shared.Agent(ctx); err != nil || c.Bearer != "api-one" || c.GitPassword != "git-one" || c.Remote != "" { |
| + t.Fatalf("shared legacy %+v %v", c.Remote, err) |
| + } |
| + if !shared.Legacy() { |
| + t.Fatal("legacy file not reported") |
| + } |
| + mixed := write(`{"agent":"equipo~owner@example.test","repositories":{"amadan.net/ns/a":{"api":"api-a","git":"git-a"},"amadan.net/ns/b":{"api":"api-b","git":"git-b"}}}`) |
| + if c, err := mixed.Agent(ctx); err == nil { |
| + t.Fatalf("ambiguous legacy file chose %q", c.Bearer) |
| + } |
| + wide := write(`{"agent":"equipo~owner@example.test","api":"api-agent","git":"git-agent","repositories":{"amadan.net/ns/a":{"api":"api-a","git":"git-a"}}}`) |
| + if c, err := wide.Agent(ctx); err != nil || c.Bearer != "api-agent" || wide.Legacy() { |
| + t.Fatalf("agent-wide %+v %v", c.Remote, err) |
| + } |
| +} |
diff --git a/internal/runner/forge/merge.go b/internal/runner/forge/merge.go| index e0c78c4d..46941bf2 100644 |
| --- a/internal/runner/forge/merge.go |
| +++ b/internal/runner/forge/merge.go |
| @@ -39,8 +39,41 @@ var ( |
| // the hub refused to make the first merge (unborn_default, or |
| // is_default once a rebuild pointed its HEAD at the task branch). |
| ErrMergeUnbornDefault = errors.New("forge: the hub cannot make the first merge into an empty repository") |
| + // ErrMergeNoCredential: the runner has no usable forge credential for |
| + // the repository (none in the credential file, and it is not one the |
| + // agent-wide credential serves), so it refused the merge itself. |
| + ErrMergeNoCredential = errors.New("forge: no usable forge credential for the repository") |
| ) |
| +// NotSentError is a merge Equipo refused itself before any merge request |
| +// left for the hub: a definite refusal, never "outcome unknown", since the |
| +// hub cannot have acted on it. Only code that has sent no merge request |
| +// returns one. |
| +type NotSentError struct { |
| + // Repo is the repository refused, "" when it is not a valid hub key. |
| + Repo string |
| + Err error |
| +} |
| + |
| +func (e *NotSentError) Error() string { |
| + repo := e.Repo |
| + if repo == "" { |
| + repo = "this repository" |
| + } |
| + return fmt.Sprintf("%v (%s; refused by the runner, no merge request was sent)", e.Err, repo) |
| +} |
| + |
| +func (e *NotSentError) Unwrap() error { return e.Err } |
| + |
| +// NotSent is err as a refusal made before the merge request, naming repo |
| +// only when it is a valid hub repository. |
| +func NotSent(repo string, err error) error { |
| + if !validRepository(repo) { |
| + repo = "" |
| + } |
| + return &NotSentError{Repo: repo, Err: err} |
| +} |
| + |
| // HubError is the hub's answer to a merge it did not make: its HTTP |
| // status, its machine-readable reason (the JSON "reason") and its |
| // sentence (the JSON "error", or a page's text), both redacted and |
| @@ -65,7 +98,8 @@ func hubError(res MergeResult, err error) error { |
| // uncertain is ErrMergeUncertain with what is known of why: the hub's |
| // answer when it gave one, else the cause's words. Only the words: a |
| -// cause's own identity (a local refusal, say) never decides the outcome. |
| +// cause's own identity never decides the outcome (MergeBranch settles a |
| +// NotSentError, the one refusal known to have sent nothing, before this). |
| func uncertain(res MergeResult, cause error) error { |
| switch { |
| case res.Status != 0: |
| @@ -149,16 +183,20 @@ type hubMergeBody struct { |
| // HubMerge sends one merge request to the hub with the agent's bearer. |
| // A transport failure or an unreadable answer is an error: the caller |
| -// cannot know whether the merge happened. |
| +// cannot know whether the merge happened. What it refuses before sending |
| +// is a NotSentError. |
| func HubMerge(ctx context.Context, client *http.Client, hub string, cred Credential, repo, branch string, req MergeRequest) (MergeResult, error) { |
| - if !validRepository(repo) || !validRef(branch) || cred.Bearer == "" || strings.ContainsAny(cred.Bearer, "\r\n") { |
| - return MergeResult{}, ErrMergeRefused |
| + if !validRepository(repo) || !validRef(branch) { |
| + return MergeResult{}, NotSent(repo, ErrMergeRefused) |
| + } |
| + if cred.Bearer == "" || strings.ContainsAny(cred.Bearer, "\r\n") { |
| + return MergeResult{}, NotSent(repo, ErrMergeNoCredential) |
| } |
| parts := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") |
| body, _ := json.Marshal(req) |
| hr, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(hub, "/")+"/api/v1/repos/"+url.PathEscape(parts[0])+"/"+url.PathEscape(parts[1])+"/branches/"+url.PathEscape(branch)+"/merge", bytes.NewReader(body)) |
| if err != nil { |
| - return MergeResult{}, ErrMergeRefused |
| + return MergeResult{}, NotSent(repo, ErrMergeRefused) |
| } |
| hr.Header.Set("Authorization", "Bearer "+cred.Bearer) |
| hr.Header.Set("Content-Type", "application/json") |
| @@ -225,6 +263,10 @@ type BranchMerge struct { |
| Request func(context.Context, MergeRequest) (MergeResult, error) |
| // Confirm checks the execution lease right before the request. |
| Confirm func(context.Context) error |
| + // Preflight, if set, makes the runner's own checks that need no |
| + // remote (the credential the inspection and the request use) before |
| + // the remote is read. It returns a NotSentError to refuse. |
| + Preflight func(context.Context) error |
| // beforeRequest runs right before the request (tests move the branch). |
| beforeRequest func() |
| } |
| @@ -375,6 +417,22 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) { |
| if found && rec.Phase == mergeMerged { |
| return MergeOutcome{SHA: rec.SHA, Into: rec.Into, Strategy: rec.Strategy, Source: SourceCached}, nil |
| } |
| + // An earlier request may still land: reconcile from the default branch |
| + // (a read) before the runner's write check, which then gates only a |
| + // new request. |
| + unresolved := found && rec.Phase == mergeRequested |
| + if m.Preflight != nil && !unresolved { |
| + // The runner's own refusals come before the remote is read (that |
| + // read needs the same credential): definite, as no request was |
| + // ever sent. |
| + if err := m.Preflight(ctx); err != nil { |
| + var ns *NotSentError |
| + if !errors.As(err, &ns) { |
| + return MergeOutcome{}, uncertain(MergeResult{}, err) |
| + } |
| + return MergeOutcome{}, err |
| + } |
| + } |
| if !found { |
| rec = mergeRecord{Task: m.Task, Repo: m.Repo, Branch: m.Branch, Commit: m.Commit, Phase: mergePrepared, Strategy: m.Strategy} |
| } |
| @@ -401,6 +459,14 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) { |
| return MergeOutcome{}, ErrMergeUncertain |
| } |
| } |
| + before := rec.Phase |
| + if m.Preflight != nil && unresolved { |
| + // Not landed, and the earlier request is unresolved: a new one only |
| + // with write access confirmed; without it, still unknown. |
| + if err := m.Preflight(ctx); err != nil { |
| + return MergeOutcome{}, uncertain(MergeResult{}, err) |
| + } |
| + } |
| if err := m.Confirm(ctx); err != nil { |
| return MergeOutcome{}, fmt.Errorf("%w: confirming the lease: %v", ErrMergeUncertain, err) |
| } |
| @@ -412,6 +478,19 @@ func MergeBranch(ctx context.Context, m BranchMerge) (MergeOutcome, error) { |
| m.beforeRequest() |
| } |
| res, rerr := m.Request(ctx, MergeRequest{ExpectSHA: m.Commit, Message: m.Message, Strategy: m.Strategy, Agent: m.Agent}) |
| + var notSent *NotSentError |
| + if errors.As(rerr, ¬Sent) && before != mergeRequested { |
| + // Refused here before anything left for the hub, and no earlier |
| + // request is unresolved: definite, nothing to reconcile. The |
| + // record goes back to prepared, so a later Merge asks as usual. |
| + // After an unresolved request it is no answer at all: the default |
| + // branch decides below, and the record stays requested. |
| + rec.Phase = before |
| + if err := m.save(rec); err != nil { |
| + return MergeOutcome{}, ErrMergeUncertain |
| + } |
| + return MergeOutcome{}, rerr |
| + } |
| if rerr == nil && res.Merged { |
| rec.Phase, rec.SHA, rec.Into = mergeMerged, res.SHA, firstOf(res.Into, st.Default) |
| if err := m.save(rec); err != nil { |
diff --git a/internal/runner/forge/merge_notsent_test.go b/internal/runner/forge/merge_notsent_test.go| new file mode 100644 |
| index 00000000..3dc31c3d |
| --- /dev/null |
| +++ b/internal/runner/forge/merge_notsent_test.go |
| @@ -0,0 +1,208 @@ |
| +package forge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| +) |
| + |
| +// TestMergeBranchLocalRefusalIsDefinite: a merge Equipo refuses itself |
| +// before any request leaves for the hub (no usable credential, say) is a |
| +// definite refusal with its own reason, never "outcome unknown": the |
| +// remote is not read again to reconcile, the record goes back to the phase |
| +// it had (prepared), and a later call asks the hub as usual. |
| +func TestMergeBranchLocalRefusalIsDefinite(t *testing.T) { |
| + h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| + m := newMerge(t, h) |
| + var inspects atomic.Int32 |
| + m.Inspect = func(ctx context.Context) (RemoteState, error) { inspects.Add(1); return h.inspect(ctx) } |
| + refusing := m |
| + refusing.Request = func(context.Context, MergeRequest) (MergeResult, error) { |
| + return MergeResult{}, NotSent(m.Repo, ErrMergeNoCredential) |
| + } |
| + _, err := MergeBranch(context.Background(), refusing) |
| + if !errors.Is(err, ErrMergeNoCredential) || errors.Is(err, ErrMergeUncertain) { |
| + t.Fatalf("local refusal: %v", err) |
| + } |
| + if !strings.Contains(err.Error(), m.Repo) || strings.Contains(err.Error(), "outcome unknown") { |
| + t.Fatalf("local refusal words: %v", err) |
| + } |
| + if inspects.Load() != 1 { |
| + t.Fatalf("a local refusal read the remote %d times", inspects.Load()) |
| + } |
| + if rec, ok, _ := m.load(); !ok || rec.Phase != mergePrepared { |
| + t.Fatalf("record after a local refusal: %+v", rec) |
| + } |
| + out, err := MergeBranch(context.Background(), m) |
| + if err != nil || out.Source != SourceHub || len(h.requests) != 1 { |
| + t.Fatalf("after the refusal %+v %v (%d requests)", out, err, len(h.requests)) |
| + } |
| +} |
| + |
| +// TestNotSentNamesOnlyAValidRepository: the refusal's words name the |
| +// repository only when it is a valid hub key. |
| +func TestNotSentNamesOnlyAValidRepository(t *testing.T) { |
| + if err := NotSent("amadan.net/../x\nInjected", ErrMergeRefused); strings.Contains(err.Error(), "Injected") || !errors.Is(err, ErrMergeRefused) { |
| + t.Fatalf("invalid repository named: %v", err) |
| + } |
| +} |
| + |
| +// TestHubMergeRefusesLocallyBeforeSending: HubMerge's own refusals (no |
| +// bearer, a bad repository or branch) are made before any request and |
| +// say so; the hub is never contacted. |
| +func TestHubMergeRefusesLocallyBeforeSending(t *testing.T) { |
| + var hits atomic.Int32 |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits.Add(1); w.WriteHeader(500) })) |
| + defer srv.Close() |
| + req := MergeRequest{ExpectSHA: strings.Repeat("a", 40), Strategy: "merge"} |
| + for _, c := range []struct { |
| + cred Credential |
| + repo, branch string |
| + want error |
| + }{ |
| + {Credential{Agent: "equipo~p@example.com"}, "amadan.net/oficina/sample", "equipo/tk1-x", ErrMergeNoCredential}, |
| + {Credential{Agent: "equipo~p@example.com", Bearer: "a\nb"}, "amadan.net/oficina/sample", "equipo/tk1-x", ErrMergeNoCredential}, |
| + {Credential{Agent: "equipo~p@example.com", Bearer: "token"}, "github.com/x/y", "equipo/tk1-x", ErrMergeRefused}, |
| + {Credential{Agent: "equipo~p@example.com", Bearer: "token"}, "amadan.net/oficina/sample", "bad..ref", ErrMergeRefused}, |
| + } { |
| + _, err := HubMerge(context.Background(), srv.Client(), srv.URL, c.cred, c.repo, c.branch, req) |
| + var ns *NotSentError |
| + if !errors.Is(err, c.want) || !errors.As(err, &ns) || errors.Is(err, ErrMergeUncertain) { |
| + t.Fatalf("%+v %s %s: %v", c.cred.Agent, c.repo, c.branch, err) |
| + } |
| + if strings.Contains(err.Error(), "token") { |
| + t.Fatalf("bearer in the refusal: %v", err) |
| + } |
| + } |
| + if hits.Load() != 0 { |
| + t.Fatalf("the hub was contacted %d times", hits.Load()) |
| + } |
| +} |
| + |
| +// TestMergeBranchLocalRefusalAfterAnUnresolvedRequest: a first request |
| +// whose answer was lost (it may still land) leaves the record requested. |
| +// A later local refusal must not end that as definite: it stays uncertain, |
| +// the remote is read again, and once the earlier request lands a restart |
| +// settles it from the default branch with no new request. |
| +func TestMergeBranchLocalRefusalAfterAnUnresolvedRequest(t *testing.T) { |
| + h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| + m := newMerge(t, h) |
| + var delayed MergeRequest |
| + lost := m |
| + lost.Request = func(_ context.Context, req MergeRequest) (MergeResult, error) { |
| + delayed = req // the hub has it, and has not acted yet |
| + return MergeResult{}, errors.New("answer lost") |
| + } |
| + if _, err := MergeBranch(context.Background(), lost); !errors.Is(err, ErrMergeUncertain) { |
| + t.Fatalf("lost answer: %v", err) |
| + } |
| + var inspects atomic.Int32 |
| + refusing := m |
| + refusing.Inspect = func(ctx context.Context) (RemoteState, error) { inspects.Add(1); return h.inspect(ctx) } |
| + refusing.Request = func(context.Context, MergeRequest) (MergeResult, error) { |
| + return MergeResult{}, NotSent(m.Repo, ErrMergeNoCredential) |
| + } |
| + _, err := MergeBranch(context.Background(), refusing) |
| + if !errors.Is(err, ErrMergeUncertain) || errors.Is(err, ErrMergeNoCredential) { |
| + t.Fatalf("local refusal after an unresolved request: %v", err) |
| + } |
| + if inspects.Load() != 2 { |
| + t.Fatalf("not reconciled: %d inspections", inspects.Load()) |
| + } |
| + if rec, ok, _ := m.load(); !ok || rec.Phase != mergeRequested { |
| + t.Fatalf("record %+v", rec) |
| + } |
| + // A preflight refusal with the request still unresolved is uncertain too. |
| + preflight := m |
| + preflight.Preflight = func(context.Context) error { return NotSent(m.Repo, ErrMergeNoCredential) } |
| + if _, err := MergeBranch(context.Background(), preflight); !errors.Is(err, ErrMergeUncertain) { |
| + t.Fatalf("preflight after an unresolved request: %v", err) |
| + } |
| + // The delayed request lands; a restart settles it, asking nothing. |
| + h.mu.Lock() |
| + mergeNow(h, delayed) |
| + h.mu.Unlock() |
| + out, err := MergeBranch(context.Background(), m) |
| + if err != nil || !out.Reconciled || out.SHA != strings.Repeat("8", 40) || len(h.requests) != 0 { |
| + t.Fatalf("settled %+v %v (%d requests)", out, err, len(h.requests)) |
| + } |
| + if rec, ok, _ := m.load(); !ok || rec.Phase != mergeMerged { |
| + t.Fatalf("record after settling %+v", rec) |
| + } |
| +} |
| + |
| +// TestMergeBranchPreflight: a local refusal found before the remote is |
| +// read (the inspection itself needs the credential) is definite when no |
| +// request was ever sent: nothing is inspected, confirmed or requested. |
| +func TestMergeBranchPreflight(t *testing.T) { |
| + h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| + m := newMerge(t, h) |
| + var inspects, confirms atomic.Int32 |
| + m.Inspect = func(ctx context.Context) (RemoteState, error) { inspects.Add(1); return h.inspect(ctx) } |
| + m.Confirm = func(context.Context) error { confirms.Add(1); return nil } |
| + refused := m |
| + refused.Preflight = func(context.Context) error { return NotSent(m.Repo, ErrMergeNoCredential) } |
| + _, err := MergeBranch(context.Background(), refused) |
| + if !errors.Is(err, ErrMergeNoCredential) || errors.Is(err, ErrMergeUncertain) || inspects.Load() != 0 || confirms.Load() != 0 || len(h.requests) != 0 { |
| + t.Fatalf("preflight: %v (%d inspections, %d confirms, %d requests)", err, inspects.Load(), confirms.Load(), len(h.requests)) |
| + } |
| + // Passing, it merges as usual. |
| + m.Preflight = func(context.Context) error { return nil } |
| + if out, err := MergeBranch(context.Background(), m); err != nil || out.Source != SourceHub { |
| + t.Fatalf("after %+v %v", out, err) |
| + } |
| +} |
| + |
| +// TestMergeBranchReconcilesBeforeTheWriteCheck: an earlier request whose |
| +// answer was lost landed meanwhile. The write check fails now (a revoked |
| +// grant, a hub list that cannot be fetched), yet the default branch reads |
| +// fine: the merge settles from it, and the write check is never asked. |
| +func TestMergeBranchReconcilesBeforeTheWriteCheck(t *testing.T) { |
| + for _, refusal := range []error{ErrMergeRefused, workspace.ErrHubUnavailable} { |
| + h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| + m := newMerge(t, h) |
| + lost := m |
| + lost.Request = func(_ context.Context, req MergeRequest) (MergeResult, error) { |
| + mergeNow(h, req) // landed; the answer is lost |
| + return MergeResult{}, errors.New("answer lost") |
| + } |
| + lost.Inspect = func(context.Context) (RemoteState, error) { |
| + if rec, ok, _ := m.load(); ok && rec.Phase == mergeRequested { |
| + return RemoteState{}, errors.New("process killed") |
| + } |
| + return h.inspect(context.Background()) |
| + } |
| + if _, err := MergeBranch(context.Background(), lost); !errors.Is(err, ErrMergeUncertain) { |
| + t.Fatalf("lost: %v", err) |
| + } |
| + var preflights atomic.Int32 |
| + m.Preflight = func(context.Context) error { preflights.Add(1); return NotSent(m.Repo, refusal) } |
| + out, err := MergeBranch(context.Background(), m) |
| + if err != nil || !out.Reconciled || out.SHA != strings.Repeat("8", 40) || preflights.Load() != 0 || len(h.requests) != 0 { |
| + t.Fatalf("%v: settled %+v %v (%d preflights, %d requests)", refusal, out, err, preflights.Load(), len(h.requests)) |
| + } |
| + } |
| +} |
| + |
| +// TestPushRemoteUnavailableIsNotRefused: a remote the hub could not be |
| +// asked about (write access unconfirmed) is a failure to try again, never |
| +// the definite refusal a missing credential is. |
| +func TestPushRemoteUnavailableIsNotRefused(t *testing.T) { |
| + b := BranchPush{Repo: "amadan.net/oficina/sample", Remote: func(context.Context) (workspace.Remote, error) { |
| + return workspace.Remote{}, workspace.ErrHubUnavailable |
| + }} |
| + _, err := b.remote(context.Background()) |
| + if !errors.Is(err, workspace.ErrHubUnavailable) || errors.Is(err, ErrPushRefused) { |
| + t.Fatalf("unavailable: %v", err) |
| + } |
| + b.Remote = func(context.Context) (workspace.Remote, error) { return workspace.Remote{}, workspace.ErrGitPassword } |
| + if _, err := b.remote(context.Background()); !errors.Is(err, ErrPushRefused) { |
| + t.Fatalf("no credential: %v", err) |
| + } |
| +} |
diff --git a/internal/runner/forge/repositories.go b/internal/runner/forge/repositories.go| index 13a10e5d..eb50af18 100644 |
| --- a/internal/runner/forge/repositories.go |
| +++ b/internal/runner/forge/repositories.go |
| @@ -11,6 +11,10 @@ func (f FileCredentials) RepositoryNames() ([]string, error) { |
| if err := readCredentialFile(f.Path, &file); err != nil { |
| return nil, err |
| } |
| + return repositoryNames(file) |
| +} |
| + |
| +func repositoryNames(file forgeCredentialFile) ([]string, error) { |
| if len(file.Repositories) > 256 { |
| return nil, provider.ErrPolicy |
| } |
diff --git a/internal/runner/thin/forge.go b/internal/runner/thin/forge.go| index 156c80a3..f917ecee 100644 |
| --- a/internal/runner/thin/forge.go |
| +++ b/internal/runner/thin/forge.go |
| @@ -11,6 +11,7 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "log/slog" |
| "net/http" |
| "os" |
| "os/exec" |
| @@ -94,6 +95,8 @@ type fileForge struct { |
| // etag is the hub's validator for the last list, so a check that |
| // finds nothing new costs a 304. |
| etag string |
| + // listKey is scopeKey of the credential the list was fetched with. |
| + listKey string |
| } |
| // reachEvery is how long the hub's list of what the agent reaches is |
| @@ -160,25 +163,153 @@ func (f *fileForge) Remote(ctx context.Context, repo string, use Use) (workspace |
| } |
| return f.remoteCredential(ctx, repo) |
| } |
| - f.list(ctx) |
| - if !slices.Contains(f.Repos(), repo) { |
| + // A push: the repository's own entry, or the fallback with the hub's |
| + // current word (writeCredential). |
| + if names, _ := f.creds.RepositoryNames(); slices.Contains(names, repo) { |
| + return f.creds.Resolve(ctx, repo) |
| + } |
| + c, err := f.writeCredential(ctx, repo) |
| + if errors.Is(err, workspace.ErrHubUnavailable) { |
| + return workspace.Remote{}, workspace.ErrHubUnavailable |
| + } |
| + if err != nil || c.GitPassword == "" { |
| return workspace.Remote{}, workspace.ErrGitPassword |
| } |
| - return f.remoteCredential(ctx, repo) |
| + return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil |
| } |
| func (f *fileForge) remoteCredential(ctx context.Context, repo string) (workspace.Remote, error) { |
| - names, _ := f.creds.RepositoryNames() |
| - if !slices.Contains(names, repo) { |
| - // Created or reachable through the agent's namespace grant: the |
| - // agent-wide git password serves them. |
| - c, err := f.agent(ctx) |
| - if err != nil || c.GitPassword == "" { |
| - return workspace.Remote{}, workspace.ErrGitPassword |
| + if names, _ := f.creds.RepositoryNames(); slices.Contains(names, repo) { |
| + return f.creds.Resolve(ctx, repo) |
| + } |
| + // Created or reachable through the agent's namespace grant: the |
| + // agent-wide git password serves them. |
| + c, err := f.credential(ctx, repo) |
| + if err != nil || c.GitPassword == "" { |
| + return workspace.Remote{}, workspace.ErrGitPassword |
| + } |
| + return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil |
| +} |
| + |
| +// credential is the forge credential for repo, which the caller has |
| +// already found in scope (Reachable for reads, Repos for CI reads): its own |
| +// entry in the credential file, or else the agent-wide credential. A |
| +// repository with its own entry never falls back: an unusable entry is |
| +// refused, not replaced. Writes go through writeCredential, which also |
| +// needs the hub's current word for a fallback. |
| +func (f *fileForge) credential(ctx context.Context, repo string) (forge.Credential, error) { |
| + names, err := f.creds.RepositoryNames() |
| + if err != nil { |
| + return forge.Credential{}, err |
| + } |
| + if slices.Contains(names, repo) { |
| + return f.creds.Credential(ctx, repo) |
| + } |
| + if !forgekey.ValidHub(repo) { |
| + return forge.Credential{}, forge.ErrMergeNoCredential |
| + } |
| + c, err := f.creds.Agent(ctx) |
| + if err != nil { |
| + return forge.Credential{}, err |
| + } |
| + c.Remote = "https://" + repo |
| + return c, nil |
| +} |
| + |
| +// writeCredential is the credential a merge or a push to repo uses, or a |
| +// forge.NotSentError: the repository's own entry, else the agent-wide |
| +// credential, but only for a repository the hub lists now as writable, |
| +// in a list fetched with that same credential (writable). A repository |
| +// the runner created is no exception: a revoked grant, a rename or a |
| +// replaced credential ends its fallback. No usable credential is |
| +// ErrMergeNoCredential; no current write scope is a policy refusal. |
| +func (f *fileForge) writeCredential(ctx context.Context, repo string) (forge.Credential, error) { |
| + names, err := f.creds.RepositoryNames() |
| + if err != nil { |
| + return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential) |
| + } |
| + if slices.Contains(names, repo) { |
| + c, err := f.creds.Credential(ctx, repo) |
| + if err != nil { |
| + return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential) |
| + } |
| + return c, nil |
| + } |
| + if !forgekey.ValidHub(repo) { |
| + return forge.Credential{}, forge.NotSent(repo, errOutOfScope) |
| + } |
| + c, err := f.creds.Agent(ctx) |
| + if err != nil { |
| + return forge.Credential{}, forge.NotSent(repo, forge.ErrMergeNoCredential) |
| + } |
| + listed, confirmed := f.writable(ctx, repo, scopeKey(c)) |
| + if !confirmed { |
| + return forge.Credential{}, forge.NotSent(repo, workspace.ErrHubUnavailable) |
| + } |
| + if !listed { |
| + return forge.Credential{}, forge.NotSent(repo, errOutOfScope) |
| + } |
| + c.Remote = "https://" + repo |
| + return c, nil |
| +} |
| + |
| +// scopeKey names a credential without holding it: what the hub's list |
| +// was fetched with. |
| +func scopeKey(c forge.Credential) string { |
| + sum := sha256.Sum256([]byte(c.Agent + "\x00" + c.Bearer)) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// writable asks the hub now whether it lists repo as writable with the |
| +// credential key names: confirmed is whether it answered (a list fetched |
| +// just now with that credential), listed whether the repository is in it. |
| +// A write is rare, so it never trusts the cached list; the request is |
| +// conditional (a 304 when nothing changed). Unconfirmed, the write waits. |
| +func (f *fileForge) writable(ctx context.Context, repo, key string) (listed, confirmed bool) { |
| + f.mu.Lock() |
| + f.nsAt = time.Time{} |
| + f.mu.Unlock() |
| + f.list(ctx) |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + confirmed = f.listKey == key && !f.nsAt.IsZero() |
| + return confirmed && slices.Contains(f.listed, repo), confirmed |
| +} |
| + |
| +// MergePreflight refuses, before anything is read or sent, a merge this |
| +// runner has no credential or no current write scope for. |
| +func (f *fileForge) MergePreflight(ctx context.Context, repo string) error { |
| + _, err := f.writeCredential(ctx, repo) |
| + return err |
| +} |
| + |
| +// The start check's warnings: a repository the runner created that has no |
| +// usable credential (its merges are refused), and a legacy credential |
| +// file whose per-repository bearer serves as the agent's. |
| +const ( |
| + createdNoCredential = "created repository has no usable forge credential; merges there will be refused" |
| + legacyAgentCredential = "forge credential file has no agent-wide entry; its shared per-repository credential serves as the agent's" |
| +) |
| + |
| +// checkCreated warns once if the credential file is a legacy one, and, |
| +// with repository creation on, once per repository this runner created |
| +// that has no usable credential. It reads the files, never the hub, and |
| +// logs repositories, never a credential. |
| +func (f *fileForge) checkCreated(ctx context.Context, log *slog.Logger) { |
| + if log == nil { |
| + return |
| + } |
| + if f.creds.Legacy() { |
| + log.Warn(legacyAgentCredential) |
| + } |
| + if !f.enabled { |
| + return |
| + } |
| + for _, repo := range f.createdRepos() { |
| + if c, err := f.credential(ctx, repo); err != nil || c.Bearer == "" { |
| + log.Warn(createdNoCredential, "repo", repo) |
| } |
| - return workspace.Remote{URL: "https://" + repo, GitPassword: c.GitPassword}, nil |
| } |
| - return f.creds.Resolve(ctx, repo) |
| } |
| // list asks the hub which repositories the agent may write to, at most |
| @@ -187,13 +318,19 @@ func (f *fileForge) remoteCredential(ctx context.Context, repo string) (workspac |
| func (f *fileForge) list(ctx context.Context) ([]string, []string) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - if time.Since(f.nsAt) < reachEvery && f.ns != nil { |
| - return slices.Clone(f.ns), slices.Clone(f.listed) |
| - } |
| c, err := f.agent(ctx) |
| if err != nil { |
| + f.listKey = "" |
| return []string{}, []string{} |
| } |
| + if key := scopeKey(c); key != f.listKey { |
| + // Another credential: what the hub said for the last one says |
| + // nothing about this one. |
| + f.ns, f.listed, f.nsAt, f.etag, f.listKey = nil, nil, time.Time{}, "", key |
| + } |
| + if time.Since(f.nsAt) < reachEvery && f.ns != nil { |
| + return slices.Clone(f.ns), slices.Clone(f.listed) |
| + } |
| req, _ := http.NewRequestWithContext(ctx, "GET", f.hub+"/api/v1/repos", nil) |
| req.Header.Set("Authorization", "Bearer "+c.Bearer) |
| if f.etag != "" && f.ns != nil { |
| @@ -208,6 +345,12 @@ func (f *fileForge) list(ctx context.Context) ([]string, []string) { |
| f.nsAt = time.Now() |
| return slices.Clone(f.ns), slices.Clone(f.listed) |
| } |
| + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { |
| + // The hub answered: this credential reaches nothing (revoked, or |
| + // another's). A denial, not an outage. |
| + f.ns, f.listed, f.nsAt, f.etag = []string{}, []string{}, time.Now(), "" |
| + return []string{}, []string{} |
| + } |
| var out struct { |
| Repos []struct { |
| NS string `json:"ns"` |
| @@ -315,16 +458,17 @@ func (f *fileForge) adopt(repo string) error { |
| return ErrAdopted |
| } |
| -// Merge sends the hub the merge request with the agent's credential for |
| -// repo (its own entry, or the agent-wide one). |
| +// errOutOfScope: the repository has no entry of its own in the credential |
| +// file and the hub does not list it now as the agent's to write (a read |
| +// grant, a revoked grant, a rename). A policy refusal. |
| +var errOutOfScope = fmt.Errorf("%w: not a repository this runner's agent may write now", forge.ErrMergeRefused) |
| + |
| +// Merge sends the hub the merge request with writeCredential's credential. |
| +// Without one it refuses before contacting the hub (forge.NotSent). |
| func (f *fileForge) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) { |
| - f.list(ctx) |
| - if !slices.Contains(f.Repos(), repo) { |
| - return forge.MergeResult{}, forge.ErrMergeRefused |
| - } |
| - c, err := f.creds.Credential(ctx, repo) |
| + c, err := f.writeCredential(ctx, repo) |
| if err != nil { |
| - return forge.MergeResult{}, forge.ErrMergeRefused |
| + return forge.MergeResult{}, err |
| } |
| return forge.HubMerge(ctx, f.client, f.hub, c, repo, branch, req) |
| } |
| @@ -353,7 +497,7 @@ func (f *fileForge) ciCredential(ctx context.Context, repo string) (forge.Creden |
| if !slices.Contains(f.Repos(), repo) { |
| return forge.Credential{}, forge.ErrCIRead |
| } |
| - c, err := f.creds.Credential(ctx, repo) |
| + c, err := f.credential(ctx, repo) |
| if err != nil { |
| return forge.Credential{}, forge.ErrCIRead |
| } |
diff --git a/internal/runner/thin/forges.go b/internal/runner/thin/forges.go| index c2828e79..0914e356 100644 |
| --- a/internal/runner/thin/forges.go |
| +++ b/internal/runner/thin/forges.go |
| @@ -96,10 +96,29 @@ func (f *Forges) Propose(ctx context.Context, p Proposal) (ProposalRef, error) { |
| func (f *Forges) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) { |
| fg, key, err := f.route(repo) |
| if err != nil { |
| - return forge.MergeResult{}, errors.Join(forge.ErrMergeRefused, err) |
| + return forge.MergeResult{}, forge.NotSent(repo, errors.Join(forge.ErrMergeRefused, err)) |
| } |
| return fg.Merge(ctx, key, branch, req) |
| } |
| + |
| +// mergePreflighter is a forge that can refuse a merge on the runner |
| +// before the remote is read (forge.BranchMerge.Preflight). |
| +type mergePreflighter interface { |
| + MergePreflight(ctx context.Context, repo string) error |
| +} |
| + |
| +// MergePreflight routes to the repository's forge, when it has one. |
| +func (f *Forges) MergePreflight(ctx context.Context, repo string) error { |
| + fg, key, err := f.route(repo) |
| + if err != nil { |
| + return forge.NotSent(repo, errors.Join(forge.ErrMergeRefused, err)) |
| + } |
| + if p, ok := fg.(mergePreflighter); ok { |
| + return p.MergePreflight(ctx, key) |
| + } |
| + return nil |
| +} |
| + |
| func (f *Forges) catalog(list func(Forge) []string) []string { |
| var out []string |
| for host, fg := range f.byHost { |
diff --git a/internal/runner/thin/forges_review_test.go b/internal/runner/thin/forges_review_test.go| index 57c1860d..8d8f53cf 100644 |
| --- a/internal/runner/thin/forges_review_test.go |
| +++ b/internal/runner/thin/forges_review_test.go |
| @@ -107,7 +107,9 @@ func TestRouterWithProductionFileForge(t *testing.T) { |
| if rep, err := f.PollAccess(ctx, "ar_one", c); err != nil || rep.State != "approved" { |
| t.Fatal("poll", rep, err) |
| } |
| - want := []string{"GET /api/v1/repos", "POST /api/v1/repos/carlos/platform/branches/" + branch + "/merge", "GET /api/v1/repos/carlos/platform/ci/hosted", "GET /api/v1/repos/carlos/platform/ci/status", "POST /api/v1/agents/access-requests", "GET /api/v1/agents/access-requests/ar_one"} |
| + // The read lists once; the push and the merge, writes with the |
| + // agent-wide credential, each ask the hub afresh (writable). |
| + want := []string{"GET /api/v1/repos", "GET /api/v1/repos", "GET /api/v1/repos", "POST /api/v1/repos/carlos/platform/branches/" + branch + "/merge", "GET /api/v1/repos/carlos/platform/ci/hosted", "GET /api/v1/repos/carlos/platform/ci/status", "POST /api/v1/agents/access-requests", "GET /api/v1/agents/access-requests/ar_one"} |
| if !reflect.DeepEqual(calls, want) { |
| t.Fatalf("hub calls: %v", calls) |
| } |
diff --git a/internal/runner/thin/merge_credential_test.go b/internal/runner/thin/merge_credential_test.go| new file mode 100644 |
| index 00000000..ad5c437c |
| --- /dev/null |
| +++ b/internal/runner/thin/merge_credential_test.go |
| @@ -0,0 +1,440 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// mergeCredRig is a runner forge whose credential file has per-repository |
| +// entries only (no agent-wide api), as on the runner of tkbstr6cjl7h, and |
| +// whose state lists created as a repository it made. The hub answers the |
| +// repository list per bearer (lists), or with listStatus when set, and |
| +// records every merge request's path and bearer. |
| +type mergeCredRig struct { |
| + f *fileForge |
| + path string |
| + mu sync.Mutex |
| + merges []string |
| + lists map[string][]string |
| + listStatus int |
| + // etag, when set, is a validator that ignores the caller (a cache |
| + // keyed by URL): a request carrying it is answered 304. |
| + etag string |
| +} |
| + |
| +func newMergeCredRig(t *testing.T, file string, created, listed []string) *mergeCredRig { |
| + t.Helper() |
| + rig := &mergeCredRig{lists: map[string][]string{"api-first": listed}} |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + rig.mu.Lock() |
| + defer rig.mu.Unlock() |
| + if r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos" { |
| + if rig.listStatus != 0 { |
| + w.WriteHeader(rig.listStatus) |
| + return |
| + } |
| + if rig.etag != "" { |
| + if r.Header.Get("If-None-Match") == rig.etag { |
| + w.WriteHeader(http.StatusNotModified) |
| + return |
| + } |
| + w.Header().Set("ETag", rig.etag) |
| + } |
| + var parts []string |
| + for _, repo := range rig.lists[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] { |
| + p := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/") |
| + parts = append(parts, fmt.Sprintf(`{"ns":%q,"name":%q}`, p[0], p[1])) |
| + } |
| + fmt.Fprintf(w, `{"repos":[%s]}`, strings.Join(parts, ",")) |
| + return |
| + } |
| + if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/merge") { |
| + rig.merges = append(rig.merges, r.URL.EscapedPath()+" "+r.Header.Get("Authorization")) |
| + fmt.Fprintf(w, `{"merged":true,"sha":%q,"into":"main","branch_closed":true}`, strings.Repeat("8", 40)) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNotFound) |
| + })) |
| + t.Cleanup(srv.Close) |
| + dir := t.TempDir() |
| + rig.path = filepath.Join(dir, "amadan.json") |
| + if file != "" { |
| + if err := os.WriteFile(rig.path, []byte(file), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + rig.f = NewFileForge(rig.path, dir, true).(*fileForge) |
| + rig.f.hub, rig.f.client = srv.URL, srv.Client() |
| + for _, repo := range created { |
| + if err := rig.f.record(repo); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return rig |
| +} |
| + |
| +func (rig *mergeCredRig) requests() []string { |
| + rig.mu.Lock() |
| + defer rig.mu.Unlock() |
| + return append([]string(nil), rig.merges...) |
| +} |
| + |
| +func (rig *mergeCredRig) set(fn func()) { |
| + rig.mu.Lock() |
| + defer rig.mu.Unlock() |
| + fn() |
| +} |
| + |
| +const perRepoOnly = `{"agent":"equipo~owner@example.com","repositories":{"amadan.net/paulca/first":{"api":"api-first","git":"git-first"},"amadan.net/paulca/stale":{"git":"git-stale"}}}` |
| + |
| +var mergeReq = forge.MergeRequest{ExpectSHA: strings.Repeat("a", 40), Strategy: "merge", Agent: forge.AgentMeta{Session: "equipo-tk1", Harness: "equipo", Host: "test"}} |
| + |
| +// TestMergeCredentialFallsBackForCreatedRepos: a repository the runner |
| +// created, absent from the credential file and listed by the hub for the |
| +// agent's bearer, merges with the agent-wide credential, the one push and |
| +// Create use for it. |
| +func TestMergeCredentialFallsBackForCreatedRepos(t *testing.T) { |
| + rig := newMergeCredRig(t, perRepoOnly, []string{"amadan.net/paulca/nearys"}, []string{"amadan.net/paulca/nearys"}) |
| + res, err := rig.f.Merge(context.Background(), "amadan.net/paulca/nearys", "equipo/tk1-x", mergeReq) |
| + if err != nil || !res.Merged { |
| + t.Fatalf("created repository: %+v %v", res, err) |
| + } |
| + if got := rig.requests(); len(got) != 1 || got[0] != "/api/v1/repos/paulca/nearys/branches/equipo%2Ftk1-x/merge Bearer api-first" { |
| + t.Fatalf("merge requests %q", got) |
| + } |
| + // The hub's CI is read with the same credential. |
| + if c, err := rig.f.ciCredential(context.Background(), "amadan.net/paulca/nearys"); err != nil || c.Bearer != "api-first" || c.Remote != "https://amadan.net/paulca/nearys" { |
| + t.Fatalf("CI credential %+v %v", c.Remote, err) |
| + } |
| + // A repository the hub lists as writable by the agent is in scope too. |
| + rig = newMergeCredRig(t, perRepoOnly, nil, []string{"amadan.net/paulca/listed"}) |
| + if _, err := rig.f.Merge(context.Background(), "amadan.net/paulca/listed", "equipo/tk1-x", mergeReq); err != nil || len(rig.requests()) != 1 { |
| + t.Fatalf("listed repository: %v %q", err, rig.requests()) |
| + } |
| +} |
| + |
| +// TestMergeCredentialStaysInScope: a repository that is neither in the |
| +// credential file, nor created here, nor listed by the hub is refused by |
| +// policy before any request; one whose own entry is unusable never falls |
| +// back to the agent-wide credential. Both refusals are definite and name |
| +// the repository, never a credential. |
| +func TestMergeCredentialStaysInScope(t *testing.T) { |
| + rig := newMergeCredRig(t, perRepoOnly, []string{"amadan.net/paulca/nearys"}, []string{"amadan.net/paulca/listed"}) |
| + for repo, want := range map[string]error{"amadan.net/paulca/unrelated": forge.ErrMergeRefused, "amadan.net/paulca/stale": forge.ErrMergeNoCredential} { |
| + _, err := rig.f.Merge(context.Background(), repo, "equipo/tk1-x", mergeReq) |
| + var ns *forge.NotSentError |
| + if !errors.Is(err, want) || !errors.As(err, &ns) || errors.Is(err, forge.ErrMergeUncertain) { |
| + t.Fatalf("%s: %v", repo, err) |
| + } |
| + if !strings.Contains(err.Error(), repo) || strings.Contains(err.Error(), "api-") || strings.Contains(err.Error(), "git-") { |
| + t.Fatalf("%s: refusal words %q", repo, err) |
| + } |
| + if _, err := rig.f.ciCredential(context.Background(), repo); err == nil { |
| + t.Fatalf("%s: CI credential out of scope", repo) |
| + } |
| + } |
| + if got := rig.requests(); len(got) != 0 { |
| + t.Fatalf("out-of-scope merge reached the hub: %q", got) |
| + } |
| + // No agent-wide credential at all: a created repository is refused too. |
| + rig = newMergeCredRig(t, `{"agent":"equipo~owner@example.com","repositories":{}}`, []string{"amadan.net/paulca/nearys"}, nil) |
| + if _, err := rig.f.Merge(context.Background(), "amadan.net/paulca/nearys", "equipo/tk1-x", mergeReq); !errors.Is(err, forge.ErrMergeNoCredential) || len(rig.requests()) != 0 { |
| + t.Fatalf("no agent credential: %v", err) |
| + } |
| +} |
| + |
| +// TestMergeStepLocalRefusal: a merge refused on the runner before the hub |
| +// was contacted ends the step at once (one attempt, no retries) with its |
| +// own reason, and the log tail names the repository, not "outcome |
| +// unknown"; the forge record is back at prepared. |
| +func TestMergeStepLocalRefusal(t *testing.T) { |
| + old := mergeBackoff |
| + mergeBackoff = time.Millisecond |
| + t.Cleanup(func() { mergeBackoff = old }) |
| + e, f, r, _ := hubRig(t) |
| + f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) { |
| + return forge.MergeResult{}, forge.NotSent(r.Repo, forge.ErrMergeNoCredential) |
| + } |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepFailed || rep.Reason != "merge_credential" || !rep.Termination || f.requests != 1 { |
| + t.Fatalf("report %+v (%d requests)", rep, f.requests) |
| + } |
| + if !strings.Contains(rep.LogTail, r.Repo) || strings.Contains(rep.LogTail, "outcome unknown") { |
| + t.Fatalf("log tail %q", rep.LogTail) |
| + } |
| + paths, _ := filepath.Glob(filepath.Join(e.root(), "merge", "merge-*.json")) |
| + if len(paths) != 1 { |
| + t.Fatalf("merge records %v", paths) |
| + } |
| + if raw, err := os.ReadFile(paths[0]); err != nil || !strings.Contains(string(raw), `"phase":"prepared"`) { |
| + t.Fatalf("record %s %v", raw, err) |
| + } |
| + // A later Merge tap asks the hub again and lands it. |
| + f.answer = nil |
| + if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 2 { |
| + t.Fatalf("again %+v (%d requests)", rep, f.requests) |
| + } |
| +} |
| + |
| +// TestCheckCreatedCredentials: at start, with repository creation on, |
| +// every repository the runner created is checked for a usable credential |
| +// by the merge lookup; each missing one gets one fixed warning naming it, |
| +// and no credential is logged. |
| +func TestCheckCreatedCredentials(t *testing.T) { |
| + var buf bytes.Buffer |
| + log := slog.New(slog.NewTextHandler(&buf, nil)) |
| + rig := newMergeCredRig(t, perRepoOnly, []string{"amadan.net/paulca/nearys"}, nil) |
| + rig.f.checkCreated(context.Background(), log) |
| + if strings.Contains(buf.String(), createdNoCredential) { |
| + t.Fatalf("warned with a usable credential: %s", buf.String()) |
| + } |
| + rig = newMergeCredRig(t, `{"agent":"equipo~owner@example.com","repositories":{}}`, []string{"amadan.net/paulca/nearys", "amadan.net/paulca/other"}, nil) |
| + rig.f.checkCreated(context.Background(), log) |
| + out := buf.String() |
| + if strings.Count(out, createdNoCredential) != 2 || !strings.Contains(out, "amadan.net/paulca/nearys") || !strings.Contains(out, "amadan.net/paulca/other") || !strings.Contains(out, "level=WARN") { |
| + t.Fatalf("warnings %s", out) |
| + } |
| + if len(rig.requests()) != 0 { |
| + t.Fatal("the check contacted the hub") |
| + } |
| + // Creation off: nothing is checked. |
| + buf.Reset() |
| + rig.f.enabled = false |
| + rig.f.checkCreated(context.Background(), log) |
| + if buf.Len() != 0 { |
| + t.Fatalf("checked with creation off: %s", buf.String()) |
| + } |
| +} |
| + |
| +// TestMergeFallbackNeedsCurrentWriteScope: the agent-wide fallback writes |
| +// only to a repository the hub lists now, for the credential in the file |
| +// now. A grant revoked (no longer listed), a list the hub fails to give, |
| +// a replaced credential and a repository renamed after the runner created |
| +// it all refuse the merge and the push before any merge request. |
| +func TestMergeFallbackNeedsCurrentWriteScope(t *testing.T) { |
| + ctx := context.Background() |
| + repo := "amadan.net/paulca/nearys" |
| + blocked := func(t *testing.T, rig *mergeCredRig, what string, want error) { |
| + t.Helper() |
| + before := len(rig.requests()) |
| + _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq) |
| + var ns *forge.NotSentError |
| + if !errors.Is(err, want) || !errors.As(err, &ns) || len(rig.requests()) != before { |
| + t.Fatalf("%s: merge %v (%d requests)", what, err, len(rig.requests())-before) |
| + } |
| + if _, err := rig.f.Remote(ctx, repo, Push); err == nil { |
| + t.Fatalf("%s: push credential", what) |
| + } |
| + } |
| + refused := func(t *testing.T, rig *mergeCredRig, what string) { |
| + t.Helper() |
| + blocked(t, rig, what, forge.ErrMergeRefused) |
| + } |
| + t.Run("revoked", func(t *testing.T) { |
| + rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo}) |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil { |
| + t.Fatal(err) |
| + } |
| + rig.set(func() { rig.lists["api-first"] = nil }) |
| + refused(t, rig, "grant revoked") |
| + }) |
| + t.Run("list fails", func(t *testing.T) { |
| + rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo}) |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The cached list expires; the refresh fails: the cache no longer |
| + // authorises a fallback write. |
| + rig.f.mu.Lock() |
| + rig.f.nsAt = time.Now().Add(-2 * reachEvery) |
| + rig.f.mu.Unlock() |
| + // A 500 is not a denial: write access is unconfirmed (it recovers, |
| + // see TestWriteScopeUnavailableRecovers), and nothing is sent. A 401 |
| + // is the hub refusing the credential: a denial. |
| + for status, want := range map[int]error{http.StatusInternalServerError: workspace.ErrHubUnavailable, http.StatusUnauthorized: forge.ErrMergeRefused} { |
| + rig.set(func() { rig.listStatus = status }) |
| + blocked(t, rig, fmt.Sprint("list ", status), want) |
| + } |
| + }) |
| + t.Run("credential replaced", func(t *testing.T) { |
| + rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo}) |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Within the minute the list is cached, another agent's credential |
| + // replaces the file; the hub lists nothing for it. |
| + replaced := `{"agent":"other~owner@example.com","repositories":{"amadan.net/paulca/first":{"api":"api-other","git":"git-other"}}}` |
| + if err := os.WriteFile(rig.path, []byte(replaced), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused(t, rig, "credential replaced") |
| + }) |
| + t.Run("credential replaced behind a validator", func(t *testing.T) { |
| + // The list's validator ignores who asks: the old credential's |
| + // validator must not confirm its list for the new one. |
| + rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo}) |
| + rig.set(func() { rig.etag = `"v1"` }) |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil { |
| + t.Fatal(err) |
| + } |
| + replaced := `{"agent":"other~owner@example.com","repositories":{"amadan.net/paulca/first":{"api":"api-other","git":"git-other"}}}` |
| + if err := os.WriteFile(rig.path, []byte(replaced), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused(t, rig, "credential replaced behind a validator") |
| + }) |
| + t.Run("renamed", func(t *testing.T) { |
| + rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{"amadan.net/paulca/nearys-site"}) |
| + refused(t, rig, "created, then renamed on the hub") |
| + }) |
| + // Created a moment ago, not yet in the cached list: the write asks |
| + // the hub afresh, which lists it. |
| + rig := newMergeCredRig(t, perRepoOnly, nil, nil) |
| + rig.f.list(ctx) |
| + rig.set(func() { rig.lists["api-first"] = []string{repo} }) |
| + if err := rig.f.record(repo); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil || len(rig.requests()) != 1 { |
| + t.Fatalf("just created: %v %q", err, rig.requests()) |
| + } |
| +} |
| + |
| +// TestMergeStepCredentialIntegrated: through the runner's real forge (the |
| +// inspection needs the credential too), a missing credential file and an |
| +// unusable entry for the repository each end the step merge_credential at |
| +// once, naming the repository, with no merge request and no retries. |
| +func TestMergeStepCredentialIntegrated(t *testing.T) { |
| + old := mergeBackoff |
| + mergeBackoff = time.Millisecond |
| + t.Cleanup(func() { mergeBackoff = old }) |
| + for name, file := range map[string]string{ |
| + "missing file": "", |
| + "unusable entry": `{"agent":"equipo~owner@example.com","repositories":{"amadan.net/oficina/sample":{"git":"git-only"}}}`, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + e, _, r, _ := hubRig(t) |
| + rig := newMergeCredRig(t, file, []string{r.Repo}, []string{r.Repo}) |
| + fg, err := NewForges(rig.f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + e.Forge, e.Clones.Forge = fg, fg |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepFailed || rep.Reason != wire.ReasonMergeCredential || !rep.Termination { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if !strings.Contains(rep.LogTail, r.Repo) || strings.Contains(rep.LogTail, "outcome unknown") || strings.Contains(rep.LogTail, "git-only") { |
| + t.Fatalf("log tail %q", rep.LogTail) |
| + } |
| + if got := rig.requests(); len(got) != 0 { |
| + t.Fatalf("merge requests %q", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestCheckCredentialsWarnsOnLegacyFiles: at start a credential file with |
| +// no agent-wide entry gets one fixed warning that its per-repository |
| +// credential serves as the agent's; one with an agent-wide entry none. |
| +func TestCheckCredentialsWarnsOnLegacyFiles(t *testing.T) { |
| + var buf bytes.Buffer |
| + log := slog.New(slog.NewTextHandler(&buf, nil)) |
| + newMergeCredRig(t, perRepoOnly, nil, nil).f.checkCreated(context.Background(), log) |
| + if strings.Count(buf.String(), legacyAgentCredential) != 1 || strings.Contains(buf.String(), "api-first") { |
| + t.Fatalf("legacy warning %s", buf.String()) |
| + } |
| + buf.Reset() |
| + newMergeCredRig(t, `{"agent":"equipo~owner@example.com","api":"api-first","git":"git-first"}`, nil, nil).f.checkCreated(context.Background(), log) |
| + if buf.Len() != 0 { |
| + t.Fatalf("warned with an agent-wide entry: %s", buf.String()) |
| + } |
| +} |
| + |
| +// TestWriteScopeUnavailableRecovers: a hub list that fails (a 500, a 502) |
| +// is not a denial: the merge is refused as "hub |
| +// unavailable", the push says so rather than asking for a git password, |
| +// and both go through once the hub answers again. A list that answers |
| +// without the repository is the denial. |
| +func TestWriteScopeUnavailableRecovers(t *testing.T) { |
| + ctx := context.Background() |
| + repo := "amadan.net/paulca/nearys" |
| + rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo}) |
| + for _, fail := range []func(){ |
| + func() { rig.listStatus = http.StatusInternalServerError }, |
| + func() { rig.listStatus = http.StatusBadGateway }, |
| + } { |
| + rig.set(fail) |
| + _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq) |
| + var ns *forge.NotSentError |
| + if !errors.Is(err, workspace.ErrHubUnavailable) || errors.Is(err, forge.ErrMergeRefused) || !errors.As(err, &ns) { |
| + t.Fatalf("merge while the list fails: %v", err) |
| + } |
| + if _, err := rig.f.Remote(ctx, repo, Push); !errors.Is(err, workspace.ErrHubUnavailable) || errors.Is(err, workspace.ErrGitPassword) { |
| + t.Fatalf("push while the list fails: %v", err) |
| + } |
| + } |
| + rig.set(func() { rig.listStatus = 0 }) |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil { |
| + t.Fatalf("merge after recovery: %v", err) |
| + } |
| + if remote, err := rig.f.Remote(ctx, repo, Push); err != nil || remote.GitPassword != "git-first" { |
| + t.Fatalf("push after recovery: %v", err) |
| + } |
| + // Answered, without the repository: a denial. |
| + rig.set(func() { rig.lists["api-first"] = nil }) |
| + if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); !errors.Is(err, forge.ErrMergeRefused) || errors.Is(err, workspace.ErrHubUnavailable) { |
| + t.Fatalf("denied: %v", err) |
| + } |
| +} |
| + |
| +// TestMergeStepHubUnavailable: the hub cannot confirm write access. The |
| +// step tries again in place, and goes through once the hub answers; still |
| +// unavailable, it is deferred (the queue moves on), and past the wait it |
| +// ends amadan_unreachable, naming the repository. |
| +func TestMergeStepHubUnavailable(t *testing.T) { |
| + old := []time.Duration{mergeBackoff, mergeHubWait} |
| + mergeBackoff, mergeHubWait = time.Millisecond, 50*time.Millisecond |
| + t.Cleanup(func() { mergeBackoff, mergeHubWait = old[0], old[1] }) |
| + e, f, r, _ := hubRig(t) |
| + f.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) { |
| + if n == 1 { |
| + return forge.MergeResult{}, forge.NotSent(r.Repo, workspace.ErrHubUnavailable) |
| + } |
| + return merge() |
| + } |
| + if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 2 { |
| + t.Fatalf("recovered %+v (%d requests)", rep, f.requests) |
| + } |
| + e, f, r, _ = hubRig(t) |
| + f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) { |
| + return forge.MergeResult{}, forge.NotSent(r.Repo, workspace.ErrHubUnavailable) |
| + } |
| + if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != stepDeferred || f.requests != mergeAttempts { |
| + t.Fatalf("unavailable %+v (%d requests)", rep, f.requests) |
| + } |
| + e.O.State.deferStep(context.Background(), r, time.Millisecond) |
| + e.O.State.db.Exec("UPDATE steps SET deferred_since=? WHERE step_id=?", stamp(time.Now().Add(-time.Hour)), r.StepID) |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + if rep.State != wire.StepFailed || rep.Reason != wire.ReasonAmadanUnreachable || !strings.Contains(rep.LogTail, r.Repo) { |
| + t.Fatalf("after the wait %+v", rep) |
| + } |
| +} |
diff --git a/internal/runner/thin/mergestep.go b/internal/runner/thin/mergestep.go| index 4b39a078..7a2aabd8 100644 |
| --- a/internal/runner/thin/mergestep.go |
| +++ b/internal/runner/thin/mergestep.go |
| @@ -35,6 +35,9 @@ var ( |
| mergeBackoff = 3 * time.Second |
| mergeCIWait = 10 * time.Minute |
| mergeCIPoll = 15 * time.Second |
| + // mergeHubWait: how long a merge waits, deferred, for the hub to |
| + // confirm write access again (workspace.ErrHubUnavailable). |
| + mergeHubWait = 10 * time.Minute |
| ) |
| // MergeAgentHarness names the runner to the hub in the merge's agent block. |
| @@ -93,6 +96,11 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| return e.Forge.Merge(ctx, r.Repo, r.Branch, req) |
| }, |
| Confirm: confirmMerge} |
| + if p, ok := e.Forge.(mergePreflighter); ok { |
| + // No credential for the repository (the inspection needs it too): |
| + // refused here, before anything is read or sent. |
| + m.Preflight = func(ctx context.Context) error { return p.MergePreflight(ctx, r.Repo) } |
| + } |
| // Once the request may be with the hub, a cancel never stops the |
| // merge from being settled: the forge calls outlive the step's context |
| // (the instance refuses cancels while merging; shutdown keeps the |
| @@ -104,7 +112,11 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| cctx, cancel := context.WithTimeout(mctx, 3*time.Minute) |
| out, err = forge.MergeBranch(cctx, m) |
| cancel() |
| - if maskDetail != "" || notAuthorized || !errors.Is(err, forge.ErrMergeUncertain) || uncertain+1 >= mergeAttempts { |
| + // Tried again: an outcome the hub may have acted on, and a hub that |
| + // could not confirm write access. Any other refusal made here |
| + // before contacting it (forge.NotSentError) ends the step. |
| + again := errors.Is(err, forge.ErrMergeUncertain) || errors.Is(err, workspace.ErrHubUnavailable) |
| + if maskDetail != "" || notAuthorized || !again || uncertain+1 >= mergeAttempts { |
| break |
| } |
| time.Sleep(time.Duration(uncertain+1) * mergeBackoff) |
| @@ -128,6 +140,17 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| return rep |
| } |
| } |
| + if errors.Is(err, workspace.ErrHubUnavailable) { |
| + // Nothing was sent: held for later, releasing the queue, until the |
| + // hub answers or the wait is over. |
| + e.logDetail("merge", err) |
| + since := e.O.State.deferredSince(mctx, r) |
| + if since.IsZero() || time.Since(since) < mergeHubWait { |
| + rep.State = stepDeferred |
| + return rep |
| + } |
| + return fail(wire.ReasonAmadanUnreachable) |
| + } |
| switch { |
| case err == nil: |
| // Done: the merge watch for this candidate ends here, so only this |
| @@ -159,6 +182,11 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| return fail("merge_forbidden") |
| case errors.Is(err, forge.ErrMergeUnbornDefault): |
| return fail(wire.ReasonMergeUnbornDefault) |
| + case errors.Is(err, forge.ErrMergeNoCredential): |
| + // Refused on this runner before the hub was contacted: no |
| + // credential serves the repository. The log tail names it. |
| + e.logDetail("merge", err) |
| + return fail(wire.ReasonMergeCredential) |
| case errors.Is(err, forge.ErrMergeRefused): |
| return fail("policy_rejected") |
| } |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 3315e656..9a431dba 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -196,6 +196,9 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if fg == nil { |
| ff := NewFileForge(c.AmadanCredentialPath, c.StateDir, !o.NoCreate).(*fileForge) |
| ff.accessTargets = state.accessReadTargets |
| + // Each repository it created must have a credential its merges |
| + // can use; say which do not, before a merge finds out. |
| + ff.checkCreated(ctx, o.Logger) |
| fg, err = NewForges(ff) |
| if err != nil { |
| return err |
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go| index 301f2628..f4823cfa 100644 |
| --- a/internal/runner/workspace/workspace.go |
| +++ b/internal/runner/workspace/workspace.go |
| @@ -39,6 +39,11 @@ func (r Remote) Username() string { |
| var ErrGitPassword = errors.New("configure a repository git password (PAT) in EQUIPO_AMADAN_CREDENTIAL_PATH") |
| +// ErrHubUnavailable: the forge could not be asked whether the agent may |
| +// write to the repository now (no answer, an error status, an unreadable |
| +// list). Nothing was sent; unlike a denial, it is worth trying again. |
| +var ErrHubUnavailable = errors.New("the forge could not be reached to confirm write access; nothing was sent") |
| + |
| type ForgeRead interface { |
| Resolve(context.Context, string) (Remote, error) |
| } |
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go| index 9cf6ba56..6ea9b383 100644 |
| --- a/internal/wire/tasks.go |
| +++ b/internal/wire/tasks.go |
| @@ -1058,6 +1058,13 @@ var StepReasons = map[string]bool{ |
| // merge_not_authorized: the instance refused the merge request's |
| // confirmation (merge authority); nothing was sent to the hub. |
| "merge_not_authorized": true, |
| + // The runner has no usable forge credential for the repository and |
| + // refused the merge itself; nothing was sent to the hub |
| + // (ReasonMergeCredential). |
| + ReasonMergeCredential: true, |
| + // The hub could not confirm write access in time; nothing was sent |
| + // (ReasonAmadanUnreachable). |
| + ReasonAmadanUnreachable: true, |
| // Previews (protocol 9): the runner is too old (settled at its |
| // connection); the account's 20 temporary apps are taken; the task's |
| // preview expired and its name is still in the Trash; the config is |
| @@ -1138,3 +1145,15 @@ const MaxSimilarTasks = 3 |
| // the first merge (before amadan#139). Nothing merged; it waits on the |
| // platform, never retried on its own (protocol 8). |
| const ReasonMergeUnbornDefault = "merge_unborn_default" |
| + |
| +// ReasonMergeCredential: the runner refused a merge step before contacting |
| +// the hub because no forge credential it holds serves the repository. A |
| +// definite refusal: nothing was sent, and a later Merge may try again |
| +// once the credential is there. An older instance records it as unknown. |
| +const ReasonMergeCredential = "merge_credential" |
| + |
| +// ReasonAmadanUnreachable: the hub could not be asked whether the runner |
| +// may still write to the repository, for longer than the merge waits. |
| +// Nothing was sent; a later Merge may try again. An older instance records |
| +// it as unknown. |
| +const ReasonAmadanUnreachable = "amadan_unreachable" |
diff --git a/native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift b/native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift| index ee5b7779..f07d72ec 100644 |
| --- a/native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift |
| +++ b/native/apple/Sources/EquipoKit/Attachments/AttachmentsFixture.swift |
| @@ -15,7 +15,8 @@ public struct AttachmentsFixture: View { |
| #if os(iOS) |
| .navigationBarTitleDisplayMode(.inline) |
| #endif |
| - }.task { |
| + }.preferredColorScheme(ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_DARK"] == "1" ? .dark : .light) |
| + .task { |
| await session.refresh() |
| if ProcessInfo.processInfo.environment["EQUIPO_ATTACHMENTS_FIXTURE"] != "sent" { |
| await Self.seedDraft(session) |
diff --git a/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift b/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift| index 0fbdfae3..f45f17d7 100644 |
| --- a/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift |
| +++ b/native/apple/Sources/EquipoKit/Attachments/PhoneAttachmentPicker.swift |
| @@ -21,8 +21,12 @@ struct PhoneAttachmentPicker: View { |
| Button { files = true } label: { Label(EquipoStrings.text("native.attach.files"), systemImage: "folder") } |
| Button { paste() } label: { Label(EquipoStrings.text("native.attach.paste"), systemImage: "document.on.clipboard") } |
| } label: { |
| - Image(systemName: "plus").font(.system(size: 20)).frame(width: 44, height: 44) |
| + Image(systemName: "plus").font(.system(size: 16, weight: .semibold)) |
| + .foregroundStyle(Palette.secondary) |
| + .frame(width: 34, height: 34).background(Palette.surface2, in: Circle()) |
| + .frame(width: 44, height: 44).contentShape(Circle()) |
| } |
| + .buttonStyle(.plain) |
| .accessibilityLabel(EquipoStrings.text("chat.attach.add")) |
| .photosPicker(isPresented: $choosingPhotos, selection: $photos, maxSelectionCount: max(1, AttachmentLimits.maxCount - draft.items.count), matching: .images) |
| .fileImporter(isPresented: $files, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift| index 8db46c80..86f1a941 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/ConversationScreen.swift |
| @@ -31,6 +31,7 @@ public struct ConversationScreen: View { |
| .padding(.horizontal, 16).padding(.top, 12).padding(.bottom, 20) |
| .frame(maxWidth: 760).frame(maxWidth: .infinity) |
| } |
| + .accessibilityIdentifier("conversation-scroll") |
| .defaultScrollAnchor(.bottom) |
| .refreshable { await session.refresh() } |
| .onChange(of: items.count) { _, _ in |
| @@ -48,6 +49,7 @@ public struct ConversationScreen: View { |
| } |
| } |
| } |
| + .scrollDismissesKeyboard(.interactively) |
| } |
| func sendFromComposer(_ text: String) -> Task<Void, Never> { session.sendFromComposer(text) } |
| @@ -125,7 +127,7 @@ struct OutgoingMessage: View { |
| } |
| } |
| -/// The composer: a pill with a send button centred in it. |
| +/// The composer: attachments above, an add button beside the tinted field. |
| struct Composer: View { |
| let placeholder: String |
| var attachments: AttachmentDraft? = nil |
| @@ -134,35 +136,44 @@ struct Composer: View { |
| @FocusState private var focused: Bool |
| var body: some View { |
| let has = attachments?.canSend(text: text) ?? !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| - let shape = RoundedRectangle(cornerRadius: 22, style: .continuous) |
| + let shape = RoundedRectangle(cornerRadius: 10, style: .continuous) |
| VStack(spacing: 4) { |
| if let attachments { AttachmentDraftStrip(draft: attachments) } |
| - HStack(alignment: .bottom, spacing: 0) { |
| + HStack(alignment: .bottom, spacing: 8) { |
| #if os(iOS) |
| if let attachments { PhoneAttachmentPicker(draft: attachments) } |
| #endif |
| - TextField("", text: $text, prompt: Text(placeholder).foregroundColor(Palette.placeholder), axis: .vertical) |
| - .font(Typo.body).foregroundStyle(Palette.controlText).textFieldStyle(.plain) |
| - .lineLimit(1...6).focused($focused) |
| - .padding(.leading, 18).padding(.vertical, 11) |
| - .accessibilityLabel(placeholder) |
| - .onSubmit(send) |
| - Button(action: send) { |
| - Image(systemName: "arrow.up").font(.system(size: 16, weight: .bold)) |
| - .foregroundStyle(has ? Color.white : Palette.faint) |
| - .frame(width: 34, height: 34) |
| - .background(has ? Palette.primaryFill : Palette.surface2, in: Circle()) |
| - .frame(width: 44, height: 44).contentShape(Circle()) |
| + HStack(alignment: .bottom, spacing: 0) { |
| + TextField("", text: $text, prompt: Text(placeholder).foregroundColor(Palette.placeholder), axis: .vertical) |
| + .font(Typo.body).foregroundStyle(Palette.controlText).textFieldStyle(.plain) |
| + .lineLimit(1...6).focused($focused) |
| + .padding(.leading, 14).padding(.vertical, 11) |
| + .frame(minHeight: 44) |
| + .accessibilityLabel(placeholder) |
| + .onSubmit(send) |
| + Button(action: send) { |
| + Image(systemName: "arrow.up").font(.system(size: 16, weight: .bold)) |
| + .foregroundStyle(has ? Color.white : Palette.faint) |
| + .frame(width: 34, height: 34) |
| + .background(has ? Palette.primaryFill : Palette.surface2, in: Circle()) |
| + .frame(width: 44, height: 44).contentShape(Circle()) |
| + } |
| + .buttonStyle(.plain).disabled(!has) |
| + .accessibilityLabel(Text(String(localized: "composer.send", bundle: .module))) |
| + } |
| + .background(Palette.surface2, in: shape) |
| + .overlay(shape.strokeBorder(Palette.controlBorder, lineWidth: 1)) |
| + .background { |
| + if focused { |
| + RoundedRectangle(cornerRadius: 13, style: .continuous) |
| + .strokeBorder(Palette.accent, lineWidth: 2).padding(-3) |
| + } |
| + } |
| } |
| - .buttonStyle(.plain).disabled(!has) |
| - .accessibilityLabel(Text(String(localized: "composer.send", bundle: .module))) |
| - } |
| - .background(Palette.surface, in: shape) |
| - .overlay(shape.strokeBorder(focused ? Palette.accent : Palette.controlBorder, lineWidth: 1)) |
| } |
| .padding(.horizontal, 16).padding(.top, 10).padding(.bottom, 8) |
| .frame(maxWidth: 760).frame(maxWidth: .infinity) |
| - .background(.bar) |
| + .background(Palette.background) |
| } |
| private func send() { |
| let value = text.trimmingCharacters(in: .whitespacesAndNewlines) |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/NeedsScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/NeedsScreen.swift| index 10179d14..9bcbd520 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/NeedsScreen.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/NeedsScreen.swift |
| @@ -38,6 +38,7 @@ public struct NeedsScreen: View { |
| } |
| .padding(16).frame(maxWidth: 760).frame(maxWidth: .infinity) |
| } |
| + .scrollDismissesKeyboard(.interactively) |
| .refreshable { await session.refresh() } |
| .background(Palette.background) |
| } |
diff --git a/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift b/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift| index 20667346..fd584897 100644 |
| --- a/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift |
| +++ b/native/apple/Sources/EquipoKit/UI/Screens/TaskDetailScreen.swift |
| @@ -62,6 +62,7 @@ public struct TaskScreen: View { |
| actions: { Button(EquipoStrings.text("read.retry")) { Task { await model.load() } } } |
| } else { ProgressView().accessibilityLabel(EquipoStrings.text("work.details.task")) } |
| } |
| + .scrollDismissesKeyboard(.interactively) |
| .background(Palette.background) |
| .task(id: model.session.task(model.taskID)?.revision) { await model.load() } |
| .refreshable { await model.session.refresh(); await model.load() } |
diff --git a/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift b/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift| index e21ad59e..b79da011 100644 |
| --- a/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift |
| +++ b/native/apple/Sources/EquipoMac/MacAttachmentsFixture.swift |
| @@ -25,7 +25,7 @@ struct MacAttachmentsFixture: NSViewRepresentable { |
| try? await Task.sleep(for: .seconds(2)) |
| guard let path = ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_CAPTURE"], |
| let window = view.window, let content = window.contentView else { return } |
| - window.appearance = NSAppearance(named: .aqua) |
| + window.appearance = NSAppearance(named: ProcessInfo.processInfo.environment["EQUIPO_FIXTURE_DARK"] == "1" ? .darkAqua : .aqua) |
| try? await Task.sleep(for: .milliseconds(200)) |
| window.setContentSize(NSSize(width: 1000, height: 760)) |
| content.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
diff --git a/native/apple/Sources/EquipoMac/MacComposer.swift b/native/apple/Sources/EquipoMac/MacComposer.swift| index e707bb5a..31137e6f 100644 |
| --- a/native/apple/Sources/EquipoMac/MacComposer.swift |
| +++ b/native/apple/Sources/EquipoMac/MacComposer.swift |
| @@ -47,11 +47,11 @@ final class ComposerEditor: NSTextView { |
| final class ComposerPill: NSView { |
| override var isFlipped: Bool { true } |
| override func draw(_ dirtyRect: NSRect) { |
| - let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 22, yRadius: 22) |
| - NSColor.webFace.setFill(); path.fill() |
| + let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 10, yRadius: 10) |
| + NSColor.webSurface2.setFill(); path.fill() |
| let focused = window?.firstResponder is ComposerEditor && window?.isKeyWindow == true |
| (focused ? NSColor.webAccent : NSColor.webBorder).setStroke() |
| - path.lineWidth = 1; path.stroke() |
| + path.lineWidth = focused ? 2 : 1; path.stroke() |
| } |
| } |
| @@ -62,6 +62,7 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| override var isFlipped: Bool { true } |
| let editor = ComposerEditor() |
| let send = ActionButton("", style: .send, symbol: "arrow.up") {} |
| + let attachmentButton = ActionButton("", style: .attachment, symbol: "plus") {} |
| let pill = ComposerPill() |
| let textScroll = NSScrollView() |
| var onSend: ((String) -> Void)? |
| @@ -74,6 +75,7 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| func attach(_ draft: AttachmentDraft) { |
| self.draft = draft |
| + attachmentButton.isHidden = false |
| let host = NSHostingView(rootView: AnyView(AttachmentDraftStrip(draft: draft).fixedSize(horizontal: false, vertical: true) |
| .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { [weak self] height in |
| Task { @MainActor in |
| @@ -118,6 +120,11 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| init() { |
| super.init(frame: .zero) |
| addSubview(pill) |
| + addSubview(attachmentButton) |
| + attachmentButton.isHidden = true |
| + attachmentButton.toolTip = EquipoStrings.text("chat.attach.add") |
| + attachmentButton.setAccessibilityLabel(EquipoStrings.text("chat.attach.add")) |
| + attachmentButton.actionBlock = { [weak self] in self?.chooseFiles() } |
| pill.addSubview(textScroll); pill.addSubview(send) |
| textScroll.documentView = editor |
| textScroll.drawsBackground = false |
| @@ -155,6 +162,23 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| func textDidBeginEditing(_ notification: Notification) { pill.needsDisplay = true } |
| func textDidEndEditing(_ notification: Notification) { pill.needsDisplay = true } |
| + func chooseFiles() { |
| + guard let draft, let window else { return } |
| + let panel = Self.makeAttachmentPanel() |
| + panel.beginSheetModal(for: window) { response in |
| + guard response == .OK else { return } |
| + for url in panel.urls { Task { await draft.add(url: url) } } |
| + } |
| + } |
| + |
| + static func makeAttachmentPanel() -> NSOpenPanel { |
| + let panel = NSOpenPanel() |
| + panel.canChooseFiles = true |
| + panel.canChooseDirectories = false |
| + panel.allowsMultipleSelection = true |
| + return panel |
| + } |
| + |
| func setText(_ text: String) { editor.string = text; editor.needsDisplay = true; refresh() } |
| func submit() { |
| @@ -175,7 +199,8 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| super.layout() |
| guard !updating, bounds.width > 80 else { return } |
| updating = true |
| - let pillWidth = bounds.width |
| + let attachmentSpaceX: CGFloat = draft == nil ? 0 : 52 |
| + let pillWidth = bounds.width - attachmentSpaceX |
| let editorWidth = pillWidth - 44 |
| editor.frame.size.width = editorWidth |
| editor.textContainer?.containerSize = NSSize(width: max(1, editorWidth - 36), height: .greatestFiniteMagnitude) |
| @@ -183,9 +208,10 @@ final class MacComposer: NSView, NSTextViewDelegate { |
| let used = editor.layoutManager?.usedRect(for: editor.textContainer!).height ?? 24 |
| let contentHeight = max(24, ceil(used)) |
| let height = min(164, contentHeight + 20) |
| - attachmentHost?.frame = NSRect(x: 0, y: 0, width: pillWidth, height: attachmentHeight) |
| + attachmentHost?.frame = NSRect(x: 0, y: 0, width: bounds.width, height: attachmentHeight) |
| let attachmentSpace = attachmentHeight > 0 ? attachmentHeight + 8 : 0 |
| - pill.frame = NSRect(x: 0, y: attachmentSpace, width: pillWidth, height: height) |
| + attachmentButton.frame = NSRect(x: 0, y: attachmentSpace + height - 44, width: 44, height: 44) |
| + pill.frame = NSRect(x: attachmentSpaceX, y: attachmentSpace, width: pillWidth, height: height) |
| textScroll.frame = NSRect(x: 0, y: 10, width: editorWidth, height: height - 20) |
| editor.frame.size = NSSize(width: editorWidth, height: contentHeight) |
| textScroll.hasVerticalScroller = contentHeight > 144 |
diff --git a/native/apple/Sources/EquipoMac/MacStyle.swift b/native/apple/Sources/EquipoMac/MacStyle.swift| index f96e7b8e..eb7d3f31 100644 |
| --- a/native/apple/Sources/EquipoMac/MacStyle.swift |
| +++ b/native/apple/Sources/EquipoMac/MacStyle.swift |
| @@ -57,7 +57,7 @@ func symbolImage(_ name: String, size: CGFloat, weight: NSFont.Weight = .medium, |
| /// The web's controls, drawn in AppKit: rest, hover, pressed, focus, |
| /// disabled and busy. |
| final class ActionButton: NSButton { |
| - enum Style { case choice, primary, quiet, round, send, glyph, row, link, miniSend, aside } |
| + enum Style { case choice, primary, quiet, round, send, attachment, glyph, row, link, miniSend, aside } |
| var style: Style { didSet { needsDisplay = true } } |
| var symbol: String? { didSet { needsDisplay = true } } |
| var forced: ForcedState? { didSet { needsDisplay = true } } |
| @@ -111,7 +111,7 @@ final class ActionButton: NSButton { |
| switch style { |
| case .choice, .primary: return NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 6, yRadius: 6) |
| case .round: return NSBezierPath(ovalIn: bounds.insetBy(dx: 0.5, dy: 0.5)) |
| - case .send: return NSBezierPath(ovalIn: bounds.insetBy(dx: 6, dy: 6)) |
| + case .send, .attachment: return NSBezierPath(ovalIn: bounds.insetBy(dx: 6, dy: 6)) |
| case .miniSend: return NSBezierPath(ovalIn: bounds.insetBy(dx: 4, dy: 4)) |
| case .glyph: return NSBezierPath(ovalIn: bounds.insetBy(dx: 9, dy: 9)) |
| case .aside: return NSBezierPath(roundedRect: NSRect(x: (bounds.width - 28) / 2, y: (bounds.height - 28) / 2, width: 28, height: 28), xRadius: 6, yRadius: 6) |
| @@ -137,6 +137,8 @@ final class ActionButton: NSButton { |
| (pressed ? NSColor.webPrimaryEdge : hover ? NSColor.webPrimaryHover : NSColor.webPrimary).setFill(); path.fill() |
| if style == .primary { NSColor.webPrimaryEdge.setStroke(); path.lineWidth = 1; path.stroke() } |
| textColor = .white; symbolColor = .white |
| + case .attachment: |
| + (pressed ? NSColor.webFacePressed : hover ? NSColor.webFaceHover : NSColor.webSurface2).setFill(); path.fill() |
| case .miniSend: |
| if hasContent { (pressed ? NSColor.webPrimaryEdge : hover ? NSColor.webPrimaryHover : NSColor.webPrimary).setFill(); symbolColor = .white } |
| else { NSColor.webSurface2.setFill(); symbolColor = .webFaint } |
diff --git a/native/apple/Tests/EquipoKitTests/ComposerPolishTests.swift b/native/apple/Tests/EquipoKitTests/ComposerPolishTests.swift| new file mode 100644 |
| index 00000000..e105bd67 |
| --- /dev/null |
| +++ b/native/apple/Tests/EquipoKitTests/ComposerPolishTests.swift |
| @@ -0,0 +1,39 @@ |
| +import Foundation |
| +import Testing |
| +@testable import EquipoKit |
| +#if os(macOS) |
| +import AppKit |
| +@testable import EquipoMac |
| +#endif |
| + |
| +struct ComposerPolishTests { |
| + // This suite follows the existing source-contract tests; there is no |
| + // ViewInspector dependency. The simulator also exercises a real drag. |
| + @Test(arguments: ["ConversationScreen.swift", "TaskDetailScreen.swift", "NeedsScreen.swift"]) |
| + func scrollsContainingReplyFieldsDismissInteractively(_ file: String) throws { |
| + let sources = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Sources/EquipoKit/UI/Screens") |
| + let source = try String(contentsOf: sources.appendingPathComponent(file), encoding: .utf8) |
| + #expect(source.contains(".scrollDismissesKeyboard(.interactively)")) |
| + } |
| + |
| + #if os(macOS) |
| + @MainActor @Test func attachmentButtonIsOutsideFieldWithFullTarget() throws { |
| + let composer = MacComposer() |
| + composer.attach(AttachmentDraft(client: EquipoClient(transport: AttachmentServer(), token: "fixture"))) |
| + composer.frame = NSRect(x: 0, y: 0, width: 600, height: 80) |
| + composer.layoutSubtreeIfNeeded() |
| + let button = try #require(composer.subviews.compactMap { $0 as? NSButton }.first { $0.accessibilityLabel() == EquipoStrings.text("chat.attach.add") }) |
| + #expect(button.frame.width >= 44) |
| + #expect(button.frame.height >= 44) |
| + #expect(button.frame.maxX < composer.pill.frame.minX) |
| + #expect(composer.send.frame.width >= 44) |
| + #expect(composer.send.frame.height >= 44) |
| + } |
| + @MainActor @Test func macPanelAcceptsMultipleFilesOnly() { |
| + let panel = MacComposer.makeAttachmentPanel() |
| + #expect(panel.canChooseFiles) |
| + #expect(!panel.canChooseDirectories) |
| + #expect(panel.allowsMultipleSelection) |
| + } |
| + #endif |
| +} |
diff --git a/native/ios/UITests/AttachmentSourceUITests.swift b/native/ios/UITests/AttachmentSourceUITests.swift| index c7dbb08a..61b263bc 100644 |
| --- a/native/ios/UITests/AttachmentSourceUITests.swift |
| +++ b/native/ios/UITests/AttachmentSourceUITests.swift |
| @@ -7,13 +7,53 @@ final class AttachmentSourceUITests: XCTestCase { |
| app.launchEnvironment["EQUIPO_ATTACHMENTS_FIXTURE"] = "sent" |
| app.launch() |
| XCTAssertTrue(app.buttons["Attach"].waitForExistence(timeout: 10)) |
| + XCTAssertGreaterThanOrEqual(app.buttons["Attach"].frame.width, 44) |
| + XCTAssertGreaterThanOrEqual(app.buttons["Attach"].frame.height, 44) |
| app.buttons["Attach"].tap() |
| XCTAssertTrue(app.buttons["Photos"].waitForExistence(timeout: 5)) |
| + XCTAssertTrue(app.buttons["Files"].exists) |
| + XCTAssertTrue(app.buttons["Paste"].exists) |
| capture("iphone-add-menu") |
| app.buttons["Photos"].tap() |
| XCTAssertTrue(app.navigationBars["Photos"].waitForExistence(timeout: 10)) |
| capture("iphone-photos-picker") |
| } |
| + @MainActor func testComposerAppearances() throws { |
| + for mode in ["light", "dark"] { |
| + let app = XCUIApplication() |
| + app.launchEnvironment["EQUIPO_ATTACHMENTS_FIXTURE"] = "sent" |
| + app.launchEnvironment["EQUIPO_FIXTURE_DARK"] = mode == "dark" ? "1" : "0" |
| + app.launch() |
| + let field = app.textFields.firstMatch |
| + XCTAssertTrue(field.waitForExistence(timeout: 10)) |
| + capture("iphone-" + mode + "-keyboard-down") |
| + field.tap() |
| + field.typeText("Please fix the sign-in button.") |
| + XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) |
| + capture("iphone-" + mode + "-keyboard-up") |
| + app.terminate() |
| + } |
| + } |
| + @MainActor func testConversationDragDismissesKeyboard() throws { |
| + let app = XCUIApplication() |
| + app.launchEnvironment["EQUIPO_ATTACHMENTS_FIXTURE"] = "sent" |
| + app.launch() |
| + let field = app.textFields.firstMatch |
| + XCTAssertTrue(field.waitForExistence(timeout: 10)) |
| + field.tap() |
| + field.typeText("Please fix the sign-in button.") |
| + XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) |
| + let message = app.staticTexts["You said: Home’s sign-in button is cut off on my phone."] |
| + message.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) |
| + .press(forDuration: 0.01, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.99)), withVelocity: .fast, thenHoldForDuration: 0) |
| + XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5)) |
| + XCTAssertEqual(field.value as? String, "Please fix the sign-in button.") |
| + field.tap() |
| + XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) |
| + app.scrollViews["conversation-scroll"].coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) |
| + .press(forDuration: 0.01, thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.99)), withVelocity: .fast, thenHoldForDuration: 0) |
| + XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5)) |
| + } |
| @MainActor private func capture(_ name: String) { |
| let attachment = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) |
| attachment.name = name; attachment.lifetime = .keepAlways; add(attachment) |