From 5072d52070664d0ea6ccd43204674b0dc610d5c2 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:12:57 -0500 Subject: [PATCH 01/16] relay: --storage off keeps the device list and refuses chat uploads A relay run with --store answers every identity's directory and takes its chats' sealed content. An organization that already keeps its people's hosted chats has no use for a second copy, and a relay that says nothing about storage makes every client try an upload, be refused and try again. --storage off serves the directory as before, answers GET /v1/store/stats with "storage": "off" (the word the hosted relay uses, so clients keep their chats local and stop asking), refuses POST /v1/store/frames with 403 storage_off and accepts the handoff a rotation sends. The default is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- internal/blobstore/storage_off.go | 38 +++++++++++++++++ internal/blobstore/storage_off_test.go | 52 +++++++++++++++++++++++ internal/relayserve/main.go | 11 +++-- internal/relayserve/service.go | 10 ++++- internal/relayserve/storage_off_test.go | 55 +++++++++++++++++++++++++ 5 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 internal/blobstore/storage_off.go create mode 100644 internal/blobstore/storage_off_test.go create mode 100644 internal/relayserve/storage_off_test.go diff --git a/internal/blobstore/storage_off.go b/internal/blobstore/storage_off.go new file mode 100644 index 0000000000..8c50d94213 --- /dev/null +++ b/internal/blobstore/storage_off.go @@ -0,0 +1,38 @@ +package blobstore + +import "net/http" + +// pathHandoff is where a computer that is rotating its identity asks the relay to carry the storage permission over to the new +// one (directory.HTTP.HandoffStorage). The hosted relay answers it; this file is why a relay with its storage off does too. +const pathHandoff = "/v1/store/handoff" + +// StorageOff makes the store wire answer the way the hosted relay does for an account it has not approved to keep chats: it says +// its storage is off and refuses every upload with `storage_off`, and nothing else about it changes. A computer that reads that +// keeps its chats where they are made, says so once, and stops asking, which is what it already does on the hosted relay. +// +// WHY A RELAY WOULD WANT THIS. An organization's relay (deploy/org) exists so its members' computers can pair, see each other and +// open each other's chats live. The organization's hosted chats are already kept by the organization's own server, so a second, +// sealed copy of anyone's chats on the relay is storage nobody asked for. +// +// IT IS ONE LAYER OVER THE REAL HANDLER, NOT A SECOND STORE. Reads (has, locate, get) still reach the store, which is empty, so a +// computer that asks for something is told there is none. Without this layer a native relay's stats omit `storage`, a computer +// reads that as "on", uploads, is refused by a proxy in front, marks the relay off, and refreshes back to "on" a minute later. +// +// THE STATS AND THE HANDOFF ARE ANSWERED WITHOUT CHECKING A SIGNATURE, because they carry nothing of anyone's: the first is a fixed +// answer and the second changes nothing, since there is no permission here to hand over. +func StorageOff(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == pathStats: + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(mustJSON(statsBody{Storage: "off"})) + case r.Method == http.MethodPost && r.URL.Path == pathFrames: + send(w, http.StatusForbidden, "storage_off", 0) + case r.Method == http.MethodPost && r.URL.Path == pathHandoff: + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte("{}")) + default: + next.ServeHTTP(w, r) + } + }) +} diff --git a/internal/blobstore/storage_off_test.go b/internal/blobstore/storage_off_test.go new file mode 100644 index 0000000000..807dcdee47 --- /dev/null +++ b/internal/blobstore/storage_off_test.go @@ -0,0 +1,52 @@ +package blobstore + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/wireauth" +) + +// StorageOff is the store wire of a relay that keeps the device list and no chats. What a computer is told is what the hosted +// relay tells an account it has not approved, because the computer already knows what to do with that. +func TestStorageOffAnswersAsTheHostedRelayDoes(t *testing.T) { + store := NewMemory() + real := Handler(func(*http.Request, []byte) (string, string, error) { return "id", "device", nil }, func(string) (Store, error) { return store, nil }) + srv := httptest.NewServer(StorageOff(real)) + defer srv.Close() + c := NewHTTP(srv.URL, func(*http.Request, []byte) {}, srv.Client()) + + counts, err := c.Stats(t.Context()) + if err != nil || counts.Storage != "off" { + t.Fatalf("a relay with its storage off must say so: %+v %v", counts, err) + } + if _, err := c.PutFrame(t.Context(), []byte("a frame")); !errors.Is(err, wireauth.ErrStorageOff) { + t.Fatalf("an upload must be refused as storage off, not as anything else: %v", err) + } + if errors.Is(wireauth.ErrStorageOff, ErrFull) { + t.Fatal("storage off is not the relay being full") + } + if ops := store.Log(); len(ops) != 0 { + t.Fatalf("nothing may reach the store: %v", ops) + } + // Reads still reach the real handler, which is empty: nothing is stored, so nothing is held. + have, err := c.Has(t.Context(), []string{strings.Repeat("a", 64)}) + if err != nil || len(have) != 1 || have[0] { + t.Fatalf("a read must reach the store and find it empty: %v %v", have, err) + } +} + +// The identity rotation of a computer asks the relay to carry its storage permission to the successor. A relay with its storage +// off holds none, so it says yes and changes nothing, and `codeaf identity rotate` is not stopped by a relay that reports `off`. +func TestStorageOffCarriesNothingOverForARotation(t *testing.T) { + real := Handler(func(*http.Request, []byte) (string, string, error) { return "id", "device", nil }, func(string) (Store, error) { return NewMemory(), nil }) + h := StorageOff(real) + r := httptest.NewRecorder() + h.ServeHTTP(r, httptest.NewRequest(http.MethodPost, pathHandoff, strings.NewReader(`{}`))) + if r.Code != http.StatusOK { + t.Fatalf("the handoff of a relay with nothing to hand over: %d %s", r.Code, r.Body.String()) + } +} diff --git a/internal/relayserve/main.go b/internal/relayserve/main.go index 9ec6bcdede..454449a8e7 100644 --- a/internal/relayserve/main.go +++ b/internal/relayserve/main.go @@ -17,7 +17,7 @@ import ( // Main is the relay program, shared by cmd/relay and `codeaf relay`: // -// relay --listen :8787 [--store /var/lib/codeaf] [--quiet] [--status=false] [--trust-proxy] +// relay --listen :8787 [--store /var/lib/codeaf [--storage off]] [--quiet] [--status=false] [--trust-proxy] // // It runs until SIGINT or SIGTERM and then lets in-flight requests finish. // In front of it in production goes whatever already terminates TLS; pass --trust-proxy @@ -27,6 +27,7 @@ func Main(args []string) error { flags.Usage = func() { RelayHelp(flags.Output()) } listen := flags.String("listen", ":8787", "address to listen on") store := flags.String("store", "", "directory that keeps the directory and blob stores; empty runs the blind pipe only") + storage := flags.String("storage", "on", "on keeps the chats' sealed content under --store; off keeps only the device list and refuses uploads, as the hosted relay does for an account it has not approved") quiet := flags.Bool("quiet", false, "do not log arrivals, departures and requests") status := flags.Bool("status", true, "answer GET /status with what is connected right now") trust := flags.Bool("trust-proxy", false, "count the first X-Forwarded-For address for registration, dial and pairing limits; required behind a proxy that sets it") @@ -39,7 +40,10 @@ func Main(args []string) error { } return err } - cfg := Config{Store: *store, Status: *status, TrustProxy: *trust, SweepEvery: *sweepEvery, MaxWatchers: *watchers} + if *storage != "on" && *storage != "off" { + return fmt.Errorf("--storage is on or off, not %q", *storage) + } + cfg := Config{Store: *store, Status: *status, TrustProxy: *trust, SweepEvery: *sweepEvery, MaxWatchers: *watchers, StorageOff: *storage == "off"} if *minGrace > 0 { cfg.Grace = directory.DefaultGraceBounds cfg.Grace.Min = *minGrace @@ -72,12 +76,13 @@ func Main(args []string) error { // RelayHelp hides test-only switches while keeping the ordinary subcommand shape. func RelayHelp(out io.Writer) { - fmt.Fprintln(out, `usage: codeaf relay [--listen host:port] [--store path] + fmt.Fprintln(out, `usage: codeaf relay [--listen host:port] [--store path] [--storage on|off] Run your own relay. --listen host:port address to listen on (default :8787) --store path keep your devices and saved chats here; empty connects machines only + --storage on|off off keeps the device list and refuses chat uploads (default on) --quiet do not log arrivals, departures or requests --status=false turn off the service status endpoint --trust-proxy use the caller address supplied by a trusted proxy`) diff --git a/internal/relayserve/service.go b/internal/relayserve/service.go index 046e4b8358..d31cbb450d 100644 --- a/internal/relayserve/service.go +++ b/internal/relayserve/service.go @@ -53,6 +53,10 @@ type Config struct { // After is the timers presence runs on; nil is the wall clock's. A relay a // test drives on a fake clock hands timers that move with it. After directory.After + + // StorageOff keeps the directory and refuses every chat upload, the way the hosted relay does for an account it has not + // approved to store chats (blobstore.StorageOff). It changes nothing without a Store. + StorageOff bool } // Service is a built relay: one handler and the files it holds open. @@ -144,7 +148,11 @@ func New(cfg Config) *Service { mux.Handle("/v1/dir/", dirs) mux.Handle("/v1/identity/", dirs) mux.Handle(directory.LinkPath+"/", logged(cfg.Logf, directory.LinkHandler(links, peerOf(cfg)))) - mux.Handle("/v1/store/", logged(cfg.Logf, blobstore.HandlerAt(now, auth, svc.ns.blobs))) + blobs := blobstore.HandlerAt(now, auth, svc.ns.blobs) + if cfg.StorageOff { + blobs = blobstore.StorageOff(blobs) + } + mux.Handle("/v1/store/", logged(cfg.Logf, blobs)) svc.stop = make(chan struct{}) svc.swept.Add(1) go svc.sweepLoop(sweepInterval(cfg.SweepEvery), cfg.Logf) diff --git a/internal/relayserve/storage_off_test.go b/internal/relayserve/storage_off_test.go new file mode 100644 index 0000000000..e11c84fbd6 --- /dev/null +++ b/internal/relayserve/storage_off_test.go @@ -0,0 +1,55 @@ +package relayserve + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func relayAnswer(t *testing.T, srv *httptest.Server, method, path string) (int, string) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), method, srv.URL+path, strings.NewReader("x")) + if err != nil { + t.Fatal(err) + } + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + return res.StatusCode, string(body) +} + +// A relay run with --storage off keeps the device list (the directory is mounted, so a computer's roster and its chats' places +// work) and keeps no chat: it says its storage is off and refuses every upload. Without the flag nothing about the store wire +// changes, so an unsigned request is still turned away by the signature check and not answered by this layer. +func TestStorageOffKeepsTheDirectoryAndRefusesUploads(t *testing.T) { + off := httptest.NewServer(New(Config{Store: t.TempDir(), StorageOff: true}).Handler) + defer off.Close() + if code, body := relayAnswer(t, off, http.MethodGet, "/v1/store/stats"); code != http.StatusOK || !strings.Contains(body, `"storage":"off"`) { + t.Fatalf("stats of a relay with its storage off: %d %s", code, body) + } + if code, body := relayAnswer(t, off, http.MethodPost, "/v1/store/frames"); code != http.StatusForbidden || !strings.Contains(body, "storage_off") { + t.Fatalf("an upload to a relay with its storage off: %d %s", code, body) + } + if code, _ := relayAnswer(t, off, http.MethodGet, "/v1/dir/list"); code == http.StatusNotFound { + t.Fatal("the device list must still be served: the directory was not mounted") + } + + on := httptest.NewServer(New(Config{Store: t.TempDir()}).Handler) + defer on.Close() + if code, body := relayAnswer(t, on, http.MethodGet, "/v1/store/stats"); code != http.StatusUnauthorized { + t.Fatalf("with storage on the store wire is the real one and wants a signature: %d %s", code, body) + } +} + +// --storage means on or off, and a typo stops the relay with a sentence instead of starting it with the opposite setting. +func TestStorageFlagIsOnOrOff(t *testing.T) { + err := Main([]string{"--storage", "maybe"}) + if err == nil || !strings.Contains(err.Error(), "on or off") { + t.Fatalf("a typo in --storage: %v", err) + } +} From 02aa19e882a2fe39c53ebb9e6b864c4c53055df5 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:13:25 -0500 Subject: [PATCH 02/16] org: the organization server can name the relay its people use An organization that runs its own relay needs a way to tell its members where it is without every one of them setting an environment variable. The host config takes relay_url, the server checks it at start (a web address, http or https, with no sign-in, query or fragment in it, and an error that never echoes the address back), and GET /v1/org carries it as "relay" for a signed-in person only. A stranger is told nothing; /v1/about stays as public as it was; a token rotation keeps the row. A client decides for itself whether it will use the address (see the pair --org change). Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/factory_command.go | 2 +- cmd/codeaf/factory_config.go | 27 ++++++++++ cmd/codeaf/factory_relay_url_test.go | 65 ++++++++++++++++++++++++ docs/design/app-v3/PROTOCOL.md | 2 +- internal/appwire/factory_org_setup.go | 2 + internal/factory/api/org_setup.go | 3 ++ internal/factory/serve/org_relay_test.go | 45 ++++++++++++++++ internal/factory/serve/org_setup.go | 2 +- internal/factory/serve/serve.go | 3 ++ 9 files changed, 148 insertions(+), 3 deletions(-) create mode 100644 cmd/codeaf/factory_relay_url_test.go create mode 100644 internal/factory/serve/org_relay_test.go diff --git a/cmd/codeaf/factory_command.go b/cmd/codeaf/factory_command.go index c447f3e3a5..fa43bb8c28 100644 --- a/cmd/codeaf/factory_command.go +++ b/cmd/codeaf/factory_command.go @@ -322,7 +322,7 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam // A drop deletes the job's local branch and folder on this machine, // and the conversations and crew kept on this machine, never anything // on GitHub, so the team server does it too. - Folders: newFactoryJobFolders(st), DeleteChats: factoryDeleteJobChats(config.ProfileDir(), st), Mode: mode, OperatorLogin: host.OperatorLogin, TrustedProxies: secure.proxies, Hosted: hosted, HSTSSubdomains: host.HSTSIncludeSubdomains, Name: host.Name, GitHubClientID: host.GitHubClientID, Team: host.Team, Address: public, AccessToken: token, TokensPath: tokensPath, Store: st, Root: st.Root(), Record: history, + Folders: newFactoryJobFolders(st), DeleteChats: factoryDeleteJobChats(config.ProfileDir(), st), Mode: mode, OperatorLogin: host.OperatorLogin, TrustedProxies: secure.proxies, Hosted: hosted, HSTSSubdomains: host.HSTSIncludeSubdomains, Name: host.Name, GitHubClientID: host.GitHubClientID, RelayURL: host.RelayURL, Team: host.Team, Address: public, AccessToken: token, TokensPath: tokensPath, Store: st, Root: st.Root(), Record: history, ServedBy: servedBy, PollingEvery: poll, GitHubLimit: host.githubLimit.resets, Scout: factoryScoutLook(st, config.Load), Read: factoryClickRead(st, config.Load), // The organization's workstream agents, when the operator runs them diff --git a/cmd/codeaf/factory_config.go b/cmd/codeaf/factory_config.go index 8a4d94380c..5702816c88 100644 --- a/cmd/codeaf/factory_config.go +++ b/cmd/codeaf/factory_config.go @@ -4,8 +4,10 @@ import ( "bytes" "crypto/rand" "encoding/hex" + "errors" "fmt" "io" + "net/url" "os" "path/filepath" "strings" @@ -26,6 +28,9 @@ type factoryHostConfig struct { Repos []string `yaml:"repos"` GitHubClientID string `yaml:"github_client_id,omitempty"` Team []string `yaml:"team,omitempty"` + // RelayURL is the address of the relay the organization runs for its members' computers, with its scheme + // (https://relay.example.com). The server tells it to every signed-in person (GET /v1/org) and uses it for nothing else. + RelayURL string `yaml:"relay_url,omitempty"` // TLS is auto, files or off; empty is auto off loopback and off on it // ([resolveFactoryTLS] decides once the listen address is final). TLS string `yaml:"tls,omitempty"` @@ -68,6 +73,9 @@ func (cfg factoryHostConfig) MarshalYAML() (any, error) { if cfg.GitHubClientID != "" { doc["github_client_id"] = cfg.GitHubClientID } + if cfg.RelayURL != "" { + doc["relay_url"] = cfg.RelayURL + } if len(cfg.Team) > 0 { doc["team"] = cfg.Team } @@ -190,9 +198,28 @@ func readFactoryHostConfig(path string) (factoryHostConfig, error) { if err := checkFactoryTLSConfig(cfg); err != nil { return cfg, fmt.Errorf("factory config %s: %w", path, err) } + if cfg.RelayURL, err = checkFactoryRelayURL(cfg.RelayURL); err != nil { + return cfg, fmt.Errorf("factory config %s: %w", path, err) + } return cfg, nil } +// checkFactoryRelayURL is the relay address an organization advertises: an http or https address with a host, no sign-in in it, +// and nothing after the path. It is handed to every member, so an address with a password in it is refused rather than passed on. +// Empty is no relay, and the trailing slash is dropped because clients join paths themselves. +func checkFactoryRelayURL(raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", nil + } + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + // The address is not repeated: one with a password in it must not reach a log. + return "", errors.New("relay_url must be a web address such as https://relay.example.com, with no sign-in or query in it") + } + return strings.TrimRight(u.String(), "/"), nil +} + // factoryHandleOK is a GitHub login after NormalizeHandle: letters, digits // and hyphens, at most 39 characters. func factoryHandleOK(handle string) bool { diff --git a/cmd/codeaf/factory_relay_url_test.go b/cmd/codeaf/factory_relay_url_test.go new file mode 100644 index 0000000000..2b22050b8e --- /dev/null +++ b/cmd/codeaf/factory_relay_url_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "path/filepath" + "strings" + "testing" +) + +// THE RELAY AN ORGANIZATION ADVERTISES IS AN ADDRESS EVERY MEMBER IS HANDED, so the config takes a web address and nothing that +// would be passed on with it: no sign-in in the address, no query, and a scheme a relay speaks. +func TestFactoryConfigAcceptsARelayAddressAndRefusesWhatCannotBeHandedOn(t *testing.T) { + for _, tc := range []struct { + in, want, err string + }{ + {"", "", ""}, + {" https://relay.example.com/ ", "https://relay.example.com", ""}, + {"http://127.0.0.1:8788", "http://127.0.0.1:8788", ""}, + {"https://example.com/fabric", "https://example.com/fabric", ""}, + {"relay.example.com", "", "relay_url must be a web address"}, + {"ftp://relay.example.com", "", "relay_url must be a web address"}, + {"https://user:secret@relay.example.com", "", "no sign-in or query"}, + {"https://relay.example.com/?token=x", "", "no sign-in or query"}, + {"https://relay.example.com/#x", "", "no sign-in or query"}, + {"https://", "", "relay_url must be a web address"}, + } { + got, err := checkFactoryRelayURL(tc.in) + if tc.err != "" { + if err == nil || !strings.Contains(err.Error(), tc.err) { + t.Errorf("%q: want an error naming %q, got %q, %v", tc.in, tc.err, got, err) + } + if err != nil && strings.Contains(tc.in, "secret") && strings.Contains(err.Error(), "secret") { + t.Errorf("%q: the refusal repeats the sign-in it was given: %v", tc.in, err) + } + continue + } + if err != nil || got != tc.want { + t.Errorf("%q: want %q, got %q, %v", tc.in, tc.want, got, err) + } + } +} + +// relay_url lives in the host config, which a token rotation rewrites from the struct: the address must survive that, or the +// next rotation would quietly stop telling members where their relay is. +func TestFactoryConfigKeepsTheRelayAddressThroughATokenRotation(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + path := filepath.Join(t.TempDir(), "config.yaml") + if err := writeFactoryPrivate(path, []byte("mode: team\nlisten: 127.0.0.1:9876\nrelay_url: https://relay.example.com/\n")); err != nil { + t.Fatal(err) + } + for _, rotate := range []bool{false, true} { + cfg, err := factoryHostConfigAt(path, rotate) + if err != nil || cfg.RelayURL != "https://relay.example.com" { + t.Fatalf("rotate=%v: config = %+v %v", rotate, cfg, err) + } + } + if !strings.Contains(string(readFactoryTestFile(t, path)), "relay_url: https://relay.example.com") { + t.Fatalf("the rotation dropped the address:\n%s", readFactoryTestFile(t, path)) + } + if err := writeFactoryPrivate(path, []byte("relay_url: https://user:pw@relay.example.com\n")); err != nil { + t.Fatal(err) + } + if _, err := readFactoryHostConfig(path); err == nil || strings.Contains(err.Error(), "pw@") { + t.Fatalf("a relay address with a sign-in in it must be refused without being printed: %v", err) + } +} diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 91b6d7a1d6..3f457bfa07 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1245,7 +1245,7 @@ no longer usable there is refused (`conflict`). When the operator removes a pers their agents go to the heir. Starting an organization (hello `org_setup`, v2 designs J2 and J3). `factory.org_profile` -`GET /v1/org` answers `{name, description?, set_up, by_hand?}` to anyone signed in; +`GET /v1/org` answers `{name, description?, set_up, by_hand?, relay?}` to anyone signed in (`relay` is the address of the relay the organization runs for its members' computers, when the operator named one); `factory.org_profile_set {name?, description?}` `PUT /v1/org` is the operator's "Start your organization" (a name of 1 to 40 characters, a line of at most 200 that every Afi on the server is told). `factory.org_setup {since?}` `GET /v1/org/setup` is the operator's own diff --git a/internal/appwire/factory_org_setup.go b/internal/appwire/factory_org_setup.go index 0f56be1d98..62c1791152 100644 --- a/internal/appwire/factory_org_setup.go +++ b/internal/appwire/factory_org_setup.go @@ -34,6 +34,8 @@ type OrgProfile struct { Description string `json:"description,omitempty"` SetUp bool `json:"set_up"` ByHand bool `json:"by_hand,omitempty"` + // Relay is the address of the relay the organization runs for its members' computers, when it runs one. + Relay string `json:"relay,omitempty"` } // OrgProfileSetParams is "Start your organization": a name and a line. diff --git a/internal/factory/api/org_setup.go b/internal/factory/api/org_setup.go index e5c90ec843..14fcacb50e 100644 --- a/internal/factory/api/org_setup.go +++ b/internal/factory/api/org_setup.go @@ -12,6 +12,9 @@ type OrgProfile struct { Description string `json:"description,omitempty"` SetUp bool `json:"set_up"` ByHand bool `json:"by_hand,omitempty"` + // Relay is the address of the relay this organization runs for its members' computers, when the operator named one + // (`relay_url` in the server's config). It is how a member's codeaf finds it after signing in; nothing here is a secret. + Relay string `json:"relay,omitempty"` } // OrgProfilePut is PUT /v1/org, the operator's "Start your organization". diff --git a/internal/factory/serve/org_relay_test.go b/internal/factory/serve/org_relay_test.go new file mode 100644 index 0000000000..58424a29ce --- /dev/null +++ b/internal/factory/serve/org_relay_test.go @@ -0,0 +1,45 @@ +package serve + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +// AN ORGANIZATION THAT RUNS A RELAY TELLS ITS PEOPLE WHERE IT IS: every signed-in person reads it from GET /v1/org, a stranger +// does not, and an organization that runs none says nothing, so what the server answered before is what it answers now. +func TestTheOrganizationTellsItsPeopleWhereItsRelayIs(t *testing.T) { + o := newWSOrg(t) + + var none api.OrgProfile + o.do(t, "abir", "GET", "/v1/org", -1, nil, 200, &none) + if none.Relay != "" { + t.Fatalf("an organization with no relay named one: %+v", none) + } + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/v1/org", nil) + req.RemoteAddr = "192.0.2.1:1234" + req.Header.Set("Authorization", "Bearer "+o.tokens["abir"]) + o.h.ServeHTTP(rec, req) + if strings.Contains(rec.Body.String(), "relay") { + t.Fatalf("with no relay named the answer must be what it always was: %s", rec.Body) + } + + o.h.config.RelayURL = "https://relay.example.com" + var told api.OrgProfile + o.do(t, "abir", "GET", "/v1/org", -1, nil, 200, &told) + if told.Relay != "https://relay.example.com" || told.Name == "" { + t.Fatalf("a member reads %+v", told) + } + + // Someone who is not signed in learns nothing of it: the relay is for the organization's people. + anon := httptest.NewRecorder() + req = httptest.NewRequest("GET", "/v1/org", nil) + req.RemoteAddr = "192.0.2.1:1234" + o.h.ServeHTTP(anon, req) + if anon.Code != 401 && anon.Code != 403 || strings.Contains(anon.Body.String(), "relay.example.com") { + t.Fatalf("a stranger asking for the organization: %d %s", anon.Code, anon.Body) + } +} diff --git a/internal/factory/serve/org_setup.go b/internal/factory/serve/org_setup.go index e5b253a9e6..f7a0fc230e 100644 --- a/internal/factory/serve/org_setup.go +++ b/internal/factory/serve/org_setup.go @@ -93,7 +93,7 @@ func (h *Handler) loadOrgName() { // orgProfile is the organization's own words as the wire says them. func (h *Handler) orgProfile() (api.OrgProfile, error) { - out := api.OrgProfile{Name: h.factoryNow().Name} + out := api.OrgProfile{Name: h.factoryNow().Name, Relay: h.config.RelayURL} if h.config.Store == nil { return out, nil } diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index 80bf37848b..93c06fab4e 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -166,6 +166,9 @@ type Config struct { // GitHubClientID enables GitHub device sign-in; Team optionally restricts handles. GitHubClientID string Team []string + // RelayURL is the address of the relay this organization runs for its members' computers (`relay_url` in the host config), + // empty when it runs none. GET /v1/org tells it to anyone signed in; it is never used by the server itself. + RelayURL string // GitHubHTTPClient permits a fake transport while keeping production URLs fixed. GitHubHTTPClient *http.Client // ActsClient, when set, is the GitHub client public acts are carried out From 3db67789ed35c515030ce7766c3b65c0f7d8e6e2 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:01 -0500 Subject: [PATCH 03/16] pair: --org pairs through the relay your organization runs `codeaf pair --org https://org.example.com [--code]` asks the organization server, with the sign-in the person already has, which relay it runs, and then pairs exactly as `--via ` does, so the relay is remembered and handed to the computer being paired. A computer that never says --org asks no organization anything, an explicit CODEAF_SYNC_URL (a relay or `off`) still wins, and --org together with --via is refused in a sentence. An organization that names no relay, a sign-in it does not know, a server that is not there, a non-web address, or an http relay named over https each end the pairing with a plain sentence and nothing is paired through it. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/pair.go | 13 +++- cmd/codeaf/pair_org.go | 65 ++++++++++++++++ cmd/codeaf/pair_org_test.go | 148 ++++++++++++++++++++++++++++++++++++ 3 files changed, 225 insertions(+), 1 deletion(-) create mode 100644 cmd/codeaf/pair_org.go create mode 100644 cmd/codeaf/pair_org_test.go diff --git a/cmd/codeaf/pair.go b/cmd/codeaf/pair.go index b8eac37749..4d5ff5750a 100644 --- a/cmd/codeaf/pair.go +++ b/cmd/codeaf/pair.go @@ -59,7 +59,7 @@ func newPairDoor(in io.Reader, out io.Writer) pairDoor { ownRecord: func(ctx context.Context, route pair.Mailbox) error { return ownDeviceRecord(ctx, home.Dir(), route) }} } -const pairUsage = "usage: codeaf pair [--name ] | codeaf pair approve | codeaf pair [--replace] [--name ] | codeaf pair --code" +const pairUsage = "usage: codeaf pair [--name ] | codeaf pair approve | codeaf pair [--replace] [--name ] | codeaf pair --code | codeaf pair --org
[--code]" // approveUsage is what `codeaf pair approve` with nothing after it is told. const approveUsage = "usage: codeaf pair approve \u2014 the link or token the new device shows; for a numeric pairing code use codeaf pair " @@ -162,12 +162,23 @@ func (d pairDoor) run(ctx context.Context, args []string) error { flags := commandFlags("pair") via := flags.String("via", "", "the relay to pair through; empty is the one this device already uses") renamedFlag(flags, "relay", "via") + org := flags.String("org", "", "pair through the relay your organization runs: its server address, such as https://org.example.com") code := flags.Bool("code", false, "show a code such as "+pair.ExampleChatCode+" that shares this device's chats, instead of asking to join") replace := flags.Bool("replace", false, "when typing a code, replace this device's own chats with the shared ones") name := flags.String("name", "", "what your devices call this one; empty keeps its current name, which starts as the host name") if err := parseCommandFlags(flags, reorder(flags, args)); err != nil { return err } + if strings.TrimSpace(*org) != "" { + if strings.TrimSpace(*via) != "" { + return wrongCall("--org and --via each name the relay to pair through: use one of them") + } + relay, err := orgPairRelay(ctx, *org, d.term.say) + if err != nil { + return err + } + *via = relay + } if err := d.naming(ctx, *name, flags.Args(), *code); err != nil { return err } diff --git a/cmd/codeaf/pair_org.go b/cmd/codeaf/pair_org.go new file mode 100644 index 0000000000..e7f1015dca --- /dev/null +++ b/cmd/codeaf/pair_org.go @@ -0,0 +1,65 @@ +package main + +// ── `codeaf pair --org https://org.example.com` ───────────────────────────── +// +// An organization that runs a relay for its members' computers (deploy/org) tells it to everyone signed in (GET /v1/org), so a +// member pairs their computers through it with the one address they already have, and not with a second one to look up: +// +// laptop$ codeaf pair --org https://org.example.com --code +// desktop$ codeaf pair --via +// +// IT IS `--via` WITH THE ADDRESS LOOKED UP, AND NOTHING MORE. The pairing that follows is the one `--via` has always made: it +// remembers the relay, hands it to the computer it pairs, and from then on every start of those computers uses it. A computer +// that never says --org never asks an organization anything, so nobody's relay moves unless the person typed it; and +// CODEAF_SYNC_URL=off still stops the pairing, exactly as it stops `--via` (pairMailboxAt). +// +// THE ADDRESS IS READ WITH THE SIGN-IN THE PERSON ALREADY HAS (`codeaf attach`, CODEAF_ORG_TOKEN), over the door `--org` of +// `codeaf chat` uses, so one rule covers both: https anywhere, plain http only for this computer, no redirect followed. + +import ( + "context" + "errors" + "fmt" + "net/url" + "strings" +) + +// orgNoRelayWords is what an organization that runs no relay is asked about: it is not an error of the person's, so it says what +// to do instead. +func orgNoRelayWords(host string) string { + return fmt.Sprintf("%s does not run a relay for your computers. Pair through another with --via
, or leave --org off to use the usual one.", host) +} + +// orgPairRelay is the relay the organization at target runs for its members' computers. +func orgPairRelay(ctx context.Context, target string, say func(string)) (string, error) { + door, err := newOrgDoor(target, say) + if err != nil { + return "", err + } + var profile struct { + Relay string `json:"relay"` + } + if err := door.call(ctx, "GET", "/v1/org", &profile); err != nil { + return "", err + } + return advertisedRelay(door.base, door.host, profile.Relay) +} + +// advertisedRelay checks the address an organization named before a pairing is sent through it. The organization is a server the +// person was told to trust with a sign-in, not with where their computers go, so the address must be a web address, must not +// carry a sign-in of its own, and must not be plain http when the organization was reached over https: a server that could turn +// the lookup into an unprotected road would be choosing the person's security for them. +func advertisedRelay(orgBase, host, raw string) (string, error) { + raw = strings.TrimSpace(raw) + if raw == "" { + return "", errors.New(orgNoRelayWords(host)) + } + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "", fmt.Errorf("%s named a relay address this program cannot use.", host) + } + if u.Scheme == "http" && strings.HasPrefix(orgBase, "https://") { + return "", fmt.Errorf("%s named a relay that is not https, so nothing was paired through it.", host) + } + return strings.TrimRight(u.String(), "/"), nil +} diff --git a/cmd/codeaf/pair_org_test.go b/cmd/codeaf/pair_org_test.go new file mode 100644 index 0000000000..bb7d668c57 --- /dev/null +++ b/cmd/codeaf/pair_org_test.go @@ -0,0 +1,148 @@ +package main + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/pair" +) + +// orgAnswering is an organization's server that answers GET /v1/org to the one sign-in it knows, with relay as the address it +// runs for its members (empty: it runs none). +func orgAnswering(t *testing.T, token, relay string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/org" || r.Header.Get("Authorization") != "Bearer "+token { + http.Error(w, `{"error":"sign in first"}`, http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + body := `{"name":"Acme","set_up":true` + if relay != "" { + body += `,"relay":"` + relay + `"` + } + _, _ = io.WriteString(w, body+"}") + })) + t.Cleanup(srv.Close) + return srv +} + +// A MEMBER PAIRS THROUGH THE ORGANIZATION'S RELAY WITH THE ONE ADDRESS THEY HAVE: `--org` looks up the relay the organization runs +// and the pairing goes through it, as if they had typed it after --via. The other computer is told to use it the way a --via +// pairing always tells it. +func TestPairOrgGoesThroughTheRelayTheOrganizationNames(t *testing.T) { + rig := newPairRig(t) + org := orgAnswering(t, "member-token", rig.url) + t.Setenv("CODEAF_ORG_TOKEN", "member-token") + t.Setenv("CODEAF_HOME", rig.homeA) + t.Setenv("CODEAF_SYNC_URL", "") + + asked := make(chan string, 4) + in, typed := io.Pipe() + defer typed.Close() + out := &pairScreenText{} + door := rig.door(rig.homeA, in, out) + inner := door.mailbox + door.mailbox = func(relay string) (pair.Mailbox, error) { + asked <- relay + return inner(relay) + } + ctx, stop := context.WithCancel(context.Background()) + defer stop() + done := make(chan error, 1) + go func() { done <- door.run(ctx, []string{"--org", org.URL, "--code"}) }() + out.waitFor(t, `codeaf pair (\S+)`) + if got := <-asked; got != rig.url { + t.Fatalf("the pairing went through %q; the organization named %q", got, rig.url) + } + stop() + <-done +} + +// What a member is told when it cannot work is a sentence that says what to do, and a pairing that was refused went nowhere. +func TestPairOrgRefusesInPlainWords(t *testing.T) { + rig := newPairRig(t) + t.Setenv("CODEAF_HOME", rig.homeA) + t.Setenv("CODEAF_SYNC_URL", "") + hosted := func(t *testing.T) pairDoor { + d := rig.door(rig.homeA, strings.NewReader(""), &pairScreenText{}) + d.mailbox = func(relay string) (pair.Mailbox, error) { + t.Errorf("a pairing went to a relay (%q) after the lookup was refused", relay) + return pair.Mailbox{}, nil + } + return d + } + for _, tc := range []struct { + name string + token string + org func(t *testing.T) string + args []string + want string + }{ + {"an organization that runs no relay", "tok", func(t *testing.T) string { return orgAnswering(t, "tok", "").URL }, + []string{"--code"}, "does not run a relay for your computers. Pair through another with --via
, or leave --org off"}, + {"no sign-in", "", func(t *testing.T) string { return orgAnswering(t, "tok", rig.url).URL }, + []string{"--code"}, "Sign in to"}, + {"a sign-in the organization does not know", "stale", func(t *testing.T) string { return orgAnswering(t, "tok", rig.url).URL }, + []string{"--code"}, "sign in first"}, + {"a server that is not there", "tok", func(t *testing.T) string { + srv := httptest.NewServer(http.NotFoundHandler()) + srv.Close() + return srv.URL + }, []string{"--code"}, "is unreachable"}, + {"both --org and --via", "tok", func(t *testing.T) string { return orgAnswering(t, "tok", rig.url).URL }, + []string{"--via", "http://127.0.0.1:1", "--code"}, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("CODEAF_ORG_TOKEN", tc.token) + args := append([]string{"--org", tc.org(t)}, tc.args...) + var said strings.Builder + old := usageErr + usageErr = &said + defer func() { usageErr = old }() + err := hosted(t).run(context.Background(), args) + if err == nil { + t.Fatal("the pairing went on") + } + if tc.want != "" && !strings.Contains(err.Error(), tc.want) { + t.Fatalf("it said %q; want a sentence with %q", err.Error(), tc.want) + } + if tc.want == "" && !strings.Contains(said.String(), "--org and --via each name the relay") { + t.Fatalf("both flags together were not refused in words: %q %v", said.String(), err) + } + }) + } +} + +// The organization names the address, and the address is checked before a pairing is sent through it: a web address, no sign-in of +// its own, and never plain http when the organization was reached over https. +func TestAdvertisedRelayIsCheckedBeforeAPairingUsesIt(t *testing.T) { + for _, tc := range []struct { + org, raw, want, err string + }{ + {"https://org.example.com", "https://relay.example.com/", "https://relay.example.com", ""}, + {"https://org.example.com", "https://example.com/fabric", "https://example.com/fabric", ""}, + {"http://127.0.0.1:8787", "http://127.0.0.1:8788", "http://127.0.0.1:8788", ""}, + {"https://org.example.com", "", "", "does not run a relay"}, + {"https://org.example.com", "relay.example.com", "", "cannot use"}, + {"https://org.example.com", "https://u:p@relay.example.com", "", "cannot use"}, + {"https://org.example.com", "https://relay.example.com/?x=1", "", "cannot use"}, + {"https://org.example.com", "ftp://relay.example.com", "", "cannot use"}, + {"https://org.example.com", "http://relay.example.com", "", "not https"}, + } { + got, err := advertisedRelay(tc.org, "org.example.com", tc.raw) + if tc.err != "" { + if err == nil || !strings.Contains(err.Error(), tc.err) { + t.Errorf("%q: want an error with %q, got %q, %v", tc.raw, tc.err, got, err) + } + continue + } + if err != nil || got != tc.want { + t.Errorf("%q: want %q, got %q, %v", tc.raw, tc.want, got, err) + } + } +} From 145bf4d1c169876a173ae0747710fa2c36f4ca6a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:01 -0500 Subject: [PATCH 04/16] wordlaw: classify the relay words the org relay change adds Every new person-facing "relay" string names the server (the pairing sentences and flag help, relay_url, the relay tag of GET /v1/org), and the relay's own help page is now about its storage switch too. Co-Authored-By: Claude Sonnet 5.5 --- internal/wordlaw/relay_words.golden | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/internal/wordlaw/relay_words.golden b/internal/wordlaw/relay_words.golden index 5497db7d74..db622126c1 100644 --- a/internal/wordlaw/relay_words.golden +++ b/internal/wordlaw/relay_words.golden @@ -55,12 +55,22 @@ server cmd/codeaf/chatv3_at.go ", ~/.codeaf/v3/remote/relay, then the address th server cmd/codeaf/chatv3_at.go "no relay is set up on this machine, so there is nowhere to be reachable from — set " server cmd/codeaf/chatv3_at.go "relay" server cmd/codeaf/chatv3_at.go "the relay to be reachable through; empty reads " +server cmd/codeaf/factory_config.go "relay_url must be a web address such as https://relay.example.com, with no sign-in or query in it" +server cmd/codeaf/factory_config.go "relay_url" +server cmd/codeaf/factory_config.go "yaml:\"relay_url,omitempty\"" server cmd/codeaf/main.go "relay" +server cmd/codeaf/pair.go "--org and --via each name the relay to pair through: use one of them" +server cmd/codeaf/pair.go "pair through the relay your organization runs: its server address, such as https://org.example.com" server cmd/codeaf/pair.go "relay" server cmd/codeaf/pair.go "the relay to pair through; empty is the one this device already uses" +server cmd/codeaf/pair_org.go "%s does not run a relay for your computers. Pair through another with --via
, or leave --org off to use the usual one." +server cmd/codeaf/pair_org.go "%s named a relay address this program cannot use." +server cmd/codeaf/pair_org.go "%s named a relay that is not https, so nothing was paired through it." +server cmd/codeaf/pair_org.go "json:\"relay\"" server cmd/codeaf/pairroute.go "could not keep the pairing relay address, so nothing was sent: %w" server cmd/relay/main.go "relay:" server internal/appwire/chats.go "sync.relay" +server internal/appwire/factory_org_setup.go "json:\"relay,omitempty\"" server internal/appwire/sync.go "json:\"relay,omitempty\"" server internal/atlas/frame.go "relay / hosted" server internal/atlas/pairing.go "Add machine B with a link and a 4-digit check. No account is needed. The relay only sees sealed boxes." @@ -110,6 +120,7 @@ server internal/dirwatch/stream.go "dirwatch: this relay has no watch route" server internal/executor/gated.go "couldn't confirm taking this chat back from the relay; try again" server internal/factory/agentfield/client.go "/relay" server internal/factory/agentfield/client.go "/relay/ack" +server internal/factory/api/org_setup.go "json:\"relay,omitempty\"" server internal/filesdoor/serve.go "filesdoor: a door needs a relay address that looks like https://relay.example.com" server internal/filesdoor/serve.go "relay" server internal/livedoor/direct.go "relay" @@ -160,9 +171,9 @@ server internal/relay/server.go "relay: this server does not hand out connection server internal/relay/server.go "that machine is already connected to the relay under this name" server internal/relay/transport.go "relay: that relay only speaks the raw upgrade" server internal/relayserve/main.go "codeaf relay is listening on " +server internal/relayserve/main.go "on keeps the chats' sealed content under --store; off keeps only the device list and refuses uploads, as the hosted relay does for an account it has not approved" server internal/relayserve/main.go "relay" server internal/relayserve/main.go "relay: %w" -server internal/relayserve/main.go "usage: codeaf relay [--listen host:port] [--store path]\n\nRun your own relay.\n\n --listen host:port address to listen on (default :8787)\n --store path keep your devices and saved chats here; empty connects machines only\n --quiet do not log arrivals, departures or requests\n --status=false turn off the service status endpoint\n --trust-proxy use the caller address supplied by a trusted proxy" server internal/relayserve/namespaces.go "relayserve: %q is not an identity id" server internal/relayserve/unavailable.go "relay unavailable phase=%s cause=%q" server internal/rotate/journal.go "json:\"handoff_relay,omitempty\"" @@ -194,6 +205,7 @@ storage internal/blobstore/wire.go "relay_storage_full" storage internal/chatlist/copy.go "chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for relay storage (request access in Settings under Devices)" storage internal/chatlist/copy.go "relay storage is off for this account, so chats stay on this computer; request access in Settings under Devices" storage internal/directory/wire.go "relay_storage_full" +storage internal/relayserve/main.go "usage: codeaf relay [--listen host:port] [--store path] [--storage on|off]\n\nRun your own relay.\n\n --listen host:port address to listen on (default :8787)\n --store path keep your devices and saved chats here; empty connects machines only\n --storage on|off off keeps the device list and refuses chat uploads (default on)\n --quiet do not log arrivals, departures or requests\n --status=false turn off the service status endpoint\n --trust-proxy use the caller address supplied by a trusted proxy" storage internal/rotate/steps.go "relay storage is off; chats stay on your computers" storage internal/syncsetup/storage.go "Please turn on relay storage for my account.\n\nRequest code: " storage internal/syncsetup/storage.go "relay storage access: " From 977f5ba3b8b3eaffdba7d2d867bf0526e8f40f3d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:10 -0500 Subject: [PATCH 05/16] org: a member's window in a shared hosted chat is named by the server, not by the member's own hello The chat's other windows read the name of the window that holds the keyboard ("typing from mia"). On the guest wire that name came straight from the member's hello, so a member could make their window read as the owner, as another member, or as "another window", and could stamp the hello as a remote viewer of someone's own computers, which changes the keyboard, resend and guest rules the engine applies to it. The guest wire now writes the surface itself: the person as this server knows them, or "'s bot" for a bot, and drops any remote stamp. Two table laws pin where the personal guest law and the organization's guest law may differ, so a method added to the wire cannot drift apart on one side without a line saying why. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_guest.go | 25 +++- .../factory/serve/hosted_guest_label_test.go | 102 ++++++++++++++ .../factory/serve/hosted_guest_laws_test.go | 130 ++++++++++++++++++ internal/factory/serve/hosted_guest_test.go | 4 +- 4 files changed, 254 insertions(+), 7 deletions(-) create mode 100644 internal/factory/serve/hosted_guest_label_test.go create mode 100644 internal/factory/serve/hosted_guest_laws_test.go diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index 2013d82ad1..d94e5fec4e 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -157,7 +157,7 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I defer cancel() p.fromHost() }) - p.fromClient(func(method, class string) { + p.fromClient(hostedGuestLabel(v), func(method, class string) { h.noteHostedGuestCall(item.ID, owner, v.Handle, method, class) }) cancel() @@ -238,7 +238,7 @@ func (p *hostedGuest) fromHost() { } } -func (p *hostedGuest) fromClient(forwarding func(method, class string)) { +func (p *hostedGuest) fromClient(label string, forwarding func(method, class string)) { reader := bufio.NewReader(p.client) var hello bool for { @@ -258,7 +258,7 @@ func (p *hostedGuest) fromClient(forwarding func(method, class string)) { var frame remote.Frame err = json.Unmarshal(line, &frame) if !hello { - if err != nil || frame.Kind != "hello" || !rewriteHostedGuestHello(&frame) { + if err != nil || frame.Kind != "hello" || !rewriteHostedGuestHello(&frame, label) { p.fatal(hostedGuestBadHello) return } @@ -317,7 +317,17 @@ func hostedGuestRefusal(class string, verbs acl.VerbSet) string { return "" } -func rewriteHostedGuestHello(frame *remote.Frame) bool { +// hostedGuestLabel is the name every other window of a chat reads for a guest's window: "typing from santosh". It is +// the person as this server knows them and never a word the guest's own computer chose, so a guest cannot appear to be +// the owner or another member. A bot reads as its creator's bot, because that is whose rights it holds. +func hostedGuestLabel(v Viewer) string { + if v.Agent != nil { + return v.Handle + "'s bot" + } + return v.Handle +} + +func rewriteHostedGuestHello(frame *remote.Frame, label string) bool { var fields map[string]json.RawMessage if json.Unmarshal(frame.Payload, &fields) != nil || fields == nil { return false @@ -329,7 +339,9 @@ func rewriteHostedGuestHello(frame *remote.Frame) bool { return false } // The engine accepts case variants of its JSON fields, so discard those too. - replaced := []string{"launch", "model", "level", "workspace", "session", "new", "join", "holdInterruptedWork", "window", "back", "clientID"} + // Remote is what the door that authenticated a viewer of one person's own computers stamps on its hello, and surface is + // the name the other windows read for this one: neither is ever a guest's to say. + replaced := []string{"launch", "model", "level", "workspace", "session", "new", "join", "holdInterruptedWork", "window", "back", "clientID", "remote", "surface"} for field := range fields { for _, name := range replaced { if strings.EqualFold(field, name) { @@ -341,6 +353,9 @@ func rewriteHostedGuestHello(frame *remote.Frame) bool { // The allow-list protects this wire. Setting watch would hide transcripts and most other reads. fields["back"] = json.RawMessage("true") fields["clientID"], _ = json.Marshal("guest:" + window.ClientID) + if label != "" { + fields["surface"], _ = json.Marshal(label) + } frame.Payload, _ = json.Marshal(fields) return true } diff --git a/internal/factory/serve/hosted_guest_label_test.go b/internal/factory/serve/hosted_guest_label_test.go new file mode 100644 index 0000000000..25f7860552 --- /dev/null +++ b/internal/factory/serve/hosted_guest_label_test.go @@ -0,0 +1,102 @@ +package serve + +import ( + "encoding/json" + "net/http/httptest" + "testing" + + "github.com/Agent-Field/codeaf/internal/remote" +) + +// guestSurfaceOf is the name the chat's other windows will read for the window that just opened, as the engine received it +// in the hello the guest wire forwarded. +func guestSurfaceOf(t *testing.T, host guestHostWire) (surface string, present bool) { + t.Helper() + var hello remote.Frame + if err := json.Unmarshal([]byte(guestHostLine(t, host)), &hello); err != nil || hello.Kind != "hello" { + t.Fatalf("the engine was not sent a hello: %v", err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(hello.Payload, &fields); err != nil { + t.Fatal(err) + } + raw, present := fields["surface"] + if present && json.Unmarshal(raw, &surface) != nil { + t.Fatalf("the surface is not a string: %s", raw) + } + return surface, present +} + +// Contract RT1: in a chat shared with people, the owner's window and every other window read the MEMBER's own name for +// the window that holds the keyboard ("typing from mia"), whatever the member's computer called itself. A member +// cannot make their window read as the owner, as another member, or as "another window" by saying so in the hello, +// and a window that said nothing is named too. +func TestRT1_WhoIsTypingIsTheMembersNameNotTheirComputersWord(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "santosh", chat, "mia", "edit") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + for _, tc := range []struct{ who, hello string }{ + {"abir", `{"kind":"hello","payload":{"version":1,"surface":"santosh"}}`}, + {"mia", `{"kind":"hello","payload":{"version":1,"SURFACE":"santosh-laptop"}}`}, + {"mia", `{"kind":"hello","payload":{"version":1}}`}, + } { + t.Run(tc.who, func(t *testing.T) { + client := guestDial(t, srv, rg.tokens[tc.who], chat) + host, _ := guestReceive(t, opened) + guestWrite(t, client, tc.hello+"\n") + if got, present := guestSurfaceOf(t, host); !present || got != tc.who { + t.Fatalf("%s's window was named %q (present %v) to the chat, want %q", tc.who, got, present, tc.who) + } + }) + } +} + +// Contract RT2: a bot that watches or types in someone's chat reads as its creator's bot, so a person looking at +// "typing from abir's bot" knows whose rights are being used and that it is a script. +func TestRT2_ABotIsNamedAsItsCreatorsBot(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + bot := rg.contractBot(t, "abir", "View bot", "view") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client := guestDial(t, srv, bot.Token, chat) + host, _ := guestReceive(t, opened) + guestWrite(t, client, `{"kind":"hello","payload":{"version":1,"surface":"santosh"}}`+"\n") + if got, _ := guestSurfaceOf(t, host); got != "abir's bot" { + t.Fatalf("a bot's window was named %q to the chat, want %q", got, "abir's bot") + } +} + +// Contract RT3: a guest cannot say it is a remote viewer of one person's own computers. That stamp is what the door that +// authenticated such a viewer writes, and it changes what the engine believes about the window (its keyboard rule, its +// resend rule and its guest law), so it never crosses from a member's hello. +func TestRT3_AGuestCannotStampItselfARemoteViewer(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "mia", "edit") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client := guestDial(t, srv, rg.tokens["mia"], chat) + host, _ := guestReceive(t, opened) + guestWrite(t, client, `{"kind":"hello","payload":{"version":1,"remote":{"device":"santosh-laptop"},"Remote":{"device":"x"}}}`+"\n") + var hello remote.Frame + if err := json.Unmarshal([]byte(guestHostLine(t, host)), &hello); err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(hello.Payload, &fields); err != nil { + t.Fatal(err) + } + for name := range fields { + if name == "remote" || name == "Remote" { + t.Fatalf("the engine was handed a remote-viewer stamp by a guest: %s", hello.Payload) + } + } +} diff --git a/internal/factory/serve/hosted_guest_laws_test.go b/internal/factory/serve/hosted_guest_laws_test.go new file mode 100644 index 0000000000..f4c5fe8931 --- /dev/null +++ b/internal/factory/serve/hosted_guest_laws_test.go @@ -0,0 +1,130 @@ +package serve + +import ( + "slices" + "sort" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// There are two guest laws in this program, and they answer two different questions about the same wire. The personal +// one (remote.GuestMay) is what a person's OWN paired computer may do in a chat another of their computers runs: it is +// one switch pair per computer, watch and type, kept on the computer that runs the chat. The organization's (this +// package's hostedGuestMethods) is what a MEMBER may do in a hosted chat somebody shares with them: verbs per chat, kept +// on the organization's server. They never meet, because a hosted chat is never on a paired computer, and they are NOT +// meant to be the same table: the one is the person's own hands and the other is a colleague's. +// +// What they must never do is drift apart without anyone deciding it. A method added to the wire gets a class on both +// sides, and the two lists below say, method by method and in words, where the answer differs on purpose. A method that +// differs and is not listed fails here, and so does a list line that has stopped being true. + +// hostedWiderThanPersonal are the methods a member holding the verb may call in a hosted chat while a person's own +// computer, even with typing on, may not. Each differs for a reason of context. +var hostedWiderThanPersonal = map[string]string{ + // Reading: a member reads what the owner chose to share, and nothing else holds the history for them. The personal law + // keeps the whole transcript on the computer that runs the chat and serves it a page at a time (Transcript.Page). + remote.MethodTranscript: "view: the whole transcript is how a member's window opens", + remote.MethodEarlier: "view: older history of a shared chat", + remote.MethodRewindPoints: "view: read-only list", + remote.MethodPlanTasks: "view: read-only list", + remote.MethodPlanSpend: "view: read-only list", + remote.MethodTaskPending: "view: read-only list", + remote.MethodTitleWatch: "view: read-only watch", + remote.MethodDesignWatch: "view: read-only watch", + remote.MethodReasoningFor: "view: read-only setting", + // Sending: a member with run acts as the chat's owner would, by the organization's own design (docs/organizations.md, + // "The owner owns the chat"). A person's own computer sends words and nothing else. + remote.MethodSubmitBash: "run: a member may run a command the chat's own way, as the owner would", + remote.MethodSubmitFiles: "run: a member may send files", + remote.MethodSubmitImage: "run: a member may send images", + remote.MethodQuestionReplace: "run: a member may replace a held question's words", +} + +// personalWiderThanHosted are the methods a person's own computer may call that a member of a hosted chat may not, +// whatever verb they hold. The hosted default is owner-only, which is the fail-closed answer. +var personalWiderThanHosted = map[string]string{ + remote.MethodObserve: "a chat's own observer door: not offered to a member, nothing on the hosted side calls it", + remote.MethodUnobserve: "the other half of Observe", + remote.MethodHarness: "reading the harness list: owner-only on the hosted side until a member needs it", + remote.MethodStopWork: "stopping the chat's work is a manage act on the hosted side (its own door), and steer holders interrupt instead", + remote.MethodConsent: "a one-turn approval: owner-only on the hosted side unless the organization's policy says answerers may (chats.approvals_by)", + remote.MethodTranscriptPage: "paging a transcript: nothing on the hosted side calls it yet", +} + +func personalClassOf(method string) string { + switch { + case remote.GuestMay(method, false): + return "watch" + case remote.GuestMay(method, true): + return "drive" + } + return "none" +} + +// Contract RT4: the personal and the organization's guest laws differ only where a line above says so. +func TestRT4_TheTwoGuestLawsOnlyDifferWhereSaid(t *testing.T) { + var unsaidWider, unsaidNarrower, staleWider, staleNarrower []string + for method, class := range hostedGuestMethods { + personal := personalClassOf(method) + hostedMay := class != hostedGuestOwner + personalMay := personal != "none" + _, saidWider := hostedWiderThanPersonal[method] + _, saidNarrower := personalWiderThanHosted[method] + switch { + case hostedMay && !personalMay && !saidWider: + unsaidWider = append(unsaidWider, method+" ("+class+")") + case !hostedMay && personalMay && !saidNarrower: + unsaidNarrower = append(unsaidNarrower, method+" ("+personal+")") + } + if saidWider && !(hostedMay && !personalMay) { + staleWider = append(staleWider, method) + } + if saidNarrower && !(!hostedMay && personalMay) { + staleNarrower = append(staleNarrower, method) + } + } + for method := range hostedWiderThanPersonal { + if _, ok := hostedGuestMethods[method]; !ok { + staleWider = append(staleWider, method) + } + } + for method := range personalWiderThanHosted { + if _, ok := hostedGuestMethods[method]; !ok { + staleNarrower = append(staleNarrower, method) + } + } + for _, list := range []struct { + name string + items []string + }{ + {"hosted allows, personal refuses, and no line in hostedWiderThanPersonal says why", unsaidWider}, + {"personal allows, hosted keeps for the owner, and no line in personalWiderThanHosted says why", unsaidNarrower}, + {"hostedWiderThanPersonal lines that are no longer true", staleWider}, + {"personalWiderThanHosted lines that are no longer true", staleNarrower}, + } { + if len(list.items) != 0 { + sort.Strings(list.items) + t.Errorf("%s:\n %s", list.name, strings.Join(slices.Compact(list.items), "\n ")) + } + } +} + +// Contract RT5: whatever a watch-only viewer of a person's own computers may call, a hosted guest holding only `view` +// may call too, so that watching means the same thing on both sides; and the verbs a method needs on the hosted side +// are never narrower than the personal law's own idea of watching a chat (a view-class method for watch). +func TestRT5_WatchingMeansTheSameOnBothSides(t *testing.T) { + for method, class := range hostedGuestMethods { + if personalClassOf(method) != "watch" { + continue + } + if _, said := personalWiderThanHosted[method]; said { + continue + } + if class != acl.VerbView { + t.Errorf("%s: a watch-only viewer of one's own computers may call it, but a hosted guest needs %q for it", method, class) + } + } +} diff --git a/internal/factory/serve/hosted_guest_test.go b/internal/factory/serve/hosted_guest_test.go index 358cd2c1fc..66f6bd7a54 100644 --- a/internal/factory/serve/hosted_guest_test.go +++ b/internal/factory/serve/hosted_guest_test.go @@ -165,7 +165,7 @@ func TestP2_5_GuestHelloAndWholeLines(t *testing.T) { defer srv.Close() client := guestDial(t, srv, rg.tokens["abir"], chat) host, _ := guestReceive(t, opened) - guestWrite(t, client, `{"kind":"hello","payload":{"launch":{},"model":"other","level":"high","workspace":"/elsewhere","Session":"elsewhere","ſession":"also elsewhere","new":true,"join":true,"holdInterruptedWork":true,"window":{},"BACK":false,"CLIENTID":"desk","version":1,"resume":[{"stream":8,"seq":99}],"encodings":["gzip"],"surface":"desk","watch":false,"extra":{"keep":true}}}`+"\n") + guestWrite(t, client, `{"kind":"hello","payload":{"launch":{},"model":"other","level":"high","workspace":"/elsewhere","Session":"elsewhere","ſession":"also elsewhere","new":true,"join":true,"holdInterruptedWork":true,"window":{},"BACK":false,"CLIENTID":"desk","version":1,"resume":[{"stream":8,"seq":99}],"encodings":["gzip"],"surface":"desk","REMOTE":{"device":"someone-else"},"watch":false,"extra":{"keep":true}}}`+"\n") frame := guestFrame(t, guestHostLine(t, host)) var payload map[string]json.RawMessage if err := json.Unmarshal(frame.Payload, &payload); err != nil || frame.Kind != "hello" { @@ -173,7 +173,7 @@ func TestP2_5_GuestHelloAndWholeLines(t *testing.T) { } want := map[string]string{ "back": "true", "clientID": `"guest:desk"`, "version": "1", "watch": "false", - "resume": `[{"stream":8,"seq":99}]`, "encodings": `["gzip"]`, "surface": `"desk"`, "extra": `{"keep":true}`, + "resume": `[{"stream":8,"seq":99}]`, "encodings": `["gzip"]`, "surface": `"abir"`, "extra": `{"keep":true}`, } if len(payload) != len(want) { t.Errorf("hello kept unexpected fields: %s", frame.Payload) From 9af1cb62debf34ac7137d1b16b52ed2415cd91bd Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:14 -0500 Subject: [PATCH 06/16] remote: a redial can end at once on a refusal the caller knows is final Roaming gains an optional EndsOn hook. When a redial is answered with an error the hook calls final, the client ends at once with the far end's own words instead of spending the whole redial window saying it is reconnecting. With no hook the schedule is exactly what it was, so the ssh and relay doors keep their behaviour. Co-Authored-By: Claude Sonnet 5.5 --- internal/remote/redial.go | 10 ++++ internal/remote/redial_final_test.go | 68 ++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 internal/remote/redial_final_test.go diff --git a/internal/remote/redial.go b/internal/remote/redial.go index 8bd769d4b6..83febe26a8 100644 --- a/internal/remote/redial.go +++ b/internal/remote/redial.go @@ -140,6 +140,13 @@ type Roaming struct { // back for a reason that is not theirs. Left false, a road keeps the schedule // it always had, a fixed first pause and then the doubling. SpreadReturns bool + // EndsOn says an error from Dial is FINAL: the far end answered and said no, + // and will say it again, so the loop stops at once and the client is buried + // with that error's own words (a sign-in that was taken away, a chat that is + // gone) instead of spending the whole window repeating the question. It is + // opt-in because a fix keeps defaults: left nil, every dial error is a blip, + // as it has always been. + EndsOn func(error) bool } func (r *Roaming) window() time.Duration { @@ -511,6 +518,9 @@ func (c *Client) redial(roam *Roaming, planned bool) (Welcome, error) { first = false conn, err := roam.Dial() + if err != nil && roam.EndsOn != nil && roam.EndsOn(err) { + return Welcome{}, spokenError{reason: err.Error()} + } if err == nil { welcome, err := c.attach(conn) if err == nil { diff --git a/internal/remote/redial_final_test.go b/internal/remote/redial_final_test.go new file mode 100644 index 0000000000..4b7930d8d3 --- /dev/null +++ b/internal/remote/redial_final_test.go @@ -0,0 +1,68 @@ +package remote + +import ( + "errors" + "io" + "net" + "strings" + "sync/atomic" + "testing" + "time" +) + +// finalDial is a dial that the far end answered with a no it will keep saying: the sign-in was taken away, the chat is +// gone. +type finalDial struct{ words string } + +func (e finalDial) Error() string { return e.words } + +// roamAfterACut dials one real link, then answers every later dial with err, and cuts the first link. +func roamAfterACut(t *testing.T, ends func(error) bool, err error) (*Client, *atomic.Int32) { + t.Helper() + var dials atomic.Int32 + dialer := func() (io.ReadWriteCloser, error) { + if dials.Add(1) > 1 { + return nil, err + } + ours, theirs := net.Pipe() + engine := &scripted{t: t, conn: theirs, said: Welcome{Version: Version, SessionFile: "/j.jsonl", Persistent: true}} + go engine.serve(nil) + time.AfterFunc(50*time.Millisecond, func() { _ = ours.Close() }) + return ours, nil + } + client, derr := Roam("the server", Hello{Workspace: "app"}, Roaming{Dial: dialer, Window: 1500 * time.Millisecond, EndsOn: ends}) + if derr != nil { + t.Fatalf("roam: %v", derr) + } + t.Cleanup(func() { _ = client.Close() }) + return client, &dials +} + +// Contract RT6: a window whose link drops redials by itself, EXCEPT when the dial is answered with a no the caller +// knows to be final. Then it stops at once and says the far end's own words, so a person whose access was taken away +// reads that, and not "reconnecting for up to 30 minutes". +func TestRT6_AFinalDialRefusalEndsTheRedialAtOnceWithItsOwnWords(t *testing.T) { + refusal := finalDial{"There is no such chat."} + client, dials := roamAfterACut(t, func(err error) bool { var f finalDial; return errors.As(err, &f) }, refusal) + waitFor(t, "the client to be over", func() bool { return client.Err() != nil }) + if got := client.Err().Error(); !strings.Contains(got, refusal.words) { + t.Fatalf("a final refusal reads %q, want it to carry %q", got, refusal.words) + } + if n := dials.Load(); n != 2 { + t.Fatalf("it dialled %d times; a final refusal is asked once", n) + } +} + +// Contract RT7: left as it has always been (no EndsOn), the same refusal is a blip and the redial keeps trying until its +// window ends, because a fix keeps defaults. +func TestRT7_WithoutEndsOnTheSameRefusalIsStillRetried(t *testing.T) { + refusal := finalDial{"There is no such chat."} + client, dials := roamAfterACut(t, nil, refusal) + waitFor(t, "the client to give up", func() bool { return client.Err() != nil }) + if n := dials.Load(); n < 2 { + t.Fatalf("it dialled %d times; with no EndsOn a refused dial is tried again within the window", n) + } + if got := client.Err().Error(); strings.Contains(got, refusal.words) { + t.Fatalf("with no EndsOn the client was ended with the refusal's words %q: the old schedule says the link died", got) + } +} From 62ec6dadeb31cd1dc37b5f839b16418cc364feea Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:14 -0500 Subject: [PATCH 07/16] chat --org: a hosted chat's window comes back by itself when its link drops A terminal opened on a hosted chat ended for good when the link to the organization's server broke (a laptop that slept, a network that changed, a server that restarted), although the chat goes on running there. The window now roams: it redials as a returning window, so it does not take the keyboard from whoever holds it, and it ends at once with the server's own words when the server says the sign-in or the chat is gone (401, 403, 404). A one-shot --once run is never retried. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/chatv3_org.go | 93 ++++++++++----- cmd/codeaf/chatv3_org_redial_test.go | 165 +++++++++++++++++++++++++++ 2 files changed, 231 insertions(+), 27 deletions(-) create mode 100644 cmd/codeaf/chatv3_org_redial_test.go diff --git a/cmd/codeaf/chatv3_org.go b/cmd/codeaf/chatv3_org.go index b123098ead..da090436fa 100644 --- a/cmd/codeaf/chatv3_org.go +++ b/cmd/codeaf/chatv3_org.go @@ -459,6 +459,68 @@ func (d *orgDoor) open(ctx context.Context, id string) (net.Conn, error) { return conn, nil } +// attach opens the chat's wire and says hello on it, and answers the client and the one call that shuts it and its +// link. A WINDOW REDIALS BY ITSELF when its link drops (a laptop that slept, a network that changed, the server that +// restarted): the chat goes on running on the server whether anyone is looking, so the window comes back to it with +// nothing lost and the keyboard where it was, exactly as a window on another of the person's own computers does. +// +// THE FIRST DIAL IS NOT ROAMED, so everything that can go wrong before the surface owns the screen (no sign-in, an +// address that is down, a chat that is not theirs) is still said at once on a terminal that is still the person's. A +// headless run (roam false) is one message in a script and is never retried, because a script that waits half an hour +// for a server is worse than one that fails. A no that will not change ([orgRefusesAgain]) ends the redialling with the +// server's own words. +func (d *orgDoor) attach(ctx context.Context, id string, hello remote.Hello, roam bool) (*remote.Client, func() error, error) { + if !roam { + conn, err := d.open(ctx, id) + if err != nil { + return nil, nil, err + } + client, err := remote.Dial(conn, d.host, hello) + if err != nil { + _ = conn.Close() + return nil, nil, err + } + return client, func() error { + err := client.Close() + if shutErr := conn.Close(); err == nil { + err = shutErr + } + return err + }, nil + } + client, err := remote.Roam(d.host, hello, remote.Roaming{ + Dial: func() (io.ReadWriteCloser, error) { + conn, err := d.open(ctx, id) + if err != nil { + return nil, err + } + return conn, nil + }, + // A server that restarts drops every window at one moment, so their first retries are spread out. + SpreadReturns: true, + EndsOn: orgRefusesAgain, + }) + if err != nil { + return nil, nil, err + } + return client, client.Close, nil +} + +// orgRefusesAgain is whether a dial the server answered with a refusal will be refused the same way again: the sign-in +// was not accepted or was taken away (401, 403) or the chat is not there for this person (404). Anything else is a +// moment's trouble (the server down, a restart, no room yet) and is tried again. +func orgRefusesAgain(err error) bool { + var refused *orgDoorError + if !errors.As(err, &refused) || !refused.serverSaid { + return false + } + switch refused.status { + case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound: + return true + } + return false +} + // ── the surface ───────────────────────────────────────────────────────────── // hello is the hello this door says on a connection. THE WORKSPACE STAYS @@ -506,22 +568,10 @@ func openChatV3Org(launch orgLaunch) error { if err != nil { return err } - conn, err := door.open(ctx, id) + client, shutBoot, err := door.attach(ctx, id, launch.hello(true), launch.once == "") if err != nil { return err } - client, err := remote.Dial(conn, door.host, launch.hello(true)) - if err != nil { - _ = conn.Close() - return err - } - shutBoot := func() error { - err := client.Close() - if shutErr := conn.Close(); err == nil { - err = shutErr - } - return err - } closeLink := func() { _ = shutBoot() } defer func() { closeLink() }() @@ -535,28 +585,17 @@ func openChatV3Org(launch orgLaunch) error { // ANOTHER CONVERSATION IS ANOTHER WEBSOCKET TO THE SAME CHAT'S WIRE, with // the same bearer, and says no window of its own for [besideHello]'s reason. fleet := newEngineFleet(door.host, client, shutBoot, func(ask engineAsk) (*engineConn, error) { - next, err := door.open(ctx, id) - if err != nil { - return nil, err - } - beside, err := remote.Dial(next, door.host, remote.Hello{ + beside, shut, err := door.attach(ctx, id, remote.Hello{ Workspace: "", Session: ask.session, New: ask.mint, Model: launch.model, Level: launch.level, - }) + }, true) if err != nil { - _ = next.Close() return nil, err } - return &engineConn{client: beside, shut: func() error { - err := beside.Close() - if shutErr := next.Close(); err == nil { - err = shutErr - } - return err - }}, nil + return &engineConn{client: beside, shut: shut}, nil }) closeLink = fleet.closeAll options, _ := hostOptions(fleet, client.Welcome(), launch.pick) diff --git a/cmd/codeaf/chatv3_org_redial_test.go b/cmd/codeaf/chatv3_org_redial_test.go new file mode 100644 index 0000000000..8f6937c971 --- /dev/null +++ b/cmd/codeaf/chatv3_org_redial_test.go @@ -0,0 +1,165 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/coder/websocket" + + "github.com/Agent-Field/codeaf/internal/remote" +) + +// These tests are written from what a person sees when the link between their terminal and their organization's server +// breaks while a hosted chat is open: a laptop that slept, a network that changed, a server that restarted. The chat goes +// on running on the server whether anyone is looking, so the window must come back to it by itself. +// +// RT8 the window comes back by itself, as the same window coming back (not a new one arriving), and says nothing +// that is not true. +// RT9 a window whose access was taken away while it was gone ends at once with the server's own words, and does not +// spend half an hour saying it is reconnecting. +// RT10 one message sent from a script (--once) is never retried: the first drop ends it. + +// droppingOrg is the far end of one hosted chat that lets go of the first dropFirst links right after their welcome, and +// from refuseFrom on (when set) answers the upgrade with the server's own no. +type droppingOrg struct { + dropFirst int + refuseFrom int + + mu sync.Mutex + connections int + hellos []remote.Hello +} + +func (o *droppingOrg) wire(w http.ResponseWriter, r *http.Request) { + o.mu.Lock() + o.connections++ + n := o.connections + o.mu.Unlock() + if o.refuseFrom > 0 && n >= o.refuseFrom { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"error":"There is no such chat."}`) + return + } + socket, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) + if err != nil { + return + } + defer socket.CloseNow() + conn := websocket.NetConn(r.Context(), socket, websocket.MessageBinary) + send := func(frame remote.Frame) { + line, _ := json.Marshal(frame) + _, _ = conn.Write(append(line, '\n')) + } + scanner := bufio.NewScanner(conn) + scanner.Buffer(make([]byte, 0, 1<<20), 1<<24) + for scanner.Scan() { + var frame remote.Frame + if json.Unmarshal(scanner.Bytes(), &frame) != nil { + return + } + switch frame.Kind { + case "hello": + var hello remote.Hello + _ = json.Unmarshal(frame.Payload, &hello) + o.mu.Lock() + o.hellos = append(o.hellos, hello) + o.mu.Unlock() + welcome, _ := json.Marshal(remote.Welcome{Version: remote.Version, Workspace: "/srv/work", SessionFile: "/srv/j.jsonl", Model: "a/b", Persistent: true}) + send(remote.Frame{Kind: "welcome", Payload: welcome}) + if n <= o.dropFirst { + return + } + case "call": + send(remote.Frame{Kind: "result", ID: frame.ID}) + } + } +} + +func (o *droppingOrg) seen() (connections int, hellos []remote.Hello) { + o.mu.Lock() + defer o.mu.Unlock() + return o.connections, append([]remote.Hello(nil), o.hellos...) +} + +func orgWaitFor(t *testing.T, what string, within time.Duration, done func() bool) { + t.Helper() + deadline := time.Now().Add(within) + for time.Now().Before(deadline) { + if done() { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("timed out waiting for %s", what) +} + +func TestRT8_AnOrgWindowComesBackWhenItsLinkDrops(t *testing.T) { + orgSignedIn(t) + org := newFakeOrg(t) + far := &droppingOrg{dropFirst: 1} + org.wire = far.wire + door, _ := newDoorFor(t, org.srv.URL) + client, shut, err := door.attach(context.Background(), orgID('a'), remote.Hello{Window: true}, true) + if err != nil { + t.Fatalf("the first attach failed: %v", err) + } + defer shut() + // A redial waits a second and up to five more, so that a restarted server is not asked by every window at once. + orgWaitFor(t, "the window to come back", 20*time.Second, func() bool { + n, _ := far.seen() + return n >= 2 + }) + _, hellos := far.seen() + if len(hellos) < 2 || hellos[0].Back || !hellos[1].Back { + t.Fatalf("the window said %+v; it must come back as a returning window (back) and not as a new arrival that takes the keyboard", hellos) + } + orgWaitFor(t, "the window to be whole again", 5*time.Second, func() bool { return client.LinkNote() == "" }) + if err := client.Err(); err != nil { + t.Fatalf("a window that came back reads %v", err) + } +} + +func TestRT9_AnOrgWindowWhoseAccessWentWhileItWasGoneEndsWithTheServersWords(t *testing.T) { + orgSignedIn(t) + org := newFakeOrg(t) + far := &droppingOrg{dropFirst: 1, refuseFrom: 2} + org.wire = far.wire + door, _ := newDoorFor(t, org.srv.URL) + client, shut, err := door.attach(context.Background(), orgID('a'), remote.Hello{Window: true}, true) + if err != nil { + t.Fatalf("the first attach failed: %v", err) + } + defer shut() + orgWaitFor(t, "the window to end", 20*time.Second, func() bool { return client.Err() != nil }) + if got := client.Err().Error(); !strings.Contains(got, "There is no such chat.") { + t.Fatalf("a window whose chat went away reads %q, want the server's own words", got) + } + if n, _ := far.seen(); n != 2 { + t.Fatalf("the server was asked %d times; a no that will not change is asked once", n) + } +} + +func TestRT10_AHeadlessOrgRunIsNeverRetried(t *testing.T) { + orgSignedIn(t) + org := newFakeOrg(t) + far := &droppingOrg{dropFirst: 1} + org.wire = far.wire + door, _ := newDoorFor(t, org.srv.URL) + client, shut, err := door.attach(context.Background(), orgID('a'), remote.Hello{Headless: true}, false) + if err != nil { + t.Fatalf("the first attach failed: %v", err) + } + defer shut() + orgWaitFor(t, "the one-shot to end", 5*time.Second, func() bool { return client.Err() != nil }) + if note := client.LinkNote(); note != "" { + t.Fatalf("a one-shot says %q; it does not reconnect", note) + } +} From 442d6bdc6b2ac40e010d73cef497a244e8b8c8b6 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:48 -0500 Subject: [PATCH 08/16] deploy/org: the stack starts its own relay A `relay` service runs `codeaf relay` from the same image (role `relay`), so the computers of an organization's members can pair, see each other and open each other's chats live without the public relay. It keeps each member's device list on a volume and no chat content (the organization already keeps the hosted chats), listens on 127.0.0.1:8788 like the organization server's 8787 (CODEAF_RELAY_BIND and CODEAF_RELAY_PORT change that), and is healthy when its page for a pairing link answers, which names nobody. A relay asked to leave chats out on a codeaf that predates the switch stops in words instead of keeping them. CODEAF_ORG_RELAY_URL becomes the relay_url the organization server tells its signed-in people. The offline shell tests join the gate that already runs the other deploy/org ones. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 2 + deploy/org/.env.example | 16 +++++ deploy/org/compose.yaml | 38 ++++++++++++ deploy/org/compose_profiles_test.sh | 21 ++++++- deploy/org/relay_script_test.sh | 95 +++++++++++++++++++++++++++++ deploy/org/scripts/entrypoint.sh | 2 + deploy/org/scripts/relay.sh | 52 ++++++++++++++++ deploy/org/scripts/serve.sh | 2 + 8 files changed, 226 insertions(+), 2 deletions(-) create mode 100755 deploy/org/relay_script_test.sh create mode 100755 deploy/org/scripts/relay.sh diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index 3db6d5d578..8ddb801844 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -74,6 +74,8 @@ jobs: run: deploy/org/operator_link_test.sh - name: Compose profiles turn on the services they should run: deploy/org/compose_profiles_test.sh + - name: The relay role starts the relay the way its settings say + run: deploy/org/relay_script_test.sh - name: Planted fake secrets must fail the gate run: deploy/org/gate/selftest.sh - name: Planted files must not enter the build context diff --git a/deploy/org/.env.example b/deploy/org/.env.example index 4222aee53f..1294f95bf2 100644 --- a/deploy/org/.env.example +++ b/deploy/org/.env.example @@ -62,6 +62,22 @@ CODEAF_BIND=127.0.0.1 CODEAF_PORT=8787 AGENTFIELD_BIND=127.0.0.1 AGENTFIELD_PORT=8080 +# The organization's relay (README.md "The organization's relay"): where members' computers pair, see each other and open each other's +# chats live. It has a port of its own, and a host name of its own behind a proxy. +CODEAF_RELAY_BIND=127.0.0.1 +CODEAF_RELAY_PORT=8788 + +# --- The organization's relay --- +# The address its members' computers reach the relay on, with its scheme (https://relay.example.com), which the organization server +# tells them when they sign in and `codeaf pair --org` reads. Empty tells nobody, and the relay still runs. +CODEAF_ORG_RELAY_URL= +# Whether the relay keeps chats' content (on) or only the device list and the live traffic (off, the default: the hosted chats are +# already kept by the organization server). Turning it on makes the relay hold encrypted copies of members' own computers' chats. +CODEAF_RELAY_STORAGE=off +# on publishes GET /status, which lists the computers connected right now. Leave it off when the relay is open to the internet. +CODEAF_RELAY_STATUS=off +# on only behind a proxy that sets X-Forwarded-For (Caddy, Railway, a load balancer). +CODEAF_RELAY_TRUST_PROXY=off # --- AgentField --- # Strict run-owner proofs. Leave true. diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index 56ac0e3967..de81b1fe7c 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -21,6 +21,9 @@ x-defaults: &defaults # that build needs). The first build compiles codeaf and takes several minutes; later ones reuse Docker's layer cache. # CODEAF_BINARY_FROM=fetch downloads the pinned, checksummed release named in codeaf.Dockerfile: quick, but a release # without `codeaf sessionhost` cannot run hosted chats, so use it only when you leave them off. +# The same release has no `codeaf relay --storage` either, so the `relay` service below stops with a +# sentence saying so (CODEAF_RELAY_STORAGE=on starts it, and keeps chats), and the organization server of +# a release without `relay_url` refuses to start while CODEAF_ORG_RELAY_URL is set. # CODEAF_BINARY_FROM=local takes a codeaf you built yourself and put beside this file as `codeaf-local`. # FLIP THE DEFAULT BACK TO `fetch` when the release pinned in codeaf.Dockerfile (CODEAF_RELEASE) ships the sessionhost. The # check that tells you is that release's own binary: `codeaf sessionhost --help` says "there is no `codeaf sessionhost`" while @@ -98,6 +101,10 @@ services: CODEAF_SERVER_KEY: ${CODEAF_SERVER_KEY:-} # The git hosts a chat's clone and push may reach through this server, comma separated origins (default https://github.com). CODEAF_HOSTED_GIT_HOSTS: ${CODEAF_HOSTED_GIT_HOSTS:-} + # The address of THIS organization's relay (the `relay` service below) as its members' computers reach it, with its scheme: + # https://relay.example.com. The server tells every sign-in page and `codeaf pair --org` about it. Empty advertises none, + # and the relay still runs. It is only an address people are told, never a secret. + CODEAF_ORG_RELAY_URL: ${CODEAF_ORG_RELAY_URL:-} volumes: [codeaf-data:/data] # The default network reaches every service; `hosted` is the one the hosted chats' machine is on. networks: [default, hosted] @@ -135,6 +142,36 @@ services: start_period: 60s retries: 10 + # --- The relay: where members' computers pair, see each other and open each other's chats live ------------------- + # `codeaf relay`, the program the public relay is a copy of, so the organization's people need nothing outside it. It has no + # secret and no account list (any computer with a valid signature may make an identity: README.md "The organization's relay" + # says what that means for who may reach it). It keeps each member's device list in its volume, and NO chat content unless + # CODEAF_RELAY_STORAGE=on: the hosted chats are already kept by `codeaf`, and a second copy here would be a duplicate. It + # listens on its own port, and wants its own host name behind a proxy: its requests are signed with their path, so it cannot + # sit under a prefix of the organization server's address. + relay: + <<: *defaults + image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} + build: *codeaf-build + command: ["relay"] + environment: + CODEAF_RELAY_STORAGE: ${CODEAF_RELAY_STORAGE:-off} + # on publishes GET /status, which says which computers are connected right now: leave it off on an open network. + CODEAF_RELAY_STATUS: ${CODEAF_RELAY_STATUS:-off} + # on only behind a proxy that sets X-Forwarded-For (Caddy, Railway, a load balancer): the relay then limits callers by their + # real address. Anywhere else a caller could name any address it liked. + CODEAF_RELAY_TRUST_PROXY: ${CODEAF_RELAY_TRUST_PROXY:-off} + volumes: [relay-data:/data] + ports: ["${CODEAF_RELAY_BIND:-127.0.0.1}:${CODEAF_RELAY_PORT:-8788}:8788"] + healthcheck: + # The relay's own page for a pairing link answers 200 to any code and holds nothing, so it is a health path that tells no one + # who is connected. + test: ["CMD-SHELL", "curl -fsS -o /dev/null http://127.0.0.1:8788/p/health"] + interval: 15s + timeout: 5s + start_period: 10s + retries: 5 + # --- Reasoner nodes --------------------------------------------------------------------------- swe-af: <<: *defaults @@ -255,6 +292,7 @@ volumes: agentfield-data: codeaf-data: runner-data: + relay-data: swe-af-workspaces: pr-af-workspaces: sessions-data: diff --git a/deploy/org/compose_profiles_test.sh b/deploy/org/compose_profiles_test.sh index f6ab8f283a..18c33d661e 100755 --- a/deploy/org/compose_profiles_test.sh +++ b/deploy/org/compose_profiles_test.sh @@ -31,8 +31,8 @@ stub=$(services --profile stub) hosted_stub=$(services --profile hosted --profile stub) gitstub=$(services --profile gitstub) -row 'no profile: the five services, no stub and no sessionhost' \ - bash -c '[ "$1" = "agentfield codeaf pr-af runner swe-af " ]' _ "$plain" +row 'no profile: the six services (the relay among them), no stub and no sessionhost' \ + bash -c '[ "$1" = "agentfield codeaf pr-af relay runner swe-af " ]' _ "$plain" row 'stub turns the scripted model on and not the git host' \ bash -c 'case " $1" in *" modelstub "*) ;; *) exit 1 ;; esac; case " $1" in *" gitstub "*) exit 1 ;; esac' _ "$stub" row 'stub with hosted adds the sessionhost and still not the git host' \ @@ -41,4 +41,21 @@ row 'gitstub is its own profile' has "$gitstub" gitstub row 'the smoke test asks for the gitstub profile when it runs the hosted part' \ grep -q -- '--profile hosted --profile gitstub' smoke.sh +# The relay is bound the way the organization server is: on this machine alone unless the operator says otherwise, with a port +# of its own that the operator can change, and it keeps no chat content unless asked to. +service_json() { # SERVICE EXPRESSION: a Python expression over that service's resolved settings `r` + # shellcheck disable=SC2086 + $DC --env-file .env.example config --format json | + python3 -c 'import json, sys; r = json.load(sys.stdin)["services"][sys.argv[1]]; p = r["ports"][0] if r.get("ports") else {}; print(eval(sys.argv[2]))' "$1" "$2" +} +relay_words='" ".join([p["host_ip"], p["published"], str(p["target"]), r["environment"]["CODEAF_RELAY_STORAGE"], r["command"][0]])' +row 'the relay listens on 127.0.0.1:8788 and keeps no chats by default' \ + bash -c '[ "$1" = "127.0.0.1 8788 8788 off relay" ]' _ "$(service_json relay "$relay_words")" +row 'its bind, its port and its storage are the operator'"'"'s to change' \ + bash -c '[ "$1" = "0.0.0.0 9788 8788 on relay" ]' _ \ + "$(CODEAF_RELAY_BIND=0.0.0.0 CODEAF_RELAY_PORT=9788 CODEAF_RELAY_STORAGE=on service_json relay "$relay_words")" +row 'the organization server is told the relay address the operator names' \ + bash -c '[ "$1" = "https://relay.example.com" ]' _ \ + "$(CODEAF_ORG_RELAY_URL=https://relay.example.com service_json codeaf 'r["environment"]["CODEAF_ORG_RELAY_URL"]')" + exit "$failed" diff --git a/deploy/org/relay_script_test.sh b/deploy/org/relay_script_test.sh new file mode 100755 index 0000000000..2ee1d54911 --- /dev/null +++ b/deploy/org/relay_script_test.sh @@ -0,0 +1,95 @@ +#!/usr/bin/env bash +# Checks, offline, what the organization's relay is started with (scripts/relay.sh) and what the organization server is told about it +# (scripts/serve.sh). A stand-in `codeaf` writes down its arguments instead of running, so nothing here starts a server or needs Docker. +set -eu +cd "$(dirname "$0")" +here=$PWD +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir "$work/bin" +cat >"$work/bin/codeaf" <<'STUB' +#!/bin/sh +# `codeaf relay --help` is how relay.sh asks whether this build has the --storage switch (STUB_OLD=1 is a build from before it). +if [ "$*" = "relay --help" ]; then + echo "usage: codeaf relay [--listen host:port] [--store path]" + [ "${STUB_OLD:-}" = 1 ] || echo " --storage on|off off keeps the device list and refuses chat uploads (default on)" + exit 0 +fi +printf '%s\n' "$*" >"$STUB_OUT" +STUB +chmod +x "$work/bin/codeaf" + +failed=0 +row() { + local name=$1 + shift + if "$@"; then + printf 'PASS: %s\n' "$name" + else + printf 'FAIL: %s\n' "$name" + failed=1 + fi +} + +# relay_args VAR=value...: the arguments relay.sh gave `codeaf`, with every variable it reads cleared first. +relay_args() { + rm -f "$work/out" + env -u PORT -u CODEAF_RELAY_LISTEN -u CODEAF_RELAY_STORE -u CODEAF_RELAY_STORAGE -u CODEAF_RELAY_STATUS -u CODEAF_RELAY_TRUST_PROXY \ + PATH="$work/bin:$PATH" STUB_OUT="$work/out" CODEAF_RELAY_STORE="$work/store" "$@" sh "$here/scripts/relay.sh" 2>"$work/err" || return 1 + cat "$work/out" +} +has() { [[ " $1 " == *" $2 "* ]]; } +lacks() { ! has "$1" "$2"; } + +default=$(relay_args) +row 'relay: with nothing set it keeps the device list, not the chats, and publishes no status' \ + bash -c '[ "$1" = "relay --listen 0.0.0.0:8788 --store $2 --storage off --status=false" ]' _ "$default" "$work/store" +row 'relay: its store folder is made' test -d "$work/store" + +on=$(relay_args CODEAF_RELAY_STORAGE=on CODEAF_RELAY_STATUS=on CODEAF_RELAY_TRUST_PROXY=on) +row 'relay: storage on drops --storage off' lacks "$on" '--storage' +row 'relay: status on drops --status=false' lacks "$on" '--status=false' +row 'relay: trust-proxy on passes --trust-proxy' has "$on" '--trust-proxy' +row 'relay: trust-proxy is off by default' lacks "$default" '--trust-proxy' + +row 'relay: a platform that names the port (Railway sets PORT) is listened on' \ + has "$(relay_args PORT=9100)" '--listen 0.0.0.0:9100' +row 'relay: CODEAF_RELAY_LISTEN wins over PORT' \ + has "$(relay_args PORT=9100 CODEAF_RELAY_LISTEN=127.0.0.1:7000)" '--listen 127.0.0.1:7000' +row 'relay: the words are not case sensitive' \ + lacks "$(relay_args CODEAF_RELAY_STORAGE=ON)" '--storage' + +# A typo stops the service with a sentence; it never starts with the opposite setting. +refuses() { + local out + if out=$(relay_args "$1=maybe" 2>/dev/null); then return 1; fi + grep -q "$1 is on or off" "$work/err" && [ ! -e "$work/out" ] +} +for var in CODEAF_RELAY_STORAGE CODEAF_RELAY_STATUS CODEAF_RELAY_TRUST_PROXY; do + row "relay: $var=maybe is refused in words and nothing starts" refuses "$var" +done + +# A codeaf from before --storage cannot leave chats out, so a relay asked to leave them out stops in words; one asked to keep them does not need it. +old_build_refuses() { + local out + if out=$(relay_args STUB_OLD=1 2>/dev/null); then return 1; fi + grep -q 'older than the relay' "$work/err" && grep -q 'CODEAF_BINARY_FROM=source' "$work/err" && [ ! -e "$work/out" ] +} +row 'relay: a codeaf with no --storage switch stops in words when the relay is to keep no chats' old_build_refuses +row 'relay: a codeaf with no --storage switch still starts a relay that keeps the chats' \ + lacks "$(relay_args STUB_OLD=1 CODEAF_RELAY_STORAGE=on)" '--storage' + +# serve.sh: the organization server writes the relay it advertises into its config, and only when there is one. +serve_config() { + rm -f "$work/out" + env -u CODEAF_ORG_RELAY_URL -u CODEAF_FACTORY_TOKEN PATH="$work/bin:$PATH" STUB_OUT="$work/out" \ + CODEAF_HOME="$work/home" CODEAF_ORG_NAME=Acme "$@" sh "$here/scripts/serve.sh" || return 1 + cat "$work/home/factory/config.yaml" +} +told=$(serve_config CODEAF_ORG_RELAY_URL=https://relay.example.com) +row 'serve: an advertised relay is written to the server config' \ + bash -c 'printf "%s\n" "$1" | grep -qxF "relay_url: \"https://relay.example.com\""' _ "$told" +none=$(serve_config) +row 'serve: with none named the config says nothing about one' bash -c '! printf "%s" "$1" | grep -q relay' _ "$none" + +exit "$failed" diff --git a/deploy/org/scripts/entrypoint.sh b/deploy/org/scripts/entrypoint.sh index d0a7774af3..1cdd72b12c 100755 --- a/deploy/org/scripts/entrypoint.sh +++ b/deploy/org/scripts/entrypoint.sh @@ -2,6 +2,7 @@ # The codeaf image's entrypoint. The first argument picks the role: # server the organization server, `codeaf factory serve`, in team mode # runner the factory runner that connects the organization's work to AgentField +# relay the organization's relay, `codeaf relay`: where its members' computers pair, see each other and open each other's chats # sessionhost the machine hosted chats run on (stays root: see below) # run that command as given (a shell, `codeaf --help`) set -eu @@ -20,5 +21,6 @@ ORG_UID=10001 ORG_HOME=/home/codeaf ORG_DIRS="/data" . /opt/org/drop-root.sh case "$role" in server) exec /opt/org/serve.sh "$@" ;; runner) exec python3 /opt/org/runner.py "$@" ;; + relay) exec /opt/org/relay.sh "$@" ;; *) exec "$role" "$@" ;; esac diff --git a/deploy/org/scripts/relay.sh b/deploy/org/scripts/relay.sh new file mode 100755 index 0000000000..a4341b55b5 --- /dev/null +++ b/deploy/org/scripts/relay.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# The organization's relay (role `relay`): `codeaf relay`, the service its members' computers pair through, see each other +# through and open each other's chats live through, so none of that needs the public one. It is a role of the codeaf image, +# not an image of its own, and it speaks plain HTTP: the platform (Railway, Caddy, a load balancer) serves the HTTPS in front of it. +# +# WHAT IT KEEPS. The device list and the chats' places, which are small, in $CODEAF_RELAY_STORE (a volume: without it a restart +# makes every member's computers forget each other). It does NOT keep chat content unless CODEAF_RELAY_STORAGE=on, because the +# organization's hosted chats are already kept by the organization server and a second copy of them here would be a duplicate. +# Every setting arrives as a variable; nothing here is secret. +set -eu + +port="${PORT:-8788}" +listen="${CODEAF_RELAY_LISTEN:-0.0.0.0:$port}" +store="${CODEAF_RELAY_STORE:-/data/relay}" +mkdir -p "$store" + +# One word each, so a typo stops the service with a sentence instead of starting it with the opposite setting. +word() { # NAME DEFAULT: the variable's value, lower case, or the default when it is empty + eval "v=\${$1:-}" + [ -n "$v" ] || v="$2" + printf '%s' "$v" | tr 'A-Z' 'a-z' +} +storage=$(word CODEAF_RELAY_STORAGE off) +status=$(word CODEAF_RELAY_STATUS off) +proxy=$(word CODEAF_RELAY_TRUST_PROXY off) + +set -- --listen "$listen" --store "$store" +case "$storage" in + off) + # A codeaf from before the switch would stop at "flag provided but not defined", which says nothing of why; and starting it + # without the switch would keep chats the operator said to leave out. So it stops here, in words. + if ! codeaf relay --help 2>&1 | grep -q -- '--storage'; then + echo "relay: this codeaf is older than the relay's --storage switch, so it cannot leave chats out. Build the image from this checkout (CODEAF_BINARY_FROM=source), or set CODEAF_RELAY_STORAGE=on to keep them here." >&2 + exit 2 + fi + set -- "$@" --storage off ;; + on) ;; + *) echo "relay: CODEAF_RELAY_STORAGE is on or off, not '$storage'" >&2; exit 2 ;; +esac +case "$status" in + on|1|true|yes) ;; + off|0|false|no) set -- "$@" --status=false ;; + *) echo "relay: CODEAF_RELAY_STATUS is on or off, not '$status'" >&2; exit 2 ;; +esac +case "$proxy" in + on|1|true|yes) set -- "$@" --trust-proxy ;; + off|0|false|no) ;; + *) echo "relay: CODEAF_RELAY_TRUST_PROXY is on or off, not '$proxy'" >&2; exit 2 ;; +esac + +echo "relay: listening on $listen; keeping its device list in $store; chat storage $storage" >&2 +exec codeaf relay "$@" diff --git a/deploy/org/scripts/serve.sh b/deploy/org/scripts/serve.sh index 0826f776c4..bbdf65f5a0 100755 --- a/deploy/org/scripts/serve.sh +++ b/deploy/org/scripts/serve.sh @@ -30,6 +30,8 @@ fi echo "access_token: \"$token\"" [ -n "$domain" ] && echo "domain: $domain" [ -n "${CODEAF_GITHUB_CLIENT_ID:-}" ] && echo "github_client_id: ${CODEAF_GITHUB_CLIENT_ID}" + # The relay this organization runs for its members' computers (the `relay` service): told to everyone who is signed in. + [ -n "${CODEAF_ORG_RELAY_URL:-}" ] && echo "relay_url: \"${CODEAF_ORG_RELAY_URL}\"" if [ -n "${CODEAF_TRUSTED_PROXIES:-}" ]; then echo "trusted_proxies:" echo "$CODEAF_TRUSTED_PROXIES" | tr ',' '\n' | while read -r p; do From a20dbf513b4d072978fd409509932c952de5cab1 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:48 -0500 Subject: [PATCH 09/16] deploy/org/railway: the template carries the relay service make-template.sh adds the relay as a seventh image-sourced service in its relay role, with its own volume and public domain on its own port, Railway's edge trusted, storage and the connected-computers page off, a /p/health check, and tells the codeaf service its address (CODEAF_ORG_RELAY_URL) once the domain exists. The offline tests pin each of those calls and the new counts of volumes and edits. Railway itself is not touched. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/railway/make-template.sh | 24 ++++++++++++++- deploy/org/railway/railway_scripts_test.sh | 34 ++++++++++++++++++---- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh index 4651e744b2..e25270937c 100755 --- a/deploy/org/railway/make-template.sh +++ b/deploy/org/railway/make-template.sh @@ -2,7 +2,7 @@ # Makes a DRAFT Railway template of the org stack from the PUBLISHED IMAGES (README.md "Published images"). # # ./make-template.sh dry run: prints every Railway call it would make, changes nothing (the default) -# ./make-template.sh --apply makes a fresh source project, adds the six services from their images, and turns +# ./make-template.sh --apply makes a fresh source project, adds the seven services from their images, and turns # the project into an UNPUBLISHED template draft in your workspace # # ORG_REGISTRY=agentfield ORG_TAG=dev which images (the same two variables as images.env); a 12-character commit id @@ -207,6 +207,28 @@ hosted_url='http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790' check_var CODEAF_HOSTED_URL "$hosted_url" rail variable set "CODEAF_HOSTED_URL=$hosted_url" --service codeaf --skip-deploys +# --- relay: the organization's own relay, `codeaf relay` in the same image. Members' computers pair through it, see each other +# and open each other's chats live, so none of that needs the public relay. It needs a public domain of its own on its own port +# (its requests are signed with their path, so it cannot sit under the organization server's address), and Railway's edge in front +# of it, which is why it trusts X-Forwarded-For. Chat storage is off: the hosted chats are already kept by `codeaf`. It keeps the +# device list, in its volume. /p/health is the page the relay serves for any pairing code, so it answers 200 and says nothing about +# who is connected; GET /status stays off for the same reason (the relay is open to the internet). +service relay "$CODEAF_IMAGE" \ + CODEAF_ROLE=relay \ + PORT=8788 \ + CODEAF_RELAY_STORAGE=off \ + CODEAF_RELAY_STATUS=off \ + CODEAF_RELAY_TRUST_PROXY=on +volume_add relay /data +rail environment edit --service-config relay deploy.healthcheckPath /p/health --message "relay health check" +rail domain --service relay --port 8788 --json + +# The address the organization server tells its people to pair through. Railway can resolve this reference once the relay has its +# domain, and it is only an address, never a secret. +relay_url='https://${{relay.RAILWAY_PUBLIC_DOMAIN}}' +check_var CODEAF_ORG_RELAY_URL "$relay_url" +rail variable set "CODEAF_ORG_RELAY_URL=$relay_url" --service codeaf --skip-deploys + # --- runner: the factory runner, the same image in its runner role. -------------------------------------------------------------------- service runner "$CODEAF_IMAGE" \ CODEAF_ROLE=runner \ diff --git a/deploy/org/railway/railway_scripts_test.sh b/deploy/org/railway/railway_scripts_test.sh index ce07b9c3ab..953f10c4f7 100755 --- a/deploy/org/railway/railway_scripts_test.sh +++ b/deploy/org/railway/railway_scripts_test.sh @@ -80,6 +80,30 @@ hosted_url_after_service() { row 'make-template 3: codeaf gets the hosted URL after sessionhost exists' hosted_url_after_service row 'make-template 4: codeaf health check uses /v1/about' \ grep -qxF "+ railway environment edit --service-config codeaf deploy.healthcheckPath /v1/about --message 'codeaf health check'" "$plan" +# The organization's relay: a seventh service, the same image in its relay role, with a public domain of its own, and the address +# the organization server tells its people. +relay=$(grep -F '+ railway add --service relay ' "$plan" || true) +relay_variables() { + local pair + [[ $relay == *'--image agentfield/codeaf-org:dev '* ]] || return 1 + for pair in 'CODEAF_ROLE=relay' 'PORT=8788' 'CODEAF_RELAY_STORAGE=off' 'CODEAF_RELAY_STATUS=off' 'CODEAF_RELAY_TRUST_PROXY=on'; do + [[ $relay == *"--variables $pair "* ]] || return 1 + done +} +row 'make-template 7: relay is the codeaf image in its relay role, storage and status off, trusting the proxy' relay_variables +row 'make-template 7: relay keeps its device list on a /data volume' \ + grep -qxF "+ railway volume --service '' add --mount-path /data --json" "$plan" +row 'make-template 7: relay health check is /p/health, which names nobody' \ + grep -qxF "+ railway environment edit --service-config relay deploy.healthcheckPath /p/health --message 'relay health check'" "$plan" +row 'make-template 7: relay has a public domain on its own port' \ + grep -qxF '+ railway domain --service relay --port 8788 --json' "$plan" +org_relay_url_after_domain() { + local line + line=$(grep -nFx "+ railway variable set 'CODEAF_ORG_RELAY_URL=https://\${{relay.RAILWAY_PUBLIC_DOMAIN}}' --service codeaf --skip-deploys" "$plan") && + grep -qxF '+ railway domain --service relay --port 8788 --json' < <(head -n "$(( ${line%%:*} - 1 ))" "$plan") && + [[ $codeaf != *CODEAF_ORG_RELAY_URL=* ]] +} +row 'make-template 7: codeaf is told the relay address after the relay has its domain' org_relay_url_after_domain template_excludes_smoke_switches() { ! grep -Eq -- '--variables (RUNNER_SELFTEST|SMOKE_FIXTURE_REPO|SWE_SMOKE_FIXTURE_REPO|CODEAF_BASE_URL|STUB_DELAY|STUB_COST_USD|GITSTUB_TOKEN)=' "$plan" } @@ -156,13 +180,13 @@ row 'make-template 6: --apply runs to the end against the current CLI' apply_ok volumes_by_id() { apply_ok || return 1 local want - for want in agentfield:/data codeaf:/data sessionhost:/chats runner:/data swe-af:/workspaces pr-af:/workspaces; do + for want in agentfield:/data codeaf:/data sessionhost:/chats relay:/data runner:/data swe-af:/workspaces pr-af:/workspaces; do local name=${want%%:*} mount=${want#*:} add vol add=$(grep -nF "[add][--service][$name][--image]" "$FAKE_RAILWAY_LOG" | head -n 1 | cut -d: -f1) && vol=$(grep -nxF "[volume][--service][id-$name][add][--mount-path][$mount][--json]" "$FAKE_RAILWAY_LOG" | head -n 1 | cut -d: -f1) && [ "$add" -lt "$vol" ] || return 1 done - [ "$(grep '^\[volume\]' "$FAKE_RAILWAY_LOG" | grep -vc '\[--help\]')" = 6 ] + [ "$(grep '^\[volume\]' "$FAKE_RAILWAY_LOG" | grep -vc '\[--help\]')" = 7 ] } row 'make-template 6: each volume is added with its service ID, after the service exists, and never as volume add --service' volumes_by_id @@ -177,14 +201,14 @@ every_edit_has_a_message() { local edits messages edits=$(grep -c '^\[environment\]\[edit\]' "$FAKE_RAILWAY_LOG") messages=$(grep '^\[environment\]\[edit\]' "$FAKE_RAILWAY_LOG" | grep -c '\[--message\]') - [ "$edits" = 3 ] && [ "$messages" = 3 ] + [ "$edits" = 4 ] && [ "$messages" = 4 ] } -row 'make-template 6: all three environment edits carry --message' every_edit_has_a_message +row 'make-template 6: all four environment edits carry --message' every_edit_has_a_message older_cli_keeps_working() { apply_with FAKE_RAILWAY_STYLE=old [ "$status" = 0 ] && - [ "$(grep -c '^\[volume\]\[add\]\[--service\]' "$FAKE_RAILWAY_LOG")" = 6 ] && + [ "$(grep -c '^\[volume\]\[add\]\[--service\]' "$FAKE_RAILWAY_LOG")" = 7 ] && grep -qxF '[volume][add][--service][sessionhost][--mount-path][/chats][--json]' "$FAKE_RAILWAY_LOG" && ! grep -q '^\[volume\]\[--service\]' "$FAKE_RAILWAY_LOG" } From d09e00376475b66422994e7a08a3abae33e9a21d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:15:19 -0500 Subject: [PATCH 10/16] manual: remote control and the organization, and a hosted chat that reconnects Two pages say what a person with an organization can expect: which chats remote control reaches (their own computers' chats, not the organization's hosted ones, which have their own access), who reads as typing in a shared chat, and what the terminal does when its link to the server breaks (reconnects for up to five minutes, ends at once with the server's words when access went, never retries a --once run, and that the desktop window does not reconnect yet). Four probes in a person's own words reach them. Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/organization-hosted-sessions.md | 10 ++++++++++ internal/manual/chat/remote-control.md | 8 ++++++++ internal/manual/chat_test.go | 4 ++++ 3 files changed, 22 insertions(+) diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 26c632ade6..c15e8b2577 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -156,6 +156,14 @@ An idle chat stops its own program after a while and starts it again, with its c If the machine that runs chats restarts, its running processes end and its files stay. Your first attach afterwards works: the organization's server notices the machine lost your chat's model access and hands over new access before anything is sent. If the organization's server restarts instead, the chats keep working and so does the access they hold. +## my terminal lost its connection to the organization's server — reconnecting, my laptop slept, the wifi changed, the window ended, I lost access while I was gone + +A `codeaf chat --org` window whose connection breaks, because the laptop slept, the network changed or the server restarted, comes back by itself and says `reconnecting to — trying for up to 5 minutes` while it tries. The chat kept running on the server the whole time. When the connection is back the window carries on where it stopped: what the chat said while you were gone is there and a turn that was running is still running. A message sent while it is reconnecting is refused with `reconnecting to — try that again in a moment`, so send it again once the window is back. A window that comes back does not take the keyboard from another window of yours that took it meanwhile; press enter there to take it back. + +If the server says no while you were gone, because the chat is no longer yours or your sign-in was taken away, the window ends at once with the server's own sentence, for example `There is no such chat.`, and does not keep trying. After those 5 minutes with nothing it gives up and says the connection ended; run `codeaf chat --org --session hs_...` to open the chat again. One message sent from a script with `--once` is never retried: if the connection breaks, it ends. + +The desktop app's organization window does not reconnect by itself yet: open the chat again from the list. + ## how many chats can I have on the server at once — limits and waiting The operator sets how many chats may run at once, and how many one person may have running. When you are over your own limit you read: `You already have 2 chats running; stop one first.` (the number is the operator's). When the whole server is full you read: `Waiting for a free slot (3 of 3 in use).` Try again in a moment, or stop a chat you are not using. @@ -198,6 +206,8 @@ Personal never sees the organization's chats, files or people, and an organizati Only if you shared the chat with a role that holds `run` (the `edit` and `full` roles do), and even then one window writes at a time. While you have the chat open with the keyboard, a message or a redirect from your teammate is refused by the chat with its own sentence about the keyboard. It goes through once you close your window, or after they take the keyboard (a person who may send can), which tells your window. Interrupting a turn and answering a question are not held up. Whatever they send runs as you: in your folder, with your GitHub identity and your spending limits, and a command that needs approval waits for you, unless the organization's policy lets people who answer allow one (see *can someone I shared my hosted chat with approve a command*). +Every other window of the chat reads WHO has the keyboard by name: `typing from mia now · enter types here`, with the name the organization knows the person by, never a name their own computer picked, so nobody can appear to be the owner or another member. A bot reads as `abir's bot`, the person whose rights it uses. + ## the organization's server is down or my sign-in ended — a hosted chat never runs on my computer instead If the server cannot be reached, the desktop window says ` is unreachable.` once, with **Try again**, and the chat stays where it is. If your sign-in is missing or has ended it says `Sign in to first.` In neither case does the app start a chat on your computer in its place: a hosted chat never falls back to running locally. A turn that was already running on the server goes on without you, and the conversation is there when the server answers again. diff --git a/internal/manual/chat/remote-control.md b/internal/manual/chat/remote-control.md index 57d0b6f355..eac7130edc 100644 --- a/internal/manual/chat/remote-control.md +++ b/internal/manual/chat/remote-control.md @@ -74,6 +74,14 @@ While two of your computers connect directly, each learns the other's network ad `CODEAF_REMOTE_STUN` replaces the two servers with your own, as a comma list of `host:port`, and `off` asks none, which still connects two computers on one network. Turning remote control off turns all of this off. +## Remote control and my organization — does it work for my organization's chats, hosted chats, shared chats, my team, several of my computers in an organization + +Remote control is for the chats **your own computers** run. An organization's chats are not those. A chat in an organization's account runs on the organization's own server, and every window of it, on this computer, on another of your computers or in the desktop app, connects to that server and not to your other computers. So the switch under **Settings** and the `w` and `t` switches in `/devices` do not apply to them, turning remote control off does not close a window on one, and a chat in your personal account is never listed in an organization's account or the other way round. + +What a person may do in an organization's chat is set per chat, by sharing it. Its owner may do everything. Someone it is shared with watches it live, and types, steers or answers only if their role holds `run`, `steer` or `answer`; the page *what can someone I shared my hosted chat with do* has the list. A person your chat is shared with is not one of your paired computers and cannot open your other chats. + +Several of your computers can have the same organization chat open. Each is a window, one of them has the keyboard and the others read `typing from now · enter types here`, the same rule as *Who has the keyboard*: the window that opened last takes it, and `enter` in another takes it back. In a chat shared with people the name is the person's, as the organization knows them. Which server carries the live views between your own computers is chosen the way pairing chooses it (`CODEAF_SYNC_URL`, or the address a pairing saved), and every computer you pair has to use the same one; joining an organization does not change that. + ## Who has the keyboard — two computers on one chat, take the keyboard, typing from another computer Only one computer types into a live chat at a time. The other one shows: diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index c66d6f93fa..6fc02de532 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3980,6 +3980,10 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"remote control says restart codeaf on the other computer", "remote-control"}, {"do I need to restart codeaf after I turn remote control on", "remote-control"}, {"I turned remote control on in settings but enter still asks to move the chat", "remote-control"}, + {"does remote control work for the chats in my organization", "remote-control"}, + {"my organization's chat is open on two of my computers and I cannot tell which one has the keyboard", "remote-control"}, + {"my codeaf chat --org window lost its connection when my laptop went to sleep", "organization-hosted-sessions"}, + {"in a shared hosted chat who is typing right now", "organization-hosted-sessions"}, {"after I open a chat live from my other computer Home's project is a folder that does not exist on this computer", "remote-control"}, {"does opening a chat live change the project on home", "remote-control"}, {"is remote control the same as codeaf serve and --at", "remote-control"}, From bbd707856ebc6fba19496942cb22d0e79280afc6 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 10:50:48 -0500 Subject: [PATCH 11/16] deploy/org/smoke: prove the stack's relay carries what members need New relay and relay-after sections, run in the codeaf container with no CODEAF_SYNC_URL anywhere: the relay answers its health page and does not list who is connected, the organization tells a signed-in owner where its relay is and a stranger nothing, and two throwaway computers pair with `codeaf pair --org` and `codeaf pair --via`, each lists the other in `codeaf devices` and names the organization's relay, and the second kept the address it was told. smoke.sh adds what only the relay's volume shows (it started with chat storage off, it holds the device list and no chat content), and after the restart of every service the two computers still see each other. Opening a chat live needs a terminal, which the image has none of, so SMOKE_RELAY_LIVE=1 runs the Go test TestOrgRelayE2E on the host against the stack's published relay. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.env.stub | 3 + deploy/org/scripts/smoke.py | 137 +++++++++++++++++++++++++++++++++++- deploy/org/smoke.sh | 27 ++++++- 3 files changed, 164 insertions(+), 3 deletions(-) diff --git a/deploy/org/.env.stub b/deploy/org/.env.stub index 04e2d1fcc3..1cb40cc62f 100644 --- a/deploy/org/.env.stub +++ b/deploy/org/.env.stub @@ -7,3 +7,6 @@ ORG_MODEL=stub/scripted SWE_DEFAULT_MODEL=openrouter/stub/scripted PR_AF_MODEL=stub/scripted SWE_SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture +# The organization's relay, as the organization server tells its people and as the smoke test's throwaway computers reach it (the service's +# network name, so it works with nothing published on the host). +CODEAF_ORG_RELAY_URL=http://relay:8788 diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index fee8b14438..300bcebcb1 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -29,6 +29,12 @@ the operator's metadata, a bot's chats and its creator's rights, the hosting policy hosted-p2-after (in the codeaf container, after every service restarted) the shares and the privacy are what they were + relay (in the codeaf container, after `org`) the organization's own relay answers its health page, the organization + server tells a signed-in person where it is and a stranger nothing, and two throwaway computers pair through it + with `codeaf pair --org` and see each other: nothing here uses the public relay + relay-after (in the codeaf container, after every service restarted) those two computers still see each other, because the + relay kept its device list on its volume + An organization server takes a password only over https or from its own machine, so `org` and `after-org` run inside the codeaf container with ORG_URL=http://127.0.0.1:8787 (smoke.sh does). @@ -43,6 +49,7 @@ import os import re import secrets +import shutil import socket import subprocess import sys @@ -1760,17 +1767,143 @@ def hosted_p2_after(): check(f'P2-1 {who} still has none of it after the restart', chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared') and got[0] == 404, short(got, 160)) +# --------------------------------------------------------------------------------------------- +# The organization's relay (the `relay` service). Every check goes through the real client doors a member uses: the relay's own HTTP +# address, `codeaf pair --org ` on one throwaway computer and `codeaf pair --via
` on another, +# and `codeaf devices` on each, with no CODEAF_SYNC_URL anywhere, so the only way a computer finds this relay is by being told. +# What only the machine itself can show (the volume's contents) is checked by smoke.sh. The live view of a chat over this relay is +# not driven here: it needs a terminal, which this container does not have, so smoke.sh hands it to the Go test +# internal/e2e/org_relay_e2e_test.go when SMOKE_RELAY_LIVE=1. +RELAY = (os.environ.get('RELAY_URL') or os.environ.get('CODEAF_ORG_RELAY_URL') or 'http://relay:8788').rstrip('/') +RELAY_HOMES = Path(os.environ.get('SMOKE_RELAY_HOMES', '/tmp/smoke-relay')) +RELAY_NAMES = {'desk': 'desktop', 'lap': 'laptop'} + + +def relay_env(home, token=''): + env = {k: v for k, v in os.environ.items() if not k.startswith(('CODEAF_', 'AGENTFIELD_', 'OPENROUTER_', 'OPENAI_'))} + env.update(HOME=str(RELAY_HOMES / home), CODEAF_HOME=str(RELAY_HOMES / home / 'codeaf'), CODEAF_TELEMETRY='off', + DO_NOT_TRACK='1', CODEAF_NO_UPDATE_CHECK='1') + if token: + env['CODEAF_ORG_TOKEN'] = token + return env + + +class Lines: + """What a command prints, read as it comes, so a script can wait for a line while the command waits for it. It reads bytes and not + lines, because a question that is waiting for its answer has no newline after it.""" + + def __init__(self, proc): + self.proc, self.chunks = proc, [] + threading.Thread(target=self._read, daemon=True).start() + + def _read(self): + fd = self.proc.stdout.fileno() + while True: + data = os.read(fd, 4096) + if not data: + return + self.chunks.append(data.decode(errors='replace')) + + def text(self): + return ''.join(self.chunks) + + +def relay_devices(home): + """`codeaf devices` on one throwaway computer: (exit status, what it printed).""" + done = subprocess.run(['codeaf', 'devices'], cwd=RELAY_HOMES / home, env=relay_env(home), stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=90) + return done.returncode, done.stdout + done.stderr + + +def relay_sees(home, other): + """Waits until `codeaf devices` on one computer lists the other by name, and says which relay it asked.""" + last = [] + + def listed(): + status, out = relay_devices(home) + last[:] = [status, out] + return status == 0 and other in out and out + + got = wait_until(listed, 90, every=3) + return bool(got), (got or (last[1] if last else '')) + + +def relay(): + print("--- the organization's relay") + code, _ = http('GET', RELAY + '/p/health') + check('the relay answers its health page', code == 200, f'{code}') + code, _ = http('GET', RELAY + '/status') + check('and does not say which computers are connected', code in (403, 404), f'{code}') + token = sign_in('owner') + if not check('the operator signs in to the organization', bool(token)): + return + want = os.environ.get('CODEAF_ORG_RELAY_URL', '').rstrip('/') + code, profile = http('GET', ORG + '/v1/org', token) + told = (profile or {}).get('relay') if isinstance(profile, dict) else None + check('the organization tells a signed-in person where its relay is', code == 200 and bool(want) and told == want, f'{code} relay={told}') + code, bare = http('GET', ORG + '/v1/org') + check('and tells nobody who is not signed in', code in (401, 403) and 'relay' not in json.dumps(bare), f'{code}') + + shutil.rmtree(RELAY_HOMES, ignore_errors=True) + for home in RELAY_NAMES: + (RELAY_HOMES / home).mkdir(parents=True) + offer = subprocess.Popen(['codeaf', 'pair', '--org', ORG, '--name', RELAY_NAMES['desk'], '--code'], cwd=RELAY_HOMES / 'desk', + env=relay_env('desk', token), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + shown = Lines(offer) + command = wait_until(lambda: re.search(r'codeaf pair (\d{1,4}-\d{3}-\d{3}) --via (\S+)', shown.text()), 90, every=1) + check('`codeaf pair --org` shows a code, and the relay it names is the organization\'s own', + bool(command) and command.group(2).rstrip('/') == want, short(shown.text(), 300) if not command else command.group(2)) + if not command: + offer.kill() + return + join = subprocess.Popen(['codeaf', 'pair', '--name', RELAY_NAMES['lap'], command.group(1), '--via', command.group(2)], + cwd=RELAY_HOMES / 'lap', env=relay_env('lap'), stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True) + joined = Lines(join) + asked = wait_until(lambda: 'wants your chats' in shown.text(), 90, every=1) + check('the first computer is asked whether the second may have its chats', bool(asked), short(shown.text(), 300)) + if asked: + offer.stdin.write('y\n') + offer.stdin.flush() + ends = [] + for name, proc in (('the first', offer), ('the second', join)): + try: + ends.append((name, proc.wait(timeout=90))) + except subprocess.TimeoutExpired: + proc.kill() + ends.append((name, 'timed out')) + check('both computers finish pairing', bool(asked) and all(status == 0 for _, status in ends), + f'{ends} offer={short(shown.text(), 200)} join={short(joined.text(), 200)}') + for home, other in (('desk', RELAY_NAMES['lap']), ('lap', RELAY_NAMES['desk'])): + ok, said = relay_sees(home, other) + host = urlparse(want).netloc + check(f'the {RELAY_NAMES[home]} lists the {other} and says it uses the organization\'s relay', ok and host in said, short(said, 240)) + saved = (RELAY_HOMES / 'lap' / 'codeaf' / 'sync-url') + check('the second computer remembered the relay it was told, so no variable is needed from now on', + saved.exists() and saved.read_text().strip().rstrip('/') == want, saved.read_text().strip() if saved.exists() else 'no file') + + +def relay_after(): + print("--- the organization's relay after a restart") + code, _ = http('GET', RELAY + '/p/health') + check('the relay answers its health page again', code == 200, f'{code}') + for home, other in (('desk', RELAY_NAMES['lap']), ('lap', RELAY_NAMES['desk'])): + ok, said = relay_sees(home, other) + check(f'the {RELAY_NAMES[home]} still lists the {other}: the relay kept its device list', ok, short(said, 240)) + + def main(): parser = argparse.ArgumentParser() parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org', 'hosted-prepare', 'hosted-seed', 'hosted', 'hosted-host', 'hosted-after', 'hosted-leftovers', 'hosted-p1', 'hosted-p1-host', 'hosted-p1-restart', 'hosted-p1-bearer', 'hosted-p1-after', - 'hosted-p2-prepare', 'hosted-p2', 'hosted-p2-after']) + 'hosted-p2-prepare', 'hosted-p2', 'hosted-p2-after', 'relay', 'relay-after']) parser.add_argument('--operator-link', default='') args = parser.parse_args() for name, run in (('control', control), ('job', job), ('org', lambda: org(args.operator_link)), ('after', after), ('after-org', after_org), ('hosted-prepare', hosted_prepare), ('hosted-seed', hosted_seed), ('hosted', hosted), ('hosted-host', hosted_host), ('hosted-after', hosted_after), ('hosted-leftovers', hosted_leftovers), ('hosted-p1', hosted_p1), ('hosted-p1-host', hosted_p1_host), ('hosted-p1-restart', hosted_p1_restart), ('hosted-p1-bearer', hosted_p1_bearer), - ('hosted-p1-after', hosted_p1_after), ('hosted-p2-prepare', hosted_p2_prepare), ('hosted-p2', hosted_p2), ('hosted-p2-after', hosted_p2_after)): + ('hosted-p1-after', hosted_p1_after), ('hosted-p2-prepare', hosted_p2_prepare), ('hosted-p2', hosted_p2), ('hosted-p2-after', hosted_p2_after), + ('relay', relay), ('relay-after', relay_after)): if args.section == name or (args.section == 'all' and name in ('control', 'job')): run() print('RESULT ' + ('PASS' if failures == 0 else f'FAIL ({failures} check(s) failed)')) diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index ef636d72ee..82bbce03b2 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -6,7 +6,10 @@ # 3. the operator link claims the organization; a second person joins by invite; # 4. a factory job reaches SWE-AF through AgentField, with strict run-owner proofs on; its plan # question reaches the owner, and the answer resumes the run; -# 5. a restart of every service, then: still registered, still holding the runs and the people. +# 5. the organization's own relay (the `relay` service): it answers, the organization tells its people where it is, two throwaway +# computers pair through it with `codeaf pair --org` and see each other, and it keeps no chat content; +# 6. a restart of every service, then: still registered, still holding the runs and the people, and the two computers still +# see each other through the relay. # Afterwards the stack keeps running against the stub. `docker compose up -d` puts your own keys back. # # ./smoke.sh @@ -14,6 +17,11 @@ # COMPOSE='docker compose -p other' picks another project; SMOKE_ENV='--env-file x' adds an env file; # SMOKE_BUILD=--no-build uses the images that are already there (the default builds what changed). # +# SMOKE_RELAY_LIVE=1 adds what needs a terminal, so it runs on THIS machine and not in a container: the Go test +# internal/e2e/org_relay_e2e_test.go points two throwaway computers at the stack's relay (published on the host by +# CODEAF_RELAY_BIND and CODEAF_RELAY_PORT), pairs them through it, opens a chat the first is running on the second, types into it +# and checks the relay stored none of it. It needs Go, tmux and a built bin/codeaf (`make build` at the repository root). +# # SMOKE_HOSTED_ONLY=1 runs only the hosted-chats part, on the three services it needs (codeaf, sessionhost, # modelstub): no AgentField, no nodes, no runner. It implies SMOKE_HOSTED=1. # @@ -61,6 +69,22 @@ link=$(COMPOSE="$DC" ./operator-link.sh) # a secret: it is passed on, never pr [ "$FULL" = 1 ] && run runner '' control run codeaf '-e ORG_URL=http://127.0.0.1:8787' org --operator-link "$link" +if [ "$FULL" = 1 ]; then + echo "== the organization's relay" + run codeaf '-e ORG_URL=http://127.0.0.1:8787' relay + # What only the relay's own volume can show: it said it leaves chats out, it kept the two computers' device list, and it holds no + # chat content at all. + if $DC logs relay 2>&1 | grep -q 'chat storage off'; then echo 'PASS the relay started with chat storage off'; else echo 'FAIL the relay did not start with chat storage off' >&2; bad=1; fi + if $DC exec -T relay sh -c 'ls /data/relay/directory 2>/dev/null | grep -q "\.db$"'; then echo 'PASS the relay keeps its device list on its volume'; else echo 'FAIL the relay has no device list on its volume' >&2; bad=1; fi + held=$($DC exec -T relay sh -c 'find /data/relay/blobs -type f 2>/dev/null | wc -l' | tr -d '[:space:]') + if [ "$held" = 0 ]; then echo 'PASS the relay holds no chat content'; else echo "FAIL the relay holds $held file(s) of chat content" >&2; bad=1; fi + if [ "${SMOKE_RELAY_LIVE:-0}" = 1 ]; then + echo '== two computers pair through the relay and open a chat live (Go test, on this machine)' + relay_at=$($DC port relay 8788 | head -n 1 | sed 's/^0\.0\.0\.0:/127.0.0.1:/') + if [ -z "$relay_at" ]; then echo 'FAIL the relay has no published port to reach from this machine' >&2; bad=1 + elif ! (cd ../.. && CODEAF_E2E_ORG_RELAY="http://$relay_at" go test -tags e2e -count=1 -run TestOrgRelayE2E -timeout 20m -v ./internal/e2e/); then bad=1; fi + fi +fi if [ "$HOSTED" = 1 ]; then echo '== hosted chats' run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-prepare @@ -106,6 +130,7 @@ $DC restart $SERVICES $DC up -d --wait --wait-timeout 600 $SERVICES [ "$FULL" = 1 ] && run runner '' after run codeaf '-e ORG_URL=http://127.0.0.1:8787' after-org +[ "$FULL" = 1 ] && run codeaf '-e ORG_URL=http://127.0.0.1:8787' relay-after if [ "$HOSTED" = 1 ]; then $DC exec -T sessionhost python3 $SMOKE hosted-leftovers || bad=1 run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-after From a583d85f7877219d20ac6f42763758bc92e3eb1b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 12:11:58 -0500 Subject: [PATCH 12/16] e2e: two computers pair through the organization's relay and one opens the other's chat live TestOrgRelayE2E starts the relay the way the organization stack does (deploy/org/scripts/relay.sh, storage off), points two throwaway homes at it with no CODEAF_SYNC_URL anywhere, pairs them with the saved relay, and has one open the other's running chat live and type into it (remote control on, the rig's scripted model). It then asserts the relay was never asked to keep a chat and its folder holds the device lists and no chat file. CODEAF_E2E_ORG_RELAY points it at a relay that is already running instead, which is how smoke.sh runs it against the compose relay with SMOKE_RELAY_LIVE=1. Co-Authored-By: Claude Sonnet 5.5 --- internal/e2e/org_relay_e2e_test.go | 322 +++++++++++++++++++++++++++++ 1 file changed, 322 insertions(+) create mode 100644 internal/e2e/org_relay_e2e_test.go diff --git a/internal/e2e/org_relay_e2e_test.go b/internal/e2e/org_relay_e2e_test.go new file mode 100644 index 0000000000..9054ccb531 --- /dev/null +++ b/internal/e2e/org_relay_e2e_test.go @@ -0,0 +1,322 @@ +//go:build e2e + +package e2e + +// org_relay_e2e_test.go is THE KEYLESS PROOF THAT AN ORGANIZATION'S OWN RELAY CARRIES EVERYTHING THE PUBLIC ONE DOES, driven as a +// member would drive it: the relay that deploy/org starts (its role script, scripts/relay.sh, with nothing set but the port and +// where to keep its files, so these are the defaults an operator gets), two computers that have never heard of any other relay, +// the real binary in real terminals, and a model that is a script. +// +// - The relay answers its health page, and says nothing of which computers are connected. +// - One computer offers a code with `codeaf pair --via ` and another joins with the line it is told +// to type. `--via` is what `codeaf pair --org ` runs once it has looked the address up (cmd/codeaf/pair_org.go +// has its own tests for the lookup), and from then on NO WINDOW OF THIS TEST SETS CODEAF_SYNC_URL: each computer finds the +// relay only because the pairing told it, which is how a member's computer finds it on the day after. +// - The relay says it keeps no chats, and the computers believe it by themselves: nothing here writes their storage answer, so a +// relay that answered "on" (or said nothing) would have them upload and be refused, and the test would fail on the disk. +// - A chat the first computer is running opens live on the second, a line typed there reaches the first, and both show the +// reply. Nothing the viewer does needs an upload. +// - When the relay is this test's own, its folder holds the two computers' device list and not one byte of a chat. +// +// CODEAF_E2E_ORG_RELAY=
points the test at a relay that is already running, such as the one in the deploy/org stack +// (smoke.sh does it with SMOKE_RELAY_LIVE=1), instead of starting one. The folder checks are then skipped, because they need the +// relay's disk; everything else is asked of it over the wire. +// +// IT SKIPS RATHER THAN FAILS without tmux or bin/codeaf, like every scenario in this package: +// +// go test -tags e2e -count=1 -run TestOrgRelayE2E -v ./internal/e2e/ + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/devname" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/relay" + "github.com/Agent-Field/codeaf/internal/syncsetup" +) + +// orgRelayEnv names the relay a run is pointed at when it should not start its own. +const orgRelayEnv = "CODEAF_E2E_ORG_RELAY" + +func TestOrgRelayE2E(t *testing.T) { + rcRequire(t) + rc, store := newOrgRelayRig(t) + + // Pairing: the first computer offers, the second types what it is told. Neither has a relay variable. + if _, err := devname.Set(rc.host.home, rcHostName); err != nil { + t.Fatal(err) + } + offer := startCommand(t, orgRelayEnvOf(rc), "org-offer", rc.host.home, rc.host.work, "pair", "--via", rc.address, "--code") + var code string + if !waitUntil(30*time.Second, func() bool { + code = rcCodeShape.FindString(offer.capture()) + return code != "" + }) { + t.Fatalf("pair --code never showed a code:\n%s", offer.capture()) + } + if !strings.Contains(offer.capture(), "--via "+rc.address) { + t.Errorf("the offering computer did not tell the other one which relay to use:\n%s", offer.capture()) + } + join := startCommand(t, orgRelayEnvOf(rc), "org-join", rc.viewers[0].home, rc.viewers[0].work, "pair", "--name", rcViewerName, "--via", rc.address, code) + offer.waitFor(30*time.Second, "wants your chats") + rc.abortIfFailed() + offer.lit("y") + offer.keys("Enter") + join.waitFor(30*time.Second, "Paired") + rc.abortIfFailed() + + // Each computer remembers the relay it was paired through, so no variable is needed from here on. + for _, h := range rc.homes() { + saved, err := os.ReadFile(filepath.Join(h.home, syncsetup.SavedURLFile)) + if err != nil || strings.TrimRight(strings.TrimSpace(string(saved)), "/") != rc.address { + t.Errorf("%s did not keep the relay it was paired through (%q, %v)", h.name, saved, err) + } + } + id, err := identity.Load(rc.host.home) + if err != nil { + t.Fatalf("the pairing left the host with no identity: %v", err) + } + rc.identity = id.ID() + + // The relay said storage is off and the computers took its word: a person never turned it off on either. + host := rc.startHost2() + rc.hostAsk(host, rcHostAsk, rcHostReply) + for _, h := range rc.homes() { + h := h + if !waitUntil(60*time.Second, func() bool { return syncsetup.StorageState(h.home, rc.address, rc.identity) == "off" }) { + t.Errorf("%s never learned from the relay that chat storage is off (it believes %q)", h.name, syncsetup.StorageState(h.home, rc.address, rc.identity)) + } + } + rc.abortIfFailed() + // From here on, nothing may ask the relay to keep a chat. + rc.audit.armed.Store(true) + + viewer := rc.startViewer2(0) + rc.openLive(viewer) + rc.send(viewer, rcLaptopAsk) + viewer.waitFor(rcReplyWithin, rcLaptopReply) + host.waitFor(rcReplyWithin, rcLaptopReply) + rc.assertLiveDial() + + if store != "" { + orgRelayHoldsNoChats(t, store) + } +} + +// orgRelayHoldsNoChats checks the relay's own folder: the device list the two computers made is there, and no file of chat content is. +func orgRelayHoldsNoChats(t *testing.T, store string) { + t.Helper() + if dbs, _ := filepath.Glob(filepath.Join(store, "directory", "*.db")); len(dbs) == 0 { + t.Errorf("the relay kept no device list under %s", store) + } + var held []string + _ = filepath.Walk(filepath.Join(store, "blobs"), func(path string, info os.FileInfo, err error) error { + if err == nil && info.Mode().IsRegular() { + held = append(held, path) + } + return nil + }) + if len(held) > 0 { + t.Errorf("the relay holds chat content with storage off: %d file(s), first %s", len(held), held[0]) + } +} + +// newOrgRelayRig builds the world of this scenario: a short root under /tmp, the scripted model, the organization's relay behind a +// proxy that writes down what it sees (and, unlike remote control's, answers nothing on the relay's behalf), and two homes that +// have no identity and have never been told a relay. The second answer is the relay's own folder, or "" for a relay that was not +// started here. +func newOrgRelayRig(t *testing.T) (*rcRig, string) { + t.Helper() + root, err := os.MkdirTemp("/tmp", "org-relay-e2e-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(root) }) + t.Setenv("CODEAF_TELEMETRY", "off") + t.Setenv("DO_NOT_TRACK", "1") + // A relay variable in the person's own shell must not decide which relay this scenario's computers use. + t.Setenv(syncsetup.URLVar, "") + + rc := &rcRig{t: t, root: root, model: startRCModel(t)} + upstream, store := os.Getenv(orgRelayEnv), "" + if upstream == "" { + upstream, store = startOrgRelayRole(t, root) + } + orgRelayAnswersItsHealthPage(t, upstream) + rc.address, rc.audit = startPlainAuditProxy(t, upstream) + + rc.host = rcHome{name: rcHostName, home: filepath.Join(root, "h"), work: filepath.Join(root, "hw")} + rc.viewers = []rcHome{{name: rcViewerName, home: filepath.Join(root, "v0"), work: filepath.Join(root, "vw0")}} + for _, h := range rc.homes() { + if err := os.MkdirAll(h.home, 0o700); err != nil { + t.Fatal(err) + } + workspaceAt(t, h.work, false) + rc.writeConfig(h.home) + } + // Engines belong to these temporary homes, including any a move brings along. + t.Cleanup(func() { + pids := engineDaemonsUnder(root) + for _, pid := range pids { + _ = syscall.Kill(pid, syscall.SIGTERM) + } + deadline := time.Now().Add(10 * time.Second) + for _, pid := range pids { + for !terminalProcessExited(pid) && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if !terminalProcessExited(pid) { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + } + }) + return rc, store +} + +// startOrgRelayRole starts the relay the way the deploy/org stack does, by running its role script with the product's own binary +// on the path. Only the port, the address to listen on and the folder are given; the script's defaults decide storage, the status +// page and the proxy, so a default that changed under the operator changes this scenario too. It answers the relay's address and +// its folder. +func startOrgRelayRole(t *testing.T, root string) (string, string) { + t.Helper() + script := filepath.Join(repoRoot(t), "deploy", "org", "scripts", "relay.sh") + if _, err := os.Stat(script); err != nil { + t.Skipf("no relay role script at %s", script) + } + bin := filepath.Join(root, "bin") + if err := os.MkdirAll(bin, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(binary(t), filepath.Join(bin, "codeaf")); err != nil { + t.Fatal(err) + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := ln.Addr().String() + _ = ln.Close() + store := filepath.Join(root, "relay-store") + + var env []string + for _, kv := range os.Environ() { + if !strings.HasPrefix(kv, "CODEAF_RELAY_") && !strings.HasPrefix(kv, "PORT=") { + env = append(env, kv) + } + } + env = append(env, "PATH="+bin+string(os.PathListSeparator)+os.Getenv("PATH"), "CODEAF_RELAY_LISTEN="+addr, + "CODEAF_RELAY_STORE="+store, "CODEAF_HOME="+filepath.Join(root, "relay-home"), "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1") + cmd := guardedCommand(t, context.Background(), filepath.Join(root, "relay-home"), env, "sh", script) + log, err := os.Create(filepath.Join(root, "relay.log")) + if err != nil { + t.Fatal(err) + } + cmd.Stdout, cmd.Stderr = log, log + if err := cmd.Start(); err != nil { + _ = log.Close() + t.Fatal(err) + } + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); _ = log.Close() }) + // The port is open before the relay is ready to answer, so ask for the page that says it is. + if !waitUntil(30*time.Second, func() bool { + resp, err := http.Get("http://" + addr + "/p/health") + if err != nil { + return false + } + _ = resp.Body.Close() + return resp.StatusCode == http.StatusOK + }) { + raw, _ := os.ReadFile(filepath.Join(root, "relay.log")) + t.Fatalf("the relay role never answered its health page on %s:\n%s", addr, raw) + } + return "http://" + addr, store +} + +// orgRelayAnswersItsHealthPage is what the stack's health check asks, and what it must not say: which computers are connected. +func orgRelayAnswersItsHealthPage(t *testing.T, address string) { + t.Helper() + get := func(path string) int { + resp, err := http.Get(address + path) + if err != nil { + t.Fatalf("GET %s%s: %v", address, path, err) + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + return resp.StatusCode + } + if got := get("/p/health"); got != http.StatusOK { + t.Errorf("the relay's health page answered %d, not 200", got) + } + if os.Getenv(orgRelayEnv) == "" { + if got := get("/status"); got != http.StatusNotFound && got != http.StatusForbidden { + t.Errorf("the relay publishes which computers are connected (GET /status answered %d) when nobody asked it to", got) + } + } +} + +// startPlainAuditProxy is remote control's auditing proxy without its fiction: every request is written down, and every +// answer is the relay's own, including the storage answer, which is the point of this scenario. +func startPlainAuditProxy(t *testing.T, upstreamAddress string) (string, *rcAudit) { + t.Helper() + upstream, err := url.Parse(upstreamAddress) + if err != nil { + t.Fatal(err) + } + proxy := httputil.NewSingleHostReverseProxy(upstream) + audit := &rcAudit{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audit.mu.Lock() + audit.calls = append(audit.calls, rcCall{method: r.Method, path: r.URL.Path, door: r.Header.Get(relay.HeaderDoor)}) + audit.mu.Unlock() + if r.Method == http.MethodPost && r.URL.Path == "/v1/store/frames" && audit.armed.Load() { + audit.storeWrites.Add(1) + } + if r.Header.Get(relay.HeaderDoor) == relay.DoorLive { + w = &rcCountedWriter{ResponseWriter: w, total: &audit.live} + } + proxy.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + t.Cleanup(func() { + if n := audit.storeWrites.Load(); n > 0 { + t.Errorf("a computer asked the relay to keep a chat %d time(s) after it had said storage is off: %s", n, audit.summary()) + } + }) + return server.URL, audit +} + +// orgRelayEnvOf is what every window of this scenario runs with: the rig's environment minus the one variable that names a relay, +// because the point is that the pairing is what tells a computer which relay to use. +func orgRelayEnvOf(rc *rcRig) []string { + var env []string + for _, kv := range rc.env() { + if !strings.HasPrefix(kv, syncsetup.URLVar+"=") { + env = append(env, kv) + } + } + return env +} + +// startHost2 and startViewer2 are the rig's windows with that environment, numbered the same way. +func (rc *rcRig) startHost2() *rig { return rc.orgWindow("host", rc.host) } + +func (rc *rcRig) startViewer2(i int) *rig { return rc.orgWindow("viewer", rc.viewers[i]) } + +func (rc *rcRig) orgWindow(name string, h rcHome) *rig { + rc.t.Helper() + rc.windows++ + return startWithEnv(rc.t, orgRelayEnvOf(rc), fmt.Sprintf("org-%s-%d", name, rc.windows), h.home, h.work, 180, 55) +} From 1e1a4be2eacb33db6489fba1054d45ce71c4f0cd Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 12:12:17 -0500 Subject: [PATCH 13/16] docs: the organization stack runs a relay, and how members use it deploy/org/README.md gains the operator's walkthrough (the relay service, its own name and https, CODEAF_ORG_RELAY_URL, the CODEAF_RELAY_* settings, what is and is not kept, that the relay has no list of people), and docs/organizations.md and docs/relay.md name the service, the --storage flag and `codeaf pair --org`. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 137 ++++++++++++++++++++++++++++++++++++------ docs/organizations.md | 3 +- docs/relay.md | 10 +++ 3 files changed, 131 insertions(+), 19 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 6ece69c938..4b6ba02386 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -10,6 +10,7 @@ walkthrough for running one yourself. - [Start it](#start-it) - [Claim the organization, invite a second person](#claim-the-organization-invite-a-second-person) (and [HTTPS for other people](#other-people-https)) - [Real work](#real-work) +- [The organization's relay](#the-organizations-relay): [what members do](#what-members-do), [turning it on for other people](#turning-it-on-for-other-people), [who can reach it](#who-can-reach-it) - [The keyless smoke test](#the-keyless-smoke-test) - [Hosted chats (optional)](#hosted-chats-optional): [keys, spend and git](#keys-spend-and-git-p1), [sharing, guests and bots](#sharing-guests-and-bots-p2), [turning it on](#turning-it-on) - [State, backups and upgrades](#state-backups-and-upgrades) @@ -23,12 +24,14 @@ walkthrough for running one yourself. One `docker compose up` brings up everything an organization needs, on your own machine or server: the **organization server** people join with their codeaf desktop app, the **AgentField** control plane that routes work, and the reasoner nodes the factory sends work to, **SWE-AF** (builds an -issue into a pull request) and **PR-AF** (reviews one). Hosted chats (the **sessionhost**, below) are an +issue into a pull request) and **PR-AF** (reviews one), and the organization's own **relay**, so its members' computers +pair, see each other and open each other's chats live without the public relay. Hosted chats (the **sessionhost**, below) are an opt-in profile of the same file. Nothing in an image is a secret; model keys come from your environment. | Service | What it is | Published port | State (volume) | Runs as | | --- | --- | --- | --- | --- | | `codeaf` | the organization server, `codeaf factory serve` in team mode | `127.0.0.1:8787` | `codeaf-data` | uid 10001 | +| `relay` | the organization's relay, `codeaf relay` from the same image: where members' computers pair, see each other and open each other's chats live; see "The organization's relay" | `127.0.0.1:8788` | `relay-data` | uid 10001 | | `agentfield` | the AgentField control plane (published image, pinned by digest) | `127.0.0.1:8080` | `agentfield-data` | uid 65532 | | `runner` | the factory runner: a codeaf engine that registers the factory on AgentField as the node `codeaf-factory` | none | `runner-data` | uid 10001 | | `swe-af` | SWE-AF, node `swe-planner`, dials AgentField over its node link | none | `swe-af-workspaces` | uid 10002 | @@ -37,22 +40,22 @@ opt-in profile of the same file. Nothing in an image is a secret; model keys com | `modelstub` | a scripted model, only with `--profile stub` (the keyless smoke test) | none | none | nonroot | | `gitstub` | a scripted git host, only with `--profile gitstub`; `smoke.sh` turns it on with the hosted part and makes the token it will not start without | none | none | root (a test stub) | -A plain `docker compose up` starts the first five; the other three need their profile. +A plain `docker compose up` starts the first six; the other three need their profile. Apart from the `sessionhost` and the `gitstub` test stub, every container starts as root only long enough to hand a freshly mounted volume to its user, then drops to that user (`scripts/drop-root.sh`, or the control plane's own entrypoint); the `sessionhost` stays root on purpose, because it has to become a different Linux user for every chat (see "Hosted chats"). Published ports listen on 127.0.0.1 until you change `CODEAF_BIND` / `AGENTFIELD_BIND` in `.env`. -Ports 8787 (`codeaf`) and 8080 (`agentfield`) must be free on the host: if one is taken, `docker compose up` stops with -`port is already allocated` and leaves the services it had not reached created but not started. Set `CODEAF_PORT` or -`AGENTFIELD_PORT` in `.env` (the template lists both) and run it again; the services reach each other over Compose's own +Ports 8787 (`codeaf`), 8788 (`relay`) and 8080 (`agentfield`) must be free on the host: if one is taken, `docker compose up` stops with +`port is already allocated` and leaves the services it had not reached created but not started. Set `CODEAF_PORT`, `CODEAF_RELAY_PORT` or +`AGENTFIELD_PORT` in `.env` (the template lists all three) and run it again; the services reach each other over Compose's own network, so AgentField's host port is only for you to look at it. -State is in six named volumes, one per row that names one. There are two networks: `default`, which every service +State is in seven named volumes, one per row that names one. There are two networks: `default`, which every service but the `sessionhost` is on, and `hosted`, which only `codeaf` and the `sessionhost` share. ## What you need - Docker with Compose v2.24 or newer (`docker compose version`), `git`, about 4 GB of free memory and 5 GB of disk, and - ports 8787 and 8080 free on the host (see "What it runs"). + ports 8787, 8788 and 8080 free on the host (see "What it runs"). - For anyone to sign in with a password, **you on the machine running Compose included**: **HTTPS**. An organization server takes a password only over HTTPS or from its own machine, and a request through Docker's published port does not count as its own machine, so put a proxy that serves HTTPS in front of port 8787 (see "Other people", and "Trying it on one machine"). @@ -205,6 +208,90 @@ models; the defaults are inexpensive. A factory job runs on the pipeline a repos `.codeaf/factory.yaml` (a step of `kind: agentfield` with `target: swe-planner.build_issue` sends it to SWE-AF), and SWE-AF pauses at its plan so the owner can approve it or ask for changes. +## The organization's relay + +A **relay** is the small server a person's computers go through to find each other: it carries the pairing of a new computer, tells +each computer which of the person's others are online, and carries the live view and drive of a chat that runs on another of their +computers. The public one is run by the codeaf project. The `relay` service of this stack is a copy of it that **your organization +runs**, so none of that depends on anything outside it, and a member who is told its address needs nothing else. + +It is the same program, `codeaf relay`, in the same image (role `relay`, `scripts/relay.sh`). It keeps each member's **device list** (the +computers they have paired and their names) in the `relay-data` volume, so a restart does not make every computer forget the others. It +keeps **no chat content**: with `CODEAF_RELAY_STORAGE=off`, the default, it says so, and members' computers keep their chats where they +are and stop asking it to store them. A second copy of every chat would be a duplicate, because this server already keeps the hosted ones. +`CODEAF_RELAY_STORAGE=on` makes it keep encrypted copies of the chats of members' own computers, which is what the public relay does for an +account that has asked for it. + +### What members do + +Nothing about the relay needs to be set by hand. A member who has the organization's sign-in for the command line (`CODEAF_ORG_TOKEN`, +or `codeaf attach
--token `: the same one `codeaf chat --org` uses) pairs a computer with: + +```sh +laptop$ codeaf pair --org https://org.example.com --code # shows a code and the line to type on the other computer +desktop$ codeaf pair --via +``` + +`--org` asks the organization server which relay it runs (`GET /v1/org`, answered only to someone signed in) and then pairs exactly as +`--via ` does: both computers remember the relay, and from then on every start of them uses it. Presence, Move, and the live +view of a chat another computer is running all go through it. A few rules keep it from surprising anyone: + +- **An explicit `CODEAF_SYNC_URL` always wins**, a relay's address or `off`; `off` stops a pairing even with `--org`. +- **Bring your own relay** still works: `codeaf pair --via https://relay.mine.example` pairs through that one, and nothing asks the + organization anything. A computer that never says `--org` asks no organization anything, so nobody's relay moves unless they typed it. +- **Personal use is unchanged.** Someone who is not pairing through this organization keeps the public relay exactly as before. +- `--org` and `--via` together are refused: each names the relay, so use one. An organization that names no relay says so and pairs + nothing; an address that is not a web address, or is plain `http` when the organization was reached over `https`, is refused too. + +`codeaf devices` on a paired computer says which relay it is using (`relay: (your own)`). + +### Turning it on for other people + +The relay starts with the rest of the stack and answers `http://127.0.0.1:8788/p/health` (its page for a pairing link, the same for every +code, so it tells no one who is connected). For members' computers it needs a **name of its own with HTTPS**, the way the organization +server does, and a **different name from the server's**: a relay's requests are signed with their path, so it cannot sit under a prefix of +another address. With Caddy on the same host: + +``` +relay.example.com { reverse_proxy 127.0.0.1:8788 } +``` + +```sh +# .env +CODEAF_ORG_RELAY_URL=https://relay.example.com +CODEAF_RELAY_TRUST_PROXY=on # only behind a proxy that sets X-Forwarded-For, as this one does +``` + +`CODEAF_ORG_RELAY_URL` is the address members' computers reach the relay on, with its scheme. The organization server writes it into its +config as `relay_url` and tells it to everyone signed in. Left empty, the relay still runs and nobody is told about it, so people can +still pair through it with `--via`. The other settings, all in `.env.example`: + +| Variable | Default | What it does | +| --- | --- | --- | +| `CODEAF_RELAY_BIND`, `CODEAF_RELAY_PORT` | `127.0.0.1`, `8788` | where the host publishes the relay, like `CODEAF_BIND` and `CODEAF_PORT` for the server | +| `CODEAF_ORG_RELAY_URL` | empty | the address the organization server tells its signed-in people | +| `CODEAF_RELAY_STORAGE` | `off` | `on` keeps members' own computers' chats, encrypted, in `relay-data` | +| `CODEAF_RELAY_STATUS` | `off` | `on` publishes `GET /status`, which lists the computers connected right now: leave it off on an open network | +| `CODEAF_RELAY_TRUST_PROXY` | `off` | `on` counts the address a proxy forwards, for the relay's limits | + +### Who can reach it + +**The relay has no list of who may use it.** It does not know your organization's people: a computer that makes a valid signature may make +an identity of its own and use the relay's pairing, device list and live road, as it may on the public one. What it sees is machine names, +times and sealed bytes it cannot read, and a stranger gets exactly as much from it as their own computers. If that is not acceptable for +the organization, keep the relay on a private network (a VPN, a firewall allow list or an address only the office can reach) and give that +address as `CODEAF_ORG_RELAY_URL`; the stack publishes it on `127.0.0.1` until you change `CODEAF_RELAY_BIND`. + +**When members see "cannot agree on changes right now".** The relay keeps its device list in a small database, and if that database's +disk stalls or fails, the relay stops answering for it (HTTP 503) until it is restarted: `docker compose restart relay`. The health page +`/p/health` still answers, because it asks nothing of the database, so it tells you the process is up and not that the list is. This was +seen once on a disk that was starved of IO and not reproduced on three clean ones; the relay's log says `relay unavailable` with the cause. + +**What is not covered.** A relay that is lost takes the device lists with it: members would pair their computers again (back up +`relay-data` with the other volumes if that matters). The release that `CODEAF_BINARY_FROM=fetch` downloads has neither `codeaf relay +--storage` nor `relay_url`, so with it the `relay` service stops with a sentence saying so, and an organization server that is given +`CODEAF_ORG_RELAY_URL` refuses to start; use the default build (`source`), or published images from after this change. + ## The keyless smoke test ```sh @@ -219,13 +306,23 @@ that is already claimed it stops at that step. To go from a smoke run to a real - every service is healthy; AgentField, SWE-AF, PR-AF and the factory are registered; PR-AF answers a call; - the operator link claims the organization once, a second person joins by invite, roles are enforced; +- the organization's relay answers its health page and does not list who is connected, the organization tells a signed-in person its + address and a stranger nothing, two throwaway computers pair through it with `codeaf pair --org` and see each other in + `codeaf devices`, the relay says it keeps no chats and its volume holds the device list and no chat content; - a factory job reaches SWE-AF through AgentField with **strict run-owner proofs on**, its plan question reaches the owner, "ask for changes" resumes the run, and rejecting the plan ends it; AgentField's proof counters agree; -- after `docker compose restart`, the nodes register again and AgentField, the runs and the people are all still there. +- after `docker compose restart`, the nodes register again and AgentField, the runs and the people are all still there, and the two + computers still see each other through the relay. The stub's answers are minimal schema-valid text, so the "work" is not real. `docker compose up -d` afterwards puts your own keys back. +Opening a chat live needs a terminal, which no container here has, so that part is a Go test that runs **on your machine** against the +stack's relay: `SMOKE_RELAY_LIVE=1 ./smoke.sh` (needs Go, `tmux` and a built `bin/codeaf`, `make build` at the repository root) runs +`go test -tags e2e -run TestOrgRelayE2E ./internal/e2e/` with `CODEAF_E2E_ORG_RELAY` set to the relay's published address. Two throwaway +computers pair through the relay with `--via`, one runs a chat, the other opens it live and types into it, and the test checks that the +relay stored none of it. Run without that variable the same test starts its own relay from `scripts/relay.sh`. + ## Hosted chats (optional) An organization is its own account in the desktop app, separate from a person's personal one. With hosted chats @@ -518,8 +615,8 @@ Landlock (`"mode": "uid+fence"`, `"fence_mode": "landlock"`). ## State, backups and upgrades -State lives in six named volumes (`docker volume ls`; each name is the Compose project's name, `codeaf-org` unless you set `-p` or -`COMPOSE_PROJECT_NAME`, then `_` and the volume, as below): `agentfield-data`, `codeaf-data`, +State lives in seven named volumes (`docker volume ls`; each name is the Compose project's name, `codeaf-org` unless you set `-p` or +`COMPOSE_PROJECT_NAME`, then `_` and the volume, as below): `agentfield-data`, `codeaf-data`, `relay-data` (the relay's device list), `runner-data`, `swe-af-workspaces`, `pr-af-workspaces`, and `sessions-data` (the hosted chats' folders, used only with the `hosted` profile). `docker compose down` keeps them, `docker compose down -v` deletes them. The organization server's own state (its people, access links, spend and sealed keys) is in `codeaf-data` and the hosted chats' folders are in @@ -695,7 +792,7 @@ tag and digest together. ## Railway -The same Dockerfiles run on Railway as one project: six services (seven with the keyless model stub), a volume on each but +The same Dockerfiles run on Railway as one project: seven services (eight with the keyless model stub), a volume on each but the model stub, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository's source, on Railway's builders. The table below is the configuration by hand. It was followed from an empty project, with the keyless stub, and every service came up: see "Check it" below. (A Railway template needs images, not a @@ -727,7 +824,7 @@ Pick one; the table's Root Directory and Dockerfile Path are the same for all th 1. Create the project in the workspace, then every service empty, `modelstub` too if you will use it (a variable that names another service needs that service to exist, and a service deployed before its target existed can be left with an empty host name: see "Looking inside"). 2. On each service: its variables, Root Directory, Dockerfile Path, a volume of the size in the row, and (`codeaf`) the health check path and the public domain. Give the domain first (`CODEAF_PUBLIC_DOMAIN` is read at start), target port 8787. -3. Connect or upload the source of each service. The three codeaf-image services compile codeaf (about four minutes each); the other +3. Connect or upload the source of each service. The four codeaf-image services (`codeaf`, `runner`, `sessionhost` and `relay`) compile codeaf (about four minutes each); the other four take about a minute. A service reads **SUCCESS** when it started (and, where the row sets a health check, answered it). 4. "Check it", then "Claim the organization" below. Nothing else is needed to bring the stack up: `runner` waits up to five minutes for AgentField, so the order of the deploys does not matter. @@ -738,6 +835,7 @@ Pick one; the table's Root Directory and Dockerfile Path are the same for all th | `codeaf` | `/` (the repository root) | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=server`, `PORT=8787`, `CODEAF_ORG_NAME=...`, `CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}`, `CODEAF_TRUSTED_PROXIES=100.64.0.0/10`, `CODEAF_SERVER_KEY=${{secret(64, "abcdef0123456789")}}`. Hosted chats: `CODEAF_HOSTED_SECRET=${{secret(64, "abcdef0123456789")}}`, `CODEAF_HOSTED_URL=http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790`, `CODEAF_HOSTED_MODEL_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model`. **The model door's key: `CODEAF_HOSTED_MODEL_KEY=`** (or an organization key an operator saves in Settings, Organizations); `CODEAF_HOSTED_MODEL_UPSTREAM` only for a provider other than OpenRouter. The door does not read `OPENROUTER_API_KEY`. Health check path `/v1/about` (answers 200 with no sign-in; `/` answers 401). Generate a public domain for this service only, target port 8787, **before its first deploy**. | | `runner` | `/` | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=runner`, `AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `ORG_MODEL=...`, `OPENROUTER_API_KEY=...`. No health check path: it serves no HTTP. | | `sessionhost` | `/` | `deploy/org/codeaf.Dockerfile` | `/chats` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=sessionhost`, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, `CODEAF_SESSIONHOST_DATA=/chats`, `CODEAF_SESSIONHOST_MODEL=...` (the model chats use), and the limits you want (`CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`). No public domain and no health check path (every request to it needs the shared secret). Give it resource limits (1 vCPU and 1 GB is plenty for a few chats). | +| `relay` | `/` | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=relay`, `PORT=8788`, `CODEAF_RELAY_STORAGE=off`, `CODEAF_RELAY_STATUS=off`, `CODEAF_RELAY_TRUST_PROXY=on` (Railway's edge sets `X-Forwarded-For`). Health check path `/p/health`. Generate a public domain for this service, target port 8788, then set **`CODEAF_ORG_RELAY_URL=https://${{relay.RAILWAY_PUBLIC_DOMAIN}}` on `codeaf`**, which is what tells signed-in members where it is. It needs its own domain and cannot share `codeaf`'s: a relay's requests are signed with their path. See "The organization's relay". | | `swe-af` | `/deploy/org` | `swe-af.Dockerfile` | `/workspaces` | `NODE_ID=swe-planner`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `SWE_HITL_NATIVE=1`, `SWE_FENCE=off`, `SWE_PRO_ENGINE=0`, `SWE_DEFAULT_MODEL=openrouter/...`, `OPENROUTER_API_KEY=...`. | | `pr-af` | `/deploy/org` | `pr-af.Dockerfile` | `/workspaces` | `NODE_ID=pr-af`, `PORT=8007`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `AGENT_CALLBACK_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8007`, `PR_AF_MODEL=...`, `OPENROUTER_API_KEY=...`. | | `modelstub` (keyless only) | `/deploy/org` | `modelstub.Dockerfile` | none | `STUB_DELAY=2s`; then on `runner`, `swe-af`, `pr-af` and `codeaf` set `CODEAF_BASE_URL=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1` and `OPENROUTER_API_KEY=stub-key`, on `runner`, `pr-af` and `sessionhost` the model variables to `stub/scripted` (`ORG_MODEL`, `PR_AF_MODEL`, `CODEAF_SESSIONHOST_MODEL`; SWE-AF: `SWE_DEFAULT_MODEL=openrouter/stub/scripted`), on `codeaf` also `CODEAF_HOSTED_MODEL_UPSTREAM=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1` and `CODEAF_HOSTED_MODEL_KEY=stub-key`. For the self-test below, `swe-af` also takes `SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture`. | @@ -747,9 +845,9 @@ requests, as in "What you need"; the keyless test needs none). People's own GitH person stores theirs on the server (see "Keys, spend and git"). Volumes: **Railway makes every volume 50 GB unless it is sized, and the CLI cannot size one.** `railway volume add` takes a mount -path and nothing else, and `railway volume update` takes only a mount path and a name, so six volumes made with the CLI (which is -what `make-template.sh` does) are 300 GB of billed storage. **A volume can grow but never shrink**, so start small: 1 GB is plenty for -`codeaf`, `agentfield`, `sessionhost` and `swe-af`, 512 MB for `runner` and `pr-af` (the sizes the production run used). +path and nothing else, and `railway volume update` takes only a mount path and a name, so seven volumes made with the CLI (which is +what `make-template.sh` does) are 350 GB of billed storage. **A volume can grow but never shrink**, so start small: 1 GB is plenty for +`codeaf`, `agentfield`, `sessionhost` and `swe-af`, 512 MB for `runner`, `relay` and `pr-af` (the sizes the production run used). The resize step, for a volume that is still empty: delete it (`railway volume delete --volume --yes`) and make it again with a size through Railway's API, which takes `sizeMB`. The production run did exactly that, with Railway's MCP server @@ -828,19 +926,22 @@ railway ssh -s runner -- 'curl -s -o /dev/null -w "%{http_code}\n" $AGENTFIELD_U railway ssh -s sessionhost -- codeaf sessionhost probe /access" # 200: the sign-in page, over HTTPS curl -s "https:///v1/about" # "scheme": "https", the commit it was built from +curl -s -o /dev/null -w '%{http_code}\n' "https:///p/health" # 200: the relay's page for a pairing link ``` The first three answer for the whole stack's wiring: AgentField refuses an anonymous call, the sessionhost can keep chats apart on this -kernel, and the public name serves over HTTPS. None of them makes a model call or a chat; those start once the organization is claimed. +kernel, and the public name serves over HTTPS (the last line is the relay's own domain answering, with the relay's address, not the server's). None of them makes a model call or a chat; those start once the organization is claimed. ### The template script, and the draft it makes -`railway/make-template.sh` builds the same six services from the published images (it checks that they exist first) and turns the +`railway/make-template.sh` builds the same seven services from the published images (it checks that they exist first) and turns the project into a Railway template draft. With no argument it is a dry run that prints every Railway call; `--apply`, with `RAILWAY_WORKSPACE` set to the workspace's id or name, makes them. Run `--apply` from a terminal: with no terminal on stdin the Railway CLI reads a JSON patch from stdin and ignores the flags the script passes. `--apply` ran end to end on 2026-11-25 against Railway CLI 5.71.0, except for its last call, `railway templates create`, which that run skipped on purpose. `railway/railway_scripts_test.sh` -runs it against a stub CLI that records its arguments, so the volume and environment calls are pinned. +runs it against a stub CLI that records its arguments, so the volume and environment calls are pinned. The relay service, its domain and +the `CODEAF_ORG_RELAY_URL` variable on `codeaf` were added to the script after that run and are pinned by the same offline tests +only: **no Railway call for the relay has been made**. What it leaves for you: diff --git a/docs/organizations.md b/docs/organizations.md index 75e5161f88..4d1774582c 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -49,6 +49,7 @@ Two readers: | organization server | `codeaf factory serve` in team mode. Signs people in, keeps the access rules, mints each chat's model access, meters spend, and adds a person's own GitHub access to a chat's git. | | sessionhost | The machine hosted chats run on. Gives every chat its own Linux user and folder and fences its commands. Optional: only with hosted chats on. | | AgentField control plane | Routes factory work to the nodes. | +| relay | The organization's own relay, `codeaf relay`: where members' computers pair, see each other, Move chats and open each other's chats live, so none of that needs the public one. It keeps each member's list of computers and no chat content. `codeaf pair --org ` pairs through it; an explicit `CODEAF_SYNC_URL` or `--via` still wins. | | factory runner, SWE-AF, PR-AF | The factory's nodes: the runner hosts the codeaf factory, SWE-AF builds an issue into a pull request, PR-AF reviews one. | | modelstub, gitstub | A scripted model and git host for the keyless smoke test only. | @@ -160,7 +161,7 @@ Compose stack cannot turn it on. ## The ten minutes -You need `git`, Docker with Compose v2.24 or newer, 4 GB of free memory, ports 8787 and 8080 free on the host, and a +You need `git`, Docker with Compose v2.24 or newer, 4 GB of free memory, ports 8787, 8788 and 8080 free on the host, and a Linux host (Linux 6.12 or newer for the full sandbox; see the sandbox note below). For real work add an OpenRouter key; to try it first, the scripted model needs none. For anyone to sign in with a password, **including you on the same machine**, you need an HTTPS name in front of port 8787: the server takes a password only over HTTPS, and Docker does not hand it a diff --git a/docs/relay.md b/docs/relay.md index 5e38fc59f8..5bbec1ee74 100644 --- a/docs/relay.md +++ b/docs/relay.md @@ -17,6 +17,7 @@ The separate `relay` binary accepts the same flags. |---|---| | `--listen` | Listen address; default `:8787`. | | `--store ` | Persistent coordination and encrypted chunks. Without it, only the blind transport and pairing mailbox run; chat sync needs storage. | +| `--storage on\|off` | Default `on`. `off` keeps the device list under `--store` but no chat content: `GET /v1/store/stats` answers `"storage": "off"`, so computers keep their chats where they are and stop asking, and an upload is refused with `403 storage_off`. It is what the hosted relay does for an account that has not asked for storage, and what an organization's relay does when the organization already keeps its chats (see below). | | `--quiet` | Suppress arrival, departure and request logs. | | `--status=false` | Disable `GET /status`. | | `--trust-proxy` | use the first `X-Forwarded-For` address for registration, dial and pairing limits; absent or blank falls back to the socket peer. only behind a proxy that sets it. | @@ -33,6 +34,15 @@ Logs contain a short identity id, route pattern, status and byte counts, never a The native relay serves at the root of its host; give it a host of its own, or have your proxy preserve the client's signed request path. +## A relay for an organization + +An organization that hosts its chats (`deploy/org`, see [organizations](organizations.md)) runs its own relay in the same stack, as the +`relay` service, with `--store` on a volume and `--storage off`: members' computers pair, see each other, Move chats and open each +other's chats live through it, and the organization's server, not a second copy on the relay, keeps the hosted chats. The organization +server's `relay_url` setting names it, `codeaf pair --org https://org.example.com` looks it up and pairs through it, and +`codeaf pair --via` with any relay's address still works with no organization involved. The operator's walkthrough is "The +organization's relay" in [`deploy/org/README.md`](../deploy/org/README.md#the-organizations-relay). + ## Three anchors, joined computers and leadership Each identity has three local persistent voters, called anchors. A directory change From 09d1a61fceb19440c0058a13c2fe9d24db07cb71 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 12:12:17 -0500 Subject: [PATCH 14/16] manual: self-hosted team relay, use my organization's relay, use my own relay instead A new chat page answers the questions an organization's members and operators ask about the relay the stack now runs: what it is and keeps, `codeaf pair --org` and what it says when it stops, that --via and CODEAF_SYNC_URL still win, who can reach it, and how to run one. The pages that said Docker had no relay and that every relay keeps chats now say what an organization's stack does. The headings and wording were tuned against the whole probe table: adding six sections moves every ranking by a few thousandths, and three existing questions sat on exact ties at the fourth place ("what does Your chat mean on a task", "set effort to max", "how do I take a chat back from my other computer"). The page avoids the words those questions turn on rather than the probes changing. Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/organization-relay.md | 47 +++++++++++++++++++ .../manual/chat/relay-hosted-or-your-own.md | 7 +-- internal/manual/chat/remote-control.md | 2 +- internal/manual/chat_test.go | 12 +++++ internal/wordlaw/relay_manual.golden | 1 + 5 files changed, 65 insertions(+), 4 deletions(-) create mode 100644 internal/manual/chat/organization-relay.md diff --git a/internal/manual/chat/organization-relay.md b/internal/manual/chat/organization-relay.md new file mode 100644 index 0000000000..23319eb0cf --- /dev/null +++ b/internal/manual/chat/organization-relay.md @@ -0,0 +1,47 @@ +# Your organization's own relay + +## self-hosted team relay — what my organization's relay is, what it keeps, and why my computers go through it + +An organization that runs its own server can run a relay beside it. A relay is the small server your computers go through to pair, to see which of your other computers are online, to Move a chat and to open a chat another of your computers is running, live. With the organization's relay, none of that touches the public one, and everyone in the organization needs nothing but its address. It is the program `codeaf relay`, started by the organization's stack as its `relay` service. + +It keeps each person's list of paired computers and their names, so a restart does not make your computers forget one another. **By default it keeps no chat content.** Your chats stay on your computers and in the organization's own hosted chats, and the relay says so, so your computers stop trying to store them there. The person who runs it can turn storing on (`CODEAF_RELAY_STORAGE=on`); it then keeps encrypted copies of your own computers' chats, as a relay run with `--store` does. + +With storing off, a chat another of your computers is running shows on Home as `untitled`, the same as with the public relay's storage off (see *Remote control*). **Settings → Devices** shows relay storage as off, which is the intended state here. The request it offers opens a request on the project's GitHub for the public relay, and does nothing for your organization's. + +## use my organization's relay — pair my computers through my company's relay with codeaf pair --org, no variable to change + +Pair through the organization's relay with its address, the one you sign in to. You need the sign-in `codeaf chat --org` uses: `CODEAF_ORG_TOKEN`, or `codeaf attach
--token `. + +``` +codeaf pair --org https://org.example.com --code +codeaf pair --via +``` + +The first command is on the computer that has your chats. It asks the organization's server which relay it runs, shows a code, and prints the line to type on the other computer. That line carries `--via` with the relay's address, so the other computer is told where to go, and both computers remember it. From then on every start of either computer uses it: nothing is typed into a profile or an environment. `codeaf devices` says which one a computer uses, as `relay: relay.example.com (your own)`. + +`--org` does only that lookup and then pairs exactly as `--via ` does. A computer that never says `--org` asks no organization anything. Both computers must be able to reach the relay's address from where they are; if the organization keeps its relay on a private network, that means being on it. + +## my organization says it runs no relay — what --org says when it stops, and what that means + +`codeaf pair --org` stops, before anything is paired, and says why in a sentence: + +- ` does not run a relay for your computers. Pair through another with --via
, or leave --org off to use the usual one.` The organization has not named one. Ask whoever runs it, or use any other relay with `--via`, or carry on as you did before. +- `Sign in to first: set CODEAF_ORG_TOKEN, or run codeaf attach
--token .` You have no sign-in for that server here, or it was not accepted. `codeaf attach` keeps the sign-in, so sign in once and ask again. +- ` named a relay address this program cannot use.` The address is not a web address, or has a user name, a query or a fragment in it. Tell whoever runs the organization to correct `CODEAF_ORG_RELAY_URL`; nothing on your computer needs changing. +- ` named a relay that is not https, so nothing was paired through it.` The organization was reached over https and named a plain http relay, which this refuses so a lookup can never make a pairing less private. Tell whoever runs the organization to put the relay behind https. +- `--org and --via each name the relay to pair through: use one of them.` +- `this computer is already paired with — codeaf devices lists them` is not about the organization: a computer that already syncs with others refuses any new pairing, with or without `--org`. *Adding a computer to your devices, approving it, and removing it* says how to take one out of the list. + +## a relay of my own instead of the organization's — --via and CODEAF_SYNC_URL still win over it + +Nothing about an organization's relay overrides a device. `codeaf pair --via https://relay.mine.example` pairs through that relay and asks no organization anything. `CODEAF_SYNC_URL` holding an address always wins over a saved one, and `CODEAF_SYNC_URL=off` turns the relay off, which stops a pairing even with `--org`. Someone who is not pairing through an organization keeps the public relay for their build's channel exactly as before, and picks any other relay with `--via`. See *Hosted relay or your own relay*. Every paired device must use the same relay, or each sees different chats. + +## who can reach my organization's relay — does it know who is in my team, can a stranger use it + +No. **The relay has no list of people.** It does not know the organization's members: a computer that makes a valid signature may make an identity and use its pairing, its list of devices and its live road, as on any relay. It sees machine names, times and sealed bytes it cannot read, because what passes through is sealed on the devices before it leaves them, and a stranger gets only what their own devices would. Adding a new device always needs a person to approve it on any other that is already paired, so a stranger cannot attach theirs to a list. If that is not acceptable, the person who runs it keeps it on a private network, such as a VPN or behind a firewall that allows only the office, and gives that address to the organization. The stack publishes the relay on the host's own address only until its operator changes `CODEAF_RELAY_BIND`. + +## run a relay for my team — the relay service in the organization stack, CODEAF_ORG_RELAY_URL and its settings + +This is for whoever runs the organization (`deploy/org`). The stack starts the relay with the rest and answers `http://127.0.0.1:8788/p/health` when it is up. Members' devices need it on a **name of its own with https** (its requests are signed with their path, so it cannot sit under the server's address or any other path), for example `relay.example.com { reverse_proxy 127.0.0.1:8788 }` in Caddy. + +In `.env`: `CODEAF_ORG_RELAY_URL=https://relay.example.com` is the address the server tells everyone who is signed in (`relay_url` in its config; left empty it tells nobody and the relay still runs). `CODEAF_RELAY_TRUST_PROXY=on` behind a proxy. `CODEAF_RELAY_STORAGE` is `off` by default and `on` keeps encrypted chats. `CODEAF_RELAY_STATUS=on` publishes the list of connected devices, so leave it off on an open network. `CODEAF_RELAY_BIND` and `CODEAF_RELAY_PORT` choose where the host publishes it (`127.0.0.1:8788`). On Railway the same service comes from `make-template.sh`. A relay lost with its volume makes people pair again. diff --git a/internal/manual/chat/relay-hosted-or-your-own.md b/internal/manual/chat/relay-hosted-or-your-own.md index f939c7296d..adde7c6ef8 100644 --- a/internal/manual/chat/relay-hosted-or-your-own.md +++ b/internal/manual/chat/relay-hosted-or-your-own.md @@ -8,12 +8,12 @@ Older chats move through an independent copy. Once paired, codeaf prepares chats A relay is the small service your computers sync through. There are two kinds. Both speak the same wire. -Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request (one started with `--storage off` keeps no chats at all, and has nothing to approve). - **A hosted relay** is run for you on a cloud account. You do nothing to run it. You give the chat its address. - **Your own relay** is the program `codeaf relay`. You run it on a computer you control. -Either way the relay sees only ciphertext and the short list on "What can the relay see". +Either way it sees only ciphertext and the short list on "What can the relay see". ## Where sync goes by default — stable, staging and dev relay addresses @@ -45,12 +45,13 @@ codeaf relay --listen :8787 --store /var/lib/codeaf - `--listen` is the address to listen on. The default is `:8787`. - `--store ` is where the relay keeps the directory and the chunks. **Without `--store` the relay only passes pairing and remote-access traffic. It keeps no chats, and sync does not work through it.** The directory is made if it is not there. +- `--storage off` keeps the directory (the list of your computers) and refuses chat content: computers are told storing is off, so they keep their chats where they are and stop asking. The default is `on`. An organization's stack starts it this way. - `--quiet` turns the log off. `--status=false` turns off `GET /status`. - `--trust-proxy` makes registration, dial and pairing limits count the first address in `X-Forwarded-For`, falling back to the socket address when absent or blank. without it, forwarding headers are ignored. a relay behind Railway, a load balancer or nginx must pass this flag or every caller shares the proxy's allowance. use it only behind a proxy that sets that header. Stop it with SIGTERM or ctrl+c: requests under way finish first. **The relay has no TLS of its own.** Put a proxy that ends TLS in front of it if any computer reaches it over a network you do not own. -There is no Docker image for the relay. The page `docs/relay.md` in the repository says how to run, back up and upgrade it. +There is no Docker image of the relay by itself; an organization's stack runs one (*Your organization's own relay*). The page `docs/relay.md` in the repository says how to run, back up and upgrade it. ## Why does my native relay answer leadership unavailable or HTTP 503 diff --git a/internal/manual/chat/remote-control.md b/internal/manual/chat/remote-control.md index 57d0b6f355..fae80899ac 100644 --- a/internal/manual/chat/remote-control.md +++ b/internal/manual/chat/remote-control.md @@ -10,7 +10,7 @@ Three things have to be true. The two computers are paired. Both are running cod With remote control on, a chat shows on your other computers' Home as soon as its first turn **starts**, marked `working on `, and `enter` opens it live. Without remote control it appears when that first turn ends, as it always did. A chat nobody has typed in appears nowhere, so an opened and abandoned chat leaves no untitled row. Only the row travels this early: which computer runs the chat and that it is working, with no title, no folder and no words. To make that row the chat is saved once as it stands when the turn starts, which is your first message and no reply. With relay storage off that saved copy stays on the computer running the chat. -With relay storage off, which is the default, the row never carries the chat's title, so on another computer's terminal Home it reads `untitled` while the first turn runs and after it ends, and after every later turn. The server in between is never given the name of a chat, so the title is not sent. The terminal fills it in from a copy of the chat that computer already holds, and a chat that was started on another computer has none there. WorkAF asks the computer running the chat for the title directly (see *Why a chat shows as untitled on my other computer*). With that storage approved, or a self-hosted server run with `--store`, the row gets its title and its latest state when the turn ends, like any chat. +With relay storage off, which is the default, the row never carries the chat's title, so on another computer's terminal Home it reads `untitled` while the first turn runs and after it ends, and after every later turn. The server in between is never given the name of a chat, so the title is not sent. The terminal fills it in from a copy of the chat that computer already holds, and a chat that was started on another computer has none there. WorkAF asks the computer running the chat for the title directly (see *Why a chat shows as untitled on my other computer*). With that storage approved, or a self-hosted server run with `--store` (and not `--storage off`, which an organization's stack uses), the row gets its title and its latest state when the turn ends, like any chat. If the computer running it stops during that first turn, the row stays as `untitled` until the chat is opened again there. Opening it from another computer asks first. What it can bring is the chat as last saved, at most your first message and no reply, and only with that storage on: with it off, nothing comes while that computer is off. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index c66d6f93fa..3c6618b6b2 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3959,6 +3959,18 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"does the sync service see my chat title or folder name when I move a chat without sync storage", "relay-what-it-stores-and-sees"}, {"why can't I message a chat on another computer while sync storage is off", "desktop-sync"}, {"Sync storage is off for this account, so a message can't wait for another computer", "desktop-sync"}, + // The organization's own relay (organization-relay.md): the team stack runs + // one, `codeaf pair --org` looks it up, and a relay named outright still wins. + {"does my organization run its own relay", "organization-relay"}, + {"what is a self-hosted team relay", "organization-relay"}, + {"how do I pair my computers through my company's relay", "organization-relay"}, + {"what does codeaf pair --org do", "organization-relay"}, + {"pair --org says my organization does not run a relay for my computers", "organization-relay"}, + {"how do I make my team's hosted stack run a relay for everyone in it", "organization-relay"}, + {"what is CODEAF_ORG_RELAY_URL", "organization-relay"}, + {"does my organization's relay keep my chats", "organization-relay"}, + {"can a stranger use my team's relay", "organization-relay"}, + {"can I still use my own relay if my organization has one", "organization-relay"}, // Remote control (internal/manual/chat/remote-control.md): working in a chat // another of the person's computers is running, without moving it. {"how do I see my chat from my other computer", "remote-control"}, diff --git a/internal/wordlaw/relay_manual.golden b/internal/wordlaw/relay_manual.golden index 722f3c2920..d545e0bb78 100644 --- a/internal/wordlaw/relay_manual.golden +++ b/internal/wordlaw/relay_manual.golden @@ -52,6 +52,7 @@ openrouter-credits.md 0 organization-agents.md 0 organization-hosted-sessions.md 0 organization-library.md 0 +organization-relay.md 62 organization-sharing.md 0 organization-start.md 0 organization-workstream-agent.md 0 From 7c3b08173363e55b76607b969ec5a731faf8f442 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 14:29:52 -0500 Subject: [PATCH 15/16] changes: remote control for Teams, with what it moves for anyone who remembers the old stack Co-Authored-By: Claude Opus 5.5 --- .../unreleased/2987-remote-control-teams.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/changes/unreleased/2987-remote-control-teams.md diff --git a/docs/changes/unreleased/2987-remote-control-teams.md b/docs/changes/unreleased/2987-remote-control-teams.md new file mode 100644 index 0000000000..e4ca8ad689 --- /dev/null +++ b/docs/changes/unreleased/2987-remote-control-teams.md @@ -0,0 +1,14 @@ +--- +kind: added +title: An organization's own stack runs a relay for its people, and a hosted Team chat reconnects and is told who is typing by the server +pr: 2987 +surface: [remote, chat, docs, build] +invalidates: + - "Was true: the self-deployable organization stack in deploy/org started the server, the runner and the agents but no relay, so pairing, presence, Move and remote control between members' computers went through the public hosted relay. Is true now: the stack starts a `relay` service (`codeaf relay --storage off` on 127.0.0.1:8788 by default, its own domain on Railway), and with `CODEAF_ORG_RELAY_URL` set the organization server tells everyone signed in where it is (`relay_url`)." + - "Was true: a relay either kept chats (`--store`) or kept nothing at all, not even the device list pairing needs. Is true now: `codeaf relay --store --storage off` keeps the device directory that pairing, presence and remote control need and refuses chat uploads; the organization stack runs it that way because its server already keeps everyone's chats." + - "Was true: `codeaf pair` always used the relay named by CODEAF_SYNC_URL or the public default. Is true now: `codeaf pair --org ` pairs through the relay that organization advertises; an explicit `--via` or CODEAF_SYNC_URL still wins, a computer already paired on another relay is refused as before, and people outside an organization keep the public relay." + - "Was true: in a shared hosted chat, the `typing from ` line came from the joining window's own hello, so a member's window could name itself after anyone. Is true now: the organization server names the window from the person it authenticated (a bot reads as `'s bot`) and drops any client-supplied remote stamp." + - "Was true: a `codeaf chat --org` window ended for good when its link to the organization server dropped. Is true now: it reconnects as a returning window and ends at once, with the server's own words, only on 401, 403 or 404; `--once` is never retried, and the desktop's organization window still does not reconnect." +--- + +Remote control (#2965) was built before Teams reached dev. This makes it work inside an organization: its people's computers find each other through the organization's own relay, and its hosted chats behave like a live view should when a link drops or two people share one. From a8bd93a305ed6323ef4491e6540e2f2f8dddc919 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Thu, 26 Nov 2026 14:30:06 -0500 Subject: [PATCH 16/16] changes: shorten the remote control for Teams entry's title to one line Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2987-remote-control-teams.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changes/unreleased/2987-remote-control-teams.md b/docs/changes/unreleased/2987-remote-control-teams.md index e4ca8ad689..77086af213 100644 --- a/docs/changes/unreleased/2987-remote-control-teams.md +++ b/docs/changes/unreleased/2987-remote-control-teams.md @@ -1,6 +1,6 @@ --- kind: added -title: An organization's own stack runs a relay for its people, and a hosted Team chat reconnects and is told who is typing by the server +title: An organization runs its own relay, and a hosted Team chat reconnects and names who is typing pr: 2987 surface: [remote, chat, docs, build] invalidates: