From b8348675241dfc48eec6ceead08ab0661b458d49 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:44:21 -0500 Subject: [PATCH 1/6] org: policy settings for who approves a tool call and who starts a chat that is not running The organization's policy has a `chats` section beside `hosting`, which so far held one rule, `move_by`. Two more rules for a chat that runs on the organization's own server and is shared with other people become settings there, each optional, each reading as what the server did before it existed: - `chats.approvals_by`: `owner` (also what an absent value means) or `answer`. The wire that enforces it is the next commit. - `chats.wake_by`: `view` (also what an absent value means), `run` or `owner`. Same. Both are validated when the policy is written (422 with a sentence that names the allowed words), written under `chats` by their own names, and absent from the default policy's JSON, so a policy stored before they existed reads and saves unchanged. Tests: TestChatApprovalAndWakeRulesAreTodaysBehaviourUntilTheOrganizationChangesThem, TestChatApprovalAndWakeRulesTakeOnlyTheirWords (acl), TestOrgPolicyStoredWithoutApprovalAndWakeRulesReadsAsToday (store). Co-Authored-By: Claude Opus 5.5 --- internal/factory/acl/chats_test.go | 85 +++++++++++++++++++++++++++ internal/factory/acl/policy.go | 58 +++++++++++++++++- internal/factory/store/policy_test.go | 40 +++++++++++++ 3 files changed, 181 insertions(+), 2 deletions(-) diff --git a/internal/factory/acl/chats_test.go b/internal/factory/acl/chats_test.go index 24d4e181a1..8c0859d9ac 100644 --- a/internal/factory/acl/chats_test.go +++ b/internal/factory/acl/chats_test.go @@ -91,3 +91,88 @@ func TestChatMoveRuleTakesOnlyItsTwoWords(t *testing.T) { t.Fatalf("the setting is not written under chats.move_by: %s", data) } } + +// Contract: who approves a tool call in a shared chat, and who starts a chat that is not running, are policy settings +// whose defaults are what the server did before they existed: the owner approves, and anyone who can see the chat opens +// it. A policy with no `chats` section, whether the default policy or one stored before the settings existed, reads that +// way, is still valid, and writes back without them. +func TestChatApprovalAndWakeRulesAreTodaysBehaviourUntilTheOrganizationChangesThem(t *testing.T) { + if got := DefaultPolicy().Chats.ApprovalsByFor(); got != ApprovalsByOwner { + t.Fatalf("default policy: who approves a tool call = %q, want %q", got, ApprovalsByOwner) + } + if got := DefaultPolicy().Chats.WakeByFor(); got != WakeByView { + t.Fatalf("default policy: who starts a chat = %q, want %q", got, WakeByView) + } + var old Policy + if err := json.Unmarshal([]byte(organizationPolicyBeforeChatRules), &old); err != nil { + t.Fatal(err) + } + if old.Chats.ApprovalsByFor() != ApprovalsByOwner || old.Chats.WakeByFor() != WakeByView { + t.Fatalf("a policy stored before the settings existed reads approvals %q, wake %q", old.Chats.ApprovalsByFor(), old.Chats.WakeByFor()) + } + if err := old.Validate(Policy{}, nil); err != nil { + t.Fatalf("a policy stored before the settings existed is no longer valid: %v", err) + } + // Saying the default out loud is the same behaviour, and is written down as said. + p := DefaultPolicy() + p.Chats = Chats{ApprovalsBy: ApprovalsByOwner, WakeBy: WakeByView} + if p.Chats.ApprovalsByFor() != ApprovalsByOwner || p.Chats.WakeByFor() != WakeByView { + t.Fatalf("the defaults said out loud read %q and %q", p.Chats.ApprovalsByFor(), p.Chats.WakeByFor()) + } +} + +// Contract: approvals_by takes `owner` and `answer`, wake_by takes `view`, `run` and `owner`, any other word is refused +// with a sentence that names the words that are allowed, and a setting is written under `chats` by its own name. +func TestChatApprovalAndWakeRulesTakeOnlyTheirWords(t *testing.T) { + for _, tc := range []struct { + set Chats + wantApproval, wantWake string + }{ + {Chats{}, ApprovalsByOwner, WakeByView}, + {Chats{ApprovalsBy: "owner", WakeBy: "owner"}, ApprovalsByOwner, WakeByOwner}, + {Chats{ApprovalsBy: "answer", WakeBy: "run"}, ApprovalsByAnswer, WakeByRun}, + {Chats{WakeBy: "view"}, ApprovalsByOwner, WakeByView}, + } { + p := DefaultPolicy() + p.Chats = tc.set + if err := p.Validate(Policy{}, nil); err != nil { + t.Fatalf("%+v is refused: %v", tc.set, err) + } + if p.Chats.ApprovalsByFor() != tc.wantApproval || p.Chats.WakeByFor() != tc.wantWake { + t.Errorf("%+v resolves to %q and %q, want %q and %q", tc.set, p.Chats.ApprovalsByFor(), p.Chats.WakeByFor(), tc.wantApproval, tc.wantWake) + } + } + var validation *ValidationError + for _, tc := range []struct { + name string + set func(string) Chats + words []string + }{ + {"approvals_by", func(w string) Chats { return Chats{ApprovalsBy: w} }, []string{"owner", "answer"}}, + {"wake_by", func(w string) Chats { return Chats{WakeBy: w} }, []string{"view", "run", "owner"}}, + } { + for _, word := range []string{"anyone", "manage", "Answer", "edit"} { + p := DefaultPolicy() + p.Chats = tc.set(word) + err := p.Validate(Policy{}, nil) + if !errors.As(err, &validation) { + t.Errorf("%s %q: %v", tc.name, word, err) + continue + } + for _, allowed := range tc.words { + if !strings.Contains(err.Error(), allowed) { + t.Errorf("%s %q is refused with %q, which does not name %q", tc.name, word, err, allowed) + } + } + } + } + p := DefaultPolicy() + p.Chats = Chats{ApprovalsBy: ApprovalsByAnswer, WakeBy: WakeByRun} + data, err := json.Marshal(p) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `"chats":{"approvals_by":"answer","wake_by":"run"}`) { + t.Fatalf("the settings are not written under chats by their own names: %s", data) + } +} diff --git a/internal/factory/acl/policy.go b/internal/factory/acl/policy.go index bef4fecd89..cf6e0a88ab 100644 --- a/internal/factory/acl/policy.go +++ b/internal/factory/acl/policy.go @@ -123,12 +123,20 @@ func (h Hosting) Words(hasChatHost bool) string { } } -// Chats holds the organization's rules for the chats its people keep. There is one so far: who may move a chat to another -// workstream or into My space. +// Chats holds the organization's rules for the chats its people keep: who may move a chat to another workstream or into +// My space, and, for a chat that runs on the organization's own server and is shared with other people, who may approve +// one of its tool calls and who may start it when it is not running. Every field is optional, and an empty one means the +// rule the server had before the field existed, so a policy that never mentions a rule is unchanged by it. type Chats struct { // MoveBy is MoveByOwner or MoveByManage. Empty means MoveByOwner, so a policy stored before this field existed, and // a policy that never mentions it, keep the rule the server always had. MoveBy string `json:"move_by,omitempty"` + // ApprovalsBy is ApprovalsByOwner or ApprovalsByAnswer. Empty means ApprovalsByOwner: a tool call a shared chat wants + // to make waits for its owner, whatever role anyone else holds. + ApprovalsBy string `json:"approvals_by,omitempty"` + // WakeBy is WakeByView, WakeByRun or WakeByOwner. Empty means WakeByView: anyone who can see a shared chat opens it + // when it is not running, and it starts for its owner. + WakeBy string `json:"wake_by,omitempty"` } const ( @@ -140,6 +148,26 @@ const ( MoveByManage = "manage" ) +const ( + // ApprovalsByOwner keeps every approval of a tool call with the chat's owner. It is the default. + ApprovalsByOwner = "owner" + // ApprovalsByAnswer lets anyone who holds the answer verb on a shared chat allow one tool call once, or refuse it. + // Allowing a tool for the rest of the chat, and every other setting of the chat, stays with the owner. Under the + // starting roles that is whoever the chat is shared with at `edit` or `full`. + ApprovalsByAnswer = "answer" +) + +const ( + // WakeByView lets anyone who can see a shared chat open it when it is not running, which starts it for its owner. + // It is the default, and what the server did before the rule was a setting. + WakeByView = "view" + // WakeByRun lets only a person who may send messages in the chat (the run verb) open it when it is not running. + // Someone who can only watch it sees a running chat, and is told to ask its owner for one that is not. + WakeByRun = "run" + // WakeByOwner lets only the chat's owner start it. Everyone else sees it while it is running. + WakeByOwner = "owner" +) + // MoveByFor is the rule that applies, with an empty setting read as the default. func (c Chats) MoveByFor() string { if c.MoveBy == "" { @@ -148,6 +176,22 @@ func (c Chats) MoveByFor() string { return c.MoveBy } +// ApprovalsByFor is the rule that applies, with an empty setting read as the default. +func (c Chats) ApprovalsByFor() string { + if c.ApprovalsBy == "" { + return ApprovalsByOwner + } + return c.ApprovalsBy +} + +// WakeByFor is the rule that applies, with an empty setting read as the default. +func (c Chats) WakeByFor() string { + if c.WakeBy == "" { + return WakeByView + } + return c.WakeBy +} + // Policy is the organization's access document: the roles, what each kind of // resource starts as, who may share, what the operator and agents may do. It // is stored as one row with a revision and changes only through a PUT by the @@ -287,6 +331,16 @@ func (p Policy) Validate(prev Policy, inUse func(role string) bool) error { default: return invalid("who may move a chat must be the owner or people with manage permission") } + switch p.Chats.ApprovalsBy { + case "", ApprovalsByOwner, ApprovalsByAnswer: + default: + return invalid("who may approve a tool call in a shared chat must be owner (only its owner) or answer (anyone who may answer its questions)") + } + switch p.Chats.WakeBy { + case "", WakeByView, WakeByRun, WakeByOwner: + default: + return invalid("who may start a chat that is not running must be view (anyone who can see it), run (anyone who may send messages in it) or owner (only its owner)") + } if cost := p.Hosting.MaxSessionCostUSD; math.IsNaN(cost) || cost < 0 || cost > 1_000_000 { return invalid("hosting chat cost must be between 0 and 1,000,000 dollars") } diff --git a/internal/factory/store/policy_test.go b/internal/factory/store/policy_test.go index def905e9cb..bf9d2cfe8b 100644 --- a/internal/factory/store/policy_test.go +++ b/internal/factory/store/policy_test.go @@ -121,3 +121,43 @@ func TestOrgPolicyStoredWithoutChatRulesReadsAsOwnerOnlyMove(t *testing.T) { } } } + +// Contract: who approves a tool call and who starts a chat that is not running keep today's behaviour until the +// organization says otherwise. A policy stored before the settings existed reads as owner approves and anyone who can see +// the chat starts it; one that sets them reads as set; and a stored word that is not one of the allowed words is not +// trusted, so the defaults apply. +func TestOrgPolicyStoredWithoutApprovalAndWakeRulesReadsAsToday(t *testing.T) { + const roles = `"roles":[{"name":"view","verbs":["view"]},{"name":"comment","verbs":["view","comment"]},` + + `{"name":"edit","verbs":["view","comment","edit","run","steer","answer"]},` + + `{"name":"full","verbs":["view","comment","edit","run","steer","answer","share","manage"]}],` + + `"owner_role":"full","org_role":"view","defaults":{"chat":{"visibility":"private"}},"sharing":{"who":"share_verb"},` + + `"operator":{"role":"view","may_govern":true},"agents":{"may_create":true,"default_scope":"full"}` + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if _, err := st.SavePolicy(acl.DefaultPolicy(), 0); err != nil { + t.Fatal(err) + } + db, err := st.wsDB(false) + if err != nil { + t.Fatal(err) + } + for i, tc := range []struct{ name, doc, wantApproval, wantWake string }{ + {"stored before the settings existed", `{` + roles + `,"chats":{"move_by":"manage"}}`, acl.ApprovalsByOwner, acl.WakeByView}, + {"set", `{` + roles + `,"chats":{"approvals_by":"answer","wake_by":"run"}}`, acl.ApprovalsByAnswer, acl.WakeByRun}, + {"wake set to owner", `{` + roles + `,"chats":{"wake_by":"owner"}}`, acl.ApprovalsByOwner, acl.WakeByOwner}, + {"set to words nobody defined", `{` + roles + `,"chats":{"approvals_by":"anyone","wake_by":"anyone"}}`, acl.ApprovalsByOwner, acl.WakeByView}, + } { + if _, err := db.Exec(`UPDATE org_policy SET doc = ?, rev = ?`, tc.doc, 20+i); err != nil { + t.Fatal(err) + } + got, err := st.OrgPolicy() + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + if got.Rev != 20+i || got.Chats.ApprovalsByFor() != tc.wantApproval || got.Chats.WakeByFor() != tc.wantWake { + t.Errorf("%s: revision %d, approvals %q, wake %q, want %q and %q", tc.name, got.Rev, got.Chats.ApprovalsByFor(), got.Chats.WakeByFor(), tc.wantApproval, tc.wantWake) + } + } +} From a6f85d0970cf41ce4f33cedc1509902d3dfe67b9 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:45:14 -0500 Subject: [PATCH 2/6] org: a guest cannot approve a tool call through the answer door, and approvals_by lets an organization allow it The hosted-chat guest wire checks each call a shared chat's guest sends against a table of methods and the verb each one needs. The table keeps the tool-approval frame, `ResolveConsent`, with the owner under every role, and the docs said a command that needs approval waits for the owner. But a tool approval is also a question the chat asks, and the answer to any question is `ResolveQuestion`, which the table lets a person who holds `answer` send (the `edit` role does). Its payload names the question's kind, and the guest wire never looked: an `edit` guest could send an answer of kind `consent` with the key for "allow once" or "allow always" and the chat ran the command as its owner. Seen through the real wire in TestApprovalsByOwnerKeepsAToolApprovalWithTheOwnerOnEveryDoor, which fails on the code before this commit. Now the wire reads a `ResolveQuestion` payload with the engine's own decoder into the engine's own type, and a consent answer follows the new policy setting `chats.approvals_by`: - `owner`, also what an absent setting means: refused with the sentence the older frame already gets ("This chat is shared with you. Only its owner can do that."). Every other answer, and every other call, is unchanged. - `answer`: a person who holds `answer` may allow one call once, or refuse it, through either door. Allowing a tool for the rest of the chat, putting the approval away, revising an answer and the chat's own approval setting stay with the owner. A person who cannot answer is still told so in the words they always read. The setting is read again on every heartbeat with the verbs, so a policy change reaches a window that is already open. A guest's approval is noted as the chat's latest asker, the way an answer already was. Tests: TestApprovalsByOwnerKeepsAToolApprovalWithTheOwnerOnEveryDoor, TestApprovalsByAnswerLetsAnAnswererAllowOnceOrRefuseAndNothingWider, TestApprovalsByReachesAnOpenWindowOnTheNextHeartbeat, TestApprovalsByAnswerNamesTheApproverAsTheAsker, TestChatsSettingsAreValidatedAndShownByThePolicy. Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/hosted_guest.go | 96 ++++-- .../serve/hosted_guest_choices_test.go | 312 ++++++++++++++++++ 2 files changed, 389 insertions(+), 19 deletions(-) create mode 100644 internal/factory/serve/hosted_guest_choices_test.go diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index 09d2717ae0..54e536d5aa 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -16,6 +16,7 @@ import ( "github.com/Agent-Field/codeaf/internal/factory/acl" "github.com/Agent-Field/codeaf/internal/factory/store" "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" "github.com/coder/websocket" ) @@ -43,8 +44,9 @@ type hostedGuest struct { cancel context.CancelFunc heartbeat time.Duration client, host net.Conn - verbs atomic.Value - writeMu sync.Mutex + // rights holds a hostedGuestRights and is replaced on every heartbeat. + rights atomic.Value + writeMu sync.Mutex } // addGuest and closeHostedGuests use one lock so shutdown also reaches a wire still opening. @@ -113,14 +115,14 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I clientConn, closeClient := hostedGuestConn(ctx, client) defer closeClient() p.client = clientConn - p.verbs.Store(hostedGuestVerbs(v, item)) + p.rights.Store(hostedGuestRightsOf(v, item)) var pumps sync.WaitGroup defer func() { cancel() pumps.Wait() }() pumps.Go(func() { - p.checkHeartbeat(func() acl.VerbSet { + p.checkHeartbeat(func() hostedGuestRights { return h.refreshHostedGuest(r, item.ID, owner, v.Handle) }) }) @@ -202,8 +204,8 @@ func (p *hostedGuest) fromClient(forwarding func(method, class string)) { if err != nil { return } - verbs := p.verbs.Load().(acl.VerbSet) - if !verbs.Has(acl.VerbView) { + rights := p.rights.Load().(hostedGuestRights) + if !rights.verbs.Has(acl.VerbView) { // The heartbeat owns the final line when it takes access away. <-p.ctx.Done() return @@ -221,8 +223,8 @@ func (p *hostedGuest) fromClient(forwarding func(method, class string)) { p.fatal(hostedGuestBadCall) return } - class := hostedGuestMethods[frame.Method] - if words := hostedGuestRefusal(class, verbs); words != "" { + class, words := hostedGuestDecision(frame, rights) + if words != "" { // A result always has an ID, including when the caller used zero. result := struct { Kind string `json:"kind"` @@ -357,7 +359,63 @@ func hostedGuestVerbs(v Viewer, item Item) acl.VerbSet { return v.acc.rules().Verbs(v.caller(), v.acc.item(item), v.acc.time()) } -func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { +// hostedGuestRights is what one guest wire may do right now: the verbs the policy gives the person on the chat, and the +// organization's rule for who approves a tool call. Both are read again on every heartbeat, so a policy change reaches a +// window that is already open, in the same beat that takes a verb away. +type hostedGuestRights struct { + verbs acl.VerbSet + approvals string +} + +func hostedGuestRightsOf(v Viewer, item Item) hostedGuestRights { + return hostedGuestRights{verbs: hostedGuestVerbs(v, item), approvals: v.acc.rules().Chats.ApprovalsByFor()} +} + +// hostedGuestDecision classifies one call from a guest and answers the sentence the guest is refused with, or "" when +// the call may reach the chat. The method table decides almost everything; the two doors that carry a tool approval are +// the exception, because approving is not one method: the older frame is ResolveConsent, and the answer to ANY question +// the chat asks, an allow among them, is ResolveQuestion. +func hostedGuestDecision(frame remote.Frame, rights hostedGuestRights) (class, refusal string) { + class = hostedGuestMethods[frame.Method] + if frame.Method == remote.MethodConsent && rights.approvals == acl.ApprovalsByAnswer { + // One allow or one refusal of the call the chat is waiting on. Allowing a tool for good has its own frame, + // ResolveConsentRemember, which the table leaves with the owner under every setting. + class = acl.VerbAnswer + } + if words := hostedGuestRefusal(class, rights.verbs); words != "" { + return class, words + } + if frame.Method == remote.MethodQuestionResolve && !hostedGuestMayAnswer(frame, rights) { + return class, hostedGuestOwnerOnly + } + return class, "" +} + +// hostedGuestMayAnswer is whether a guest who already holds the answer verb may send this ResolveQuestion. An answer that +// is not to a tool approval always may. One that is waits for the owner unless the organization let answerers approve, +// and even then only the two plain answers (allow once, refuse) pass. The payload is read with the engine's own decoder +// into the engine's own type, so this cannot read an answer differently from the way the chat will. +func hostedGuestMayAnswer(frame remote.Frame, rights hostedGuestRights) bool { + var args remote.QuestionArgs + if len(frame.Payload) != 0 && json.Unmarshal(frame.Payload, &args) != nil { + // The chat cannot read it either and refuses it by itself. + return true + } + answer := args.Answer + if !strings.EqualFold(strings.TrimSpace(string(answer.Kind)), string(session.QuestionConsent)) { + return true + } + if rights.approvals != acl.ApprovalsByAnswer || answer.Dismissed || answer.Revises || answer.Clarify { + return false + } + switch answer.FirstKey() { + case "1", "3": + return true + } + return false +} + +func (p *hostedGuest) checkHeartbeat(refresh func() hostedGuestRights) { ticker := time.NewTicker(p.heartbeat) defer ticker.Stop() for { @@ -365,9 +423,9 @@ func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { case <-p.ctx.Done(): return case <-ticker.C: - verbs := refresh() - p.verbs.Store(verbs) - if !verbs.Has(acl.VerbView) { + rights := refresh() + p.rights.Store(rights) + if !rights.verbs.Has(acl.VerbView) { p.fatal(hostedGuestRemoved) return } @@ -375,34 +433,34 @@ func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { } } -func (h *Handler) refreshHostedGuest(r *http.Request, id, owner, asker string) acl.VerbSet { +func (h *Handler) refreshHostedGuest(r *http.Request, id, owner, asker string) hostedGuestRights { r = authRequest(r) if !h.allowed(r) { - return nil + return hostedGuestRights{} } v, err := h.itemViewer(r) if err != nil || v.Handle != asker || !h.teamAllows(v.Handle) || r.Context().Value(authErrorKey{}).(*authErrorState).err != nil { - return nil + return hostedGuestRights{} } st := h.config.Store if call, _ := agentCallOf(r); call.bot != "" { bot, _, state, err := st.FindBotToken(sessionHash(bearer(r)), h.now()) if err != nil || state != store.BotTokenLive || bot.ID != call.bot || bot.Creator != v.Handle { - return nil + return hostedGuestRights{} } // The stored scope and the policy bundle can both change while the bot is attached. v.Agent.Only = botScopeVerbs(v.acc.rules(), bot.Scope) } row, found, err := st.Resource(store.SessionKind, id) if err != nil || !found || row.Owner.ID != owner || !hostedRegistration(row) { - return nil + return hostedGuestRights{} } - return hostedGuestVerbs(v, h.resourceItem(row, factory.OrgWorkstream{})) + return hostedGuestRightsOf(v, h.resourceItem(row, factory.OrgWorkstream{})) } func (h *Handler) noteHostedGuestCall(id, owner, asker, method, class string) { // Attribution is approximate because the next model call can follow any accepted words. - if class == acl.VerbRun || method == remote.MethodSteer || method == remote.MethodQuestionResolve { + if class == acl.VerbRun || method == remote.MethodSteer || method == remote.MethodQuestionResolve || method == remote.MethodConsent { h.config.Hosted.state.noteAsker(id, asker) } // The chat checks the keyboard for prompts and steer. A guest with run can use Take to drive. diff --git a/internal/factory/serve/hosted_guest_choices_test.go b/internal/factory/serve/hosted_guest_choices_test.go new file mode 100644 index 0000000000..b4de65ee9e --- /dev/null +++ b/internal/factory/serve/hosted_guest_choices_test.go @@ -0,0 +1,312 @@ +package serve + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/coder/websocket" +) + +// These tests are the contract for the two settings a team can turn on in a hosted chat's policy, `chats.approvals_by` and +// `chats.wake_by`. Each one drives the real organization handler with a real store over a real WebSocket, and the only +// stand-in is the chats' host behind it, which records what reaches it. + +// guestPayloadCall is one call frame that carries a payload. +func guestPayloadCall(id int, method, payload string) string { + return fmt.Sprintf("{\"kind\":\"call\",\"id\":%d,\"method\":%q,\"payload\":%s}\n", id, method, payload) +} + +// consentAnswer is the payload of a ResolveQuestion that answers a tool approval, with extra fields spliced in. +func consentAnswer(extra string) string { + if extra != "" { + extra = "," + extra + } + return `{"answer":{"kind":"consent","id":7` + extra + `}}` +} + +// guestHostGot reads what reached the host and answers the method and payload of the one frame. +func guestHostGot(t *testing.T, host guestHostWire) (string, string) { + t.Helper() + frame := guestFrame(t, guestHostLine(t, host)) + return frame.Method, string(frame.Payload) +} + +// guestExpectNothingMore fails when anything else reached the host. +func guestExpectNothingMore(t *testing.T, host guestHostWire) { + t.Helper() + select { + case raw, ok := <-host.incoming: + if ok { + t.Fatalf("a refused call reached the chat: %q", raw) + } + case <-time.After(300 * time.Millisecond): + } +} + +// guestApprovalRig is santosh's chat shared with abir at `view` and mia at `edit`, with one guest wire open for each of +// them. The policy edit, when there is one, is saved before the wires open so nothing waits on a heartbeat. +type guestApprovalRig struct { + rg *hostedRig + chat string + srv *httptest.Server + wires map[string]guestWires +} + +type guestWires struct { + client *websocket.Conn + host guestHostWire + refusals chan string +} + +func newGuestApprovalRig(t *testing.T, edit func(*acl.Policy)) *guestApprovalRig { + t.Helper() + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "santosh", chat, "mia", "edit") + if edit != nil { + rg.setAccessPolicy(t, edit) + } + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + a := &guestApprovalRig{rg: rg, chat: chat, srv: srv, wires: map[string]guestWires{}} + for _, person := range []string{"abir", "mia"} { + client, host := guestConnect(t, srv, opened, rg.tokens[person], chat) + refusals := make(chan string, 64) + go func() { + for { + _, raw, err := client.Read(t.Context()) + if err != nil { + return + } + refusals <- string(raw) + } + }() + a.wires[person] = guestWires{client, host, refusals} + } + return a +} + +// ask sends a call as who and answers "" when it reached the chat, or the sentence the guest was refused with on its own +// wire. Every call is answered one way or the other before the next is sent, so a late frame cannot be taken for the +// next call's. +func (a *guestApprovalRig) ask(t *testing.T, who string, id int, method, payload string) string { + t.Helper() + w := a.wires[who] + line := guestCall(id, method) + if payload != "" { + line = guestPayloadCall(id, method, payload) + } + guestWrite(t, w.client, line) + select { + case raw := <-w.host.incoming: + if frame := guestFrame(t, raw); frame.Method != method || frame.ID != uint64(id) { + t.Fatalf("the chat received %q, want call %d to %s", raw, id, method) + } + return "" + case raw := <-w.refusals: + frame := guestFrame(t, raw) + if frame.Kind != "result" || frame.ID != uint64(id) || frame.Error == "" { + t.Fatalf("the refusal of %s was %q", method, raw) + } + return frame.Error + case <-time.After(5 * time.Second): + t.Fatalf("%s as %s was neither passed nor refused", method, who) + return "" + } +} + +// Contract A1: under the default policy, and under a policy that says `owner` out loud, a tool approval stays with the +// owner on BOTH of its doors, whatever role the guest holds. A person who holds `answer` (the `edit` role does) cannot +// approve or refuse a tool call by sending the answer to the chat's question; they can still answer every other question. +func TestApprovalsByOwnerKeepsAToolApprovalWithTheOwnerOnEveryDoor(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*acl.Policy) + }{ + {"absent", nil}, + {"owner", func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByOwner }}, + } { + t.Run(tc.name, func(t *testing.T) { + a := newGuestApprovalRig(t, tc.edit) + id := 0 + next := func() int { id++; return id } + // The two doors a tool approval has, and the three plain ways to say it on the second. + for _, call := range []struct{ name, method, payload string }{ + {"the older frame, allow", "ResolveConsent", `{"id":7,"allow":true}`}, + {"the older frame, remember", "ResolveConsentRemember", `{"id":7,"allow":true,"scope":"tool"}`}, + {"the answer door, allow once", "ResolveQuestion", consentAnswer(`"key":"1"`)}, + {"the answer door, allow always", "ResolveQuestion", consentAnswer(`"key":"2"`)}, + {"the answer door, refuse", "ResolveQuestion", consentAnswer(`"key":"3"`)}, + {"the answer door, a key hidden in picked", "ResolveQuestion", consentAnswer(`"key":"3","picked":["1"]`)}, + {"the answer door, the kind in capitals", "ResolveQuestion", `{"answer":{"KIND":" Consent ","ID":7,"KEY":"1"}}`}, + {"the answer door, put away", "ResolveQuestion", consentAnswer(`"key":"3","dismissed":true`)}, + } { + if got := a.ask(t, "mia", next(), call.method, call.payload); got != guestOwnerWords { + t.Errorf("%s: an edit guest reads %q, want %q", call.name, got, guestOwnerWords) + } + } + // A guest who cannot answer anything is told so in the words they always read, not the owner-only ones. + if got := a.ask(t, "abir", next(), "ResolveQuestion", consentAnswer(`"key":"1"`)); got != guestAnswerWords { + t.Errorf("a view guest answering a tool approval reads %q, want %q", got, guestAnswerWords) + } + // Everything else a guest with `answer` could always do still reaches the chat. + for _, payload := range []string{ + `{"answer":{"kind":"ask","id":3,"key":"1"}}`, + `{"answer":{"kind":"task","id":4,"key":"2"}}`, + ``, + } { + if got := a.ask(t, "mia", next(), "ResolveQuestion", payload); got != "" { + t.Errorf("an answer to %s was refused with %q", payload, got) + } + } + guestExpectNothingMore(t, a.wires["mia"].host) + }) + } +} + +// Contract A2: under `approvals_by: answer`, a person who holds `answer` can allow one tool call once, or refuse it, by +// either door. Allowing a tool for the rest of the chat, putting the approval away, and every other frame of the chat's +// settings stay with the owner, and a person who cannot answer still cannot. +func TestApprovalsByAnswerLetsAnAnswererAllowOnceOrRefuseAndNothingWider(t *testing.T) { + a := newGuestApprovalRig(t, func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByAnswer }) + id := 0 + next := func() int { id++; return id } + for _, call := range []struct{ name, method, payload string }{ + {"the older frame, allow", "ResolveConsent", `{"id":7,"allow":true}`}, + {"the older frame, refuse", "ResolveConsent", `{"id":7,"allow":false}`}, + {"the answer door, allow once", "ResolveQuestion", consentAnswer(`"key":"1"`)}, + {"the answer door, refuse", "ResolveQuestion", consentAnswer(`"key":"3"`)}, + {"the answer door, allow once picked", "ResolveQuestion", consentAnswer(`"picked":["1"]`)}, + } { + if got := a.ask(t, "mia", next(), call.method, call.payload); got != "" { + t.Errorf("%s: an edit guest was refused with %q", call.name, got) + } + } + for _, call := range []struct{ name, method, payload string }{ + {"the older frame, remember", "ResolveConsentRemember", `{"id":7,"allow":true,"scope":"tool"}`}, + {"the older frame, remember a refusal", "ResolveConsentRemember", `{"id":7,"allow":false,"scope":"tool"}`}, + {"the answer door, allow always", "ResolveQuestion", consentAnswer(`"key":"2"`)}, + {"the answer door, a pick hidden behind a plain key", "ResolveQuestion", consentAnswer(`"key":"1","picked":["2"]`)}, + {"the answer door, put away", "ResolveQuestion", consentAnswer(`"key":"3","dismissed":true`)}, + {"the answer door, a revision", "ResolveQuestion", consentAnswer(`"key":"1","revises":true`)}, + {"the answer door, no key", "ResolveQuestion", consentAnswer(``)}, + {"the chat's own approval setting", remote.MethodSetApproval, `{}`}, + } { + if got := a.ask(t, "mia", next(), call.method, call.payload); got != guestOwnerWords { + t.Errorf("%s: an edit guest reads %q, want %q", call.name, got, guestOwnerWords) + } + } + // Without the answer verb nothing changes: the guest is told they may not answer. + for _, call := range []struct{ method, payload string }{ + {"ResolveConsent", `{"id":7,"allow":true}`}, + {"ResolveQuestion", consentAnswer(`"key":"1"`)}, + } { + if got := a.ask(t, "abir", next(), call.method, call.payload); got != guestAnswerWords { + t.Errorf("a view guest sending %s reads %q, want %q", call.method, got, guestAnswerWords) + } + } + guestExpectNothingMore(t, a.wires["mia"].host) +} + +// Contract A3: the setting reaches a window that is already open, within a heartbeat, in both directions, the way a verb +// taken away does. +func TestApprovalsByReachesAnOpenWindowOnTheNextHeartbeat(t *testing.T) { + a := newGuestApprovalRig(t, nil) + allow := func(id int) string { + return a.ask(t, "mia", id, "ResolveQuestion", consentAnswer(`"key":"1"`)) + } + if got := allow(1); got != guestOwnerWords { + t.Fatalf("before the setting: %q", got) + } + a.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByAnswer }) + // Two beats let a check that was already running when the policy was saved finish. + time.Sleep(2 * guestTestHeartbeat) + if got := allow(2); got != "" { + t.Fatalf("after setting answer: %q", got) + } + a.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats = acl.Chats{} }) + time.Sleep(2 * guestTestHeartbeat) + if got := allow(3); got != guestOwnerWords { + t.Fatalf("after taking the setting out again: %q", got) + } +} + +// Contract A4: an approval answered by a guest is attributed to that guest on the chat's spend, because it is what lets +// the next model call happen. The owner's own window is not changed by any of it: it still reaches the chat through the +// unchanged byte-copying proxy. +func TestApprovalsByAnswerNamesTheApproverAsTheAsker(t *testing.T) { + a := newGuestApprovalRig(t, func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByAnswer }) + hs := a.rg.h.config.Hosted.state + if got := hs.askerOf(a.chat); got == "mia" { + t.Fatalf("mia was the asker before she did anything") + } + if got := a.ask(t, "mia", 1, "ResolveConsent", `{"id":7,"allow":true}`); got != "" { + t.Fatalf("the approval was refused: %q", got) + } + if got := hs.askerOf(a.chat); got != "mia" { + t.Fatalf("the asker after mia's approval is %q", got) + } +} + +// Contract A5 and W4: the two settings are the operator's to set, take only their words and say the allowed ones when +// refused, and the policy that GET returns shows them. An organization that set neither shows neither. +func TestChatsSettingsAreValidatedAndShownByThePolicy(t *testing.T) { + o := newWSOrg(t) + var p acl.Policy + o.do(t, "mia", "GET", policyPath, -1, nil, http.StatusOK, &p) + if p.Chats.ApprovalsBy != "" || p.Chats.WakeBy != "" { + t.Fatalf("the default policy already holds %+v", p.Chats) + } + raw := o.raw(t, "mia", "GET", policyPath, nil).Body.String() + if strings.Contains(raw, "approvals_by") || strings.Contains(raw, "wake_by") { + t.Fatalf("the default policy's JSON names a setting nobody set: %s", raw) + } + + p.Chats.ApprovalsBy = acl.ApprovalsByAnswer + o.do(t, "mia", "PUT", policyPath, p.Rev, p, http.StatusForbidden, nil) + + for _, tc := range []struct { + name string + edit func(*acl.Policy) + words []string + }{ + {"approvals_by", func(p *acl.Policy) { p.Chats.ApprovalsBy = "anyone" }, []string{"owner", "answer"}}, + {"wake_by", func(p *acl.Policy) { p.Chats.WakeBy = "anyone" }, []string{"view", "run", "owner"}}, + } { + bad := p + bad.Chats = acl.Chats{} + tc.edit(&bad) + w := o.raw(t, "owner", "PUT", policyPath, bad) + if w.Code != http.StatusUnprocessableEntity { + t.Fatalf("%s set to a word it does not take: %d %s", tc.name, w.Code, w.Body) + } + sentence := errorOf(t, w.Body.Bytes()) + for _, word := range tc.words { + if !strings.Contains(sentence, word) { + t.Errorf("the refusal of a bad %s, %q, does not name %q", tc.name, sentence, word) + } + } + } + + saved := o.setAccessPolicy(t, func(p *acl.Policy) { + p.Chats.ApprovalsBy = acl.ApprovalsByAnswer + p.Chats.WakeBy = acl.WakeByRun + }) + var read acl.Policy + o.do(t, "mia", "GET", policyPath, -1, nil, http.StatusOK, &read) + if saved.Chats.ApprovalsBy != "answer" || read.Chats.ApprovalsBy != "answer" || read.Chats.WakeBy != "run" { + t.Fatalf("the policy after the write: saved %+v, read %+v", saved.Chats, read.Chats) + } + raw = o.raw(t, "mia", "GET", policyPath, nil).Body.String() + if !strings.Contains(raw, `"approvals_by":"answer"`) || !strings.Contains(raw, `"wake_by":"run"`) { + t.Fatalf("GET of the policy does not show the settings: %s", raw) + } +} From 45a047f92833cad5aa616025131148b49324d59e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:46:11 -0500 Subject: [PATCH 3/6] org: wake_by lets an organization keep a guest from starting a chat that is not running Opening a shared chat that is not running starts it, for its owner and in their place among the chats they may have running. Today anyone who can see the chat does that, and a `view` guest's `codeaf chat --org --once` is one way: it starts the chat in one-shot mode and is then refused when it tries to send, and the owner's own window reads "already open in a different interactive or headless mode" until the chat stops or idles. The organization's policy now has `chats.wake_by`: - `view`, also what an absent setting means: anyone who can see the chat opens it. Nothing changes, and the organization server asks the chats' host for nothing it did not ask for before. - `run`: only a person who may send messages in the chat starts it. A person who can only watch is told "This chat is not running. Starting it takes permission to send messages in it. Ask its owner." and the host's wire door is never reached, so nothing is started. - `owner`: only the chat's owner starts it (a bot acting for them does not count). Others read "This chat is not running. Only its owner can start it. Ask them to open it." A chat that is already running opens for everyone who can see it under every setting. The owner's own window is the byte-copying proxy and no setting touches it. If the chat's state cannot be read, a restricted setting refuses with the "not answering" sentence instead of guessing. The rule is checked when the window opens; a chat that stops in the instant between the check and the connection can still be started by the guest. Tests: TestWakeByViewIsTodaysBehaviourAndAsksTheHostNothingExtra, TestWakeByRunKeepsAWatcherFromStartingAChatThatIsNotRunning, TestWakeByOwnerLeavesStartingAChatToItsOwner, TestWakeByTurnsBackToViewAndOpensTheChatAgain. Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/hosted_access.go | 4 + internal/factory/serve/hosted_guest.go | 45 ++++++ .../serve/hosted_guest_choices_test.go | 152 ++++++++++++++++++ internal/factory/serve/hosted_proxy_test.go | 41 ++++- 4 files changed, 241 insertions(+), 1 deletion(-) diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go index 7ed03cfcb3..a302370fc3 100644 --- a/internal/factory/serve/hosted_access.go +++ b/internal/factory/serve/hosted_access.go @@ -157,6 +157,10 @@ func (h *Handler) lookupHostedChat(w http.ResponseWriter, r *http.Request, id st return chat, true } +// hostedStateRunning is the state the chats' host reports for a chat with a live process. Anything else it says (it says +// suspended) means opening the chat starts it. +const hostedStateRunning = "running" + type hostedStatusFields struct { ID string `json:"id"` State string `json:"state"` diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index 54e536d5aa..2013d82ad1 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -35,6 +35,10 @@ const ( // A guest opening a chat that is not running starts it for its owner, and either the owner's own limit or the machine's can say no. // The sentence is the guest's, never the owner's ("You already have ... chats running"), and names no number or person. hostedGuestNoRoom = "This chat is not running, and there is no room to start it right now. Try again later." + // The two sentences a guest reads when the organization keeps them from starting a chat that is not running + // (chats.wake_by). Neither says how the chat comes to be stopped, because the guest has no use for the word. + hostedGuestWakeOwner = "This chat is not running. Only its owner can start it. Ask them to open it." + hostedGuestWakeRun = "This chat is not running. Starting it takes permission to send messages in it. Ask its owner." ) var errHostedGuestLineCap = errors.New(hostedGuestLongLine) @@ -127,6 +131,10 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I }) }) + if words := h.hostedGuestWakeRefusal(ctx, hs, item.ID, owner, v, p.rights.Load().(hostedGuestRights)); words != "" { + p.fatal(words) + return + } host, status := hs.dialGuestHost(ctx, item.ID, owner) if host == nil { switch status { @@ -155,6 +163,43 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I cancel() } +// hostedGuestWakeRefusal is the sentence a guest is refused with when the organization's rule (chats.wake_by) keeps them +// from starting a chat that is not running, and "" when the wire may go on. Opening a chat that is not running starts it +// for its owner, in its owner's place among the chats they may have running, and the rule is the only thing that says +// whether a guest may do that. The default rule asks for nothing and reads nothing, so an organization that never set it +// sees no extra request. A chat that stops between this read and the connection below it can still be started by the +// guest: the rule is checked when the window opens, not held for the life of the wire. +func (h *Handler) hostedGuestWakeRefusal(ctx context.Context, hs *hostedState, id, owner string, v Viewer, rights hostedGuestRights) string { + rule := v.acc.rules().Chats.WakeByFor() + if rule == acl.WakeByView { + return "" + } + // An owner is the person, never a bot acting for them, because a bot's scope is a limit on what it may start. + words, may := hostedGuestWakeOwner, v.Handle == owner && v.Agent == nil + if rule == acl.WakeByRun { + words, may = hostedGuestWakeRun, rights.verbs.Has(acl.VerbRun) + } + if may { + return "" + } + status, _, body, err := hs.call(ctx, http.MethodGet, "/v1/sessions/"+id, owner, nil) + if err != nil || (status != http.StatusOK && status != http.StatusNotFound) { + // Without the chat's state the rule cannot be applied, and starting it would be the one thing it forbids. + return hostedUnreachable + } + if status == http.StatusNotFound { + return hostedGuestRemoved + } + var row hostedStatusFields + if json.Unmarshal(body, &row) != nil { + return hostedUnreachable + } + if row.State == hostedStateRunning { + return "" + } + return words +} + func (hs *hostedState) dialGuestHost(ctx context.Context, id, owner string) (*websocket.Conn, int) { // The dial deadline bounds only the handshake, because a live wire may last for hours. ctx, cancel := context.WithTimeout(ctx, hostedCallTimeout) diff --git a/internal/factory/serve/hosted_guest_choices_test.go b/internal/factory/serve/hosted_guest_choices_test.go index b4de65ee9e..2558bdb473 100644 --- a/internal/factory/serve/hosted_guest_choices_test.go +++ b/internal/factory/serve/hosted_guest_choices_test.go @@ -1,6 +1,7 @@ package serve import ( + "encoding/json" "fmt" "net/http" "net/http/httptest" @@ -310,3 +311,154 @@ func TestChatsSettingsAreValidatedAndShownByThePolicy(t *testing.T) { t.Fatalf("GET of the policy does not show the settings: %s", raw) } } + +// wakeRig is santosh's chat that is NOT running, shared with abir at `view`, mia at `edit` and noor at `full`. +type wakeRig struct { + rg *hostedRig + chat string + srv *httptest.Server + opened <-chan guestHostWire +} + +func newWakeRig(t *testing.T) *wakeRig { + t.Helper() + 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) + t.Cleanup(srv.Close) + return &wakeRig{rg: rg, chat: chat, srv: srv, opened: opened} +} + +// open attaches as who and says the sentence the window was refused with, or "" when the host's wire was reached. +func (w *wakeRig) open(t *testing.T, who string) string { + t.Helper() + client := guestDial(t, w.srv, w.rg.tokens[who], w.chat) + guestWrite(t, client, guestTestHello) + frames := make(chan string, 1) + go func() { + if _, raw, err := client.Read(t.Context()); err == nil { + frames <- string(raw) + } + }() + select { + case host := <-w.opened: + var hello remote.Frame + if err := json.Unmarshal([]byte(guestHostLine(t, host)), &hello); err != nil || hello.Kind != "hello" { + t.Fatalf("the chat did not receive a hello: %v", err) + } + return "" + case raw := <-frames: + frame := guestFrame(t, raw) + if frame.Kind != "fatal" || frame.Error == "" { + t.Fatalf("a refused window was sent %+v", frame) + } + return frame.Error + case <-time.After(5 * time.Second): + t.Fatal("the window was neither let through nor refused") + return "" + } +} + +const ( + wakeOwnerWords = "This chat is not running. Only its owner can start it. Ask them to open it." + wakeRunWords = "This chat is not running. Starting it takes permission to send messages in it. Ask its owner." +) + +// Contract W1: with no setting, or `view` said out loud, anyone who can see a chat that is not running opens it, which +// starts it for its owner, exactly as before. The organization server asks the host nothing more than it always did. +func TestWakeByViewIsTodaysBehaviourAndAsksTheHostNothingExtra(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*acl.Policy) + }{ + {"absent", nil}, + {"view", func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByView }}, + } { + t.Run(tc.name, func(t *testing.T) { + w := newWakeRig(t) + if tc.edit != nil { + w.rg.setAccessPolicy(t, tc.edit) + } + before := w.rg.host.rowReads(w.chat) + if got := w.open(t, "abir"); got != "" { + t.Fatalf("a view guest was refused with %q", got) + } + if w.rg.host.wireRequests(w.chat) != 1 { + t.Fatalf("the host's wire door was reached %d times", w.rg.host.wireRequests(w.chat)) + } + // One read is the model-access check every attach has always made. + if reads := w.rg.host.rowReads(w.chat) - before; reads != 1 { + t.Fatalf("an attach read the chat's row %d times, want the one it always made", reads) + } + }) + } +} + +// Contract W2: under `wake_by: run`, a person who can only watch a chat that is not running is told to ask its owner and +// the chat is not started (the host's wire door is never reached); a person who may send messages starts it; and a chat +// that is already running opens for both. +func TestWakeByRunKeepsAWatcherFromStartingAChatThatIsNotRunning(t *testing.T) { + w := newWakeRig(t) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByRun }) + if got := w.open(t, "abir"); got != wakeRunWords { + t.Fatalf("a view guest on a chat that is not running reads %q, want %q", got, wakeRunWords) + } + if n := w.rg.host.wireRequests(w.chat); n != 0 { + t.Fatalf("the refused guest still started the chat: %d wire requests", n) + } + if got := w.open(t, "mia"); got != "" { + t.Fatalf("an edit guest was refused with %q", got) + } + if n := w.rg.host.wireRequests(w.chat); n != 1 { + t.Fatalf("the edit guest's attach reached the wire door %d times", n) + } + w.rg.host.setRunning(w.chat, true) + if got := w.open(t, "abir"); got != "" { + t.Fatalf("a view guest was refused on a running chat: %q", got) + } + if n := w.rg.host.wireRequests(w.chat); n != 2 { + t.Fatalf("the running chat's attach reached the wire door %d times in all", n) + } +} + +// Contract W3: under `wake_by: owner`, only the chat's owner starts it. A guest with `edit` is told to ask the owner, a +// running chat still opens for them, and the owner's own window is the unchanged proxy, which no setting touches. +func TestWakeByOwnerLeavesStartingAChatToItsOwner(t *testing.T) { + w := newWakeRig(t) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByOwner }) + for _, who := range []string{"abir", "mia"} { + if got := w.open(t, who); got != wakeOwnerWords { + t.Fatalf("%s on a chat that is not running reads %q, want %q", who, got, wakeOwnerWords) + } + } + if n := w.rg.host.wireRequests(w.chat); n != 0 { + t.Fatalf("a refused guest started the chat: %d wire requests", n) + } + if got := w.open(t, "santosh"); got != "" { + t.Fatalf("the owner was refused with %q", got) + } + if n := w.rg.host.wireRequests(w.chat); n != 1 { + t.Fatalf("the owner's attach reached the wire door %d times", n) + } + w.rg.host.setRunning(w.chat, true) + if got := w.open(t, "mia"); got != "" { + t.Fatalf("an edit guest was refused on a running chat: %q", got) + } +} + +// Contract W5: the setting reads the organization's policy afresh on each attach, so turning it back to `view` (or +// taking it out) lets a watcher open a chat that is not running again. +func TestWakeByTurnsBackToViewAndOpensTheChatAgain(t *testing.T) { + w := newWakeRig(t) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByOwner }) + if got := w.open(t, "abir"); got != wakeOwnerWords { + t.Fatalf("under owner a view guest reads %q", got) + } + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats = acl.Chats{} }) + if got := w.open(t, "abir"); got != "" { + t.Fatalf("after taking the setting out a view guest reads %q", got) + } +} diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index 7afaa3e688..8425c8b9af 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -35,6 +35,9 @@ type fakeChatHost struct { wire func(*websocket.Conn, *http.Request) // A wire refusal makes the host answer the wire with this status and its own sentence instead of upgrading. wireRefusal int + // running names the chats whose row says "running". Every other chat is suspended, which is what a chat is until + // somebody opens it. + running map[string]bool } type hostSeen struct { @@ -67,6 +70,38 @@ func (f *fakeChatHost) adopt(id, person string) { f.owners[id], f.tokens[id] = person, "" } +// setRunning makes a chat's row say it has a live process (or not). +func (f *fakeChatHost) setRunning(id string, running bool) { + f.mu.Lock() + defer f.mu.Unlock() + if f.running == nil { + f.running = map[string]bool{} + } + f.running[id] = running +} + +// wireRequests counts the attaches that reached the host's wire door, each of which starts a chat that is not running. +func (f *fakeChatHost) wireRequests(id string) int { + n := 0 + for _, seen := range f.requests() { + if seen.method == http.MethodGet && seen.path == "/v1/sessions/"+id+"/wire" { + n++ + } + } + return n +} + +// rowReads counts the reads of one chat's row. +func (f *fakeChatHost) rowReads(id string) int { + n := 0 + for _, seen := range f.requests() { + if seen.method == http.MethodGet && seen.path == "/v1/sessions/"+id { + n++ + } + } + return n +} + func (f *fakeChatHost) ownerOf(id string) string { f.mu.Lock() defer f.mu.Unlock() @@ -161,9 +196,13 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { if lie, ok := f.rowBearer[id]; ok { fingerprint = lie } + state := "suspended" + if f.running[id] { + state = "running" + } f.mu.Unlock() w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"id":"`+id+`","state":"suspended","model_bearer":"`+fingerprint+`"}`+"\n") + _, _ = io.WriteString(w, `{"id":"`+id+`","state":"`+state+`","model_bearer":"`+fingerprint+`"}`+"\n") case len(parts) == 1 && r.Method == http.MethodDelete: f.mu.Lock() delete(f.owners, id) From 929d10f4a83bc18163c7ca8ec59fbb6edca3431c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:46:44 -0500 Subject: [PATCH 4/6] org: test that a bot without run never counts as the owner for wake_by TestWakeByDoesNotLetABotWithoutRunStartItsCreatorsChat: a view-scoped bot is refused on its creator's chat that is not running under both owner and run, and a bot that may run chats starts it under run. Co-Authored-By: Claude Opus 5.5 --- .../serve/hosted_guest_choices_test.go | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/internal/factory/serve/hosted_guest_choices_test.go b/internal/factory/serve/hosted_guest_choices_test.go index 2558bdb473..15cc3e3d50 100644 --- a/internal/factory/serve/hosted_guest_choices_test.go +++ b/internal/factory/serve/hosted_guest_choices_test.go @@ -335,7 +335,13 @@ func newWakeRig(t *testing.T) *wakeRig { // open attaches as who and says the sentence the window was refused with, or "" when the host's wire was reached. func (w *wakeRig) open(t *testing.T, who string) string { t.Helper() - client := guestDial(t, w.srv, w.rg.tokens[who], w.chat) + return w.openWith(t, w.rg.tokens[who]) +} + +// openWith is open for a credential that is not a person's, a bot's for one. +func (w *wakeRig) openWith(t *testing.T, token string) string { + t.Helper() + client := guestDial(t, w.srv, token, w.chat) guestWrite(t, client, guestTestHello) frames := make(chan string, 1) go func() { @@ -462,3 +468,33 @@ func TestWakeByTurnsBackToViewAndOpensTheChatAgain(t *testing.T) { t.Fatalf("after taking the setting out a view guest reads %q", got) } } + +// Contract W6: a bot never counts as the owner. Its creator's own chat that is not running stays closed to a bot whose +// scope does not let it run chats, under `owner` and under `run` alike, while the creator opens it, and a bot whose scope +// holds `run` starts it under `run`. +func TestWakeByDoesNotLetABotWithoutRunStartItsCreatorsChat(t *testing.T) { + w := newWakeRig(t) + w.chat = w.rg.create(t, "abir") + view := w.rg.contractBot(t, "abir", "View bot", "view") + full := w.rg.contractBot(t, "abir", "Full bot", "full") + + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByOwner }) + if got := w.openWith(t, view.Token); got != wakeOwnerWords { + t.Fatalf("a view bot under owner reads %q, want %q", got, wakeOwnerWords) + } + if n := w.rg.host.wireRequests(w.chat); n != 0 { + t.Fatalf("a refused bot started its creator's chat: %d wire requests", n) + } + if got := w.open(t, "abir"); got != "" { + t.Fatalf("the creator was refused with %q", got) + } + + w.rg.host.setRunning(w.chat, false) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByRun }) + if got := w.openWith(t, view.Token); got != wakeRunWords { + t.Fatalf("a view bot under run reads %q, want %q", got, wakeRunWords) + } + if got := w.openWith(t, full.Token); got != "" { + t.Fatalf("a bot that may run chats was refused with %q", got) + } +} From 00bd0e78a9878711bb8dff61decd36fed3716ede Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:47:58 -0500 Subject: [PATCH 5/6] docs: describe chats.approvals_by and chats.wake_by, and write them into the manual docs/organizations.md and deploy/org/README.md describe both settings where the policy is described, and the two known limits that mention them (a guest's `--once` starting a chat for its owner, and a tool approval staying with the owner) now say what the setting changes. The app protocol's policy shape lists the two fields. The chat's own manual has a section for each setting on the hosted-chats page, in the words someone would ask with, and the refusal, keyboard and sharing sections name the new sentences. Probes keep each question on its page. Co-Authored-By: Claude Opus 5.5 --- deploy/org/README.md | 25 ++++++++++++++++--- docs/design/app-v3/PROTOCOL.md | 6 +++-- docs/organizations.md | 13 +++++++--- .../chat/organization-hosted-sessions.md | 18 ++++++++++--- internal/manual/chat/organization-sharing.md | 4 +-- internal/manual/chat_hosted_test.go | 5 ++++ 6 files changed, 57 insertions(+), 14 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 0081055de0..a89ee0335f 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -425,6 +425,24 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i into their own My space. The refusals read `Only the person who owns this chat can move it, and they need permission to manage it.` (the default) and `Only the person who owns this chat, or someone with permission to manage it, can move it.` Any other word is refused with a 422. +- **Who approves a tool call.** `PUT /v1/org/policy` takes `"chats": {"approvals_by": "owner"}` or `"chats": {"approvals_by": "answer"}`. + Absent or empty means `owner`: a command a shared chat wants to run, which needs approval under its owner's approval mode, + waits for the owner whatever role anyone else holds, on both of the chat's approval doors (`ResolveConsent`, and an answer to + the chat's question of kind `consent` sent through `ResolveQuestion`); a guest who tries either reads `This chat is shared with + you. Only its owner can do that.` `answer` lets a person who holds the `answer` verb (the `edit` and `full` roles) allow one + call once, or refuse it, by either door. Allowing a tool for the rest of the chat, putting the approval away, revising an + answer and the chat's own approval setting stay with the owner, and a person who cannot answer is refused as always. The + guest's approval is recorded as the chat's latest asker. The setting is re-read on each heartbeat, so it reaches a window + that is already open. Any other word is refused with a 422 that names the two. +- **Who may start a chat that is not running.** `PUT /v1/org/policy` takes `"chats": {"wake_by": "view"}`, `"run"` or `"owner"`. + Absent or empty means `view`: opening a shared chat that is not running starts it for its owner, in its owner's place among + the chats they may have running, for anyone who can see it (a `view` guest's `--once` included), which is what the server always + did. `run` lets only a person who holds `run` start it, and `owner` only its owner; anyone else reads `This chat is not running. + Starting it takes permission to send messages in it. Ask its owner.` or `This chat is not running. Only its owner can start it. + Ask them to open it.`, and the chats' host is never asked to start it. A chat that is already running opens for everyone who can + see it under every setting, and the owner's own window is not affected. The rule is checked when the window opens; if the + chat's state cannot be read, `run` and `owner` refuse with the "not answering" sentence. Any other word is refused with a 422 + that names the three. - **The hosting policy.** `PUT /v1/org/policy` takes `"hosting": {"local_sessions": "allow|warn|refuse", "max_session_cost_usd": 0}`. Empty `local_sessions` means `refuse` for an organization that has chats' machine and `allow` for one that does not; the list reports the value that applies, with `words` to show for `refuse` (that @@ -438,9 +456,10 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i Known limit of this version: a guest's `Steer` or prompt is refused by the chat itself, in the chat's own words about the keyboard, while the owner's window holds the keyboard, because the guest's window does not take it on arrival; it goes through when the owner has no window open, or after the guest sends `Take` (allowed with `run`, and the owner's -window is told). `Interrupt` and `ResolveQuestion` are not affected. A tool-use approval stays the owner's, so a -command that needs one waits for the owner. The proper fix for both is a guest class inside the engine itself, which -is a change to the wire's own protocol and not made here. +window is told). `Interrupt` and `ResolveQuestion` are not affected, except that an answer to a tool approval is the +owner's unless `chats.approvals_by` says `answer`. A tool-use approval stays the owner's by default, so a command that +needs one waits for the owner. The proper fix for the keyboard is a guest class inside the engine itself, which is a +change to the wire's own protocol and not made here. ### Turning it on diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 7738473254..a3e8eb7719 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1159,8 +1159,10 @@ An engine whose hello carries `org_access` serves an organization's access polic grants on its things. `factory.org_policy` `GET /v1/org/policy` answers the policy to any member: `{rev, roles: [{name, verbs}], owner_role, org_role, defaults: {: {visibility}}, sharing: {who}, operator: {role, sees_private, may_govern}, agents: {may_create, may_share, -may_grant, default_scope, scopes?}, chats?: {move_by}}` (`chats` is present only when set, and -`move_by` is `owner`, the default, or `manage`: who may move a chat), and the default policy when none was ever saved, which +may_grant, default_scope, scopes?}, chats?: {move_by?, approvals_by?, wake_by?}}` (`chats` is present only when set, and +each field only when set: `move_by` is `owner`, the default, or `manage`, who may move a chat; `approvals_by` is `owner`, the +default, or `answer`, who approves a tool call in a shared hosted chat; `wake_by` is `view`, the default, `run` or `owner`, who +may start a hosted chat that is not running), and the default policy when none was ever saved, which is how the server behaved before policies existed. A role is a named bundle of verbs from a closed list (`view`, `comment`, `edit`, `run`, `steer`, `answer`, `share`, `manage`), every role holds `view`, and the four names `view`, `comment`, `edit` and `full` are kept. Only diff --git a/docs/organizations.md b/docs/organizations.md index 8d22b1a95b..43eef08067 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -103,7 +103,8 @@ organization starts with (the operator can change their bundles; the names stay) What a guest can do in a hosted chat follows from the verbs: `view` watches and reads; `steer` also interrupts a turn and redirects it; `answer` also answers a question the chat is waiting on; `run` also sends messages, files and commands. `manage` also stops or deletes the chat. Everything else (approving a tool use, settings, opening the -chat's files) is the owner's whatever the role. +chat's files) is the owner's whatever the role, with one setting: `chats.approvals_by` set to `answer` lets a person who +holds `answer` allow one tool use once, or refuse it (never allow a tool for the rest of the chat). **The owner owns the chat.** It runs on the owner's credentials, spending limits and GitHub identity. A person who may send messages acts with the owner's GitHub identity, the owner's files and the owner's limits, and the server records @@ -146,7 +147,9 @@ The organization's policy (`GET` and `PUT /v1/org/policy`; only the operator cha `CODEAF_HOSTED_SESSION_CAP_USD` (five dollars). The monthly limit every person's spend is held to is set by the operator in Settings (twenty dollars by default). The same policy holds the roles, whether new chats start private (the default for chats and hosted chats), who may share, -who may move a chat (`chats.move_by`: `owner`, the default, or `manage`) and what bots and agents may do. +who may move a chat (`chats.move_by`: `owner`, the default, or `manage`), who approves a tool call in a shared chat +(`chats.approvals_by`: `owner`, the default, or `answer`), who may start a chat that is not running (`chats.wake_by`: +`view`, the default, `run` or `owner`) and what bots and agents may do. A **team server does not trust its own computer.** A request from the server's own machine with no sign-in is refused like any other (a solo server, a desktop window's own, still trusts it). `loopback_trust` is off for a team server; the @@ -312,11 +315,13 @@ It answers with an `access_token` the same way. - A guest's message or steer waits while the owner's window holds the keyboard: the chat itself refuses it in its own words about the keyboard. It goes through when the owner has no window open, or after the guest takes the keyboard (allowed with `run`). Interrupting and answering are not affected. A tool-use approval stays with the owner, so a command that - needs one waits for the owner. + needs one waits for the owner, unless the policy's `chats.approvals_by` is `answer`. - A guest who runs `codeaf chat --org ... --session ... --once` on a chat that is not running starts it for its owner in that one-shot mode, even when the guest's own message is refused. The owner's window then reads `this conversation is already open in a different interactive or headless mode; close it before retrying` until the chat is stopped (the owner's stop, or - `POST /v1/hosted/sessions//stop`) or stops itself when idle. + `POST /v1/hosted/sessions//stop`) or stops itself when idle. The policy's `chats.wake_by` set to `run` or `owner` + keeps a person who cannot send messages in the chat (or anyone but its owner) from starting it at all: they are told the + chat is not running and to ask its owner, and nothing starts. The default, `view`, is the behaviour described here. - By default only the owner moves a chat between My space and a workstream; the policy's `chats.move_by` set to `manage` lets people with the `manage` verb on the chat move it too (never into their own My space, never a bot). - `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index c9f2cfdfa6..43dd0d2539 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -72,7 +72,7 @@ A chat shared with you opens with `codeaf chat --org --session hs_...`, - **answer**: also answer a question the chat is waiting on. - **run** (the `edit` and `full` roles have it): also send messages, files and images, and run a command the chat's own way, as the chat's owner would. -Everything else on the chat's wire stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping its work. A command that needs approval waits for the owner. Stopping or deleting the chat itself is a separate door that needs the `manage` permission, which the `full` role holds: see *stop or delete a chat on the server*. +Everything else on the chat's wire stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping its work. A command that needs approval waits for the owner, unless the organization's policy says otherwise: see *can someone I shared my hosted chat with approve a command*. Stopping or deleting the chat itself is a separate door that needs the `manage` permission, which the `full` role holds: see *stop or delete a chat on the server*. ## what happens when I give someone run access to my hosted chat — they act with my GitHub identity, files and spending limits @@ -86,7 +86,19 @@ Only one window types at a time. While the owner has the chat open with the keyb When the owner takes your access away, or the policy changes so you no longer have it, your window is ended within a few seconds (five unless the operator set another heartbeat) and reads `Your access to this chat was removed.` -Opening a chat that is not running starts it for its owner, which can be refused while its owner or the machine is running as many chats as are allowed. Then you read `This chat is not running, and there is no room to start it right now. Try again later.` +Opening a chat that is not running starts it for its owner, which can be refused while its owner or the machine is running as many chats as are allowed. Then you read `This chat is not running, and there is no room to start it right now. Try again later.` If the organization's policy keeps you from starting a chat, you read `This chat is not running. Starting it takes permission to send messages in it. Ask its owner.` or `This chat is not running. Only its owner can start it. Ask them to open it.`: see *who may start a hosted chat that is not running*. + +## can someone I shared my hosted chat with approve a command — the owner by default, and the policy setting that lets people who answer allow one + +By default no. A command that needs approval under your approval mode waits for you, whatever role the person holds, and that is true however their window sends the answer: if they try, they read `This chat is shared with you. Only its owner can do that.` and the chat never hears it. Answering the chat's other questions is not affected: a person with the `answer` permission still answers those. + +The operator can change that in the organization's policy. `PUT /v1/org/policy` takes `"chats": {"approvals_by": "owner"}`, which is the default and what an organization with no setting has, or `"chats": {"approvals_by": "answer"}`. With `answer`, a person who holds the `answer` permission (the `edit` and `full` roles do) can allow one command once, or refuse it. Allowing a tool for the rest of the chat, putting the approval away and the chat's own approval setting stay with you, and a person who does not hold `answer` still reads that they were not given permission to answer. What they allow runs as you, in your folder, with your GitHub identity and your limits, and the server notes who answered next to what it charges. A change reaches a window that is already open within a few seconds. Any other word is refused when the policy is saved. The desktop app has no screen for this setting yet. + +## who may start a hosted chat that is not running — anyone who can see it by default, and the policy setting that limits it + +Opening a shared chat that is not running starts it, for its owner and in the owner's place among the chats they may have running. By default anyone who can see the chat does that, including a person with only `view` who runs `codeaf chat --org --session hs_... --once`: it starts the chat in one-shot mode, their own message is refused, and the owner's window then reads `this conversation is already open in a different interactive or headless mode; close it before retrying` until the chat is stopped or stops itself when idle. + +The operator can change that in the organization's policy. `PUT /v1/org/policy` takes `"chats": {"wake_by": "view"}`, which is the default and what an organization with no setting has, `"chats": {"wake_by": "run"}` or `"chats": {"wake_by": "owner"}`. With `run`, only a person who holds the `run` permission starts it; anyone else reads `This chat is not running. Starting it takes permission to send messages in it. Ask its owner.` With `owner`, only its owner does, and everyone else reads `This chat is not running. Only its owner can start it. Ask them to open it.` Nothing is started in either case. A chat that is already running opens for everyone who can see it, under every setting, and the owner's own window is never held back. The rule is checked when a window opens. Any other word is refused when the policy is saved. The desktop app has no screen for this setting yet. ## who pays for a shared chat — when someone else is in my hosted chat, it runs as the owner, with the owner's access and limits @@ -184,7 +196,7 @@ Personal never sees the organization's chats, files or people, and an organizati ## can a teammate send messages in my chat while I am using it — one window writes at a time, and the owner's keyboard comes first -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. +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*). ## the organization's server is down or my sign-in ended — a hosted chat never runs on my computer instead diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index b5645dfa61..48a86ea04a 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -37,7 +37,7 @@ What a bot makes belongs to its creator: a chat, a task or a file it creates is ## Who sets the sharing rules — the operator's organization policy -The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), who may move a chat (only its owner, or anyone holding manage on it), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. +The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), who may move a chat (only its owner, or anyone holding manage on it), for a hosted chat who approves a command and who may start it when it is not running (see *can someone I shared my hosted chat with approve a command* and *who may start a hosted chat that is not running*), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. An organization starts on the default policy, which behaves as the server always did: the four roles above, chats private, the operator seeing what is not private and nothing that is. A role can be added or its bundle changed, and the four starting names can never be removed or renamed, because old shares and clients use them. A change to the policy changes who can see things, so every person who gains or loses access to something hears about it at once. A policy that makes new chats visible to every member applies to chats made after the change only; it never opens an existing chat. @@ -45,7 +45,7 @@ An organization starts on the default policy, which behaves as the server always A person with at least **view** on a chat, Afi's pane or a task's working conversation can read what was said there, and ask again for only what is new, but cannot post to it: the message, stop and card doors stay with the person whose chat it is. Everyone else, the operator included, is told the chat is not there, with the same words as for a chat that does not exist: a private chat reveals nothing, not even that it exists. -Reading changes nothing: it does not mark the chat as touched, start its agent, or leave a line on the organization's record. When a grant is removed, runs out, or the chat is moved somewhere the person does not reach, the next read is refused. A role that holds steer or run does not give a talk door in this version for a chat in a workstream: steering someone else's chat there is not built. A chat that runs on the organization's own server (a hosted chat) is the one place it is: a person with steer can interrupt and steer it, one with answer can answer its questions, and one with run (the `edit` and `full` roles) can send messages and run commands in it as its owner, with the owner's GitHub identity and files; approving, settings and files stay the owner's. See *what can someone I shared my hosted chat with do*. +Reading changes nothing: it does not mark the chat as touched, start its agent, or leave a line on the organization's record. When a grant is removed, runs out, or the chat is moved somewhere the person does not reach, the next read is refused. A role that holds steer or run does not give a talk door in this version for a chat in a workstream: steering someone else's chat there is not built. A chat that runs on the organization's own server (a hosted chat) is the one place it is: a person with steer can interrupt and steer it, one with answer can answer its questions, and one with run (the `edit` and `full` roles) can send messages and run commands in it as its owner, with the owner's GitHub identity and files; approving, settings and files stay the owner's unless the organization's policy lets people who answer approve. See *what can someone I shared my hosted chat with do*. ## Moving a chat between My space and a workstream — move is not share diff --git a/internal/manual/chat_hosted_test.go b/internal/manual/chat_hosted_test.go index bab81d4d33..9225136bc4 100644 --- a/internal/manual/chat_hosted_test.go +++ b/internal/manual/chat_hosted_test.go @@ -38,6 +38,11 @@ func TestHostedChatQuestionsReachTheirPage(t *testing.T) { {"can the operator open my hosted chat", []string{"only metadata", "There is no such chat."}}, {"can a bot start a hosted chat", []string{"a bot cannot use this yet", "recorded as made by the bot"}}, {"may I still start a chat on my own computer after joining an organization", []string{"local_sessions", "switch to your personal account"}}, + {"can someone I shared my hosted chat with approve a command to run", []string{"approvals_by", "Only its owner can do that"}}, + {"how do I let people who can answer allow a tool call in a shared chat in the organization policy", []string{"approvals_by", "allow one command once"}}, + {"can a guest with view start my hosted chat when it is not running with codeaf chat --org --once", []string{"wake_by", "already open in a different interactive or headless mode"}}, + {"This chat is not running. Only its owner can start it.", []string{"wake_by", "Ask them to open it."}}, + {"how do I stop other people from starting a hosted chat that is not running in the organization policy", []string{"wake_by", "Starting it takes permission to send messages in it"}}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From dc1d5f8d0f4f68c1a734640a642e7c88035ee6ef Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:52:11 -0500 Subject: [PATCH 6/6] change entry 2927: a shared hosted chat's tool approvals stay with the owner, and two policy settings loosen that Co-Authored-By: Claude Opus 5.5 --- .../unreleased/2927-configurable-choices.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2927-configurable-choices.md diff --git a/docs/changes/unreleased/2927-configurable-choices.md b/docs/changes/unreleased/2927-configurable-choices.md new file mode 100644 index 0000000000..dbfbadb3a6 --- /dev/null +++ b/docs/changes/unreleased/2927-configurable-choices.md @@ -0,0 +1,15 @@ +--- +kind: fixed +title: A shared hosted chat's tool approvals stay with its owner, and two policy settings loosen that +pr: 2927 +surface: [factory, chat, docs] +invalidates: + - "A guest of a shared hosted chat who held the answer permission, which the `edit` role does, could approve a tool call by sending the chat's approval question an answer, and the chat then ran the command as its owner, although the documentation said a command that needs approval waits for the owner. Now both doors an approval has stay with the owner by default, and the guest reads the same sentence as before: `This chat is shared with you. Only its owner can do that.` Answering the chat's other questions is unchanged." + - "Who approves a tool call in a shared hosted chat could not be set. Now the organization's policy has `chats.approvals_by`: `owner`, which an absent value also means and which is the behaviour above, or `answer`, which lets a person who holds the answer permission allow one tool call once or refuse it. Allowing a tool for the rest of the chat, putting the approval away and the chat's own settings stay with the owner." + - "Anyone who could see a shared hosted chat that was not running started it for its owner by opening it, and no setting could change that. Now the policy has `chats.wake_by`: `view`, which an absent value also means and which is the behaviour from before, `run`, which lets only a person who may send messages in the chat start it, or `owner`. Under the last two a guest is told the chat is not running and to ask its owner, and nothing is started." +--- + +Both settings are the operator's to set with `PUT /v1/org/policy`, are refused with a sentence naming the allowed words +when they are not one of them, and show in `GET /v1/org/policy` once set. An organization that sets neither sees no +difference except the first line above. The keyboard rule for a guest's message while the owner's window is open, and +how a new share reaches an open desktop window, are not settings here.