Skip to content

Commit 01c2463

Browse files
robzolkosjeremy
authored andcommitted
Make connection guidance safe for CLI-first release
Reuse safe copy and lost-handover tests from Rob Zolkos’s CLI #900 at 7ba7e96 (2765820 through 7ba7e96), without its unconditional adds promises. Approval may add or replace until personal-agent adds are enabled, and shared agents still replace. Apply Jeremy Daer’s review: name the refused profile and both causes, warn overlap at guided project selection, keep live credential files, distinguish the newest lost connection from Disconnect all, and contract-test the skill stop fragment.
1 parent 786820a commit 01c2463

16 files changed

Lines changed: 177 additions & 60 deletions

‎README.md‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -271,9 +271,21 @@ basecamp connect setup -P my-agent --serve 12345 # who may give it work,
271271
basecamp connect -P my-agent # the watcher
272272
```
273273

274-
Connect each agent once. Every connection rotates the agent's secret, so a
275-
second one, from this CLI or from the HTTP handshake on Basecamp's instructions
276-
page, disconnects the first and asks you to approve again.
274+
An approval may add a connection or replace an existing one: read the approval
275+
page before proceeding. Personal agents can have several connections when
276+
Basecamp enables adding them. Otherwise, and always for shared agents, a new
277+
approval replaces the existing connection. This applies to both the CLI and
278+
Basecamp's HTTP handshake. Do not reconnect just to upgrade the CLI.
279+
280+
Each profile has its own projects, ledger, cursor, hold and local lock. When
281+
two connections serve the same project, a request both admit can be answered
282+
twice, so serve each project from one. Use a distinct `--device-name` for each
283+
profile on the same computer. Where Basecamp lists several connections, you
284+
can rename them and disconnect one without using Disconnect all. Reconnecting
285+
a profile on an add-capable server leaves its old connection live until you
286+
disconnect it; older credential files can remain live too. Do not delete them
287+
as part of setup. See the [upgrade and downgrade runbook](docs/agent-connections-rollout.md)
288+
for legacy state adoption and mixed-version precautions.
277289

278290
In Claude Code, the `/basecamp-connect` skill runs the watcher and hands each
279291
request to a subagent. It ships in this CLI's plugin from 0.12.0 on, and an

‎internal/auth/agent.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -525,8 +525,8 @@ func (m *Manager) agentMintRefusal(resp *http.Response, body []byte, mint *agent
525525
}
526526

527527
// ErrAgentCredentialRefused is the cause of a mint the token endpoint
528-
// refused for the credentials themselves: the agent was disconnected in
529-
// Basecamp, or connected on another computer, which replaced its secret.
528+
// refused for the credentials themselves: this connection may have been
529+
// disconnected in Basecamp or replaced by a newer approval.
530530
var ErrAgentCredentialRefused = errors.New("the agent's credential was refused")
531531

532532
// clientRefusalCodes are the RFC 6749 §5.2 codes that say THE CREDENTIALS

‎internal/auth/agent_connect.go‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -354,12 +354,11 @@ func (m *Manager) ConnectAgent(ctx context.Context, opts AgentConnectOptions) (*
354354
// adoptAgentGrantOrSayWhatWasLost stores the handed-over credential, and
355355
// says what a failure costs.
356356
//
357-
// The poll that answered burned the one-time code and MINTED THE AGENT'S
358-
// SECRET — a rotation, for an agent something was already connected to —
359-
// so what this holds is the only live copy and the server will not hand it
360-
// over twice. A failure here (a refused mint, a profile that cannot be
361-
// written, a Ctrl-C landing in the gap) therefore leaves the agent
362-
// connected to nothing. Retrying this command starts a new ceremony, which
357+
// The poll that answered burned the one-time code and minted this connection's
358+
// secret, possibly replacing an existing connection. The server will not hand
359+
// it over twice. A failure here (a refused mint, a profile that cannot be
360+
// written, a Ctrl-C landing in the gap) leaves this connection without a kept
361+
// credential; other connections may still work. Retrying this command starts a new ceremony, which
363362
// is the right remedy; polling the spent code again is not, and neither is
364363
// looking for the secret somewhere.
365364
func (m *Manager) adoptAgentGrantOrSayWhatWasLost(ctx context.Context, disc *discovery, conn *AgentConnection, log func(string), opts ClientCredentialsOptions) (*LoginResult, error) {
@@ -384,14 +383,14 @@ func reconnectRemedy(err error) error {
384383
return err
385384
}
386385
hinted := *e
387-
hinted.Hint = "Disconnect the agent in Basecamp and run the connect command again; the secret this connection was handed is gone."
386+
hinted.Hint = "Disconnect the newest connection in Basecamp (last in the list, where connections are listed), not Disconnect all, and run the connect command again; its secret is gone, so cleanup can wait."
388387
return &hinted
389388
}
390389

391390
// warnHandoverLost says what a failure after the handover costs, in the
392391
// one line an operator has to act on.
393392
func warnHandoverLost(log func(string)) {
394-
log("warning: the connection was approved and the agent's client secret was handed over once, but keeping it failed. Disconnect the agent in Basecamp and connect again.")
393+
log("warning: the connection was approved and its client secret was handed over once, but keeping it failed. Disconnect the newest connection in Basecamp (last in the list, where connections are listed), not Disconnect all, and connect again; its secret is gone, so cleanup can wait.")
395394
}
396395

397396
// spentHandoverError marks an error raised once the poll had already been

‎internal/auth/agent_connect_test.go‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ func TestConnectAgentRefusesATokenWiderThanTheApproval(t *testing.T) {
387387
require.Error(t, err)
388388
assert.Contains(t, err.Error(), "wider than the scope")
389389
assertNoAgentCredential(t, m)
390-
assert.Contains(t, cl.joined(), "Disconnect the agent in Basecamp and connect again")
390+
assertLostHandoverRemedy(t, cl.joined())
391391
assert.NotContains(t, cl.joined(), "minted", "no token from a refused mint is kept")
392392
}
393393

@@ -535,7 +535,7 @@ func TestConnectAgentRefusesAScopeItCannotStore(t *testing.T) {
535535
assertNoAgentCredential(t, m)
536536
// The poll was answered, so the code is burned and the secret minted
537537
// whatever this process made of the answer.
538-
assert.Contains(t, cl.joined(), "Disconnect the agent in Basecamp and connect again")
538+
assertLostHandoverRemedy(t, cl.joined())
539539
var e *output.Error
540540
assert.ErrorAs(t, err, &e, "the refusal keeps its own class through the spent-handover marker")
541541
}
@@ -728,11 +728,9 @@ func TestConnectAgentStoresNothingWhenTheProfileCannotBeCommitted(t *testing.T)
728728
require.Error(t, err)
729729
assert.Contains(t, err.Error(), "bound to another account")
730730
assertNoAgentCredential(t, m)
731-
// The poll burned the code and rotated the agent's secret, so this
732-
// failure leaves the agent connected to nothing. Saying "nothing was
733-
// stored" alone would send the operator looking for a credential that
734-
// no longer exists anywhere.
735-
assert.Contains(t, cl.joined(), "Disconnect the agent in Basecamp and connect again")
731+
// The poll burned the code and minted this connection's secret. Other
732+
// connections may survive, but this one has no retained credential.
733+
assertLostHandoverRemedy(t, cl.joined())
736734
}
737735

738736
// TestConnectAgentRefusesTheLaunchpadFallback: Launchpad has no agent
@@ -873,7 +871,7 @@ func TestConnectAgentRefusesAHandoverWiderThanTheRequest(t *testing.T) {
873871
assert.Contains(t, err.Error(), "read-only")
874872
assert.Empty(t, as.calls(&as.tokenForms), "a handover wider than the request is never minted with")
875873
assertNoAgentCredential(t, m)
876-
assert.Contains(t, cl.joined(), "Disconnect the agent in Basecamp and connect again")
874+
assertLostHandoverRemedy(t, cl.joined())
877875
}
878876

879877
// TestConnectAgentHonorsASlowRetryAfter: a Retry-After longer than a
@@ -911,7 +909,7 @@ func TestConnectAgentHandsBackARemedyTheOperatorCanFollow(t *testing.T) {
911909
require.Error(t, err)
912910
var e *output.Error
913911
require.ErrorAs(t, err, &e)
914-
assert.Contains(t, e.Hint, "Disconnect the agent in Basecamp")
912+
assertLostHandoverRemedy(t, e.Hint)
915913
assert.NotContains(t, e.Hint, "--with-client-credentials")
916914
}
917915

@@ -962,6 +960,14 @@ func TestConnectAgentReportsAnAccountLimitFromThePoll(t *testing.T) {
962960
// what it was going to do when it answered 200 — the code is burned and
963961
// the secret minted — so a body that never arrives costs exactly what a
964962
// refused mint costs and has to say the same thing.
963+
func assertLostHandoverRemedy(t *testing.T, text string) {
964+
t.Helper()
965+
assert.Contains(t, text, "Disconnect the newest connection in Basecamp")
966+
assert.Contains(t, text, "last in the list, where connections are listed")
967+
assert.Contains(t, text, "not Disconnect all")
968+
assert.Contains(t, text, "cleanup can wait")
969+
}
970+
965971
func TestConnectAgentTreatsAnInterruptedHandoverAsSpent(t *testing.T) {
966972
as := startConnectAS(t)
967973
as.pollHijack = true
@@ -970,7 +976,7 @@ func TestConnectAgentTreatsAnInterruptedHandoverAsSpent(t *testing.T) {
970976
cl := &collectLogger{}
971977
_, err := m.ConnectAgent(context.Background(), connectOptions(cl, newTestClock()))
972978
require.Error(t, err)
973-
assert.Contains(t, cl.joined(), "Disconnect the agent in Basecamp and connect again")
979+
assertLostHandoverRemedy(t, cl.joined())
974980
assertNoAgentCredential(t, m)
975981
assert.Empty(t, as.calls(&as.tokenForms), "nothing was minted with a credential that never arrived")
976982
}

‎internal/commands/auth_agent.go‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,17 @@ the agent's own OAuth client: this CLI mints an access token from it
5555
whenever it needs one, so there is no token to paste and none to renew by
5656
hand.
5757
58+
An approval may add a connection or replace an existing one; read the
59+
approval page before proceeding. Personal agents can keep several connections
60+
when Basecamp has enabled adding them. Otherwise, and always for shared
61+
agents, connecting replaces the existing connection, wherever it runs.
62+
63+
The device name defaults to this computer's name. Give each profile its own
64+
--device-name when several on this computer connect the same agent.
65+
Reconnecting a profile stores its new credential in place of the old one.
66+
Where approval adds, the old connection stays live until disconnected in
67+
Basecamp; other credential files are not removed or revoked by this CLI.
68+
5869
The account comes from the agent you approve — pass --account only to
5970
insist on one, and the connection is refused if the agent belongs to
6071
another.
@@ -83,8 +94,9 @@ for a person go to stderr, and the browser opens as it would without
8394
The link and the code are for the person approving at this computer:
8495
show them there, never anywhere else.
8596
86-
Disconnecting is done in Basecamp: disconnecting the agent there kills the
87-
client secret this holds. Drop the local copy with ` + "`basecamp auth logout -P <profile>`" + `.`,
97+
Disconnecting is done in Basecamp: disconnecting this connection there kills
98+
the secret this holds. Where several connections are listed, choose this
99+
connection, not Disconnect all. Drop the local copy with ` + "`basecamp auth logout -P <profile>`" + `.`,
88100
Annotations: map[string]string{AnnotationProfileMayCreate: "true"},
89101
Args: cobra.NoArgs,
90102
RunE: func(cmd *cobra.Command, args []string) error {
@@ -113,7 +125,7 @@ client secret this holds. Drop the local copy with ` + "`basecamp auth logout -P
113125
},
114126
}
115127

