Retire removed accounts instead of deleting them

Removing an account had no path at all, so a dead session could only be
left running or hand-edited out of the database. The first cut deleted the
account and everything it owned, which threw away conversations and media
that are worth keeping.

Retire instead: keep the row and every row it produced, destroy the stored
cookies and Matrix token. Wiping the credentials is what makes sending and
syncing impossible rather than merely disabled — isEnabledAccount requires
a verified status, so no runtime ever starts, and no session survives for
anything to use. setActive, markLoginRequired and the background credential
refresh now skip retired accounts so none of them quietly revives one;
re-importing a session deliberately does.

Keeping the content visible needed more than keeping the rows. Conversations
and media are only served from running runtimes, so a retired account's
history would have disappeared from the dashboard regardless. Media already
reads the account content table for every listed account. Conversations now
have an archive path that reads the stored ActiveChat payloads directly.

Every write path refuses a retired conversation with a 409: send-reply,
both suggest endpoints, share-media, shareable-media and all read-state
writes. Lazy-loading detail is skipped too — the fallback chat service
belongs to a different account, so it would sync the wrong session and
write the wrong cache. Archived detail derives conversation state from the
transcript alone for the same reason.

Migration 32 rebuilds reddit_accounts to admit the new status, with foreign
keys off and a foreign_key_check before they are restored, as migration 11
does. Two migration tests rewound user_version by counting back from the
head, which silently breaks whenever a migration is appended; they now
target absolute versions.

Conversations never opened before removal keep only their summary. Message
history is lazy-loaded on first open and there is no session left to fetch
the rest with.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Jamie BruntonandClaude Opus 5 committed 2026-08-12 08:58:22 +01:00
1 parent 3f60f7f665
commit a9cea7ed18
16 files changed
+433 -97

No files matched your search

+92
View File
@@ -880,4 +880,96 @@ describe('conversations route', () => {
});
});
});
describe('removed accounts', () => {
const ARCHIVED = {
username: 'alice', roomName: 'alice', roomId: 'room-alice', lastMessageTime: 500,
lastMessageSnippet: 'thanks!', isFromUs: false, unread: false,
messages: [{ sender: 'alice', text: 'thanks!', timestamp: 500, isSelf: false }],
};
const OWNED_ID = `${encodeURIComponent('@t2_gone:reddit.com')}~${encodeURIComponent('room-alice')}`;
/** A retired account: listed by the service, but with no runtime at all. */
function retiredContext() {
return {
logger: { error: vi.fn(), warn: vi.fn() },
repos: {
accountContent: {
listConversations: vi.fn((accountId: string) => accountId === '@t2_gone:reddit.com'
? [{ conversationId: 'room-alice', payloadJson: JSON.stringify(ARCHIVED) }]
: []),
},
messages: { getByChatRoomId: vi.fn(), getLatestByRecipient: vi.fn() },
},
services: {
chat: {
getCachedConversations: vi.fn().mockResolvedValue([]),
getSyncStatus: () => ({ syncing: false }),
loadConversationDetails: vi.fn(),
saveCacheExternal: vi.fn(),
},
// Present so suggest-reply reaches the read-only guard rather than
// bailing out earlier on a missing AI client.
ai: { generateReply: vi.fn() },
accountRuntimes: { list: () => [], get: () => null },
redditAccounts: {
listRemoved: () => [{ accountId: '@t2_gone:reddit.com', redditUsername: 'gone-bot' }],
},
},
} as unknown as WebContext;
}
it('keeps a retired account\'s conversations listed, read-only and out of the reply queue', async () => {
const app = express().use('/api', createConversationsRouter(retiredContext()));
const body = await (await request(app, '/api/conversations')).json();
expect(body).toEqual([expect.objectContaining({
roomId: 'room-alice',
readOnly: true,
needsReply: false,
hasUnreadInbound: false,
// Open, not resolved: the dashboard's default filter hides resolved
// conversations, and archived history has to stay browsable.
triageStatus: 'open',
owner: { accountId: '@t2_gone:reddit.com', redditUsername: 'gone-bot' },
})]);
});
it('serves the stored transcript without trying to sync more of it', async () => {
const context = retiredContext();
const app = express().use('/api', createConversationsRouter(context));
const body = await (await request(app, `/api/conversations/${encodeURIComponent(OWNED_ID)}`)).json();
expect(body).toMatchObject({ roomId: 'room-alice', readOnly: true });
expect(body.messages).toHaveLength(1);
// The fallback chat service belongs to another account: touching it would
// both sync the wrong session and mutate the wrong cache.
expect(context.services.chat!.loadConversationDetails).not.toHaveBeenCalled();
expect(context.services.chat!.saveCacheExternal).not.toHaveBeenCalled();
});
it('refuses to send, suggest or mark anything in a retired conversation', async () => {
const app = express().use(express.json()).use('/api', createConversationsRouter(retiredContext()));
const path = `/api/conversations/${encodeURIComponent(OWNED_ID)}`;
const responses = await Promise.all([
request(app, `${path}/send-reply`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'hello again' }),
}),
request(app, `${path}/suggest-reply`, { method: 'POST' }),
request(app, `${path}/read`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}',
}),
request(app, `${path}/share-media`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetId: '00000000-0000-4000-8000-000000000000' }),
}),
]);
expect(responses.map((response) => response.status)).toEqual([409, 409, 409, 409]);
expect((await responses[0].json()).error).toMatch(/removed account/i);
});
});
});