Skip to content

An open-source, faster Devin alternative

TypeScript

computer: session roles in the self-host gateway and runner

Igor Zalutski via Computerc3e59529f428
diff --git a/computer/README.md b/computer/README.md
index 48989c90..e23ac4d9 100644
--- a/computer/README.md
+++ b/computer/README.md
@@ -251,9 +251,45 @@ not refuse files that contain them. Within one scope a name is either a secret
or a variable. A variable does not replace a secret; setting a secret over a
variable is allowed, because that only tightens it.
+### Who can drive a session
+
+A session runs as its owner, the person who started it: their repositories,
+secrets and credentials. Who else may give it instructions is the session's
+`drivers`: everyone in the thread (`open`, the default), only the owner, or
+the owner and named people. A thread whose session is restricted carries a 🔒
+reaction on its first message.
+
+- **The owner and drivers** instruct the session and answer its prompts. A
+ prompt raised while a driver's message was running reads `Waiting on @them`
+ and only they or the owner can click it. Settings commands (`!mode`,
+ `!restart`, `!done`) stay the owner's.
+- **Other enabled people in the thread** (participants) are not delivered.
+ Their messages are kept as context and reach the session with the next
+ message from someone who drives, marked as context. Mentioning the bot asks
+ the owner once, in the thread, with `Allow` and `Not now`; `Allow` lets them
+ drive and runs the message that asked. They can still `!stop`, `!help` and
+ `!status`.
+- **Anyone not in `SP_PEOPLE`** is ignored, as before.
+
+The first reply's `Access` button opens the settings; `!access` does the same
+in text and is never delivered:
+
+| Typed | Does |
+|---|---|
+| `!access` | who drives now (`Change…` for the owner and admins) |
+| `!access open` / `!access owner` | everyone in the thread / only the owner |
+| `!access @a @b` | the owner and these people |
+| `!access add @a` / `!access remove @a` | edit the list |
+| `!access default open` / `!access default owner` | what new sessions start with (admins) |
+
+The owner and admins (`"admin": true` in `SP_PEOPLE`) change it; only people
+in `SP_PEOPLE` can be named. A thread started with `spawn_thread` copies its
+parent's setting. Stored in the gateway's SQLite (`sessions.drivers`,
+`session_context`, `access_requests`, `settings`). Design: work 112.
+
### Commands and code channels
-`!help` `!stop`/`!esc` `!! <text>` `!mode <m>` `!model <tier|id>` `!status` `!diff` `!restart` `!secret` `!var` `!done`.
+`!help` `!stop`/`!esc` `!! <text>` `!mode <m>` `!model <tier|id>` `!status` `!diff` `!restart` `!secret` `!var` `!access` `!done`.
Start any message with `+smart` or `+fast` (or `+default`) to switch the
thread's model and send the rest, e.g. `@Computer +smart redesign the router`
or `@Computer +fast ch bump the deps`. People pick a tier, not a model: the tiers
@@ -511,11 +547,13 @@ src/
variables.ts `!var` syntax and how values are shown (gateway; ported to the backend)
slack-text.ts Slack message markup → plain text for the model
links.ts Slack permalinks in a message → linked thread content, if everyone may see it
+ access.ts session roles: who may do what, `!access` syntax, the strings (access-views.ts: Block Kit)
build.ts which commit is running (shown in footers and !status)
log.ts, env.ts logging; .env load and write-back
gateway/ Slack endpoint, routing, SQLite tables, host WebSockets;
vault.ts and secrets-ui.ts: secrets storage, !secret and the modal;
- variables-ui.ts: !var; threads.ts: read_thread and post_thread
+ variables-ui.ts: !var; threads.ts: read_thread and post_thread;
+ access-store.ts, access-flow.ts, access-ui.ts: who can drive a session
host/ host agent: forks, runner lifecycle, token relay;
previews.ts: preview URLs (cloudflared, preview-proxy.ts, preview-probe.ts)
runner/ one session per process:
diff --git a/computer/src/gateway/access-flow.test.ts b/computer/src/gateway/access-flow.test.ts
new file mode 100644
index 00000000..da569dc0
--- /dev/null
+++ b/computer/src/gateway/access-flow.test.ts
@@ -0,0 +1,258 @@
+// Session roles through the router (work 112, "Tests"): one test per rule of
+// "Messages", "Request to drive", "Prompts", "Stop" and "One transition", on
+// routing.test.ts's fakes. U1 owns every session; UBEA0002 and UCY00003 are members, UA a
+// member admin, U9 not in the people table.
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { WebClient } from '@slack/web-api';
+import { encodeActionId, NOT_ASKED } from '../protocol.js';
+import { encodeAccessId } from '../access-views.js';
+import type { Store } from './db.js';
+import type { Hub } from './hosts.js';
+import { type Ctx, createRouter, type Msg } from './routing.js';
+import { BOT, fakeClient, fakeHub, fakeStore } from './test-fakes.js';
+
+const person = (id: string, admin = false) => ({ slackUserId: id, dir: id.toLowerCase(), gitName: id, gitEmail: `${id}@example.com`, ...(admin ? { admin } : {}) });
+
+let store: ReturnType<typeof fakeStore>;
+let hub: ReturnType<typeof fakeHub>;
+let client: ReturnType<typeof fakeClient>;
+let router: ReturnType<typeof createRouter>;
+let n = 0;
+let root: Msg;
+let key: string;
+
+const msg = (over: Partial<Msg> = {}): Msg => ({ channel: 'C1', ts: `1.${++n}`, user: 'U1', text: `<@${BOT}> do it`, ...over });
+const ctx = (): Ctx => ({ client: client as unknown as WebClient, botUserId: BOT, teamId: 'T1', eventId: `ev-${++n}` });
+const wc = () => client as unknown as WebClient;
+/** A reply in the session's thread. */
+const say = (user: string, text: string, mentioned = false) => router.route(msg({ thread_ts: root.ts, user, text }), ctx(), mentioned);
+const ephemerals = (user: string) => client.of('chat.postEphemeral').filter((a) => a.user === user).map((a) => a.text);
+const posts = () => client.of('chat.postMessage').map((a) => a.text);
+const lock = (method: 'reactions.add' | 'reactions.remove') => client.of(method).filter((a) => a.name === 'lock');
+
+beforeEach(async () => {
+ store = fakeStore(person('UBEA0002'), person('UCY00003'), person('UA', true));
+ hub = fakeHub();
+ client = fakeClient();
+ router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'default', models: () => ({ claude: { mode: 'profile', profile: 'p', vars: {}, key: 'k' } }) });
+ root = msg();
+ key = `C1:${root.ts}`;
+ await router.route(root, ctx(), true);
+ hub.delivered.length = 0;
+ client.calls.length = 0;
+});
+
+describe('messages', () => {
+ beforeEach(() => store.access.writeDrivers(key, []));
+
+ it('a participant’s message is held, not delivered and not acknowledged', async () => {
+ await say('UBEA0002', 'the bug is in login.ts');
+ expect(hub.delivered).toHaveLength(0);
+ expect(store.access.held(key)).toMatchObject([{ userId: 'UBEA0002', text: 'the bug is in login.ts' }]);
+ expect(client.calls).toHaveLength(0);
+ });
+
+ it('an outsider’s message is dropped and never held; a mention gets NOT_ENABLED', async () => {
+ await say('U9', 'hello');
+ await say('U9', `<@${BOT}> do something`, true);
+ expect(hub.delivered).toHaveLength(0);
+ expect(store.access.held(key)).toHaveLength(0);
+ expect(ephemerals('U9')).toEqual([expect.stringMatching(/not enabled/)]);
+ });
+
+ it('held context rides the next driver message and is deleted after', async () => {
+ await say('UBEA0002', 'the bug is in login.ts');
+ await say('U1', 'fix it');
+ const linked = hub.delivered[0].msg.linked!;
+ expect(linked.at(-1)).toMatchObject({ context: true, ok: true, messages: [{ name: 'Bea', text: 'the bug is in login.ts' }] });
+ expect(hub.delivered[0].msg.role).toBe('owner');
+ expect(store.access.held(key)).toHaveLength(0);
+ await say('U1', 'and the tests');
+ expect(hub.delivered[1].msg.linked).toBeUndefined();
+ });
+
+ it('a failed delivery keeps the held context', async () => {
+ await say('UBEA0002', 'the bug is in login.ts');
+ hub.reply = { ok: false, error: 'boom' };
+ await say('U1', 'fix it');
+ expect(store.access.held(key)).toHaveLength(1);
+ });
+
+ it('a settings command from a driver answers S7 and is not delivered; a command from a participant answers S8', async () => {
+ store.access.writeDrivers(key, ['UBEA0002']);
+ await say('UBEA0002', '!mode plan');
+ await say('UCY00003', '!diff');
+ expect(hub.delivered).toHaveLength(0);
+ expect(ephemerals('UBEA0002')).toEqual(['Only <@U1> can use `!mode` in this session.']);
+ expect(ephemerals('UCY00003')).toEqual(['Only people who can drive this session can use `!diff`.']);
+ expect(store.access.held(key)).toHaveLength(0);
+ });
+
+ it('a driver’s message is delivered with role driver; `!stop` from a participant with role participant', async () => {
+ store.access.writeDrivers(key, ['UBEA0002']);
+ await say('UBEA0002', 'go on');
+ await say('UCY00003', '!stop');
+ expect(hub.delivered.map((d) => [d.msg.userId, d.msg.role])).toEqual([
+ ['UBEA0002', 'driver'],
+ ['UCY00003', 'participant'],
+ ]);
+ });
+});
+
+describe('request to drive', () => {
+ beforeEach(() => store.access.writeDrivers(key, []));
+ const allow = (clicker: string, verb: 'allow' | 'deny' = 'allow') =>
+ router.access.click(encodeAccessId(key, verb, 'UBEA0002'), { user: { id: clicker }, channel: { id: 'C1' } }, wc());
+
+ it('a first mention posts S1 with buttons once and answers S2; a second answers S2b and posts nothing', async () => {
+ await say('UBEA0002', `<@${BOT}> fix the login`, true);
+ await say('UBEA0002', `<@${BOT}> please`, true);
+ const [request] = client.of('chat.postMessage');
+ expect(client.of('chat.postMessage')).toHaveLength(1);
+ expect(request).toMatchObject({ channel: 'C1', thread_ts: root.ts, text: '<@U1>, <@UBEA0002> wants to drive this session.' });
+ expect(JSON.stringify(request.blocks)).toContain(encodeAccessId(key, 'allow', 'UBEA0002'));
+ expect(ephemerals('UBEA0002')).toEqual([
+ '<@U1> decides who can drive this session and has been asked. Your message runs if they allow it.',
+ '<@U1> decides who can drive this session.',
+ ]);
+ expect(store.access.held(key)).toHaveLength(2);
+ });
+
+ it('a mention mid-message is held without a request', async () => {
+ await router.route(msg({ thread_ts: root.ts, user: 'UBEA0002', text: `ask <@${BOT}> later` }), ctx(), true);
+ expect(client.of('chat.postMessage')).toHaveLength(0);
+ expect(store.access.held(key)).toHaveLength(1);
+ });
+
+ it('Allow by someone who cannot grant (the requester too) answers S5 and changes nothing', async () => {
+ await say('UBEA0002', `<@${BOT}> fix the login`, true);
+ await allow('UCY00003');
+ await allow('UBEA0002');
+ expect(ephemerals('UCY00003')).toEqual(['Only <@U1> or an admin can answer this.']);
+ expect(store.access.drivers(key)).toEqual([]);
+ expect(store.access.request(key, 'UBEA0002')?.state).toBe('open');
+ expect(client.of('chat.update')).toHaveLength(0);
+ });
+
+ it('Allow by the owner adds the driver, edits the request and delivers the held message once', async () => {
+ await say('UBEA0002', `<@${BOT}> fix the login`, true);
+ await allow('U1');
+ expect(store.access.drivers(key)).toEqual(['UBEA0002']);
+ expect(client.of('chat.update')).toEqual([
+ { channel: 'C1', ts: '2.0', text: '<@U1> let <@UBEA0002> drive this session. It keeps running as <@U1>.', blocks: [] },
+ ]);
+ expect(hub.delivered).toHaveLength(1);
+ expect(hub.delivered[0].msg).toMatchObject({ userId: 'UBEA0002', text: 'fix the login', role: 'driver' });
+ expect(hub.delivered[0].msg.linked).toBeUndefined();
+ expect(posts()).toHaveLength(1); // the request; no separate S3
+ await allow('U1');
+ expect(hub.delivered).toHaveLength(1);
+ });
+
+ it('Not now declines: the request reads S4, the message stays context, a later mention gets S2b', async () => {
+ await say('UBEA0002', `<@${BOT}> fix the login`, true);
+ await allow('U1', 'deny');
+ expect(client.of('chat.update')[0]).toMatchObject({ text: '<@UBEA0002> asked to drive · not now', blocks: [{ type: 'context' }] });
+ expect(store.access.held(key)).toHaveLength(1);
+ await say('UBEA0002', `<@${BOT}> again`, true);
+ expect(posts()).toHaveLength(1);
+ expect(ephemerals('UBEA0002').at(-1)).toBe('<@U1> decides who can drive this session.');
+ });
+});
+
+describe('prompts', () => {
+ const click = (user: string) => router.action(encodeActionId(key, 'p1', 'allow'), user, wc(), 'C1');
+
+ it('a participant’s click answers S6 and reaches no host', async () => {
+ store.access.writeDrivers(key, []);
+ await click('UBEA0002');
+ expect(hub.actions).toHaveLength(0);
+ expect(ephemerals('UBEA0002')).toEqual(['This is waiting on someone else. Only they or <@U1> can answer it.']);
+ });
+
+ it('a click carries the clicker’s role; the runner’s not-asked answers S6', async () => {
+ await click('U1');
+ await click('UBEA0002');
+ expect(hub.actions.map((a) => [a.userId, a.role])).toEqual([
+ ['U1', 'owner'],
+ ['UBEA0002', 'driver'],
+ ]);
+ hub.actionReply = { ok: false, error: NOT_ASKED };
+ await click('UBEA0002');
+ expect(ephemerals('UBEA0002')).toHaveLength(1);
+ });
+});
+
+describe('stop', () => {
+ beforeEach(() => store.access.writeDrivers(key, []));
+
+ it('a stop by an outsider is ignored', async () => {
+ await router.stop({ channel: 'C1', thread_ts: root.ts, user: 'U9' }, 'ev-s1', wc());
+ expect(hub.stops).toHaveLength(0);
+ });
+
+ it('a stop by a participant stops the turn and posts S9; the owner’s posts nothing', async () => {
+ await router.stop({ channel: 'C1', thread_ts: root.ts, user: 'UBEA0002' }, 'ev-s2', wc());
+ await router.stop({ channel: 'C1', thread_ts: root.ts, user: 'U1' }, 'ev-s3', wc());
+ expect(hub.stops).toEqual([key, key]);
+ expect(posts()).toEqual([':octagonal_sign: <@UBEA0002> stopped the turn.']);
+ });
+});
+
+describe('setDrivers', () => {
+ const access = (user: string, text: string) => say(user, `!access ${text}`);
+
+ it('the same value does nothing', async () => {
+ await access('U1', 'open');
+ expect(posts()).toHaveLength(0);
+ expect(client.of('reactions.add')).toHaveLength(0);
+ expect(ephemerals('U1')).toEqual(['Runs as <@U1>. Everyone in this thread can drive.']);
+ });
+
+ it('restricting adds the lock and posts nothing; opening removes it and posts S3b', async () => {
+ await access('U1', 'owner');
+ expect(lock('reactions.add')).toEqual([{ channel: 'C1', timestamp: root.ts, name: 'lock' }]);
+ expect(posts()).toHaveLength(0);
+ await access('UA', 'open');
+ expect(lock('reactions.remove')).toEqual([{ channel: 'C1', timestamp: root.ts, name: 'lock' }]);
+ expect(posts()).toEqual(['<@UA> (admin) opened this session to everyone in this thread. It keeps running as <@U1>.']);
+ expect(hub.delivered).toHaveLength(0);
+ });
+
+ it('adding people posts S3 once naming them; removing posts nothing', async () => {
+ await access('U1', 'owner');
+ await access('U1', `add <@UBEA0002> <@UCY00003>`);
+ await access('U1', `remove <@UBEA0002>`);
+ expect(posts()).toEqual(['<@U1> let <@UBEA0002> and <@UCY00003> drive this session. It keeps running as <@U1>.']);
+ expect(store.access.drivers(key)).toEqual(['UCY00003']);
+ expect(lock('reactions.add')).toHaveLength(1);
+ });
+
+ it('an open request whose requester now drives is answered and delivered, not announced again', async () => {
+ await access('U1', 'owner');
+ await say('UBEA0002', `<@${BOT}> fix the login`, true);
+ await access('U1', `<@UBEA0002> <@UCY00003>`);
+ expect(client.of('chat.update')[0].text).toBe('<@U1> let <@UBEA0002> drive this session. It keeps running as <@U1>.');
+ expect(posts().at(-1)).toBe('<@U1> let <@UCY00003> drive this session. It keeps running as <@U1>.');
+ expect(hub.delivered.map((d) => d.msg.text)).toEqual(['fix the login']);
+ expect(store.access.request(key, 'UBEA0002')?.state).toBe('closed');
+ });
+});
+
+describe('new sessions', () => {
+ it('spawn copies the parent’s drivers, with the marker', async () => {
+ store.access.writeDrivers(key, ['UBEA0002']);
+ const r = await router.spawn(key, { task: 'port it', brief: 'b.md' }, wc());
+ expect(store.access.drivers(r.key)).toEqual(['UBEA0002']);
+ expect(lock('reactions.add')).toEqual([{ channel: 'C1', timestamp: '2.0', name: 'lock' }]);
+ });
+
+ it('under accessDefault owner a new session starts with only its owner, with the marker', async () => {
+ store.access.setAccessDefault('owner');
+ const m = msg();
+ await router.route(m, ctx(), true);
+ expect(store.access.drivers(`C1:${m.ts}`)).toEqual([]);
+ expect(lock('reactions.add')).toEqual([{ channel: 'C1', timestamp: m.ts, name: 'lock' }]);
+ });
+});
diff --git a/computer/src/gateway/access-flow.ts b/computer/src/gateway/access-flow.ts
new file mode 100644
index 00000000..7f1292a1
--- /dev/null
+++ b/computer/src/gateway/access-flow.ts
@@ -0,0 +1,245 @@
+// Session roles in the self-host gateway (work 112): what each Slack event
+// does per role. A message in a session is delivered, refused or held as
+// context; a participant's mention asks the owner to let them drive; `Allow`
+// and `Not now` answer that; `setDrivers` is the one write of `drivers`; held
+// context rides the next delivered message; a stop by someone else is named.
+//
+// Who may do what is access.ts (`role`, `can`); the strings and Block Kit are
+// access.ts and access-views.ts; SQL is access-store.ts. This file holds the
+// order of the steps and the Slack calls. Delivery itself is routing.ts's
+// `forward`, given as `deliver`, as secrets-ui.ts is given the hub.
+//
+// Member and admin here: a row in the people table, and that row's `admin`.
+
+import type { WebClient } from '@slack/web-api';
+import type { KnownBlock } from '@slack/types';
+import {
+ type Access,
+ type AccessAction,
+ type Actor,
+ type ChangedBy,
+ can,
+ commandAction,
+ commandWord,
+ driversCommandText,
+ type Drivers,
+ encodeDrivers,
+ gained,
+ grantedText,
+ normalize,
+ notAskedText,
+ onlyGrantorAnswersText,
+ openedText,
+ ownerCommandText,
+ ownerDecidesText,
+ requestSentText,
+ restricted,
+ type Role,
+ role,
+ sameDrivers,
+ stoppedText,
+} from '../access.js';
+import { declinedPost, requestPost } from '../access-views.js';
+import type { Delivery, SlackSessionSpec } from '../protocol.js';
+import type { Linked, LinkedMessage } from '../links.js';
+import type { Store } from './db.js';
+import type { Msg } from './routing.js';
+import { errorText, log } from '../log.js';
+
+/** The role a delivered message carries (`participant` only on `stop` and `view` commands). */
+export type DeliveredRole = NonNullable<Delivery['role']>;
+
+/** A message as the gateway received it: what a request to drive keeps, to deliver it on `Allow`. */
+export interface HeldMessage {
+ m: Msg;
+ /** Decoded, the bot's leading mention taken off. */
+ text: string;
+ /** As routing.ts reads it: mentioned, or in a DM or a code channel. */
+ mentioned: boolean;
+ /** The bot was mentioned only mid-message. */
+ inline: boolean;
+}
+
+export interface AccessFlowDeps {
+ store: Store;
+ /** Deliver as an ordinary message from `held.m.user` (routing.ts `forward`), with their role. */
+ deliver(spec: SlackSessionSpec, held: HeldMessage, role: DeliveredRole, client: WebClient): Promise<void>;
+ /** A person's name, for held context (links.ts's cached directory). */
+ name(client: WebClient, id: string): Promise<string>;
+}
+
+/** Whoever acts, as this gateway knows them. */
+export function actor(store: Store, id: string): Actor {
+ const p = store.person(id);
+ return { id, member: p !== undefined, admin: p?.admin === true };
+}
+
+export function accessOf(store: Store, spec: SlackSessionSpec): Access {
+ return { owner: spec.owner.slackUserId, drivers: store.access.drivers(spec.key) };
+}
+
+/** Who changed `drivers`: `admin` only when it is not the owner. */
+export const changedBy = (spec: SlackSessionSpec, id: string): ChangedBy => ({ id, admin: id !== spec.owner.slackUserId });
+
+const inThread = (spec: SlackSessionSpec) => (spec.kind === 'thread' && spec.threadTs ? { thread_ts: spec.threadTs } : {});
+
+export function createAccessFlow({ store, deliver, name }: AccessFlowDeps) {
+ // Held rows attached to a delivery the hub has not answered yet: the next message does not attach them again.
+ const inFlight = new Set<number>();
+
+ async function post(client: WebClient, spec: SlackSessionSpec, text: string, blocks?: unknown[]) {
+ return client.chat
+ .postMessage({ channel: spec.channel, ...inThread(spec), text, ...(blocks ? { blocks: blocks as KnownBlock[] } : {}) })
+ .catch((e) => (log.warn('access post', spec.key, errorText(e)), undefined));
+ }
+
+ async function ephemeral(client: WebClient, spec: SlackSessionSpec, user: string, text: string) {
+ await client.chat
+ .postEphemeral({ channel: spec.channel, user, text, ...inThread(spec) })
+ .catch((e) => log.warn('postEphemeral', e?.data?.error ?? e?.message));
+ }
+
+ async function update(client: WebClient, spec: SlackSessionSpec, ts: string, text: string, blocks: unknown[]) {
+ await client.chat
+ .update({ channel: spec.channel, ts, text, blocks: blocks as KnownBlock[] })
+ .catch((e) => log.warn('access update', spec.key, errorText(e)));
+ }
+
+ /** The 🔒 reaction on a thread's first message: on when restricted. */
+ async function marker(spec: SlackSessionSpec, on: boolean, client: WebClient) {
+ if (spec.kind !== 'thread' || !spec.threadTs) return;
+ const args = { channel: spec.channel, timestamp: spec.threadTs, name: 'lock' };
+ await (on ? client.reactions.add(args) : client.reactions.remove(args)).catch((e) => {
+ const code = e?.data?.error;
+ if (code !== 'already_reacted' && code !== 'no_reaction') log.warn('access marker', spec.key, errorText(e));
+ });
+ }
+
+ /**
+ * A message in an existing session ("Messages" steps 2 to 4). The role to
+ * deliver it with; `outsider` when it is dropped (routing.ts answers a
+ * mention); undefined when it was answered or held here.
+ */
+ async function message(spec: SlackSessionSpec, h: HeldMessage, client: WebClient): Promise<Role | undefined> {
+ const a = accessOf(store, spec);
+ const u = actor(store, h.m.user!);
+ const r = role(a, u);
+ const needs = commandAction(h.text);
+ if (needs !== undefined) {
+ // `!access` never gets here (routing.ts); commands never carry context.
+ if (can(a, u, needs as AccessAction)) return r;
+ const word = commandWord(h.text) ?? '';
+ if (needs === 'settings') await ephemeral(client, spec, u.id, ownerCommandText(a.owner, word));
+ else if (needs === 'instruct') await ephemeral(client, spec, u.id, driversCommandText(word));
+ return undefined;
+ }
+ if (can(a, u, 'instruct')) return r;
+ if (r === 'outsider') return 'outsider';
+ store.access.hold(spec.key, u.id, h.m.ts, h.text, (h.m.files ?? []).map((f) => f.name ?? f.id));
+ // In a code channel every message is for the bot.
+ if (!(spec.kind === 'channel' || (h.mentioned && !h.inline))) return undefined;
+ if (store.access.request(spec.key, u.id)) return void (await ephemeral(client, spec, u.id, ownerDecidesText(a.owner)));
+ await requestToDrive(spec, a, h, client);
+ return undefined;
+ }
+
+ /** "Request to drive": the visible request, its row, and S2 to the requester. */
+ async function requestToDrive(spec: SlackSessionSpec, a: Access, h: HeldMessage, client: WebClient) {
+ const requester = h.m.user!;
+ const p = requestPost(spec.key, a.owner, requester);
+ const posted = await post(client, spec, p.text, p.blocks);
+ if (!posted?.ts) return;
+ store.access.putRequest(spec.key, requester, posted.ts, JSON.stringify(h));
+ await ephemeral(client, spec, requester, requestSentText(a.owner));
+ }
+
+ /** `Allow` or `Not now` on a request, clicked by `clicker`. */
+ async function answer(key: string, verb: 'allow' | 'deny', requester: string, clicker: string, client: WebClient) {
+ const spec = store.session(key)?.spec;
+ if (!spec) return log.warn('access answer for unknown session', key);
+ const a = accessOf(store, spec);
+ if (!can(a, actor(store, clicker), 'grant')) return ephemeral(client, spec, clicker, onlyGrantorAnswersText(a.owner));
+ const q = store.access.request(key, requester);
+ if (q?.state !== 'open') return;
+ if (verb === 'deny') {
+ store.access.closeRequest(key, requester);
+ const p = declinedPost(requester);
+ return update(client, spec, q.messageTs, p.text, p.blocks);
+ }
+ if (a.drivers !== '*') return setDrivers(spec, [...a.drivers, requester], changedBy(spec, clicker), client);
+ // Everyone already drives (it cannot normally happen): the request is answered, the held message stays context.
+ store.access.closeRequest(key, requester);
+ await update(client, spec, q.messageTs, grantedText(changedBy(spec, clicker), [requester], a.owner), []);
+ }
+
+ /** "One transition": the only write of `drivers` after a session's first. */
+ async function setDrivers(spec: SlackSessionSpec, want: Drivers, by: ChangedBy, client: WebClient) {
+ const { owner, drivers: prev } = accessOf(store, spec);
+ const next = normalize(owner, want);
+ if (sameDrivers(prev, next)) return;
+ store.access.writeDrivers(spec.key, next);
+ if (restricted(prev) !== restricted(next)) await marker(spec, restricted(next), client);
+
+ const after: Access = { owner, drivers: next };
+ const handled: string[] = [];
+ const deliveries: Promise<void>[] = [];
+ for (const q of store.access.openRequests(spec.key)) {
+ if (role(after, actor(store, q.userId)) !== 'driver') continue;
+ store.access.closeRequest(spec.key, q.userId);
+ await update(client, spec, q.messageTs, grantedText(by, [q.userId], owner), []);
+ const held = JSON.parse(q.held) as HeldMessage;
+ store.access.releaseTs(spec.key, held.m.ts);
+ handled.push(q.userId);
+ // Started in request order (forward keeps a session's order); not awaited before the announcement.
+ deliveries.push(deliver(spec, held, 'driver', client).catch((e) => log.warn(`deliver held ${spec.key}:`, errorText(e))));
+ }
+
+ const g = gained(prev, next);
+ if (g === 'opened') await post(client, spec, openedText(by, owner));
+ else {
+ const added = g.filter((id) => !handled.includes(id));
+ if (added.length) await post(client, spec, grantedText(by, added, owner));
+ }
+ log.info('access', spec.key, by.id, by.admin, encodeDrivers(prev), encodeDrivers(next));
+ await Promise.all(deliveries);
+ }
+
+ /** A new session's first `drivers` (the org default, or a spawning parent's), and its marker. */
+ function begin(spec: SlackSessionSpec, drivers: Drivers, client: WebClient) {
+ const d = normalize(spec.owner.slackUserId, drivers);
+ store.access.writeDrivers(spec.key, d);
+ if (restricted(d)) void marker(spec, true, client);
+ }
+
+ /**
+ * The session's held context as one `Linked`, for a message about to be
+ * delivered; `settle` once the hub answers: accepted (delivered or queued)
+ * deletes the rows, anything else keeps them for the next message.
+ */
+ async function context(spec: SlackSessionSpec, client: WebClient): Promise<{ linked?: Linked; settle(accepted: boolean): void }> {
+ const rows = store.access.held(spec.key).filter((r) => !inFlight.has(r.seq));
+ if (!rows.length) return { settle() {} };
+ for (const r of rows) inFlight.add(r.seq);
+ const messages: LinkedMessage[] = [];
+ // One at a time: the first lookup fills the directory's cache for the rest.
+ for (const r of rows)
+ messages.push({ name: await name(client, r.userId), ts: r.ts, text: r.text, ...(r.files ? { files: r.files } : {}), ...(r.skipped ? { skipped: r.skipped } : {}) });
+ return {
+ linked: { url: '', ok: true, where: '', context: true, messages },
+ settle(accepted) {
+ for (const r of rows) inFlight.delete(r.seq);
+ if (accepted) store.access.release(rows.map((r) => r.seq));
+ },
+ };
+ }
+
+ /** A prompt button's clicker who may not answer it (S6), in the session's thread. */
+ const notAsked = (spec: SlackSessionSpec, user: string, client: WebClient) => ephemeral(client, spec, user, notAskedText(spec.owner.slackUserId));
+
+ /** S9: someone other than the owner stopped the turn with the native button. */
+ const stopped = (spec: SlackSessionSpec, user: string, client: WebClient) => post(client, spec, stoppedText(user)).then(() => {});
+
+ return { message, answer, setDrivers, begin, context, notAsked, stopped };
+}
+
+export type AccessFlow = ReturnType<typeof createAccessFlow>;
diff --git a/computer/src/gateway/access-store.test.ts b/computer/src/gateway/access-store.test.ts
new file mode 100644
index 00000000..deabdbdf
--- /dev/null
+++ b/computer/src/gateway/access-store.test.ts
@@ -0,0 +1,105 @@
+// access-store.ts against an in-memory database: drivers' default and round
+// trip, held context's limits, one request per person, the org default.
+
+import { describe, expect, it } from 'vitest';
+import { CONTEXT_MAX_AGE_MS, CONTEXT_MAX_CHARS, CONTEXT_MAX_ROWS } from '../access.js';
+import { AccessStore } from './access-store.js';
+import { Store } from './db.js';
+
+const spec = { key: 'C1:1.1', kind: 'thread', channel: 'C1', threadTs: '1.1', owner: { slackUserId: 'U1', dir: 'o', gitName: 'O', gitEmail: 'o@e' }, teamId: 'T1', title: 't', mode: 'default' } as const;
+
+function fresh() {
+ const store = new Store(':memory:');
+ store.putSession(spec);
+ return store.access;
+}
+
+describe('drivers', () => {
+ it('is open for a session without a write, and for no session at all', () => {
+ const a = fresh();
+ expect(a.drivers(spec.key)).toBe('*');
+ expect(a.drivers('nope')).toBe('*');
+ });
+
+ it('round-trips a list and `[]`', () => {
+ const a = fresh();
+ a.writeDrivers(spec.key, ['U2', 'U3']);
+ expect(a.drivers(spec.key)).toEqual(['U2', 'U3']);
+ a.writeDrivers(spec.key, []);
+ expect(a.drivers(spec.key)).toEqual([]);
+ });
+
+ it('the column is added once: a second store on the same database keeps it', () => {
+ const store = new Store(':memory:');
+ store.putSession(spec);
+ store.access.writeDrivers(spec.key, []);
+ expect(new AccessStore(store.db).drivers(spec.key)).toEqual([]);
+ });
+});
+
+describe('held context', () => {
+ it('reads oldest first, cuts long text and keeps file names', () => {
+ const a = fresh();
+ a.hold(spec.key, 'U2', '2.1', 'x'.repeat(CONTEXT_MAX_CHARS + 10), ['a.png']);
+ a.hold(spec.key, 'U3', '2.2', 'second');
+ const rows = a.held(spec.key);
+ expect(rows.map((r) => r.ts)).toEqual(['2.1', '2.2']);
+ expect(rows[0].text).toHaveLength(CONTEXT_MAX_CHARS);
+ expect(rows[0].files).toEqual(['a.png']);
+ expect(rows[1].files).toBeUndefined();
+ });
+
+ it('keeps the newest CONTEXT_MAX_ROWS and says how many were left out', () => {
+ const a = fresh();
+ for (let i = 0; i < CONTEXT_MAX_ROWS + 3; i++) a.hold(spec.key, 'U2', `2.${i}`, `m${i}`);
+ const rows = a.held(spec.key);
+ expect(rows).toHaveLength(CONTEXT_MAX_ROWS);
+ expect(rows[0]).toMatchObject({ text: 'm3', skipped: 3 });
+ expect(rows[1].skipped).toBeUndefined();
+ });
+
+ it('drops rows older than CONTEXT_MAX_AGE_MS, and only this session’s', () => {
+ const a = fresh();
+ const now = 10 * CONTEXT_MAX_AGE_MS;
+ a.hold(spec.key, 'U2', '2.1', 'old', [], now - CONTEXT_MAX_AGE_MS - 1);
+ a.hold(spec.key, 'U2', '2.2', 'new', [], now);
+ a.hold('other', 'U2', '2.3', 'old elsewhere', [], 0);
+ expect(a.held(spec.key, now).map((r) => r.text)).toEqual(['new']);
+ expect(a.held('other', 0).map((r) => r.text)).toEqual(['old elsewhere']);
+ });
+
+ it('release deletes by seq; releaseTs by the message’s ts', () => {
+ const a = fresh();
+ a.hold(spec.key, 'U2', '2.1', 'one');
+ a.hold(spec.key, 'U2', '2.2', 'two');
+ a.hold(spec.key, 'U2', '2.3', 'three');
+ a.release([a.held(spec.key)[0].seq]);
+ a.releaseTs(spec.key, '2.3');
+ expect(a.held(spec.key).map((r) => r.text)).toEqual(['two']);
+ });
+});
+
+describe('requests', () => {
+ it('one per person per session: a closed one stays and is never replaced', () => {
+ const a = fresh();
+ a.putRequest(spec.key, 'U2', '3.1', '{"m":1}', 1);
+ a.putRequest(spec.key, 'U3', '3.2', '{"m":2}', 2);
+ expect(a.openRequests(spec.key).map((r) => r.userId)).toEqual(['U2', 'U3']);
+ a.closeRequest(spec.key, 'U2');
+ a.putRequest(spec.key, 'U2', '3.3', '{"m":3}', 3);
+ expect(a.request(spec.key, 'U2')).toEqual({ key: spec.key, userId: 'U2', state: 'closed', messageTs: '3.1', held: '{"m":1}', at: 1 });
+ expect(a.openRequests(spec.key).map((r) => r.userId)).toEqual(['U3']);
+ expect(a.request(spec.key, 'U9')).toBeUndefined();
+ });
+});
+
+describe('accessDefault', () => {
+ it('is open until set, and overwrites', () => {
+ const a = fresh();
+ expect(a.accessDefault()).toBe('open');
+ a.setAccessDefault('owner');
+ expect(a.accessDefault()).toBe('owner');
+ a.setAccessDefault('open');
+ expect(a.accessDefault()).toBe('open');
+ });
+});
diff --git a/computer/src/gateway/access-store.ts b/computer/src/gateway/access-store.ts
new file mode 100644
index 00000000..5ec3e2e1
--- /dev/null
+++ b/computer/src/gateway/access-store.ts
@@ -0,0 +1,176 @@
+// Session roles in the gateway's SQLite (work 112): each session's `drivers`
+// (a column of `sessions`), the messages held as context from people who
+// cannot instruct a session, the requests to drive, and the organization's
+// default for new sessions (`settings.accessDefault`).
+//
+// Invariants:
+// - `drivers` is read through decodeDrivers: a session from before this
+// column, or with a value that is neither `'*'` nor a JSON list, reads as
+// its column says (`'*'` by default, `[]` when unreadable); only
+// access-flow.ts's setDrivers and a new session's first write change it;
+// - held context is cut to CONTEXT_MAX_CHARS when stored, and read as the
+// newest CONTEXT_MAX_ROWS of the session, oldest first, after that
+// session's rows older than CONTEXT_MAX_AGE_MS are deleted;
+// - one request per person per session, ever: a closed one stays, so a
+// declined person is never asked about twice.
+//
+// SQL only: who may do what is access.ts, what happens is access-flow.ts.
+
+import type { DatabaseSync } from 'node:sqlite';
+import {
+ type AccessDefault,
+ ACCESS_DEFAULT_SETTING,
+ CONTEXT_MAX_AGE_MS,
+ CONTEXT_MAX_CHARS,
+ CONTEXT_MAX_ROWS,
+ decodeDrivers,
+ type Drivers,
+ encodeDrivers,
+ readAccessDefault,
+} from '../access.js';
+
+/** One message held as context. */
+export interface HeldRow {
+ seq: number;
+ userId: string;
+ ts: string;
+ text: string;
+ files?: string[];
+ at: number;
+ /** Rows left out before this one (only on the first row read). */
+ skipped?: number;
+}
+
+/** A request to drive: `held` is the JSON of the message that asked, as the gateway received it. */
+export interface AccessRequest {
+ key: string;
+ userId: string;
+ state: 'open' | 'closed';
+ messageTs: string;
+ held: string;
+ at: number;
+}
+
+export class AccessStore {
+ constructor(private readonly db: DatabaseSync) {
+ try {
+ db.exec(`ALTER TABLE sessions ADD COLUMN drivers TEXT NOT NULL DEFAULT '*'`);
+ } catch {} // the column exists
+ db.exec(`
+ CREATE TABLE IF NOT EXISTS session_context (
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ key TEXT NOT NULL, user_id TEXT NOT NULL, ts TEXT NOT NULL,
+ text TEXT NOT NULL, files TEXT, at INTEGER NOT NULL);
+ CREATE INDEX IF NOT EXISTS session_context_key ON session_context (key, seq);
+ CREATE TABLE IF NOT EXISTS access_requests (
+ key TEXT NOT NULL, user_id TEXT NOT NULL, state TEXT NOT NULL,
+ message_ts TEXT NOT NULL, held TEXT NOT NULL, at INTEGER NOT NULL,
+ PRIMARY KEY (key, user_id));
+ CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ `);
+ }
+
+ // ---- drivers
+
+ /** A session's `drivers`; `'*'` for a session with no row. */
+ drivers(key: string): Drivers {
+ const r = this.db.prepare('SELECT drivers FROM sessions WHERE key = ?').get(key) as { drivers: string } | undefined;
+ return r ? decodeDrivers(r.drivers) : '*';
+ }
+
+ /** The column, as given: callers normalize (access-flow.ts). */
+ writeDrivers(key: string, d: Drivers) {
+ this.db.prepare('UPDATE sessions SET drivers = ? WHERE key = ?').run(encodeDrivers(d), key);
+ }
+
+ // ---- held context
+
+ hold(key: string, userId: string, ts: string, text: string, files: string[] = [], at = Date.now()) {
+ this.db
+ .prepare('INSERT INTO session_context (key, user_id, ts, text, files, at) VALUES (?, ?, ?, ?, ?, ?)')
+ .run(key, userId, ts, text.slice(0, CONTEXT_MAX_CHARS), files.length ? JSON.stringify(files) : null, at);
+ }
+
+ /** The session's held messages, oldest first: the newest CONTEXT_MAX_ROWS, after dropping the expired. */
+ held(key: string, now = Date.now()): HeldRow[] {
+ this.db.prepare('DELETE FROM session_context WHERE key = ? AND at < ?').run(key, now - CONTEXT_MAX_AGE_MS);
+ const { n } = this.db.prepare('SELECT COUNT(*) AS n FROM session_context WHERE key = ?').get(key) as { n: number };
+ const rows = this.db
+ .prepare('SELECT seq, user_id, ts, text, files, at FROM session_context WHERE key = ? ORDER BY seq DESC LIMIT ?')
+ .all(key, CONTEXT_MAX_ROWS) as { seq: number; user_id: string; ts: string; text: string; files: string | null; at: number }[];
+ const out: HeldRow[] = rows.reverse().map((r) => ({
+ seq: r.seq,
+ userId: r.user_id,
+ ts: r.ts,
+ text: r.text,
+ ...(r.files ? { files: JSON.parse(r.files) as string[] } : {}),
+ at: r.at,
+ }));
+ if (out.length && n > out.length) out[0].skipped = n - out.length;
+ return out;
+ }
+
+ /** Held messages that went to the session, by seq. */
+ release(seqs: readonly number[]) {
+ const del = this.db.prepare('DELETE FROM session_context WHERE seq = ?');
+ for (const seq of seqs) del.run(seq);
+ }
+
+ /** The held message with this ts (a request's, delivered on Allow). */
+ releaseTs(key: string, ts: string) {
+ this.db.prepare('DELETE FROM session_context WHERE key = ? AND ts = ?').run(key, ts);
+ }
+
+ // ---- requests to drive
+
+ request(key: string, userId: string): AccessRequest | undefined {
+ const r = this.db.prepare('SELECT * FROM access_requests WHERE key = ? AND user_id = ?').get(key, userId) as RequestRow | undefined;
+ return r ? toRequest(r) : undefined;
+ }
+
+ /** The session's open requests, oldest first. */
+ openRequests(key: string): AccessRequest[] {
+ return (this.db.prepare("SELECT * FROM access_requests WHERE key = ? AND state = 'open' ORDER BY at, rowid").all(key) as unknown as RequestRow[]).map(toRequest);
+ }
+
+ putRequest(key: string, userId: string, messageTs: string, held: string, at = Date.now()) {
+ this.db
+ .prepare("INSERT OR IGNORE INTO access_requests (key, user_id, state, message_ts, held, at) VALUES (?, ?, 'open', ?, ?, ?)")
+ .run(key, userId, messageTs, held, at);
+ }
+
+ closeRequest(key: string, userId: string) {
+ this.db.prepare("UPDATE access_requests SET state = 'closed' WHERE key = ? AND user_id = ?").run(key, userId);
+ }
+
+ // ---- the organization's default
+
+ accessDefault(): AccessDefault {
+ const r = this.db.prepare('SELECT value FROM settings WHERE key = ?').get(ACCESS_DEFAULT_SETTING) as { value: string } | undefined;
+ return readAccessDefault(r?.value);
+ }
+
+ setAccessDefault(d: AccessDefault) {
+ this.db
+ .prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
+ .run(ACCESS_DEFAULT_SETTING, d);
+ }
+}
+
+interface RequestRow {
+ key: string;
+ user_id: string;
+ state: string;
+ message_ts: string;
+ held: string;
+ at: number;
+}
+
+const toRequest = (r: RequestRow): AccessRequest => ({
+ key: r.key,
+ userId: r.user_id,
+ state: r.state === 'open' ? 'open' : 'closed',
+ messageTs: r.message_ts,
+ held: r.held,
+ at: r.at,
+});
diff --git a/computer/src/gateway/access-ui.test.ts b/computer/src/gateway/access-ui.test.ts
new file mode 100644
index 00000000..5ae4b588
--- /dev/null
+++ b/computer/src/gateway/access-ui.test.ts
@@ -0,0 +1,142 @@
+// `!access`, the Access button and the access modal's submission (work 112,
+// "Controls"), through the router on routing.test.ts's fakes. U1 owns the
+// session; UBEA0002 is a member, UADMIN01 a member admin, UOUT0009 not in the
+// people table.
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { WebClient } from '@slack/web-api';
+import { encodeAccessId } from '../access-views.js';
+import type { Store } from './db.js';
+import type { Hub } from './hosts.js';
+import { type Ctx, createRouter, type Msg } from './routing.js';
+import { BOT, fakeClient, fakeHub, fakeStore } from './test-fakes.js';
+
+const B = 'UBEA0002';
+const ADMIN = 'UADMIN01';
+const OUT = 'UOUT0009';
+const person = (id: string, admin = false) => ({ slackUserId: id, dir: id.toLowerCase(), gitName: id, gitEmail: `${id}@example.com`, ...(admin ? { admin } : {}) });
+
+let store: ReturnType<typeof fakeStore>;
+let hub: ReturnType<typeof fakeHub>;
+let client: ReturnType<typeof fakeClient>;
+let router: ReturnType<typeof createRouter>;
+let n = 0;
+let root: Msg;
+let key: string;
+
+const msg = (over: Partial<Msg> = {}): Msg => ({ channel: 'C1', ts: `1.${++n}`, user: 'U1', text: `<@${BOT}> do it`, ...over });
+const ctx = (): Ctx => ({ client: client as unknown as WebClient, botUserId: BOT, teamId: 'T1', eventId: `ev-${++n}` });
+const wc = () => client as unknown as WebClient;
+const access = (user: string, text: string) => router.route(msg({ user, thread_ts: root.ts, text: `!access${text ? ` ${text}` : ''}` }), ctx(), false);
+const answers = (user: string) => client.of('chat.postEphemeral').filter((a) => a.user === user);
+const submission = (who: string, people: string[] = [], k = key) => ({
+ private_metadata: JSON.stringify({ key: k }),
+ state: { values: { who: { v: { selected_option: { value: who } } }, people: { v: { selected_users: people } } } },
+});
+
+beforeEach(async () => {
+ store = fakeStore(person(B), person(ADMIN, true));
+ hub = fakeHub();
+ client = fakeClient();
+ router = createRouter({ store: store as unknown as Store, hub: hub as unknown as Hub, mode: 'default', models: () => ({ claude: { mode: 'profile', profile: 'p', vars: {}, key: 'k' } }) });
+ root = msg();
+ key = `C1:${root.ts}`;
+ await router.route(root, ctx(), true);
+ hub.delivered.length = 0;
+ client.calls.length = 0;
+});
+
+describe('!access', () => {
+ it('shows the state line in the thread, with Change… for someone who can grant; never delivered', async () => {
+ store.access.writeDrivers(key, [B]);
+ await access('U1', '');
+ await access(B, '');
+ const [owner] = answers('U1');
+ expect(owner).toMatchObject({ channel: 'C1', thread_ts: root.ts, text: `Runs as <@U1>. They and <@${B}> can drive.` });
+ expect(JSON.stringify(owner.blocks)).toContain(encodeAccessId(key, 'open'));
+ expect(JSON.stringify(answers(B)[0].blocks)).not.toContain('Change');
+ expect(hub.delivered).toHaveLength(0);
+ });
+
+ it('an outsider gets no answer; an unknown form gets the usage', async () => {
+ await access(OUT, '');
+ await access('U1', 'sideways');
+ expect(answers(OUT)).toHaveLength(0);
+ expect(answers('U1')[0].text).toMatch(/^`!access`/);
+ });
+
+ it('a change by someone who cannot grant answers S11 and changes nothing', async () => {
+ store.access.writeDrivers(key, [B]);
+ await access(B, 'open');
+ expect(answers(B).map((a) => a.text)).toEqual(['Only <@U1> or an admin can change who drives this session.']);
+ expect(store.access.drivers(key)).toEqual([B]);
+ });
+
+ it('naming someone who is not a member changes nothing', async () => {
+ await access('U1', `<@${B}> <@${OUT}>`);
+ expect(answers('U1').map((a) => a.text)).toEqual([`<@${OUT}> can’t be added: only full members of this workspace can drive.`]);
+ expect(store.access.drivers(key)).toBe('*');
+ });
+
+ it('a change by the owner is made, then answered with the new state', async () => {
+ await access('U1', `<@${B}>`);
+ expect(store.access.drivers(key)).toEqual([B]);
+ expect(answers('U1').map((a) => a.text)).toEqual([`Runs as <@U1>. They and <@${B}> can drive.`]);
+ });
+
+ it('outside a session (mentioned, as any message there): S12; the default by an admin works anywhere, by anyone else S15', async () => {
+ const top = (user: string, text: string) => router.route(msg({ user, text: `<@${BOT}> !access ${text}` }), ctx(), true);
+ await top('U1', 'owner');
+ await top('U1', 'default owner');
+ await top(ADMIN, 'default owner');
+ expect(answers('U1').map((a) => a.text)).toEqual(['There is no session in this thread.', 'Only an admin can change the default.']);
+ expect(answers(ADMIN).map((a) => a.text)).toEqual(['New sessions now start with only their owner driving.']);
+ expect(store.access.accessDefault()).toBe('owner');
+ });
+});
+
+describe('the Access button', () => {
+ const open = (user: string, k = key) =>
+ router.access.click(encodeAccessId(k, 'open'), { user: { id: user }, trigger_id: 'trig', container: { channel_id: 'C1', thread_ts: root.ts } }, wc());
+
+ it('opens the modal for the owner, and a read-only one for a participant; nothing for an outsider', async () => {
+ store.access.writeDrivers(key, []);
+ await open('U1');
+ await open(B);
+ await open(OUT);
+ const [mine, theirs] = client.of('views.open');
+ expect(client.of('views.open')).toHaveLength(2);
+ expect(mine).toMatchObject({ trigger_id: 'trig', view: { callback_id: 'access', submit: { text: 'Save' } } });
+ expect((theirs.view as { submit?: unknown }).submit).toBeUndefined();
+ });
+
+ it('answers S12 for a session that does not exist', async () => {
+ await open('U1', 'C1:9.9');
+ expect(answers('U1')).toMatchObject([{ channel: 'C1', thread_ts: root.ts, text: 'There is no session in this thread.' }]);
+ expect(client.of('views.open')).toHaveLength(0);
+ });
+});
+
+describe('the modal’s submission', () => {
+ it('refuses someone who cannot grant on `who`', async () => {
+ expect(await router.access.submit(submission('open'), B, wc())).toEqual({ errors: { who: 'Only <@U1> or an admin can change who drives this session.' } });
+ });
+
+ it('names a picked non-member on `people`', async () => {
+ expect(await router.access.submit(submission('people', [OUT]), 'U1', wc())).toEqual({
+ errors: { people: `${OUT} can’t be added: only full members of this workspace can drive.` },
+ });
+ });
+
+ it('a valid submission changes drivers only once acknowledged', async () => {
+ const r = await router.access.submit(submission('people', [B, 'U1']), ADMIN, wc());
+ expect(store.access.drivers(key)).toBe('*');
+ await (r as { done(c: WebClient): Promise<void> }).done(wc());
+ expect(store.access.drivers(key)).toEqual([B]);
+ expect(client.of('chat.postMessage')).toHaveLength(0); // '*' to a list: nobody gains
+ });
+
+ it('ignores a submission for an unknown session', async () => {
+ expect(await router.access.submit(submission('open', [], 'C1:9.9'), 'U1', wc())).toBeUndefined();
+ });
+});
diff --git a/computer/src/gateway/access-ui.ts b/computer/src/gateway/access-ui.ts
new file mode 100644
index 00000000..c72f9af0
--- /dev/null
+++ b/computer/src/gateway/access-ui.ts
@@ -0,0 +1,130 @@
+// Session access in Slack (work 112): `!access` typed in a thread, the `ac:`
+// buttons (Access, Change…, Allow, Not now) and the access modal's
+// submission. Every answer is private (an ephemeral, a modal or a modal error)
+// except what setDrivers posts when more people can drive.
+//
+// !access the state line; `Change…` for someone who can grant
+// !access open | owner | @a @b replace who drives, then the state line
+// !access add @a | remove @a edit the list ('*' counts as empty)
+// !access default open | owner the org default for new sessions (admins)
+//
+// Views and strings are access-views.ts and access.ts; the steps that follow a
+// change are access-flow.ts's setDrivers.
+
+import type { WebClient } from '@slack/web-api';
+import type { KnownBlock, View } from '@slack/types';
+import {
+ ACCESS_USAGE,
+ accessCommandNeeds,
+ can,
+ defaultChangedText,
+ editDrivers,
+ mention,
+ noSessionText,
+ normalize,
+ notMemberText,
+ onlyAdminDefaultText,
+ onlyGrantorChangesText,
+ overLimit,
+ parseAccessCommand,
+ stateText,
+ tooManyPeopleText,
+} from '../access.js';
+import { type AccessSubmission, accessView, decodeAccessId, readSubmission, statePost, submittedKey } from '../access-views.js';
+import type { SlackSessionSpec } from '../protocol.js';
+import type { Store } from './db.js';
+import type { Msg } from './routing.js';
+import type { ClickBody } from './secrets-ui.js';
+import { type AccessFlow, accessOf, actor, changedBy } from './access-flow.js';
+import { errorText, log } from '../log.js';
+
+export interface AccessUiDeps {
+ store: Store;
+ flow: AccessFlow;
+ /** A person's name, for the modal's member error (plain text: a mention would not render). */
+ name(client: WebClient, id: string): Promise<string>;
+}
+
+/** A modal answers within 3 s: a name not found by then is shown as the id. */
+const NAME_WAIT_MS = 1_500;
+
+export function createAccessUi({ store, flow, name }: AccessUiDeps) {
+ /** `!access …` from `m.user`, in `spec`'s thread or where no session is. Never delivered. */
+ async function command(text: string, m: Msg, spec: SlackSessionSpec | undefined, client: WebClient) {
+ const say = (t: string, blocks?: unknown[]) =>
+ client.chat
+ .postEphemeral({ channel: m.channel, user: m.user!, text: t, ...(m.thread_ts ? { thread_ts: m.thread_ts } : {}), ...(blocks ? { blocks: blocks as KnownBlock[] } : {}) })
+ .then(() => {})
+ .catch((e) => log.warn('postEphemeral', e?.data?.error ?? e?.message));
+ const c = parseAccessCommand(text);
+ const u = actor(store, m.user!);
+ if (c.kind === 'default') {
+ if (!(u.admin && u.member)) return say(onlyAdminDefaultText());
+ store.access.setAccessDefault(c.value);
+ log.info('access default', u.id, c.value);
+ return say(defaultChangedText(c.value));
+ }
+ if (!spec) return say(noSessionText());
+ const a = accessOf(store, spec);
+ if (accessCommandNeeds(c) === 'view') {
+ // Like `!help` from an outsider: no answer.
+ if (!can(a, u, 'view')) return;
+ if (c.kind === 'usage') return say(ACCESS_USAGE);
+ const p = statePost(spec.key, a, can(a, u, 'grant'));
+ return say(p.text, p.blocks);
+ }
+ if (c.kind === 'show' || c.kind === 'usage') return; // answered above; this narrows the type
+ if (!can(a, u, 'grant')) return say(onlyGrantorChangesText(a.owner));
+ const next = normalize(a.owner, editDrivers(a.drivers, c));
+ if (overLimit(next)) return say(tooManyPeopleText());
+ const named = c.kind === 'add' ? c.ids : c.kind === 'set' && c.drivers !== '*' ? c.drivers : [];
+ const stranger = named.find((id) => id !== a.owner && !actor(store, id).member);
+ if (stranger) return say(notMemberText(mention(stranger)));
+ await flow.setDrivers(spec, next, changedBy(spec, u.id), client);
+ return say(stateText(accessOf(store, spec)));
+ }
+
+ /** An `ac:` button: Access or Change… opens the modal; Allow and Not now answer a request. */
+ async function click(actionId: string, body: ClickBody, client: WebClient) {
+ const id = decodeAccessId(actionId);
+ const userId = body.user?.id;
+ if (!id || !userId) return log.warn('unknown access action', actionId);
+ if (id.verb !== 'open') return flow.answer(id.sessionKey, id.verb, id.userId!, userId, client);
+ const row = store.session(id.sessionKey);
+ if (!row) {
+ const channel = body.channel?.id ?? body.container?.channel_id;
+ const thread = body.container?.thread_ts;
+ if (channel)
+ await client.chat
+ .postEphemeral({ channel, user: userId, text: noSessionText(), ...(thread ? { thread_ts: thread } : {}) })
+ .catch((e) => log.warn('postEphemeral', e?.data?.error ?? e?.message));
+ return;
+ }
+ const view = accessView(id.sessionKey, accessOf(store, row.spec), actor(store, userId));
+ if (!view) return;
+ await client.views.open({ trigger_id: body.trigger_id ?? '', view: view as unknown as View }).catch((e) => log.warn('views.open', errorText(e)));
+ }
+
+ /** The modal's submission: errors to show in it, or the change to make once it is acknowledged. */
+ async function submit(
+ view: AccessSubmission,
+ userId: string,
+ client: WebClient,
+ ): Promise<{ errors: Record<string, string> } | { done(client: WebClient): Promise<void> } | undefined> {
+ const key = submittedKey(view);
+ const spec = key ? store.session(key)?.spec : undefined;
+ if (!spec) return undefined;
+ const r = readSubmission(view, accessOf(store, spec), actor(store, userId));
+ if (!r.ok) return { errors: r.errors };
+ const stranger = r.ids.find((id) => !actor(store, id).member);
+ if (stranger) {
+ const wait = new Promise<string>((ok) => setTimeout(() => ok(stranger), NAME_WAIT_MS).unref());
+ return { errors: { people: notMemberText(await Promise.race([name(client, stranger), wait])) } };
+ }
+ return { done: (c) => flow.setDrivers(spec, r.drivers, changedBy(spec, userId), c) };
+ }
+
+ return { command, click, submit };
+}
+
+export type AccessUi = ReturnType<typeof createAccessUi>;
diff --git a/computer/src/gateway/db.ts b/computer/src/gateway/db.ts
index 41adfff5..f2ed62e0 100644
--- a/computer/src/gateway/db.ts
+++ b/computer/src/gateway/db.ts
@@ -1,10 +1,12 @@
// The gateway's SQLite tables (work 045): sessions, people, hosts, Slack event
-// de-duplication and the outbox for hosts that are offline. Everything the
+// de-duplication and the outbox for hosts that are offline; session roles'
+// tables are access-store.ts's (work 112). Everything the
// gateway must remember across a redeploy lives here; nothing per runner.
import { createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import type { Delivery, SlackPerson, SessionReport, SlackSessionSpec, SessionStatus } from '../protocol.js';
+import { AccessStore } from './access-store.js';
export interface SessionRow {
spec: SlackSessionSpec;
@@ -17,7 +19,7 @@ export interface SessionRow {
/** A message waiting for a host: replayed in order when one connects. */
export type Queued =
| { t: 'deliver'; key: string; msg: Delivery }
- | { t: 'action'; key: string; promptId: string; value: string; userId: string };
+ | { t: 'action'; key: string; promptId: string; value: string; userId: string; role?: 'owner' | 'driver' };
const EVENT_TTL_MS = 60 * 60 * 1000;
const OUTBOX_TTL_MS = 24 * 60 * 60 * 1000;
@@ -39,8 +41,12 @@ export class Store {
CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, at INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS outbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT NOT NULL, at INTEGER NOT NULL);
`);
+ this.access = new AccessStore(this.db);
}
+ /** Session roles (work 112): drivers, held context, requests to drive, the org default. */
+ readonly access: AccessStore;
+
// ---- sessions
session(key: string): SessionRow | undefined {
diff --git a/computer/src/gateway/hosts.ts b/computer/src/gateway/hosts.ts
index e8269f7b..ae67538a 100644
--- a/computer/src/gateway/hosts.ts
+++ b/computer/src/gateway/hosts.ts
@@ -278,10 +278,12 @@ export class Hub {
return n;
}
- async action(key: string, promptId: string, value: string, userId: string): Promise<Reply | 'queued'> {
+ /** `role` (work 112): the clicker's, for the runner's `not-asked` check. */
+ async action(key: string, promptId: string, value: string, userId: string, role?: 'owner' | 'driver'): Promise<Reply | 'queued'> {
const conn = this.hostFor(key);
- if (!conn) return this.deps.store.enqueue({ t: 'action', key, promptId, value, userId }), 'queued';
- return this.request(conn, { t: 'action', sessionKey: key, promptId, value, userId });
+ const r = role ? { role } : {};
+ if (!conn) return this.deps.store.enqueue({ t: 'action', key, promptId, value, userId, ...r }), 'queued';
+ return this.request(conn, { t: 'action', sessionKey: key, promptId, value, userId, ...r });
}
/** A stop has no meaning later, so it is not queued. */
@@ -314,7 +316,7 @@ export class Hub {
for (const q of queued) {
const row = this.deps.store.session(q.key);
if (!row) continue;
- const r = q.t === 'deliver' ? await this.deliver(row.spec, q.msg) : await this.action(q.key, q.promptId, q.value, q.userId);
+ const r = q.t === 'deliver' ? await this.deliver(row.spec, q.msg) : await this.action(q.key, q.promptId, q.value, q.userId, q.role);
if (r !== 'queued' && !r.ok) log.warn(`queued ${q.t} for ${q.key} failed: ${r.error}`);
}
if (queued.length) log.info(`flushed ${queued.length} queued message(s)`);
diff --git a/computer/src/gateway/main.ts b/computer/src/gateway/main.ts
index 7a5956b4..b514e9d6 100644
--- a/computer/src/gateway/main.ts
+++ b/computer/src/gateway/main.ts
@@ -49,6 +49,7 @@ import { Vault } from './vault.js';
import { createSecretsUi, SECRET_VIEW, type SecretsUi } from './secrets-ui.js';
import { createVariablesUi } from './variables-ui.js';
import { createRouter, type Ctx, type Msg, type Router } from './routing.js';
+import { ACCESS_VIEW } from '../access-views.js';
import { errorText, log } from '../log.js';
loadEnv();
@@ -327,8 +328,9 @@ function boltHandler(): RequestListener {
await router.route(m, ctx(client, body, context), false);
});
- app.event('agent_session_stopped' as any, async ({ event, body }: any) => {
- await router.stop(event, body.event_id);
+ // `event.user`: who clicked stop (work 112: an outsider's click is ignored, anyone else but the owner is named).
+ app.event('agent_session_stopped' as any, async ({ event, body, client }: any) => {
+ await router.stop(event, body.event_id, client);
});
// post_card's link buttons (post-card.ts): Slack opens the URL; acked so it shows no error.
@@ -352,6 +354,19 @@ function boltHandler(): RequestListener {
await variablesUi.confirm(a.action_id, a.value ?? '', body, respond);
});
+ // Session access (work 112, access-ui.ts): Access and Change… open the modal; Allow and Not now answer a request to drive.
+ app.action(/^ac:/, async ({ ack, action, body, client }) => {
+ await ack();
+ await router.access.click((action as { action_id: string }).action_id, body, client);
+ });
+
+ app.view(ACCESS_VIEW, async ({ ack, view, body, client }) => {
+ const r = await router.access.submit(view, body.user.id, client);
+ if (r && 'errors' in r) return void (await ack({ response_action: 'errors', errors: r.errors }));
+ await ack();
+ await r?.done(client).catch((e) => log.warn('access saved, follow-up failed:', errorText(e)));
+ });
+
app.view(SECRET_VIEW, async ({ ack, view, body, client }) => {
const r = secretsUi.submit(view, body.user.id);
if ('errors' in r) return void (await ack({ response_action: 'errors', errors: r.errors }));
diff --git a/computer/src/gateway/routing.test.ts b/computer/src/gateway/routing.test.ts
index ad5f8b65..c43461a2 100644
--- a/computer/src/gateway/routing.test.ts
+++ b/computer/src/gateway/routing.test.ts
@@ -1,62 +1,15 @@
// The router against an in-memory store, a recording hub and a recording
// Slack client: who gets a session, what reaches the host, and what Slack sees.
+// Session roles' rules (work 112) are access-flow.test.ts, on the same fakes.
import { beforeEach, describe, expect, it } from 'vitest';
import type { WebClient } from '@slack/web-api';
-import type { Delivery, SlackPerson, SlackSessionSpec } from '../protocol.js';
import type { ModelRoutes } from '../protocol-model.js';
import type { Store } from './db.js';
import type { Hub } from './hosts.js';
import { withLinked } from '../links.js';
import { type Ctx, createRouter, type Msg, takeHarness } from './routing.js';
-
-const owner: SlackPerson = { slackUserId: 'U1', dir: 'owner', gitName: 'Owner', gitEmail: '[email protected]' };
-const BOT = 'UBOT';
-
-function fakeStore() {
- const sessions = new Map<string, SlackSessionSpec>();
- const people = new Map<string, SlackPerson>([[owner.slackUserId, owner]]);
- const events = new Set<string>();
- return {
- sessions,
- session: (key: string) => (sessions.has(key) ? { spec: sessions.get(key)!, updated: 0 } : undefined),
- putSession: (spec: SlackSessionSpec) => void sessions.set(spec.key, spec),
- person: (id: string) => people.get(id),
- firstSeen: (id: string) => (events.has(id) ? false : (events.add(id), true)),
- };
-}
-
-function fakeHub(online = true) {
- const delivered: { spec: SlackSessionSpec; msg: Delivery }[] = [];
- const stops: string[] = [];
- return {
- delivered,
- stops,
- get connected() {
- return online ? ['host-1'] : [];
- },
- deliver: async (spec: SlackSessionSpec, msg: Delivery) => (online ? (delivered.push({ spec, msg }), { ok: true }) : 'queued'),
- action: async () => ({ ok: true }),
- stop: async (key: string) => (stops.push(key), { ok: true }),
- };
-}
-
-function fakeClient() {
- const calls: { method: string; args: Record<string, unknown> }[] = [];
- const rec =
- (method: string, result: Record<string, unknown> = { ok: true }) =>
- async (args: Record<string, unknown>) => (calls.push({ method, args }), result);
- return {
- calls,
- of: (method: string) => calls.filter((c) => c.method === method).map((c) => c.args),
- chat: { postMessage: rec('chat.postMessage', { ok: true, ts: '2.0' }), postEphemeral: rec('chat.postEphemeral') },
- reactions: { add: rec('reactions.add') },
- agents: {
- sessions: { setStatus: rec('agents.sessions.setStatus'), rename: rec('agents.sessions.rename') },
- conversations: { create: rec('agents.conversations.create', { ok: true, channel_id: 'CCODE' }) },
- },
- };
-}
+import { BOT, fakeClient, fakeHub, fakeStore, owner } from './test-fakes.js';
let store: ReturnType<typeof fakeStore>;
let hub: ReturnType<typeof fakeHub>;
diff --git a/computer/src/gateway/routing.ts b/computer/src/gateway/routing.ts
index 6212c8a2..7bf4fd82 100644
--- a/computer/src/gateway/routing.ts
+++ b/computer/src/gateway/routing.ts
@@ -12,12 +12,15 @@
// read_thread / post_thread from a session → threads.ts, with this router's link resolver (work 049 L3)
// `!secret …` wherever the bot is addressed → handled here, never delivered (secrets-ui.ts, work 046)
// `!var …` likewise (variables-ui.ts)
+// `!access …`, `ac:` buttons, the access modal → access-ui.ts (work 112)
//
// Only people in the people table get a session; anyone else gets an ephemeral
-// "not enabled for you yet" and nothing else.
+// "not enabled for you yet" and nothing else. In a session, who may instruct,
+// answer and stop is access-flow.ts's (work 112): a message that may not
+// instruct is refused, held as context or dropped.
import type { WebClient } from '@slack/web-api';
-import { decodeActionId, type Delivery, type HarnessName, type PermissionMode, type SlackPerson, type SlackSessionSpec, type SpawnRequest, type SpawnResult } from '../protocol.js';
+import { decodeActionId, type Delivery, type HarnessName, NOT_ASKED, type PermissionMode, type SlackPerson, type SlackSessionSpec, type SpawnRequest, type SpawnResult } from '../protocol.js';
import type { SlackFile } from '../protocol.js';
import type { ModelRoutes } from '../protocol-model.js';
import { addressed, decodeSlack } from '../slack-text.js';
@@ -29,6 +32,9 @@ import type { Hub, Reply } from './hosts.js';
import type { SecretsUi } from './secrets-ui.js';
import type { VariablesUi } from './variables-ui.js';
import { log } from '../log.js';
+import { can, commandAction, initialDrivers, role } from '../access.js';
+import { accessOf, actor, createAccessFlow, type DeliveredRole } from './access-flow.js';
+import { createAccessUi } from './access-ui.js';
export interface Msg {
channel: string;
@@ -88,6 +94,13 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
// Reading links takes a moment; a session's messages still reach it in the order they were posted.
const sending = new Map<string, Promise<unknown>>();
+ const flow = createAccessFlow({
+ store,
+ deliver: (spec, h, r, client) => forward(spec, h.m, h.text, client, h.mentioned, h.inline, false, false, r),
+ name: resolveLinks.nameOf,
+ });
+ const access = createAccessUi({ store, flow, name: resolveLinks.nameOf });
+
const lookup = (channel: string, threadTs?: string) =>
store.session(channel) ?? (threadTs ? store.session(`${channel}:${threadTs}`) : undefined);
@@ -103,12 +116,19 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
const existing = lookup(m.channel, m.thread_ts);
if (!existing && !mentioned && m.channel_type !== 'im') return;
const person = store.person(m.user);
- // Someone else talking in a session's thread is not asking for access.
- if (!person) return mentioned || !existing ? notEnabled(m, client) : undefined;
- if (secrets && /^!secrets?(\s|$)/i.test(text)) return secrets.command(text, m, person, existing?.spec, client);
- if (variables && (await variables.command(text, m, person, existing?.spec, client))) return;
- // In a DM or a code channel every message is for the bot.
- if (existing) return forward(existing.spec, m, text, client, mentioned || m.channel_type === 'im' || existing.spec.kind === 'channel', a.inline);
+ if (!person && !existing) return notEnabled(m, client);
+ if (person && secrets && /^!secrets?(\s|$)/i.test(text)) return secrets.command(text, m, person, existing?.spec, client);
+ if (person && variables && (await variables.command(text, m, person, existing?.spec, client))) return;
+ if (commandAction(text) === 'access') return access.command(text, m, existing?.spec, client);
+ if (existing) {
+ // In a DM or a code channel every message is for the bot.
+ const forBot = mentioned || m.channel_type === 'im' || existing.spec.kind === 'channel';
+ const r = await flow.message(existing.spec, { m, text, mentioned: forBot, inline: a.inline }, client);
+ // Someone else talking in a session's thread is not asking for access.
+ if (r === 'outsider') return mentioned ? notEnabled(m, client) : undefined;
+ return r ? forward(existing.spec, m, text, client, forBot, a.inline, false, false, r) : undefined;
+ }
+ if (!person) return;
// `+codex` first; then `+smart ch <task>` and `ch +smart <task>` both work; the tier stays on the task for the session.
const { harness, text: asked } = takeHarness(text);
@@ -132,14 +152,15 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
...(harness ? { harness } : {}),
};
store.putSession(spec);
+ flow.begin(spec, initialDrivers(store.access.accessDefault()), client);
log.info(`new session ${spec.key} for ${person.dir}`);
// Mentioned mid-thread: the session also gets the replies above (it only sees what reaches it from now on).
const midThread = spec.kind === 'thread' && !!m.thread_ts && m.thread_ts !== m.ts;
- return forward(spec, m, task, client, true, a.inline, midThread, spec.kind === 'thread');
+ return forward(spec, m, task, client, true, a.inline, midThread, spec.kind === 'thread', 'owner');
}
- /** Feedback first (< 1 s, no await), then hand to the host. */
- async function forward(spec: SlackSessionSpec, m: Msg, text: string, client: WebClient, mentioned?: boolean, inline = false, midThread = false, fresh = false) {
+ /** Feedback first (< 1 s, no await), then hand to the host; `role`: the sender's (access-flow.ts), which also brings held context. */
+ async function forward(spec: SlackSessionSpec, m: Msg, text: string, client: WebClient, mentioned?: boolean, inline = false, midThread = false, fresh = false, role?: DeliveredRole) {
const msg: Delivery = {
userId: m.user!,
text,
@@ -147,6 +168,7 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
...(m.files?.length ? { files: m.files } : {}),
...(mentioned !== undefined ? { mentioned } : {}),
...(mentioned && inline ? { mentionedInline: true } : {}),
+ ...(role ? { role } : {}),
};
const command = text.startsWith('!') && !text.startsWith('!!');
const online = hub.connected.length > 0;
@@ -160,13 +182,25 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
mentioned !== undefined && !command
? Promise.all([midThread ? threadAbove(spec, m, client) : [], linkedFor(spec, m.user!, text, client).catch(() => [])]).then((r) => r.flat())
: [];
- const ready = Promise.all([sending.get(spec.key), reading]);
+ // Held context is read in turn too, so one message takes it and the next does not; commands never carry it.
+ const withContext = (role === 'owner' || role === 'driver') && !command;
+ const ready = Promise.all([sending.get(spec.key), reading]).then(async ([, linked]) => ({
+ linked,
+ held: withContext ? await flow.context(spec, client).catch(() => undefined) : undefined,
+ }));
sending.set(spec.key, ready);
- const [, linked] = await ready;
+ const { linked, held } = await ready;
if (sending.get(spec.key) === ready) sending.delete(spec.key);
- const all = [...forwarded(m.attachments), ...linked];
+ const all = [...forwarded(m.attachments), ...linked, ...(held?.linked ? [held.linked] : [])];
if (all.length) msg.linked = all;
- const r = await hub.deliver(spec, msg);
+ let accepted = false;
+ let r: Reply | 'queued';
+ try {
+ r = await hub.deliver(spec, msg);
+ accepted = r === 'queued' || r.ok;
+ } finally {
+ held?.settle(accepted);
+ }
if (r === 'queued') return ephemeral(client, m.channel, m.user!, OFFLINE, m.thread_ts);
if (!r.ok) await failed(spec, r, client);
}
@@ -260,24 +294,30 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
}
}
- /** Slack's native stop button on a processing agent session. */
- async function stop(ev: { channel: string; thread_ts?: string }, eventId?: string) {
+ /** Slack's native stop button on a processing agent session; `user`: who clicked, when Slack says. */
+ async function stop(ev: { channel: string; thread_ts?: string; user?: string }, eventId?: string, client?: WebClient) {
if (!fresh(eventId)) return;
const row = lookup(ev.channel, ev.thread_ts);
- log.info('stop button', ev.channel, ev.thread_ts, !!row);
+ log.info('stop button', ev.channel, ev.thread_ts, ev.user, !!row);
if (!row) return;
+ if (ev.user && !can(accessOf(store, row.spec), actor(store, ev.user), 'stop')) return log.info(`stop ${row.spec.key} by ${ev.user} ignored`);
const r = await hub.stop(row.spec.key);
- if (!r.ok) log.warn(`stop ${row.spec.key}: ${r.error}`);
+ if (!r.ok) return log.warn(`stop ${row.spec.key}: ${r.error}`);
+ if (ev.user && ev.user !== row.spec.owner.slackUserId && client) await flow.stopped(row.spec, ev.user, client);
}
/** A prompt button: `p:<base64url(sessionKey)>:<promptId>:<value>`. */
async function action(actionId: string, userId: string, client: WebClient, channel?: string) {
const a = decodeActionId(actionId);
if (!a) return log.warn('unknown action id', actionId);
- if (!store.person(userId)) return channel ? ephemeral(client, channel, userId, NOT_ENABLED) : undefined;
- if (!store.session(a.sessionKey)) return log.warn('action for unknown session', a.sessionKey);
- const r = await hub.action(a.sessionKey, a.promptId, a.value, userId);
+ const spec = store.session(a.sessionKey)?.spec;
+ if (!spec) return log.warn('action for unknown session', a.sessionKey);
+ const acc = accessOf(store, spec);
+ const u = actor(store, userId);
+ if (!can(acc, u, 'answer')) return flow.notAsked(spec, userId, client);
+ const r = await hub.action(a.sessionKey, a.promptId, a.value, userId, role(acc, u) === 'owner' ? 'owner' : 'driver');
if (r === 'queued') return channel ? ephemeral(client, channel, userId, OFFLINE) : undefined;
+ if (!r.ok && r.error === NOT_ASKED) return flow.notAsked(spec, userId, client);
if (!r.ok) log.warn(`action for ${a.sessionKey}: ${r.error}`);
}
@@ -319,19 +359,21 @@ export function createRouter({ store, hub, mode, models, secrets, variables }: R
...(req.tier && req.tier !== 'default' ? { model: TIERS[parent.harness ?? 'claude'][req.tier] } : !req.tier && parent.model ? { model: parent.model } : {}),
};
store.putSession(spec);
+ // Copied now, like mode and model; later changes to the parent do not follow.
+ flow.begin(spec, store.access.drivers(from), client);
log.info(`spawned ${spec.key} from ${from} for ${owner.dir}`);
const text =
`${req.task}\n\nBrief: ${req.brief}\n` +
`Started by the session in thread ${from}${parentUrl ? ` (${parentUrl})` : ''}. ` +
'Read the brief first; claim and report there.';
// Not awaited: starting the runner can take longer than the parent should wait.
- void forward(spec, { channel, ts: threadTs, thread_ts: threadTs, user: owner.slackUserId }, text, client).catch((e) =>
+ void forward(spec, { channel, ts: threadTs, thread_ts: threadTs, user: owner.slackUserId }, text, client, undefined, false, false, false, 'owner').catch((e) =>
log.warn(`deliver to spawned ${spec.key}:`, e?.message ?? e),
);
return { key: spec.key, url: await link(channel, threadTs) };
}
- return { route, stop, action, spawn, threads: threadAccess(store, resolveLinks) };
+ return { route, stop, action, spawn, access, threads: threadAccess(store, resolveLinks) };
}
export type Router = ReturnType<typeof createRouter>;
diff --git a/computer/src/gateway/test-fakes.ts b/computer/src/gateway/test-fakes.ts
new file mode 100644
index 00000000..24698e0f
--- /dev/null
+++ b/computer/src/gateway/test-fakes.ts
@@ -0,0 +1,75 @@
+// Test-only fakes for the router's tests (routing.test.ts, access-flow.test.ts,
+// access-ui.test.ts): the gateway's real Store in memory, a hub that records
+// what it delivers, and a Slack client that records every call. Never
+// imported by the gateway itself.
+
+import type { Delivery, SlackPerson, SlackSessionSpec } from '../protocol.js';
+import { Store } from './db.js';
+
+export const owner: SlackPerson = { slackUserId: 'U1', dir: 'owner', gitName: 'Owner', gitEmail: '[email protected]' };
+export const BOT = 'UBOT';
+
+/** The gateway's own store, in memory, with the owner enabled; `sessions` reads specs back. */
+export function fakeStore(...people: SlackPerson[]) {
+ const store = new Store(':memory:');
+ for (const p of [owner, ...people]) store.putPerson(p);
+ const sessions = {
+ get: (key: string) => store.session(key)?.spec,
+ get size() {
+ return (store.db.prepare('SELECT COUNT(*) AS n FROM sessions').get() as { n: number }).n;
+ },
+ };
+ return Object.assign(store, { sessions });
+}
+
+export function fakeHub(online = true) {
+ const delivered: { spec: SlackSessionSpec; msg: Delivery }[] = [];
+ const stops: string[] = [];
+ const actions: { key: string; promptId: string; value: string; userId: string; role?: string }[] = [];
+ return {
+ delivered,
+ stops,
+ actions,
+ /** What the next deliver answers (online). */
+ reply: { ok: true } as { ok: boolean; error?: string },
+ get connected() {
+ return online ? ['host-1'] : [];
+ },
+ async deliver(spec: SlackSessionSpec, msg: Delivery) {
+ if (!online) return 'queued';
+ if (this.reply.ok) delivered.push({ spec, msg });
+ return this.reply;
+ },
+ actionReply: { ok: true } as { ok: boolean; error?: string },
+ async action(key: string, promptId: string, value: string, userId: string, role?: string) {
+ actions.push({ key, promptId, value, userId, ...(role ? { role } : {}) });
+ return this.actionReply;
+ },
+ stop: async (key: string) => (stops.push(key), { ok: true }),
+ };
+}
+
+export function fakeClient() {
+ const calls: { method: string; args: Record<string, unknown> }[] = [];
+ const rec =
+ (method: string, result: Record<string, unknown> = { ok: true }) =>
+ async (args: Record<string, unknown>) => (calls.push({ method, args }), result);
+ return {
+ calls,
+ of: (method: string) => calls.filter((c) => c.method === method).map((c) => c.args),
+ chat: {
+ postMessage: rec('chat.postMessage', { ok: true, ts: '2.0' }),
+ postEphemeral: rec('chat.postEphemeral'),
+ update: rec('chat.update'),
+ getPermalink: rec('chat.getPermalink', { ok: true, permalink: 'https://example.slack.com/archives/C1/p1' }),
+ },
+ conversations: { open: rec('conversations.open', { ok: true, channel: { id: 'D1' } }) },
+ users: { list: rec('users.list', { ok: true, members: [{ id: 'UBEA0002', profile: { display_name: 'Bea' } }] }) },
+ reactions: { add: rec('reactions.add'), remove: rec('reactions.remove') },
+ views: { open: rec('views.open') },
+ agents: {
+ sessions: { setStatus: rec('agents.sessions.setStatus'), rename: rec('agents.sessions.rename') },
+ conversations: { create: rec('agents.conversations.create', { ok: true, channel_id: 'CCODE' }) },
+ },
+ };
+}
diff --git a/computer/src/host/main.ts b/computer/src/host/main.ts
index 1a45a116..704fd4e7 100644
--- a/computer/src/host/main.ts
+++ b/computer/src/host/main.ts
@@ -427,7 +427,7 @@ async function onGateway(m: GatewayToHost) {
}
case 'action': {
const r = runners.get(m.sessionKey);
- return reply(m.id, r ? call(r, { t: 'action', promptId: m.promptId, value: m.value, userId: m.userId })
+ return reply(m.id, r ? call(r, { t: 'action', promptId: m.promptId, value: m.value, userId: m.userId, ...(m.role ? { role: m.role } : {}) })
: Promise.reject(new Error('no runner for this session (the prompt ended with it)')));
}
case 'stop': {
diff --git a/computer/src/host/runner-call.ts b/computer/src/host/runner-call.ts
index c75a57f7..bc9b4c4c 100644
--- a/computer/src/host/runner-call.ts
+++ b/computer/src/host/runner-call.ts
@@ -12,7 +12,7 @@ import { send } from '../ipc.js';
export type RunnerCall =
| { t: 'deliver'; msg: Delivery; trace?: TraceContext }
- | { t: 'action'; promptId: string; value: string; userId: string }
+ | { t: 'action'; promptId: string; value: string; userId: string; role?: 'owner' | 'driver' }
| { t: 'stop' }
| { t: 'claim'; session: SessionSpec & { forkPath: string }; api?: RunnerApi };
diff --git a/computer/src/links.ts b/computer/src/links.ts
index c55cc576..1a472a3c 100644
--- a/computer/src/links.ts
+++ b/computer/src/links.ts
@@ -284,7 +284,12 @@ export function linkResolver() {
}
}
- return Object.assign(resolve, { one, thread: above });
+ /** A person's name from the cached directory (work 112: held context, refusals); their id when unknown or unreadable. */
+ async function name(client: WebClient, id: string): Promise<string> {
+ return (await directory(client).catch(() => undefined))?.get(id)?.name ?? id;
+ }
+
+ return Object.assign(resolve, { one, thread: above, nameOf: name });
}
export type LinkResolver = ReturnType<typeof linkResolver>;
diff --git a/computer/src/runner/api/golden/channel.json b/computer/src/runner/api/golden/channel.json
index 9e609d47..969d5e65 100644
--- a/computer/src/runner/api/golden/channel.json
+++ b/computer/src/runner/api/golden/channel.json
@@ -16,6 +16,20 @@
"text": ":thread: Thread `C2` · `!help` for commands"
}
]
+ },
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Access"
+ },
+ "action_id": "ac:QzI:open",
+ "value": "open"
+ }
+ ]
}
]
}
diff --git a/computer/src/runner/api/golden/plain.json b/computer/src/runner/api/golden/plain.json
index 5362f65a..9b2768c3 100644
--- a/computer/src/runner/api/golden/plain.json
+++ b/computer/src/runner/api/golden/plain.json
@@ -17,6 +17,20 @@
"text": ":thread: Thread `C1-1-0` · `!help` for commands"
}
]
+ },
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {
+ "type": "plain_text",
+ "text": "Access"
+ },
+ "action_id": "ac:QzEtMS4w:open",
+ "value": "open"
+ }
+ ]
}
]
}
diff --git a/computer/src/runner/api/surface.ts b/computer/src/runner/api/surface.ts
index 7acc515a..39eec206 100644
--- a/computer/src/runner/api/surface.ts
+++ b/computer/src/runner/api/surface.ts
@@ -44,7 +44,8 @@ export interface Surface extends Names {
showContext(s: { cwd: string; model?: string; mode: string; costUsd: number; ctxTokens: number }): Promise<void>;
setDiffView(diff: string): Promise<void>;
archive(): Promise<void>;
- intro(threadId: string): Promise<void>;
+ /** `sessionKey`: for the Access button (work 112). */
+ intro(threadId: string, sessionKey: string): Promise<void>;
userName(id: string): Promise<string>;
}
diff --git a/computer/src/runner/help.ts b/computer/src/runner/help.ts
index 34554c15..0379c6f2 100644
--- a/computer/src/runner/help.ts
+++ b/computer/src/runner/help.ts
@@ -1,6 +1,8 @@
// `!help`: the command list a thread shows. Pure text, so the session only
// supplies the current model and mode.
+import { ACCESS_HELP_LINE } from '../access.js';
+
export function helpText(model: string, mode: string) {
return [
`*Commands* (model \`${model}\` · mode \`${mode}\`)`,
@@ -14,6 +16,7 @@ export function helpText(model: string, mode: string) {
'`!status`: model, effort, mode, context, cost, thread id, cwd, session id',
'`!diff`: show uncommitted changes',
'`!secret NAME`: give the session a secret through a private form, never in a message; `!secret help` for more',
+ ACCESS_HELP_LINE,
'`!restart`: restart this thread\'s agent on the newest deployed version and current credentials (after the current turn)',
'`!done`: archive this code channel',
'`!help`: this list',
diff --git a/computer/src/runner/main.ts b/computer/src/runner/main.ts
index e8ab0442..6069c89d 100644
--- a/computer/src/runner/main.ts
+++ b/computer/src/runner/main.ts
@@ -37,6 +37,7 @@ import path from 'node:path';
import os from 'node:os';
import { WebClient } from '@slack/web-api';
import { Session, type SessionHooks, prompts } from './session.js';
+import { mayAnswer } from './prompts.js';
import { fetchAttachments, interruptDownloads } from './attachments.js';
import { type Linked, withLinked } from '../links.js';
import { SessionSecrets, redactingClient } from './session-secrets.js';
@@ -44,7 +45,7 @@ import { PromptGuard } from './prompt-guard.js';
import { codexBin } from '../runner-env.js';
import { fakeSlack } from '../dev/fake-slack.js';
import { lines, pidFileFor, send } from '../ipc.js';
-import { HOST_RUN, RUNNER_TOKEN_DIR, isSlackSpec, type RunnerApi } from '../protocol.js';
+import { HOST_RUN, NOT_ASKED, RUNNER_TOKEN_DIR, isSlackSpec, type RunnerApi } from '../protocol.js';
import { type AttachedApi, attachApi } from './api/attach.js';
import { NullSurface } from './api/surface.js';
import { RunningSubagents } from './api/running.js';
@@ -423,7 +424,7 @@ async function handle(m: Delivery, trace?: TraceContext) {
else if (s.thread.slack) void s.client.reactions.add({ channel: ss.channel!, timestamp: m.ts, name: 'eyes' }).catch(() => {});
const fetching = fetchAttachments(m.files, botToken, ss.key);
const atts = m.files?.length ? turns.timed('attachments', fetching, { count: m.files.length }) : fetching;
- await s.send(withLinked(m.text, m.linked), m.userId, atts, m.mentioned && m.mentionedInline ? 'inline' : m.mentioned);
+ await s.send(withLinked(m.text, m.linked), m.userId, atts, m.mentioned && m.mentionedInline ? 'inline' : m.mentioned, undefined, m.role);
// The gateway set the status to `processing` on receipt. A reply that only
// answered an open prompt starts no turn, and nothing would clear it.
if (!s.isBusy) void s.setStatus('active');
@@ -483,6 +484,7 @@ async function onHost(m: HostToRunner) {
(async () => {
const p = prompts.get(m.promptId);
if (!p) throw new Error('no such prompt (answered already, or the runner restarted)');
+ if (!mayAnswer(p, m.role, m.userId)) throw new Error(NOT_ASKED); // the gateway answers with S6 (work 112)
await p.onAction(m.value, m.userId);
})(),
);
diff --git a/computer/src/runner/prompts.test.ts b/computer/src/runner/prompts.test.ts
new file mode 100644
index 00000000..3b2251fc
--- /dev/null
+++ b/computer/src/runner/prompts.test.ts
@@ -0,0 +1,63 @@
+// Prompts and session roles (work 112, "Prompts"): who a prompt waits on, who
+// may click it, and that a typed reply from any driver still declines it.
+
+import { describe, expect, it } from 'vitest';
+import type { KnownBlock } from '@slack/types';
+import type { GateAsk } from './harness/types.js';
+import { mayAnswer, permissionPrompt, type PromptHost, prompts, waitingLine } from './prompts.js';
+
+/** A host whose thread records what it posts. */
+function host(driver?: string) {
+ const posted: KnownBlock[][] = [];
+ const h = {
+ info: { key: 'C1:1.0', cwd: '/tmp/w' },
+ thread: {
+ post: async (_text: string, blocks: KnownBlock[]) => (posted.push(blocks), '9.9'),
+ update: async () => {},
+ delete: async () => {},
+ userName: async (id: string) => id,
+ },
+ ...(driver ? { driver } : {}),
+ patchTask() {},
+ rotate() {},
+ persist() {},
+ };
+ return { h: h as unknown as PromptHost, posted };
+}
+
+const ask = (): GateAsk => ({ id: 't1', kind: 'tool', canRemember: false, signal: new AbortController().signal }) as unknown as GateAsk;
+const contextLine = (blocks: KnownBlock[]) => JSON.stringify(blocks.at(-1));
+
+describe('mayAnswer', () => {
+ it('refuses a driver’s click only when the prompt waits on someone else', () => {
+ expect(mayAnswer({ asked: 'U2' }, 'driver', 'U3')).toBe(false);
+ expect(mayAnswer({}, 'driver', 'U3')).toBe(false);
+ expect(mayAnswer({ asked: 'U2' }, 'driver', 'U2')).toBe(true);
+ expect(mayAnswer({ asked: 'U2' }, 'owner', 'U1')).toBe(true);
+ expect(mayAnswer({ asked: 'U2' }, undefined, 'U3')).toBe(true);
+ });
+});
+
+describe('the prompt', () => {
+ it('names the driver it waits on, and only then', async () => {
+ expect(waitingLine(undefined, 'or reply')).toBe('or reply');
+ const theirs = host('U2');
+ const mine = host();
+ void permissionPrompt(theirs.h, 'Bash', { command: 'ls' }, ask());
+ void permissionPrompt(mine.h, 'Bash', { command: 'ls' }, ask());
+ await new Promise((r) => setImmediate(r));
+ expect(contextLine(theirs.posted[0])).toContain('Waiting on <@U2> · or reply here to decline');
+ expect(contextLine(mine.posted[0])).not.toContain('Waiting on');
+ expect([...prompts.values()].map((p) => p.asked)).toEqual(['U2', undefined]);
+ for (const p of [...prompts.values()]) await p.cancel();
+ });
+
+ it('a typed reply from another driver declines it, as before', async () => {
+ const { h } = host('U2');
+ const decision = permissionPrompt(h, 'Bash', { command: 'ls' }, ask());
+ await new Promise((r) => setImmediate(r));
+ const [p] = [...prompts.values()];
+ await p.onText('use rg instead', 'U3');
+ expect(await decision).toMatchObject({ behavior: 'deny', message: 'The user declined and said: use rg instead' });
+ });
+});
diff --git a/computer/src/runner/prompts.ts b/computer/src/runner/prompts.ts
index b54c6947..c87c8996 100644
--- a/computer/src/runner/prompts.ts
+++ b/computer/src/runner/prompts.ts
@@ -35,6 +35,8 @@ export interface PromptHost {
readonly asks?: Asks;
/** The prompt a typed reply answers, by prompt id. */
openPrompt?: string;
+ /** Work 112: the driver whose message started the current turn; undefined for the owner's (or an older gateway's). */
+ readonly driver?: string;
patchTask(id: string, patch: Partial<Task>): void;
/** Finalize the live message; what follows continues in a new one below. */
rotate(): void;
@@ -52,8 +54,22 @@ export interface Pending {
askId?: string;
/** A Slack typed reply now would answer it (one question left), not decline it. */
answersText?(): boolean;
+ /** Work 112: the driver it waits on, read from the session when it was created; undefined: the owner's. */
+ asked?: string;
}
+/**
+ * Work 112: whether a button click may answer `p`. A click with `role` `driver`
+ * from someone other than the driver it waits on is refused (`not-asked`); the
+ * owner, and a click without a role (an older gateway, the API), answer as before.
+ */
+export function mayAnswer(p: Pick<Pending, 'asked'>, role: 'owner' | 'driver' | undefined, userId: string): boolean {
+ return role !== 'driver' || p.asked === userId;
+}
+
+/** The line under a prompt's buttons; `Waiting on <@asked> · ` first when a driver's message caused it. */
+export const waitingLine = (asked: string | undefined, text: string) => (asked ? `Waiting on <@${asked}> · ${text}` : text);
+
/** Open prompts (permission / question) waiting on a Slack button, by prompt id. */
export const prompts = new Map<string, Pending>();
@@ -86,6 +102,7 @@ const MODE_LABEL: Record<string, string> = { acceptEdits: 'auto-accepting edits'
export async function permissionPrompt(host: PromptHost, name: string, input: Record<string, unknown>, ask: GateAsk): Promise<GateDecision> {
const pid = randomUUID().slice(0, 8);
+ const asked = host.driver;
const isPlan = ask.kind === 'plan';
if (!isPlan) host.patchTask(ask.id, { details: 'waiting for approval ↓', waiting: true });
const title = isPlan
@@ -132,7 +149,7 @@ export async function permissionPrompt(host: PromptHost, name: string, input: Re
...(b.style ? { style: b.style } : {}),
})),
},
- { type: 'context', elements: [{ type: 'mrkdwn', text: 'or reply here to decline and say what to do instead' }] },
+ { type: 'context', elements: [{ type: 'mrkdwn', text: waitingLine(asked, 'or reply here to decline and say what to do instead') }] },
]);
return new Promise<GateDecision>((resolve) => {
@@ -194,6 +211,7 @@ export async function permissionPrompt(host: PromptHost, name: string, input: Re
session: host,
onAction: (value, user) => act(value, user),
askId: tracked?.id,
+ asked,
onText: async (text, user, reply) => {
await declined(text, user, undefined, reply);
host.rotate(); // the reply is now below; continue under it
@@ -219,6 +237,7 @@ export async function questionPrompt(
signal: AbortSignal,
): Promise<GateDecision> {
const pid = randomUUID().slice(0, 8);
+ const asked = host.driver;
host.patchTask(toolUseID, { details: 'waiting for your answer ↓', waiting: true });
const qs = input.questions ?? [];
const answers: Record<string, string> = {};
@@ -272,7 +291,7 @@ export async function questionPrompt(
let lastUser: string | undefined;
const ts = await host.thread.post(qs[0]?.question ?? 'Question', [
...render(),
- { type: 'context', elements: [{ type: 'mrkdwn', text: 'or reply here with your own answer' }] },
+ { type: 'context', elements: [{ type: 'mrkdwn', text: waitingLine(asked, 'or reply here with your own answer') }] },
]);
return new Promise<GateDecision>((resolve) => {
@@ -318,6 +337,7 @@ export async function questionPrompt(
// Claude as the user's words, so a side remark ("what's the status?")
// never becomes an answer.
askId: tracked?.id,
+ asked,
answersText: () => qs.filter((q) => !answers[q.question]).length <= 1,
onText: async (text, user, reply) => {
lastUser = user;
diff --git a/computer/src/runner/session.test.ts b/computer/src/runner/session.test.ts
index a4c23fd5..0b5e70d0 100644
--- a/computer/src/runner/session.test.ts
+++ b/computer/src/runner/session.test.ts
@@ -292,3 +292,22 @@ describe('Session: the end of a turn is off the pump (work 068 2f)', () => {
expect(t.busy).toEqual([true, true, false]);
});
});
+
+describe('Session: who prompts wait on (work 112)', () => {
+ it('a driver’s message sets `driver`; the owner’s clears it; a participant’s command leaves it', async () => {
+ const t = session();
+ await t.sess.send('hi', 'U2', [], true, undefined, 'driver');
+ expect(t.sess.driver).toBe('U2');
+ await t.sess.send('!status', 'U3', [], true, undefined, 'participant');
+ expect(t.sess.driver).toBe('U2');
+ await t.sess.send('more', 'U1', [], true, undefined, 'owner');
+ expect(t.sess.driver).toBeUndefined();
+ });
+
+ it('a fresh session’s intro carries the Access button', async () => {
+ const t = session({ fresh: true });
+ await t.sess.send('hi', 'U1');
+ await settle();
+ expect(JSON.stringify(t.of('chat.postMessage')[0].args.blocks)).toContain('"action_id":"ac:aw:open"');
+ });
+});
diff --git a/computer/src/runner/session.ts b/computer/src/runner/session.ts
index e46bdf59..f3c584c7 100644
--- a/computer/src/runner/session.ts
+++ b/computer/src/runner/session.ts
@@ -26,7 +26,7 @@ import type { Attachment } from './attachments.js';
import { labelled, type Mentioned } from './names.js';
import { log } from '../log.js';
import type { PromptGuard } from './prompt-guard.js';
-import type { CheckoutResult, EffortLevel, PermissionMode, SecretRequest, Speed, SpawnRequest, SpawnResult } from '../protocol.js';
+import type { CheckoutResult, Delivery, EffortLevel, PermissionMode, SecretRequest, Speed, SpawnRequest, SpawnResult } from '../protocol.js';
import type { ThreadHooks } from './threads.js';
import type { PreviewHooks } from './preview.js';
import { fileSender, type FileSender } from './send-file.js';
@@ -152,6 +152,8 @@ export class Session {
private addressed = true;
/** The prompt a typed reply answers (prompts.ts), by prompt id. */
openPrompt?: string;
+ /** Work 112: the last sender when the gateway said they drive (not own) it; prompts wait on them. A participant's `!stop` leaves it. */
+ driver?: string;
maxModel?: string; // the route's model ceiling (model-access.ts): `!model` stays at or below it
private costUsd = 0;
private ctxTokens = 0;
@@ -178,14 +180,10 @@ export class Session {
get client() { return this.thread.client; }
set client(c: WebClient) { this.thread.client = c; }
- get isBusy() {
- return this.busy;
- }
+ get isBusy() { return this.busy; }
/** The thread's id in a copyable form: the fork directory and branch suffix (`sp/<id>`). */
- get threadId() {
- return safeKey(this.info.key);
- }
+ get threadId() { return safeKey(this.info.key); }
private get out(): Segment {
if (this.seg?.full) this.rotate();
@@ -204,9 +202,10 @@ export class Session {
* side by side; the message goes to the model once names and attachments
* are in, and output waits for the intro only to be posted below it.
*/
- async send(raw: string, userId: string | undefined, files: Attachment[] | Promise<Attachment[]> = [], mentioned?: Mentioned, from?: SentFrom) {
+ async send(raw: string, userId: string | undefined, files: Attachment[] | Promise<Attachment[]> = [], mentioned?: Mentioned, from?: SentFrom, role?: Delivery['role']) {
this.shadow.cancel();
this.info.userId = userId ?? this.info.userId;
+ if (role !== 'participant') this.driver = role === 'driver' ? userId : undefined;
const urgent = raw.startsWith('!!');
const { tier, rest: typed } = takeTier(urgent ? raw.slice(2).trim() : raw);
const intro = this.intro();
@@ -582,7 +581,7 @@ export class Session {
/** A brand-new session's first reply, above any output (thread.ts); posted once, never throws. */
private intro() {
- if (this.fresh) this.introducing ??= this.timed('intro', this.thread.intro(this.threadId));
+ if (this.fresh) this.introducing ??= this.timed('intro', this.thread.intro(this.threadId, this.info.key));
return this.introducing;
}
diff --git a/computer/src/runner/thread.ts b/computer/src/runner/thread.ts
index 953c7ef0..e713ac53 100644
--- a/computer/src/runner/thread.ts
+++ b/computer/src/runner/thread.ts
@@ -14,6 +14,7 @@ import type { FileUpload } from './send-file.js';
import { describeChannel, type Names } from './names.js';
import { gitBranch } from '../workspace.js';
import { fmtTokens } from './format.js';
+import { accessButtonBlock } from '../access-views.js';
/** A name lookup never holds a message longer than this; the id stands in (p90 is ~240 ms). */
const LOOKUP_MS = 800;
@@ -170,11 +171,13 @@ export class SlackThread implements Names {
/** A code channel's diff tab. */
/**
* A brand-new session's first reply: the thread id to copy (later a link to
- * the thread's page) and where the commands are.
+ * the thread's page), where the commands are, and the Access button that
+ * opens the session's access modal in the gateway (work 112).
*/
- async intro(threadId: string) {
+ async intro(threadId: string, sessionKey: string) {
await this.post(`Thread ${threadId}`, [
{ type: 'context', elements: [{ type: 'mrkdwn', text: `:thread: Thread \`${threadId}\` · \`!help\` for commands` }] },
+ accessButtonBlock(sessionKey) as KnownBlock,
]).catch((e) => this.warn('intro', e));
}