116-
cmd.Flags().StringVar(&deviceName, "device-name", "", "Name this computer on the approval page (default: this host's name)")
128+
cmd.Flags().StringVar(&deviceName, "device-name", "", "Name this device/connection (default: this host's name; use a distinct name for each profile)")
117129
cmd.Flags().StringVar(&softwareName, "software-name", "", "Name the software this CLI runs inside, shown as \"Connected to\"")
118130
cmd.Flags().StringVar(&scope, "scope", "", "OAuth scope to ask for: 'read' or 'full' (default full; the approval page can downgrade it)")
119131
cmd.Flags().BoolVar(&noBrowser, "no-browser", false, "Print the link instead of opening a browser")

‎internal/commands/connect.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,15 @@ line: events seen, admission's verdicts, and a "type":"request" line for each
5959
trusted request, which is the one to act on. Logs go to stderr. SIGINT and
6060
SIGTERM exit 130 and 143. A request made before the connector started is not
6161
picked up. --shadow admits and logs in an isolated state directory and hands
62-
off nothing. --hold sets a durable hold: intake and admission run, nothing is
63-
handed off, and earlier records wait for review, until basecamp connect
64-
release. Linux and macOS only.
62+
off nothing. --hold sets this profile's durable hold: intake and admission run,
63+
nothing is handed off, and earlier records wait for review, until basecamp
64+
connect release for this profile. Linux and macOS only.
65+
66+
One connector runs per profile in this state directory. Personal agents can
67+
run several connections when Basecamp enables adding them; otherwise, and for
68+
shared agents, a new approval replaces the existing connection. Each profile
69+
serves its own projects and has its own hold. When two connections serve the
70+
same project, a request both admit can be answered twice.
6571
6672
basecamp connect status what it heard and holds
6773
basecamp connect doctor what it needs to run
@@ -391,6 +397,10 @@ does not serve is handed off, and nobody is told. --watch-completions <project-i
391397
makes the agent hear every trusted completion in that project without being
392398
assigned.
393399
400+
The list is this profile's own. When two connections of one agent serve the
401+
same project, a request both admit there can be answered twice, so serve
402+
each project from one of them.
403+
394404
Pings. A Ping is in no project, so it is never served and needs no setup.
395405
An operator (the operator, or a person passed with --allow) gives the agent
396406
work by Ping in every trust mode: every line of theirs in a direct Ping with
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package commands
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"regexp"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
)
12+
13+
// The skill is published on merge, before any server activation. Its actual
14+
// stop fragment must match runtime output, not a second frozen copy of it.
15+
func TestTheSkillDocumentsTheDisconnectLineItGets(t *testing.T) {
16+
skill, err := os.ReadFile(filepath.Join("..", "..", "skills", "basecamp-connect", "SKILL.md"))
17+
require.NoError(t, err)
18+
fragment := regexp.MustCompile(`- \*\*"([^"]*disconnected[^"]*)"\*\*: run`).FindSubmatch(skill)
19+
require.Len(t, fragment, 2)
20+
message := errAgentDisconnected("Synthetic Agent", "laptop").Message
21+
assert.Contains(t, message, string(fragment[1]))
22+
assert.Contains(t, message, `Profile "laptop"`)
23+
assert.Contains(t, message, "or replaced")
24+
}
25+
26+
func TestConnectionHelpIsSafeBeforeServerAddsAndForSharedAgents(t *testing.T) {
27+
help := newAuthAgentConnectCmd().Long
28+
assert.Contains(t, help, "approval may add a connection or replace")
29+
assert.Contains(t, help, "always for shared")
30+
assert.Contains(t, help, "when Basecamp has enabled adding")
31+
assert.NotContains(t, help, "Each approval adds")
32+
assert.Contains(t, help, "old connection stays live")
33+
assert.Contains(t, help, "not removed or revoked")
34+
help = NewConnectCmd().Long
35+
assert.Contains(t, help, "otherwise, and for")
36+
assert.Contains(t, help, "shared agents")
37+
assert.Contains(t, help, "own hold")
38+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
//go:build unix
2+
3+
package commands
4+
5+
import (
6+
"bytes"
7+
"testing"
8+
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
12+
"github.com/basecamp/basecamp-cli/internal/connector/setup"
13+
)
14+
15+
func TestGuidedProjectSelectionWarnsBeforeTheAllProjectsQuestion(t *testing.T) {
16+
var out bytes.Buffer
17+
asked := false
18+
p := &scriptedPrompter{confirms: []bool{true}, onConfirm: func(question string) {
19+
asked = true
20+
assert.Contains(t, question, "Work in all 2")
21+
// This fails if the warning is only in --help or after confirmation.
22+
assert.Contains(t, out.String(), "a request both admit can be answered twice")
23+
}}
24+
guided(t, p)
25+
chosen, err := chooseGuidedProjects(&out, guidedAgent{Profile: "agent-b", Me: setup.Person{Name: "Synthetic Agent"}, Listed: true,
26+
Projects: []guidedProject{{ID: setupProject, Name: "A"}, {ID: setupProject2, Name: "B"}}})
27+
require.NoError(t, err)
28+
assert.True(t, asked)
29+
assert.Len(t, chosen, 2)
30+
}

‎internal/commands/connect_run.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -456,8 +456,8 @@ func runConnect(cmd *cobra.Command, f *connectRunFlags) error {
456456

457457
// connectorStoppedBy is what the connector exits with when one of its parts
458458
// stopped it with err, and the connection state status keeps for that. The
459-
// stop people meet — the agent was disconnected in Basecamp, or connected on
460-
// another computer — is said in their words; anything else is returned as it
459+
// stop people meet — the connection was disconnected in Basecamp, or replaced
460+
// by a newer approval — is said in their words; anything else is returned as it
461461
// is. The feed's authorization_failed counts forbidden answers too, so it is
462462
// called a disconnect only when refused, asking Basecamp, confirms it; a
463463
// refused token renewal is already Basecamp's answer.
@@ -562,9 +562,9 @@ func feedAuthorizationFailed(err error) bool {
562562
func errAgentDisconnected(agent, profile string) *output.Error {
563563
who := richtext.SanitizeSingleLine(agent)
564564
if who == "" {
565-
who = "Your agent"
565+
who = "your agent"
566566
}
567-
e := output.ErrAuth(who + " was disconnected in Basecamp, or connected on another computer")
567+
e := output.ErrAuth(fmt.Sprintf("Profile %q's connection to %s was disconnected in Basecamp, or replaced by a newer connection", richtext.SanitizeSingleLine(profile), who))
568568
e.Hint = "Reconnect it: basecamp connect setup -P " + richtext.ShellQuote(profile)
569569
return e
570570
}
@@ -582,7 +582,9 @@ func connectSinceOverride(since int64) (int64, error) {
582582
return since, nil
583583
}
584584

585-
// connectConsumerNamespace names a run's checkpoint lineage. A shadow run
585+
// connectConsumerNamespace names a run's checkpoint lineage. It stays keyed
586+
// by agent so adopted checkpoints retain their keys; each profile's separate
587+
// ledger isolates that lineage. The server never sees this namespace. A shadow run
586588
// gets its own: it has its own state directory, ledger, lock and checkpoint
587589
// already (connectStateDir), and intake's contract is that two connectors in
588590
// one account never share a lineage (connector.Options.ConsumerNamespace) —

0 commit comments

Comments
 (0)