Skip to content

Commit 61ee3c7

Browse files
committed
fix(host): end a deleted Bot's room seats with the deletion (#2607)
deleteBot only filtered the legacy room.members array. The room's participant entry stayed current, so currentParticipants still answered the Bot and the next membership write rebuilt room.members from it, saved, and the deleted id came back after a reload. Close the seat with leftSeq/leftAt and derive members through syncMembers, the same rule a leave uses. Rooms without a participants array keep the shipped filter. Adds core/test/delete-bot-seat.test.js, red without this change.
1 parent b75b07d commit 61ee3c7

8 files changed

Lines changed: 345 additions & 30 deletions

File tree

‎changelog.d/2607.fixed.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Deleting a Bot now ends its seat in every group chat in the same save: the group's member list and a shared room's guest roster stop naming it, and the next membership change can no longer write the deleted id back into the room, also after a reload ([#2607](https://github.com/ThinkFlowLab/FlyBot/issues/2607)).

‎core/src/host/room-membership.js‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ export function currentParticipants(room) {
6666
return (room?.participants ?? []).filter(p => p.leftSeq === undefined)
6767
}
6868

69+
// The one derivation of `room.members` from the seats. `deleteBot` (roster.js) shares it so a
70+
// deletion closes the seat and derives `members` in the same step (#2607): a separate filter
71+
// leaves a current participant behind, and the next membership write rebuilds the deleted id.
72+
export function syncMembers(room) {
73+
room.members = currentParticipants(room).filter(p => p.kind === 'bot' && !p.remote).map(p => p.id)
74+
const botAdmin = currentParticipants(room).find(p => p.kind === 'bot' && !p.remote && p.role === 'admin')
75+
if (botAdmin) room.admin = botAdmin.id
76+
else if (room.admin && !room.members.includes(room.admin)) room.admin = room.members[0] ?? null
77+
}
78+
6979
export function isRemoteParticipant(p) {
7080
return p?.kind === 'bot' && p.remote === true
7181
}
@@ -407,13 +417,6 @@ export function install(rt) {
407417
return stored
408418
}
409419

410-
const syncMembers = (room) => {
411-
room.members = currentParticipants(room).filter(p => p.kind === 'bot' && !p.remote).map(p => p.id)
412-
const botAdmin = currentParticipants(room).find(p => p.kind === 'bot' && !p.remote && p.role === 'admin')
413-
if (botAdmin) room.admin = botAdmin.id
414-
else if (room.admin && !room.members.includes(room.admin)) room.admin = room.members[0] ?? null
415-
}
416-
417420
// #1987: a group without a chosen name is named after its seats, so a seat that joins or leaves moves
418421
// the name with it — and the group's own Session, the title the user reads, moves with the name. `room`
419422
// is passed for both the comparison and the write: `autoRoomName` reads the people and the remote guests

‎core/src/host/roster.js‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOT
66
import { currentColor, cut, isColor, unquote } from './text.js'
77
import { nameProblem } from '../shared/mentions.js'
88
import { cleanExternal } from './room-participant-external.js'
9-
import { implicitRoomOwner } from './room-membership.js'
9+
import { currentParticipants, implicitRoomOwner, syncMembers } from './room-membership.js'
1010
import { ownEntry } from './store.js'
1111

1212
export function install(rt) {
@@ -649,9 +649,21 @@ export function install(rt) {
649649
}
650650
const touched = []
651651
for (const room of Object.values(state.rooms)) {
652-
if (!room.members.includes(id)) continue
653-
room.members = room.members.filter(member => member !== id)
654-
if (room.admin === id) room.admin = null
652+
const seat = currentParticipants(room).find(p => p.kind === 'bot' && !p.remote && p.id === id)
653+
if (!room.members.includes(id) && seat === undefined) continue
654+
// #2607: end the seat the way leaving does, then derive `members` from the seats. A separate
655+
// filter leaves the participant current, and the next membership write writes the id back.
656+
if (Array.isArray(room.participants)) {
657+
if (seat !== undefined) {
658+
seat.leftSeq = room.seq ?? 0
659+
seat.leftAt = Date.now()
660+
}
661+
if (room.admin === id) room.admin = null
662+
syncMembers(room)
663+
} else {
664+
room.members = room.members.filter(member => member !== id)
665+
if (room.admin === id) room.admin = null
666+
}
655667
if (room.taskLead === id) delete room.taskLead
656668
rt.dropGroupSession(room, id)
657669
touched.push(room)

‎core/test/delete-bot-seat.test.js‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import assert from 'node:assert/strict'
2+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
3+
import { tmpdir } from 'node:os'
4+
import { join } from 'node:path'
5+
import { test } from 'node:test'
6+
import { createRuntime } from '../index.js'
7+
import { fakeContext } from './fake-ctx.js'
8+
9+
// #2607: deleting a Bot ends its seats in every room, the way leaving does. Before this the deletion
10+
// only filtered the legacy `room.members` array, the room's `participants` entry stayed current, and
11+
// the next membership write rebuilt `room.members` from that entry — the deleted id came back and the
12+
// following save wrote it to disk. Two rooms keep the older shape without `participants`: that path
13+
// must still drop the id from `members` and stay without a participant list.
14+
15+
const live = room => (room.participants ?? []).filter(p => p.leftSeq === undefined).map(p => `${p.kind}:${p.id}`)
16+
17+
const team = () => ({
18+
version: 2,
19+
revision: 1,
20+
mainBotIds: ['chief'],
21+
members: { owner: { id: 'owner', createdAt: 1, designatedChiefId: 'chief' } },
22+
bots: {
23+
chief: { id: 'chief', sessionId: 'chief', name: 'Chief', role: 'Lead', instructions: '', createdAt: 1, ownerId: 'owner' },
24+
writer: { id: 'writer', sessionId: 'writer', name: 'Writer', role: 'Write', instructions: '', createdAt: 2, ownerId: 'owner' },
25+
coder: { id: 'coder', sessionId: 'coder', name: 'Coder', role: 'Code', instructions: '', createdAt: 3, ownerId: 'owner' },
26+
},
27+
rooms: {
28+
// The Bot being deleted is a plain member here.
29+
desk: {
30+
id: 'desk',
31+
name: 'Desk',
32+
members: ['chief', 'writer'],
33+
admin: 'chief',
34+
named: true,
35+
log: [],
36+
seq: 0,
37+
seen: {},
38+
participants: [
39+
{ kind: 'human', id: 'owner', role: 'admin', displayName: 'Owner', joinedSeq: 0, joinedAt: 1 },
40+
{ kind: 'bot', id: 'chief', role: 'admin', displayName: 'Chief', joinedSeq: 0, joinedAt: 1 },
41+
{ kind: 'bot', id: 'writer', role: 'member', displayName: 'Writer', joinedSeq: 0, joinedAt: 1 },
42+
],
43+
},
44+
// The deleted Bot is the room's only admin and its only Bot — `members` is empty afterwards.
45+
solo: {
46+
id: 'solo',
47+
name: 'Solo',
48+
members: ['writer'],
49+
admin: 'writer',
50+
named: true,
51+
log: [],
52+
seq: 0,
53+
seen: {},
54+
participants: [
55+
{ kind: 'human', id: 'owner', role: 'admin', displayName: 'Owner', joinedSeq: 0, joinedAt: 1 },
56+
{ kind: 'bot', id: 'writer', role: 'admin', displayName: 'Writer', joinedSeq: 0, joinedAt: 1 },
57+
],
58+
},
59+
// No `participants` array: the shipped single-owner shape.
60+
legacy: { id: 'legacy', name: 'Legacy', members: ['chief', 'writer'], admin: 'chief', mode: 'everyone' },
61+
},
62+
exchanges: [],
63+
exchangeTurns: {},
64+
questions: {},
65+
revision: 1,
66+
})
67+
68+
function context() {
69+
const ctx = fakeContext()
70+
Object.assign(ctx, {
71+
sessions: { get: () => undefined, flush: async () => {} },
72+
workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} },
73+
sessionController: { create: async () => ({ sessionId: 'new1' }), resolveAgent: async id => ({ agent: { id, session: { id, header: {} } } }), selectModel: async () => {} },
74+
sessionTitle: { rename: async () => {} },
75+
llm: { listProviders: () => [] },
76+
})
77+
return ctx
78+
}
79+
80+
async function open(home) {
81+
const ctx = context()
82+
const rt = createRuntime(ctx, { home, github: false, composio: false, diagnosticsFile: false })
83+
await rt.load()
84+
return { ctx, rt }
85+
}
86+
87+
async function setup(t) {
88+
const home = mkdtempSync(join(tmpdir(), 'ds-bot-delete-seat-'))
89+
writeFileSync(join(home, 'state.json'), JSON.stringify(team()))
90+
const first = await open(home)
91+
t.after(async () => {
92+
await first.ctx.dispose()
93+
rmSync(home, { recursive: true, force: true, maxRetries: 5 })
94+
})
95+
return { home, rt: first.rt, ctx: first.ctx }
96+
}
97+
98+
test('deleting a Bot closes its participant seat and the next membership write does not write it back (#2607)', async (t) => {
99+
const { home, rt, ctx } = await setup(t)
100+
await rt.deleteBot('writer')
101+
assert.equal(rt.botOf('writer'), undefined, 'the Bot record is gone')
102+
const desk = rt.state.rooms.desk
103+
const seat = desk.participants.find(p => p.kind === 'bot' && p.id === 'writer')
104+
assert.ok(seat.leftSeq !== undefined, 'the deleted Bot no longer holds a current seat')
105+
assert.equal(typeof seat.leftAt, 'number', 'the seat records when it ended')
106+
assert.deepEqual(live(desk), ['human:owner', 'bot:chief'], 'the participant list no longer answers the deleted Bot')
107+
assert.deepEqual(rt.participantsOf(desk).map(p => `${p.kind}:${p.id}`), ['human:owner', 'bot:chief'], 'the drawer reads the same list')
108+
assert.deepEqual(desk.members, ['chief'], 'members is derived from the seats, not filtered beside them')
109+
110+
// One ordinary membership write is what used to resurrect the id through `syncMembers`.
111+
await rt.addRoomParticipant('desk', { kind: 'bot', id: 'coder' })
112+
assert.deepEqual(desk.members, ['chief', 'coder'], 'the deleted id does not come back')
113+
assert.deepEqual(live(desk), ['human:owner', 'bot:chief', 'bot:coder'])
114+
115+
// The deletion and the write were saved, so a host that reads the same state.json must agree.
116+
await ctx.dispose()
117+
const second = await open(home)
118+
t.after(async () => { await second.ctx.dispose() })
119+
const reread = second.rt.state.rooms.desk
120+
assert.equal(second.rt.botOf('writer'), undefined)
121+
assert.equal(live(reread).includes('bot:writer'), false, 'the saved seat stays closed')
122+
assert.deepEqual(reread.members, ['chief', 'coder'], 'the saved members list does not carry the deleted id')
123+
})
124+
125+
test('a deleted Bot that was the only admin, and a room left with no Bots, take the next membership write (#2607)', async (t) => {
126+
const { rt } = await setup(t)
127+
await rt.deleteBot('writer')
128+
const solo = rt.state.rooms.solo
129+
assert.deepEqual(solo.members, [], 'the room is left with no Bots')
130+
assert.equal(solo.admin, null, 'the deleted Bot is not still the admin')
131+
assert.deepEqual(live(solo), ['human:owner'])
132+
await rt.addRoomParticipant('solo', { kind: 'bot', id: 'coder' })
133+
assert.deepEqual(solo.members, ['coder'])
134+
assert.deepEqual(live(solo), ['human:owner', 'bot:coder'])
135+
// The room without a participants array keeps the shipped shape.
136+
const legacy = rt.state.rooms.legacy
137+
assert.equal(legacy.participants, undefined, 'no participant list is invented for a legacy room')
138+
assert.deepEqual(legacy.members, ['chief'])
139+
})

‎docs/subsystems/core-host.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,7 @@ An admin's `@` used to be the room's control plane: every `@Dev #1234 rebase and
238238
- The Main Bot list is deployment-wide (#613): `set-main` requires the actor to own `body.id` and, when `body.replace` names the Main Bot whose place the target takes, that Bot too, so a member cannot swap another owner's Main Bot for their own or demote it (both are `bot/forbidden`); `roster.setMain` keeps the same invariant for every caller, refusing a `replace` across owners and leaving `state.mainBotIds` unchanged. A swap inside one owner's team, the plain promotion of a Bot the caller owns, and the deployment-wide list itself are unchanged.
239239
- **A Main Bot retires a Bot; it never deletes one (#638).** `archive_bot` (`tools.js`, Main Bot only) calls `roster.archiveBot`: it writes `fields['flybot-tree'].retired = true` through `rt.setBotField` — the same path and `change` event a plugin's `fields.set` uses, so the tree and the sidebar refresh — and sets `bot.hidden = true`, the flag the tree's own archive uses to keep a Bot out of the default list while Search still finds it (#452). The record, its chat, parts and memory stay where they are, so its history stays readable; retirement has no un-retire path, and the restore entries in the sidebar and the palette only clear `hidden` (`core/src/client/new-chat.js:104`, `core/src/client/palette.js:60`), which opens the chat again but leaves the record retired. The tree's `forestOf` skips a retired record, so its slot under `maxChildren` is free again and adoption leaves it alone. A Main Bot, the caller itself and an unknown name are refused, nothing reparents, and `list_bots` leaves a retired Bot out (the record is still found by name). Retirement is terminal (#1700): the tools that resolve a Bot through `findTeamBot` — `message_bot`, `stop_bot`, `update_bot`, `create_group`, `update_group` (`add_members`, `admin`, `task_lead`) and `archive_bot` — refuse a retired record exactly as they refuse an unknown name, so `message_bot` sends nothing and starts no turn, and `archive_bot` aimed at an already-retired name answers the same "No Bot named …" line. Since [#1709](https://github.com/ThinkFlowLab/FlyBot/issues/1709) the same `retiredBot` predicate (`store.js`, one copy, imported by every caller) is the one check the host paths outside `findTeamBot` apply, and each of them is listed here: `track_tasks`' assignee and a group `@Name` resolve through it, so no card is written and no turn starts (no delivery, no Session); `attach_capability`/`detach_capability` and a `remember`/`recall` `scope:` treat a retired record exactly as an unknown name; `schedule-create`/`schedule-update`/`schedule-copy` refuse it with the same `No such Bot or group chat` answer, and `schedule-resume` refuses a paused row of a retired Bot the same way; `task-create` (the endpoint the client calls), a plugin's `routeOpenTask` and `task-send-back` (which opens a rework card on the same owner) refuse it with `No such Bot`; a send held for approval whose target has been retired meanwhile is stale (`the target Bot was retired`) instead of delivered; and a restart neither picks up a retired Bot's interrupted turn nor sends again what was queued for it. The task drive never wakes a retired owner: `drivingTasks` returns nothing for it, so a card still on the board is not delivered, and a card that arrives through none of these doors is left exactly where it is. Archiving also disarms the target's own chat and the group Sessions it speaks through, every part of each: `rt.pauseBotSchedules` (installed by `schedules.js`) takes the Bot's current part plus each earlier part in `bot.segments`, and each `room.sessions[botId]` plus each earlier part in `room.segments[botId]`, writes each active row — with the part it came from — into `state.pausedSchedules` before DSH drops it, the way pausing one task does, so a task left on an old Session by a part hand-off is not still armed after retirement (#1799), and neither is one armed where it speaks in a group; a room's own Session is left alone, since its rows belong to the whole group, and `archive_bot`'s answer says `Paused N task(s)`—or how many are still armed—instead of staying silent. Retiring means to the board what deleting means: `archiveBot` calls `rt.taskBotDeleted` with `the responsible Bot was retired`, so the cards a retired Bot still holds in `open`, `claimed`, `working` or `blocked` fail instead of waiting for a Bot that will not run again, while a card in `result-ready` stays for its requester to accept or cancel. Still not covered: an un-retire path (there is none), the memory and chat the record keeps, and the connectors a retired Bot's own Session no longer starts. Deleting remains the UI's `delete-bot` call (`roster.deleteBot`), which archives the Bot's memory first. Since [#1801](https://github.com/ThinkFlowLab/FlyBot/issues/1801) retirement also ends the reach a share gave: `archiveBot` deletes `state.grants[id]` and calls `rt.reachChanged(id)`, the way deletion clears sharing, so a friend's Bot granted the record no longer resolves it from outside and nothing is delivered to a Bot that will not run. Covered by `core/test/archive-bot.test.js` and `core/test/retired-bot-paths.test.js`.
240240
- A deleted Bot's Sessions keep their owner (#1453): `state.retiredSessions` maps a Session id to the Bot id that owned it, written by `roster.deleteBot` for the own chat and its parts and for each group Session and its parts before the Bot leaves the state, so `indexSessions` can put them in `pastOwners` again on the next rebuild. The record only fills what the live indexes do not claim — a live Bot or room holding the same id wins — and it only grows, one entry per Session of each Bot ever deleted, with no pruning in this change. `selfOf` then names a Bot that no longer exists, so `connector-access.js` `whoseAgent` answers `{ unknown: true }` and every connector is refused with `the Bot this Agent works for could not be determined`, in the process that deleted the Bot and after a reload, because the team file carries the record. The owner's own Session, an id no Bot ever had and a call with no Agent keep the connectors. The schedule tools are not covered by this change: they carry no connector id and are refused or allowed before that branch, and widening them is the #1237 decision.
241+
- Deleting a Bot ends its room seats (#2607): `roster.deleteBot` closes the Bot's `participants` entry with `leftSeq`/`leftAt` and derives `room.members` through `syncMembers` in `room-membership.js`, the same rule a leave uses, so `participantsOf()`, a shared room's roster and `room.members` stop naming a Bot `state.bots` no longer holds and the next membership write cannot rebuild the id from a current seat; the save that follows keeps the closed seat. A room without a `participants` array keeps the shipped `members` filter. A deletion is not `removeRoomParticipant`: it never refuses on the two-Bot floor. Covered by `core/test/delete-bot-seat.test.js`.
241242

242243
- Context sharing (#53) is specified in [team](team.md), **Context sharing foundation**: the own-chat brief is share-gated (`share-brief` / `briefShared`), a memory review reads only its owner as the user (`isUserLine`) and labels another human as `peer` (not `bot`), and keeps cross-owner entries out of the team scope (`teamAllowedFrom`), a retired Bot is never reviewed — neither a lagging group member is brought along nor a review queued before the archive runs, so its archived `MEMORY.md` is not rewritten and no model call is billed for it (#1786), `list_bots` lists only the caller's owner's Bots (a granted child: that child's `createdBy` subtree), Bots granted to the same owner, and Bots in the current room — another owner's folder and instructions stay private — and a `dsh-session:` chip in actor-authored `send` / `room-post` / `answer-question` / `schedule-create` text must resolve for the author (`sessionOwnedBy`; `schedule-create` authz keys off `body.target`). Bot-authored group posts and Bot-to-Bot / own-chat followups drop chips so they cannot tunnel a private chat into another Session. Host modules: `src/host/groups.js`, `src/host/memory.js`, `src/host/tools.js`, `src/host/channel.js`, `src/host/room-membership.js`, `src/host/authz.js`. Team mode stays disabled.
243244

0 commit comments

Comments
 (0)