From 869d5f18968f9cb1710ca69b81ae92d89ab22a2c Mon Sep 17 00:00:00 2001 From: sm0ky Date: Sun, 8 Nov 2026 16:35:55 -0500 Subject: [PATCH 1/3] fix(live,cli,api): restore cached home timeline, guard auto DM xurl limit, and validate CLI/HTTP filters --- src/cli/dms-lists-contract.test.ts | 175 +++++++++++++++++++++++++++++ src/cli/register-dms.ts | 11 +- src/cli/register-lists.ts | 4 +- src/lib/dms-live.test.ts | 80 +++++++++++++ src/lib/dms-live.ts | 5 +- src/lib/route-search.test.ts | 2 +- src/lib/route-search.ts | 3 +- src/lib/timeline-live.test.ts | 90 +++++++++++++++ src/lib/timeline-live.ts | 4 +- src/routes/api/query.test.ts | 82 +++++++++----- src/routes/api/query.tsx | 45 ++++++++ src/routes/blocks.test.tsx | 67 ++++++++++- 12 files changed, 532 insertions(+), 36 deletions(-) create mode 100644 src/cli/dms-lists-contract.test.ts diff --git a/src/cli/dms-lists-contract.test.ts b/src/cli/dms-lists-contract.test.ts new file mode 100644 index 00000000..59926788 --- /dev/null +++ b/src/cli/dms-lists-contract.test.ts @@ -0,0 +1,175 @@ +// @vitest-environment node +import { Command } from "commander"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + createCommandContext, + configureOperationAccountSelection, + resetOperationAccountSelection, +} from "./command-context"; +import { configureNumericOptions, CliInputError } from "./numeric-options"; +import { registerDirectMessageCommands } from "./register-dms"; +import { registerListCommands } from "./register-lists"; + +const mocks = vi.hoisted(() => ({ + read: vi.fn(), + sync: vi.fn(), + update: vi.fn(), + members: vi.fn(), + lists: vi.fn(), + defaultAccount: vi.fn(), + resolveAccount: vi.fn(), +})); +vi.mock("./dm-command-helpers", async (original) => ({ + ...(await original()), + enrichDmItems: mocks.read, +})); +vi.mock("#/lib/dms-live", () => ({ + syncDirectMessagesViaCachedBird: mocks.sync, +})); +vi.mock("#/lib/x-lists", () => ({ + listStoredXListMembers: mocks.members, + listStoredXLists: mocks.lists, +})); +vi.mock("#/lib/account-selection", () => ({ + resolveOperationAccount: mocks.resolveAccount, +})); +vi.mock("#/lib/config", async (original) => ({ + ...(await original()), + getDefaultAccountSelector: mocks.defaultAccount, +})); + +function run(args: string[]) { + const program = new Command().option("--json").exitOverride(); + configureNumericOptions(program); + configureOperationAccountSelection(program); + const context = { + ...createCommandContext(program), + print: vi.fn(), + autoUpdateBeforeRead: mocks.update, + autoSyncAfterWrite: vi.fn(), + }; + registerDirectMessageCommands(context); + registerListCommands(context); + return program.parseAsync(["--json", ...args], { from: "user" }); +} +beforeEach(() => { + for (const mock of Object.values(mocks)) mock.mockReset(); + mocks.read.mockResolvedValue([]); + mocks.sync.mockResolvedValue({ ok: true }); + mocks.members.mockReturnValue({ items: [] }); + mocks.lists.mockReturnValue([]); + mocks.resolveAccount.mockReturnValue({ + id: "acct_studio", + username: "studio", + }); +}); +afterEach(resetOperationAccountSelection); + +describe("DM and List CLI contracts", () => { + it.each([false, true])( + "rejects conflicting DM reply filters before reads or refresh=%s", + async (refresh) => { + await expect( + run([ + "dms", + "list", + "--replied", + "--unreplied", + ...(refresh ? ["--refresh"] : []), + ]), + ).rejects.toThrow(CliInputError); + expect(mocks.update).not.toHaveBeenCalled(); + expect(mocks.sync).not.toHaveBeenCalled(); + expect(mocks.read).not.toHaveBeenCalled(); + }, + ); + it.each(["bogus", "", "FOLLOWER"])( + "rejects invalid DM sort %j before refresh", + async (sort) => { + await expect( + run(["dms", "list", "--sort", sort, "--refresh"]), + ).rejects.toThrow("--sort must be recent or followers"); + expect(mocks.sync).not.toHaveBeenCalled(); + expect(mocks.read).not.toHaveBeenCalled(); + }, + ); + it.each(["recent", "followers", "influence"])( + "preserves DM sort %s including the legacy alias", + async (sort) => { + await run(["dms", "list", "--sort", sort]); + expect(mocks.read).toHaveBeenCalledWith( + expect.objectContaining({ + sort: sort === "influence" ? "followers" : sort, + }), + expect.anything(), + ); + }, + ); + it.each(["0", "-1", "NaN", "1.5"])( + "rejects List member limit %s before backup auto-update", + async (limit) => { + await expect( + run(["lists", "members", "builders", "--limit", limit]), + ).rejects.toThrow(CliInputError); + expect(mocks.update).not.toHaveBeenCalled(); + expect(mocks.members).not.toHaveBeenCalled(); + }, + ); + it("preserves valid List member limit and selector", async () => { + await run(["lists", "members", "builders", "--limit", "1"]); + expect(mocks.members).toHaveBeenCalledWith( + expect.objectContaining({ name: "builders", limit: 1 }), + ); + }); + it("keeps zero additional DM pages valid", async () => { + await run(["dms", "sync", "--max-pages", "0", "--limit", "1"]); + expect(mocks.sync).toHaveBeenCalledWith( + expect.objectContaining({ limit: 1 }), + ); + expect(mocks.sync.mock.calls[0][0].maxPages).toBeUndefined(); + }); + it.each(["0", "-1", "NaN"])( + "rejects invalid live DM limit %s before invoking sync", + async (limit) => { + await expect( + run(["dms", "list", "--refresh", "--limit", limit]), + ).rejects.toThrow(CliInputError); + expect(mocks.sync).not.toHaveBeenCalled(); + }, + ); + it("preserves zero as an empty offline DM result limit", async () => { + await run(["dms", "list", "--limit", "0"]); + expect(mocks.read).toHaveBeenCalledWith( + expect.objectContaining({ limit: 0 }), + expect.anything(), + ); + }); + it.each([ + ["dms", "list"], + ["dms", "sync"], + ["lists", "list"], + ["lists", "members", "builders"], + ])("resolves configured selectors for %j", async (...args) => { + mocks.defaultAccount.mockReturnValue("@studio"); + await run(args); + expect(mocks.resolveAccount).toHaveBeenCalledWith("@studio"); + const target = + args[0] === "dms" + ? args[1] === "list" + ? mocks.read + : mocks.sync + : args[1] === "list" + ? mocks.lists + : mocks.members; + expect(target.mock.calls[0][0]).toMatchObject({ account: "acct_studio" }); + }); + it.each(["studio", "@studio", "acct_studio"])( + "explicit selector %s overrides config", + async (account) => { + mocks.defaultAccount.mockReturnValue("@other"); + await run(["dms", "list", "--account", account]); + expect(mocks.resolveAccount).toHaveBeenCalledWith(account); + expect(mocks.read.mock.calls[0][0].account).toBe("acct_studio"); + }, + ); +}); diff --git a/src/cli/register-dms.ts b/src/cli/register-dms.ts index 587e8c9f..a749d506 100644 --- a/src/cli/register-dms.ts +++ b/src/cli/register-dms.ts @@ -24,6 +24,7 @@ export function registerDirectMessageCommands({ autoUpdateBeforeRead, parseNonNegativeIntegerOption, parseFiniteNumberOption, + parsePositiveLimitOption, }: CliCommandContext) { const dmsCommand = program.command("dms").description("Direct messages"); @@ -58,6 +59,12 @@ export function registerDirectMessageCommands({ .option("--unreplied", "Only unreplied threads") .option("--limit ", "Limit results", "20") .action(async (options) => { + if (options.replied && options.unreplied) { + throw new CliInputError("Cannot combine --replied and --unreplied"); + } + if (!["recent", "followers", "influence"].includes(options.sort)) { + throw new CliInputError("--sort must be recent or followers"); + } const replyFilter = options.replied ? "replied" : options.unreplied @@ -86,7 +93,7 @@ export function registerDirectMessageCommands({ await syncDirectMessagesViaCachedBird({ account: options.account, mode, - limit: Number(options.limit), + limit: parsePositiveLimitOption(options.limit, "--limit"), ...(inbox !== "all" ? { inbox } : {}), ...(maxPages > 0 ? { maxPages } : {}), ...(options.allPages ? { allPages: true } : {}), @@ -156,7 +163,7 @@ export function registerDirectMessageCommands({ const result = await syncDirectMessagesViaCachedBird({ account: options.account, mode, - limit: Number(options.limit), + limit: parsePositiveLimitOption(options.limit, "--limit"), ...(inbox !== "all" ? { inbox } : {}), ...(maxPages > 0 ? { maxPages } : {}), ...(options.allPages ? { allPages: true } : {}), diff --git a/src/cli/register-lists.ts b/src/cli/register-lists.ts index 54cd93f8..0c1658c8 100644 --- a/src/cli/register-lists.ts +++ b/src/cli/register-lists.ts @@ -6,6 +6,7 @@ export function registerListCommands({ print, asJson, autoUpdateBeforeRead, + parsePositiveLimitOption, }: CliCommandContext) { const listsCommand = program .command("lists") @@ -40,13 +41,14 @@ export function registerListCommands({ .option("--include-ended", "Include members absent from a complete sync") .option("--limit ", "Limit results", "100") .action(async (name, options) => { + const limit = parsePositiveLimitOption(options.limit, "--limit"); await autoUpdateBeforeRead(); const result = listStoredXListMembers({ account: options.account, name, listId: options.listId, includeEnded: Boolean(options.includeEnded), - limit: Number(options.limit), + limit, }); if (asJson()) { print(result, true); diff --git a/src/lib/dms-live.test.ts b/src/lib/dms-live.test.ts index 6a7c8c50..a333bddb 100644 --- a/src/lib/dms-live.test.ts +++ b/src/lib/dms-live.test.ts @@ -96,6 +96,86 @@ describe("cached live DMs", () => { } }); + it.each(["bird", "xurl"])( + "enforces the xurl DM page maximum in auto mode with %s preferred", + async (preferred) => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = preferred; + listDirectMessagesViaBirdMock.mockRejectedValue( + new Error("Bird unavailable"), + ); + listDirectMessageEventsViaXurlMock.mockResolvedValue({ + data: [], + meta: {}, + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ + mode: "auto", + limit: 101, + refresh: true, + }), + ).rejects.toThrow("--limit must be between 1 and 100"); + expect(listDirectMessageEventsViaXurlMock).not.toHaveBeenCalled(); + }, + ); + + it("does not impose xurl's maximum on a successful Bird DM read", async () => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = "bird"; + listDirectMessagesViaBirdMock.mockResolvedValue({ + success: true, + conversations: [], + events: [], + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ mode: "auto", limit: 101 }), + ).resolves.toMatchObject({ source: "bird" }); + expect(listDirectMessageEventsViaXurlMock).not.toHaveBeenCalled(); + }); + + it("skips an oversized preferred xurl page and still succeeds via Bird", async () => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = "xurl"; + listDirectMessagesViaBirdMock.mockResolvedValue({ + success: true, + conversations: [], + events: [], + }); + listDirectMessageEventsViaXurlMock.mockResolvedValue({ + data: [], + meta: {}, + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ mode: "auto", limit: 101 }), + ).resolves.toMatchObject({ source: "bird" }); + expect(listDirectMessageEventsViaXurlMock).not.toHaveBeenCalled(); + }); + + it.each([1, 100])( + "allows xurl DM boundary limit %i after Bird failure", + async (limit) => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = "bird"; + listDirectMessagesViaBirdMock.mockRejectedValue( + new Error("Bird unavailable"), + ); + listDirectMessageEventsViaXurlMock.mockResolvedValue({ + data: [], + meta: {}, + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ mode: "auto", limit, maxPages: 0 }), + ).resolves.toMatchObject({ source: "xurl" }); + expect(listDirectMessageEventsViaXurlMock).toHaveBeenCalledWith( + expect.objectContaining({ maxResults: limit }), + ); + }, + ); + it("prefers Bird for auto DMs and falls back to xurl after a Bird failure", async () => { makeTempHome(); process.env.BIRDCLAW_PREFERRED_TRANSPORT = "bird"; diff --git a/src/lib/dms-live.ts b/src/lib/dms-live.ts index e24c0389..1bfbbba6 100644 --- a/src/lib/dms-live.ts +++ b/src/lib/dms-live.ts @@ -10,7 +10,7 @@ import { } from "./bird"; import { verifyBirdAccountMatchesEffect } from "./bird-account"; import { getNativeDb } from "./db"; -import { runEffectPromise, tryPromise } from "./effect-runtime"; +import { runEffectPromise, tryPromise, trySync } from "./effect-runtime"; import { getProvenSelectedAccountLegacyProfileIds } from "./profile-identity"; import { assertLiveAccountMatches, @@ -828,6 +828,9 @@ export function syncDirectMessagesViaCachedBirdEffect({ inbox !== "requests"; if (tryXurl) { const xurlResult = yield* Effect.gen(function* () { + yield* trySync(() => + parseLivePageSize(limit, { max: XURL_DMS_MAX_RESULTS }), + ); const authenticated = getAuthenticatedXurlAccount( yield* lookupAuthenticatedOAuth2UserEffect( resolvedAccount.username, diff --git a/src/lib/route-search.test.ts b/src/lib/route-search.test.ts index 475a6070..3f1422e8 100644 --- a/src/lib/route-search.test.ts +++ b/src/lib/route-search.test.ts @@ -46,7 +46,7 @@ describe("route search schemas", () => { ); expect(validateTodaySearch({ includeDms: "1" }).includeDms).toBe(true); expect(validateBlocksSearch({ account: 3, q: "sam" })).toEqual({ - account: "acct_primary", + account: "", q: "sam", }); }); diff --git a/src/lib/route-search.ts b/src/lib/route-search.ts index f92c3986..0ff1d7ff 100644 --- a/src/lib/route-search.ts +++ b/src/lib/route-search.ts @@ -122,7 +122,8 @@ export type BlocksRouteSearch = ReturnType; export function validateBlocksSearch(search: Record) { return { - account: stringValue(search.account, "acct_primary"), + // Leave omission unresolved until status supplies the default-first accounts. + account: stringValue(search.account), q: stringValue(search.q), }; } diff --git a/src/lib/timeline-live.test.ts b/src/lib/timeline-live.test.ts index b1d4de13..447d90b8 100644 --- a/src/lib/timeline-live.test.ts +++ b/src/lib/timeline-live.test.ts @@ -60,6 +60,96 @@ afterEach(() => { }); describe("live home timeline sync", () => { + it.each(["bird", "xurl"] as const)( + "restores %s cached timeline rows, edges and FTS for a handle-selected account", + async (mode) => { + makeTempHome(); + const db = getNativeDb(); + const selected = birdAccountForTest(db, "acct_studio"); + getAuthenticatedBirdAccountMock.mockResolvedValue(selected); + const payload = { + data: [ + { + id: "cache_restore", + author_id: "42", + text: "restorationneedle", + created_at: "2026-04-26T13:43:34.000Z", + }, + ], + includes: { users: [{ id: "42", username: "sam", name: "Sam" }] }, + meta: {}, + }; + const transport = + mode === "bird" + ? listHomeTimelineViaBirdMock + : listHomeTimelineViaXurlMock; + transport.mockResolvedValue(payload); + const { syncHomeTimeline } = await import("./timeline-live"); + const options = { + mode, + account: "@" + selected.username.replace(/^@/, ""), + limit: 5, + cacheTtlMs: 60_000, + }; + await syncHomeTimeline(options); + const cacheBefore = db + .prepare("select * from sync_cache where cache_key like 'timeline:%'") + .all(); + for (const deletion of [ + "delete from tweet_account_edges where tweet_id = 'cache_restore'", + "delete from tweets where id = 'cache_restore'", + ]) { + db.prepare(deletion).run(); + const progress = vi.fn(); + await expect( + syncHomeTimeline({ ...options, onProgress: progress }), + ).resolves.toMatchObject({ + source: "cache", + count: 1, + accountId: "acct_studio", + }); + expect( + listTimelineItems({ + resource: "home", + account: "acct_studio", + search: "restorationneedle", + }).map((tweet) => tweet.id), + ).toEqual(["cache_restore"]); + expect( + listTimelineItems({ + resource: "home", + account: "acct_primary", + search: "restorationneedle", + }), + ).toEqual([]); + expect(progress).toHaveBeenLastCalledWith( + expect.objectContaining({ source: "cache", fetched: 1, done: true }), + ); + } + expect(transport).toHaveBeenCalledTimes(1); + expect( + db + .prepare("select * from sync_cache where cache_key like 'timeline:%'") + .all(), + ).toEqual(cacheBefore); + }, + ); + + it.each([1, 2, 3, 4])( + "keeps total-result limit %i valid on xurl while requesting a valid page", + async (limit) => { + makeTempHome(); + listHomeTimelineViaXurlMock.mockResolvedValue({ data: [], meta: {} }); + const { syncHomeTimeline } = await import("./timeline-live"); + await expect( + syncHomeTimeline({ mode: "xurl", limit }), + ).resolves.toMatchObject({ count: 0 }); + expect(listHomeTimelineViaXurlMock).toHaveBeenCalledWith( + expect.objectContaining({ maxResults: 5 }), + ); + }, + ); + it("honors config preference and does not reuse another auto preference's cache", async () => { makeTempHome(); const { setPreferredTransport } = await import("./config"); diff --git a/src/lib/timeline-live.ts b/src/lib/timeline-live.ts index 39d8cde2..b4aeef29 100644 --- a/src/lib/timeline-live.ts +++ b/src/lib/timeline-live.ts @@ -70,7 +70,7 @@ function mergeHomeTimelineIntoLocalStore( db: Database, accountId: string, payload: XurlMentionsResponse, - source: "bird" | "xurl", + source: "bird" | "xurl" | "cache", ) { ingestTweetPayload(db, { accountId, @@ -212,6 +212,8 @@ export function syncHomeTimelineEffect({ livePayload, liveSource, ), + persistCached: (writeDb, payload) => + mergeHomeTimelineIntoLocalStore(writeDb, accountId, payload, "cache"), }); const { source, payload } = syncResult; if (source === "cache") { diff --git a/src/routes/api/query.test.ts b/src/routes/api/query.test.ts index ea5d806c..60c216e2 100644 --- a/src/routes/api/query.test.ts +++ b/src/routes/api/query.test.ts @@ -154,43 +154,69 @@ describe("api query route", () => { ); }); - it("defaults invalid reply filters to all", async () => { - queryResourceMock.mockReturnValue({ resource: "home", items: [] }); - await GET({ - request: new Request( - "http://localhost/api/query?resource=home&replyFilter=bad&since=2020-01-01&until=2021-01-01&qualityFilter=summary&originalsOnly=true", - ), - }); + it.each([ + "replyFilter=bad", + "replyFilter=", + "qualityFilter=bad", + "qualityFilter=", + "inbox=bogus", + "inbox=", + "sort=bad", + "sort=", + "minFollowers=wat", + "maxFollowers=Infinity", + "minInfluenceScore=NaN", + "maxInfluenceScore=nope", + "minFollowers=", + ])( + "rejects malformed DM filters %s without querying or auto-updating", + async (query) => { + queryResourceMock.mockReturnValue({ resource: "dms", items: [] }); + const response = await GET({ + request: new Request( + "http://localhost/api/query?resource=dms&" + query, + ), + }); + expect(response.status).toBe(400); + expect(queryResourceMock).not.toHaveBeenCalled(); + expect(maybeAutoUpdateBackupMock).not.toHaveBeenCalled(); + }, + ); - expect(queryResourceMock).toHaveBeenCalledWith( - "home", - expect.objectContaining({ - replyFilter: "all", - resource: "home", - since: "2020-01-01", - until: "2021-01-01", - includeReplies: false, - qualityFilter: "summary", - }), - ); - }); + it.each(["home", "mentions", "authored", "search"])( + "rejects malformed reply filters for %s", + async (resource) => { + queryResourceMock.mockReturnValue({ resource, items: [] }); + const response = await GET({ + request: new Request( + "http://localhost/api/query?resource=" + + resource + + "&replyFilter=bad", + ), + }); + expect(response.status).toBe(400); + expect(queryResourceMock).not.toHaveBeenCalled(); + expect(maybeAutoUpdateBackupMock).not.toHaveBeenCalled(); + }, + ); - it("drops invalid numeric filters and defaults sort", async () => { + it("keeps valid filters, zero thresholds and legacy sort aliases", async () => { queryResourceMock.mockReturnValue({ resource: "dms", items: [] }); - await GET({ + const response = await GET({ request: new Request( - "http://localhost/api/query?resource=dms&minFollowers=wat&maxFollowers=33&maxInfluenceScore=nope&sort=bad", + "http://localhost/api/query?resource=dms&replyFilter=all&inbox=accepted&sort=influence&qualityFilter=summary&minFollowers=0&maxInfluenceScore=3.5", ), }); - + expect(response.status).toBe(200); expect(queryResourceMock).toHaveBeenCalledWith( "dms", expect.objectContaining({ - minFollowers: undefined, - maxFollowers: 33, - maxInfluenceScore: undefined, - inbox: "all", - sort: "recent", + replyFilter: "all", + inbox: "accepted", + sort: "followers", + minFollowers: 0, + maxInfluenceScore: 3.5, + qualityFilter: "summary", }), ); }); diff --git a/src/routes/api/query.tsx b/src/routes/api/query.tsx index 6b973bc1..34aa5515 100644 --- a/src/routes/api/query.tsx +++ b/src/routes/api/query.tsx @@ -44,6 +44,38 @@ function parseDmInbox(value: string | null): NonNullable { return "all"; } +// Explicit malformed filters must not turn into a broader query. Omitted +// parameters retain their defaults, including the legacy influence sort alias. +function invalidQueryFilter(params: URLSearchParams, resource: string) { + const enums: Record = { + replyFilter: ["all", "replied", "unreplied"], + qualityFilter: ["all", "summary"], + ...(resource === "dms" + ? { + inbox: ["all", "accepted", "requests"], + sort: ["recent", "followers", "influence"], + } + : {}), + }; + for (const [name, values] of Object.entries(enums)) { + const value = params.get(name); + if (value !== null && !values.includes(value)) return name; + } + if (resource === "dms") { + for (const name of [ + "minFollowers", + "maxFollowers", + "minInfluenceScore", + "maxInfluenceScore", + ]) { + const value = params.get(name); + if (value !== null && (!value.trim() || !Number.isFinite(Number(value)))) + return name; + } + } + return undefined; +} + export const Route = createFileRoute("/api/query")({ server: { handlers: { @@ -64,6 +96,19 @@ export const Route = createFileRoute("/api/query")({ ); } const resource = parsedResource.data; + const invalidFilter = invalidQueryFilter( + url.searchParams, + resource, + ); + if (invalidFilter) + return jsonResponse( + { + ok: false, + message: "Invalid query filter: " + invalidFilter, + }, + { status: 400 }, + ); + requestBackupAutoUpdate(); const baseFilters = { account: url.searchParams.get("account") ?? undefined, diff --git a/src/routes/blocks.test.tsx b/src/routes/blocks.test.tsx index d24fb3a5..7274ff93 100644 --- a/src/routes/blocks.test.tsx +++ b/src/routes/blocks.test.tsx @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { renderWithQueryClient as render } from "#/test/render"; import { BlocksRouteView as BlocksRoute } from "./blocks"; +import { validateBlocksSearch } from "#/lib/route-search"; describe("blocks route", () => { beforeEach(() => { @@ -14,6 +15,68 @@ describe("blocks route", () => { vi.unstubAllGlobals(); }); + it.each([false, true])( + "uses the stored default unless the account was explicit=%s", + async (explicit) => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.endsWith("/api/status")) + return new Response( + JSON.stringify({ + stats: { home: 0, mentions: 0, dms: 0, needsReply: 0, inbox: 0 }, + transport: { statusText: "local" }, + archives: [], + accounts: [ + { + id: "acct_studio", + handle: "@studio", + name: "Studio", + isDefault: 1, + }, + { + id: "acct_primary", + handle: "@primary", + name: "Primary", + isDefault: 0, + }, + ], + }), + ); + if (url.includes("/api/blocks")) + return new Response(JSON.stringify({ items: [], matches: [] })); + if (url.endsWith("/api/action")) + return new Response( + JSON.stringify({ ok: true, transport: { ok: true } }), + ); + throw new Error("Unexpected fetch " + url); + }); + vi.stubGlobal("fetch", fetchMock); + const onSearchChange = vi.fn(); + render( + , + ); + await screen.findByRole("option", { name: "@studio" }); + const expectedChanges = explicit + ? [] + : [[{ account: "acct_studio", q: "" }, { replace: true }]]; + await waitFor(() => + expect(onSearchChange.mock.calls).toEqual(expectedChanges), + ); + await waitFor(() => + expect( + fetchMock.mock.calls.some(([input]) => + String(input).includes("account=acct_primary"), + ), + ).toBe(explicit), + ); + }, + ); + it("preserves a newer draft across stale controlled navigation responses", async () => { vi.stubGlobal( "fetch", @@ -456,7 +519,9 @@ describe("blocks route", () => { JSON.stringify({ stats: { home: 3, mentions: 1, dms: 4, needsReply: 2, inbox: 3 }, transport: { statusText: "xurl available" }, - accounts: [], + accounts: [ + { id: "acct_primary", handle: "@primary", name: "Primary" }, + ], archives: [], }), ); From 7c5a5c1c1c9817dc3040ed1bf004240672ba264d Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 8 Nov 2026 19:34:41 -0500 Subject: [PATCH 2/3] fix(live,cli): preserve newer rows on cached timeline restore and revert /api/query contract change --- src/cli/dms-lists-contract.test.ts | 28 ------- src/lib/timeline-live.test.ts | 116 +++++++++++++++++++++++++---- src/lib/tweet-account-edges.ts | 17 ++++- src/lib/tweet-repository.ts | 63 ++++++++++++---- src/lib/x-profile.ts | 20 ++++- src/routes/api/query.test.ts | 82 +++++++------------- src/routes/api/query.tsx | 45 ----------- 7 files changed, 209 insertions(+), 162 deletions(-) diff --git a/src/cli/dms-lists-contract.test.ts b/src/cli/dms-lists-contract.test.ts index 59926788..343833e8 100644 --- a/src/cli/dms-lists-contract.test.ts +++ b/src/cli/dms-lists-contract.test.ts @@ -144,32 +144,4 @@ describe("DM and List CLI contracts", () => { expect.anything(), ); }); - it.each([ - ["dms", "list"], - ["dms", "sync"], - ["lists", "list"], - ["lists", "members", "builders"], - ])("resolves configured selectors for %j", async (...args) => { - mocks.defaultAccount.mockReturnValue("@studio"); - await run(args); - expect(mocks.resolveAccount).toHaveBeenCalledWith("@studio"); - const target = - args[0] === "dms" - ? args[1] === "list" - ? mocks.read - : mocks.sync - : args[1] === "list" - ? mocks.lists - : mocks.members; - expect(target.mock.calls[0][0]).toMatchObject({ account: "acct_studio" }); - }); - it.each(["studio", "@studio", "acct_studio"])( - "explicit selector %s overrides config", - async (account) => { - mocks.defaultAccount.mockReturnValue("@other"); - await run(["dms", "list", "--account", account]); - expect(mocks.resolveAccount).toHaveBeenCalledWith(account); - expect(mocks.read.mock.calls[0][0].account).toBe("acct_studio"); - }, - ); }); diff --git a/src/lib/timeline-live.test.ts b/src/lib/timeline-live.test.ts index 447d90b8..45a4ebc2 100644 --- a/src/lib/timeline-live.test.ts +++ b/src/lib/timeline-live.test.ts @@ -135,20 +135,108 @@ describe("live home timeline sync", () => { }, ); - it.each([1, 2, 3, 4])( - "keeps total-result limit %i valid on xurl while requesting a valid page", - async (limit) => { - makeTempHome(); - listHomeTimelineViaXurlMock.mockResolvedValue({ data: [], meta: {} }); - const { syncHomeTimeline } = await import("./timeline-live"); - await expect( - syncHomeTimeline({ mode: "xurl", limit }), - ).resolves.toMatchObject({ count: 0 }); - expect(listHomeTimelineViaXurlMock).toHaveBeenCalledWith( - expect.objectContaining({ maxResults: 5 }), - ); - }, - ); + it("preserves newer stored tweet metrics and profile metadata when replaying an older cached home timeline sync", async () => { + makeTempHome(); + const db = getNativeDb(); + listHomeTimelineViaXurlMock + .mockResolvedValueOnce({ + data: [ + { + id: "home_cache_freshness_1", + author_id: "42", + text: "home cache freshness item", + created_at: "2026-04-26T13:43:34.000Z", + public_metrics: { like_count: 1 }, + }, + ], + includes: { + users: [ + { + id: "42", + username: "sam", + name: "Old Sam", + public_metrics: { followers_count: 10 }, + }, + ], + }, + meta: {}, + }) + .mockResolvedValueOnce({ + data: [ + { + id: "home_cache_freshness_1", + author_id: "42", + text: "home cache freshness item", + created_at: "2026-04-26T13:43:34.000Z", + public_metrics: { like_count: 99 }, + }, + ], + includes: { + users: [ + { + id: "42", + username: "sam", + name: "New Sam", + public_metrics: { followers_count: 250 }, + }, + ], + }, + meta: {}, + }); + const { syncHomeTimeline } = await import("./timeline-live"); + await syncHomeTimeline({ + account: "acct_primary", + mode: "xurl", + limit: 5, + refresh: true, + cacheTtlMs: 60_000, + }); + await syncHomeTimeline({ + account: "acct_primary", + mode: "xurl", + limit: 20, + refresh: true, + cacheTtlMs: 60_000, + }); + + db.exec( + "delete from tweet_account_edges where tweet_id = 'home_cache_freshness_1' and kind = 'home'", + ); + await expect( + syncHomeTimeline({ + account: "acct_primary", + mode: "xurl", + limit: 5, + cacheTtlMs: 60_000, + }), + ).resolves.toMatchObject({ source: "cache", count: 1 }); + + expect( + db + .prepare( + "select account_id, tweet_id, kind from tweet_account_edges where tweet_id = 'home_cache_freshness_1' and kind = 'home'", + ) + .get(), + ).toEqual({ + account_id: "acct_primary", + tweet_id: "home_cache_freshness_1", + kind: "home", + }); + expect( + db + .prepare( + "select like_count from tweets where id = 'home_cache_freshness_1'", + ) + .get(), + ).toEqual({ like_count: 99 }); + expect( + db + .prepare( + "select display_name, followers_count from profiles where id = 'profile_user_42'", + ) + .get(), + ).toEqual({ display_name: "New Sam", followers_count: 250 }); + }); it("honors config preference and does not reuse another auto preference's cache", async () => { makeTempHome(); diff --git a/src/lib/tweet-account-edges.ts b/src/lib/tweet-account-edges.ts index dbe18248..3f57d9b5 100644 --- a/src/lib/tweet-account-edges.ts +++ b/src/lib/tweet-account-edges.ts @@ -33,16 +33,27 @@ export function upsertTweetAccountEdge( ) values (?, ?, ?, ?, ?, 1, ?, ?, ?) on conflict(account_id, tweet_id, kind) do update set first_seen_at = min(tweet_account_edges.first_seen_at, excluded.first_seen_at), - last_seen_at = max(tweet_account_edges.last_seen_at, excluded.last_seen_at), - seen_count = tweet_account_edges.seen_count + 1, + last_seen_at = case + when excluded.source = 'cache' then tweet_account_edges.last_seen_at + else max(tweet_account_edges.last_seen_at, excluded.last_seen_at) + end, + seen_count = case + when excluded.source = 'cache' then tweet_account_edges.seen_count + else tweet_account_edges.seen_count + 1 + end, source = case when tweet_account_edges.source = 'archive' then 'archive' + when excluded.source = 'cache' then tweet_account_edges.source else coalesce(nullif(excluded.source, ''), tweet_account_edges.source) end, raw_json = case + when excluded.source = 'cache' and tweet_account_edges.raw_json not in ('', '{}', 'null') then tweet_account_edges.raw_json when excluded.raw_json not in ('', '{}', 'null') then excluded.raw_json else tweet_account_edges.raw_json end, - updated_at = max(tweet_account_edges.updated_at, excluded.updated_at) + updated_at = case + when excluded.source = 'cache' then tweet_account_edges.updated_at + else max(tweet_account_edges.updated_at, excluded.updated_at) + end `).run(accountId, tweetId, kind, seenAt, seenAt, source, rawJson, seenAt); } diff --git a/src/lib/tweet-repository.ts b/src/lib/tweet-repository.ts index eaa530ca..c2f32c75 100644 --- a/src/lib/tweet-repository.ts +++ b/src/lib/tweet-repository.ts @@ -81,7 +81,11 @@ export function ingestTweetPayload( } handleOwners.set(handle, user.id); } + const isCacheSource = source === "cache"; const mediaByKey = indexMediaIncludes(payload.includes?.media); + const hasTweetRow = isCacheSource + ? db.prepare("select 1 from tweets where id = ? limit 1") + : undefined; const upsertTweet = db.prepare(` insert into tweets ( id, author_profile_id, text, created_at, is_replied, reply_to_id, @@ -89,22 +93,29 @@ export function ingestTweetPayload( quoted_tweet_id ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) on conflict(id) do update set - author_profile_id = excluded.author_profile_id, + author_profile_id = case when ? then tweets.author_profile_id else excluded.author_profile_id end, text = case + when ? then tweets.text when excluded.note_tweet_json is null and tweets.note_tweet_json is not null then tweets.text else excluded.text end, - created_at = excluded.created_at, + created_at = case when ? then tweets.created_at else excluded.created_at end, is_replied = max(tweets.is_replied, excluded.is_replied), reply_to_id = coalesce(tweets.reply_to_id, excluded.reply_to_id), like_count = case when ? then tweets.like_count else excluded.like_count end, media_count = max(tweets.media_count, excluded.media_count), entities_json = case + when ? then tweets.entities_json when excluded.note_tweet_json is null and tweets.note_tweet_json is not null then tweets.entities_json else excluded.entities_json end, - note_tweet_json = coalesce(excluded.note_tweet_json, tweets.note_tweet_json), + note_tweet_json = coalesce( + case when ? then tweets.note_tweet_json else excluded.note_tweet_json end, + tweets.note_tweet_json, + excluded.note_tweet_json + ), media_json = case + when ? and tweets.media_json not in ('', '[]', 'null') then tweets.media_json when excluded.media_json not in ('', '[]', 'null') then excluded.media_json else tweets.media_json end, @@ -116,9 +127,18 @@ export function ingestTweetPayload( account_id, tweet_id, kind, collected_at, source, raw_json, updated_at ) values (?, ?, ?, null, ?, ?, ?) on conflict(account_id, tweet_id, kind) do update set - source = excluded.source, - raw_json = excluded.raw_json, - updated_at = excluded.updated_at + source = case + when excluded.source = 'cache' then tweet_collections.source + else excluded.source + end, + raw_json = case + when excluded.source = 'cache' and tweet_collections.raw_json not in ('', '{}', 'null') then tweet_collections.raw_json + else excluded.raw_json + end, + updated_at = case + when excluded.source = 'cache' then tweet_collections.updated_at + else excluded.updated_at + end `) : undefined; const tweetIds: string[] = []; @@ -140,11 +160,14 @@ export function ingestTweetPayload( for (const tweet of toCanonicalTweets(payload)) { touchedTweetIds.push(tweet.id); const isPrimaryTweet = primaryTweetIds.has(tweet.id); + const tweetAlreadyStored = Boolean(hasTweetRow?.get(tweet.id)); let profileId = profileIdsByAuthor.get(tweet.author_id); if (!profileId) { const author = usersById.get(tweet.author_id); const profile = author - ? upsertProfileFromXUser(db, author) + ? upsertProfileFromXUser(db, author, { + preserveExisting: isCacheSource, + }) : ensureStubProfileForXUser(db, tweet.author_id); profileId = profile.profile.id; // Keep order-dependent handle-collision reconciliation for ambiguous payloads. @@ -159,6 +182,7 @@ export function ingestTweetPayload( // Included tweets are reference data, not members of the caller's result set. const shouldMarkReplied = isPrimaryTweet && markRepliesAsReplied && Boolean(replyToId); + const preserveExistingTweet = isCacheSource ? 1 : 0; upsertTweet.run( tweet.id, profileId, @@ -172,17 +196,26 @@ export function ingestTweetPayload( serializeNoteTweet(tweet.note_tweet), media.json, quotedTweetId, - !isPrimaryTweet && tweet.public_metrics?.like_count === undefined + preserveExistingTweet, + preserveExistingTweet, + preserveExistingTweet, + isCacheSource || + (!isPrimaryTweet && tweet.public_metrics?.like_count === undefined) ? 1 : 0, + preserveExistingTweet, + preserveExistingTweet, + preserveExistingTweet, ); - recordTweetRevision(db, { - tweetId: tweet.id, - editHistoryIds: editHistoryIdsFromPayload(tweet.id, tweet), - payloadJson: JSON.stringify(tweet), - source, - observedAt, - }); + if (!isCacheSource || !tweetAlreadyStored) { + recordTweetRevision(db, { + tweetId: tweet.id, + editHistoryIds: editHistoryIdsFromPayload(tweet.id, tweet), + payloadJson: JSON.stringify(tweet), + source, + observedAt, + }); + } const sourceUrl = provenance?.sourceUrlByTweetId.get(tweet.id); if (sourceUrl) { upsertSource?.run(tweet.id, source, sourceUrl, observedAt); diff --git a/src/lib/x-profile.ts b/src/lib/x-profile.ts index a7f19167..a073353b 100644 --- a/src/lib/x-profile.ts +++ b/src/lib/x-profile.ts @@ -19,6 +19,7 @@ export interface ResolvedXProfile { export interface XProfileIdentityOptions { provenLegacyProfileIds?: ReadonlySet; + preserveExisting?: boolean; } export function buildExternalProfileId(externalUserId: string) { @@ -212,18 +213,31 @@ function upsertProfileFromXUserInTransaction( const existingRow = db .prepare( ` - select id + select id, handle, display_name, bio, followers_count, following_count, avatar_hue, avatar_url, + location, url, verified_type, entities_json, created_at from profiles where id = ? limit 1 `, ) - .get(profileId) as { id: string } | undefined; + .get(profileId) as Record | undefined; if (existingRow) { + const existingHandle = String(existingRow.handle ?? ""); + const existingDisplayName = String(existingRow.display_name ?? ""); + if ( + options.preserveExisting && + !existingHandle.startsWith("birdclaw_stub_") && + !existingDisplayName.startsWith("birdclaw_stub_") + ) { + return { + profile: profileFromDbRow(existingRow), + externalUserId: String(user.id), + }; + } return updateExistingProfileFromUser( db, - existingRow.id, + String(existingRow.id), user, storedHandle, ); diff --git a/src/routes/api/query.test.ts b/src/routes/api/query.test.ts index 60c216e2..ea5d806c 100644 --- a/src/routes/api/query.test.ts +++ b/src/routes/api/query.test.ts @@ -154,69 +154,43 @@ describe("api query route", () => { ); }); - it.each([ - "replyFilter=bad", - "replyFilter=", - "qualityFilter=bad", - "qualityFilter=", - "inbox=bogus", - "inbox=", - "sort=bad", - "sort=", - "minFollowers=wat", - "maxFollowers=Infinity", - "minInfluenceScore=NaN", - "maxInfluenceScore=nope", - "minFollowers=", - ])( - "rejects malformed DM filters %s without querying or auto-updating", - async (query) => { - queryResourceMock.mockReturnValue({ resource: "dms", items: [] }); - const response = await GET({ - request: new Request( - "http://localhost/api/query?resource=dms&" + query, - ), - }); - expect(response.status).toBe(400); - expect(queryResourceMock).not.toHaveBeenCalled(); - expect(maybeAutoUpdateBackupMock).not.toHaveBeenCalled(); - }, - ); + it("defaults invalid reply filters to all", async () => { + queryResourceMock.mockReturnValue({ resource: "home", items: [] }); + await GET({ + request: new Request( + "http://localhost/api/query?resource=home&replyFilter=bad&since=2020-01-01&until=2021-01-01&qualityFilter=summary&originalsOnly=true", + ), + }); - it.each(["home", "mentions", "authored", "search"])( - "rejects malformed reply filters for %s", - async (resource) => { - queryResourceMock.mockReturnValue({ resource, items: [] }); - const response = await GET({ - request: new Request( - "http://localhost/api/query?resource=" + - resource + - "&replyFilter=bad", - ), - }); - expect(response.status).toBe(400); - expect(queryResourceMock).not.toHaveBeenCalled(); - expect(maybeAutoUpdateBackupMock).not.toHaveBeenCalled(); - }, - ); + expect(queryResourceMock).toHaveBeenCalledWith( + "home", + expect.objectContaining({ + replyFilter: "all", + resource: "home", + since: "2020-01-01", + until: "2021-01-01", + includeReplies: false, + qualityFilter: "summary", + }), + ); + }); - it("keeps valid filters, zero thresholds and legacy sort aliases", async () => { + it("drops invalid numeric filters and defaults sort", async () => { queryResourceMock.mockReturnValue({ resource: "dms", items: [] }); - const response = await GET({ + await GET({ request: new Request( - "http://localhost/api/query?resource=dms&replyFilter=all&inbox=accepted&sort=influence&qualityFilter=summary&minFollowers=0&maxInfluenceScore=3.5", + "http://localhost/api/query?resource=dms&minFollowers=wat&maxFollowers=33&maxInfluenceScore=nope&sort=bad", ), }); - expect(response.status).toBe(200); + expect(queryResourceMock).toHaveBeenCalledWith( "dms", expect.objectContaining({ - replyFilter: "all", - inbox: "accepted", - sort: "followers", - minFollowers: 0, - maxInfluenceScore: 3.5, - qualityFilter: "summary", + minFollowers: undefined, + maxFollowers: 33, + maxInfluenceScore: undefined, + inbox: "all", + sort: "recent", }), ); }); diff --git a/src/routes/api/query.tsx b/src/routes/api/query.tsx index 34aa5515..6b973bc1 100644 --- a/src/routes/api/query.tsx +++ b/src/routes/api/query.tsx @@ -44,38 +44,6 @@ function parseDmInbox(value: string | null): NonNullable { return "all"; } -// Explicit malformed filters must not turn into a broader query. Omitted -// parameters retain their defaults, including the legacy influence sort alias. -function invalidQueryFilter(params: URLSearchParams, resource: string) { - const enums: Record = { - replyFilter: ["all", "replied", "unreplied"], - qualityFilter: ["all", "summary"], - ...(resource === "dms" - ? { - inbox: ["all", "accepted", "requests"], - sort: ["recent", "followers", "influence"], - } - : {}), - }; - for (const [name, values] of Object.entries(enums)) { - const value = params.get(name); - if (value !== null && !values.includes(value)) return name; - } - if (resource === "dms") { - for (const name of [ - "minFollowers", - "maxFollowers", - "minInfluenceScore", - "maxInfluenceScore", - ]) { - const value = params.get(name); - if (value !== null && (!value.trim() || !Number.isFinite(Number(value)))) - return name; - } - } - return undefined; -} - export const Route = createFileRoute("/api/query")({ server: { handlers: { @@ -96,19 +64,6 @@ export const Route = createFileRoute("/api/query")({ ); } const resource = parsedResource.data; - const invalidFilter = invalidQueryFilter( - url.searchParams, - resource, - ); - if (invalidFilter) - return jsonResponse( - { - ok: false, - message: "Invalid query filter: " + invalidFilter, - }, - { status: 400 }, - ); - requestBackupAutoUpdate(); const baseFilters = { account: url.searchParams.get("account") ?? undefined, From 69928a5c563ecf66e57b2b59568f7cde49edd1c9 Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 8 Nov 2026 20:15:30 -0500 Subject: [PATCH 3/3] fix(timeline,profiles): preserve handle ownership before cached reconciliation and scope to CLI/sync contracts --- src/lib/live-sync-engine.ts | 13 +++---- src/lib/route-search.test.ts | 2 +- src/lib/route-search.ts | 3 +- src/lib/timeline-live.test.ts | 48 ++++++++++++++++++++++--- src/lib/x-profile.ts | 49 ++++++++++++++++--------- src/routes/blocks.test.tsx | 67 +---------------------------------- 6 files changed, 87 insertions(+), 95 deletions(-) diff --git a/src/lib/live-sync-engine.ts b/src/lib/live-sync-engine.ts index 4d608957..75696b08 100644 --- a/src/lib/live-sync-engine.ts +++ b/src/lib/live-sync-engine.ts @@ -1,5 +1,5 @@ import { Effect } from "effect"; -import { getPreferredTransport } from "./config"; +import { getPreferredTransport, isReadOnlyDeployment } from "./config"; import { findOperationAccount } from "./account-selection"; import { databaseWriteEffect } from "./database-writer"; import { toError } from "./effect-runtime"; @@ -257,11 +257,12 @@ export function runCachedLiveSyncEffect< }); const cached = cache.entry; if (!refresh && cached && cache.fresh) { - const persisted = persistCached - ? yield* databaseWriteEffect((writeDb) => - persistCached(writeDb, cached.value), - ) - : undefined; + const persisted = + persistCached && !isReadOnlyDeployment() + ? yield* databaseWriteEffect((writeDb) => + persistCached(writeDb, cached.value), + ) + : undefined; return { source: "cache", payload: cached.value, diff --git a/src/lib/route-search.test.ts b/src/lib/route-search.test.ts index 3f1422e8..475a6070 100644 --- a/src/lib/route-search.test.ts +++ b/src/lib/route-search.test.ts @@ -46,7 +46,7 @@ describe("route search schemas", () => { ); expect(validateTodaySearch({ includeDms: "1" }).includeDms).toBe(true); expect(validateBlocksSearch({ account: 3, q: "sam" })).toEqual({ - account: "", + account: "acct_primary", q: "sam", }); }); diff --git a/src/lib/route-search.ts b/src/lib/route-search.ts index 0ff1d7ff..f92c3986 100644 --- a/src/lib/route-search.ts +++ b/src/lib/route-search.ts @@ -122,8 +122,7 @@ export type BlocksRouteSearch = ReturnType; export function validateBlocksSearch(search: Record) { return { - // Leave omission unresolved until status supplies the default-first accounts. - account: stringValue(search.account), + account: stringValue(search.account, "acct_primary"), q: stringValue(search.q), }; } diff --git a/src/lib/timeline-live.test.ts b/src/lib/timeline-live.test.ts index 45a4ebc2..7bf5876f 100644 --- a/src/lib/timeline-live.test.ts +++ b/src/lib/timeline-live.test.ts @@ -46,6 +46,7 @@ function makeTempHome() { } afterEach(() => { + vi.unstubAllEnvs(); delete process.env.BIRDCLAW_PREFERRED_TRANSPORT; resetDatabaseForTests(); resetBirdclawPathsForTests(); @@ -170,15 +171,28 @@ describe("live home timeline sync", () => { created_at: "2026-04-26T13:43:34.000Z", public_metrics: { like_count: 99 }, }, + { + id: "home_cache_freshness_2", + author_id: "43", + text: "second home item", + created_at: "2026-04-26T13:44:34.000Z", + public_metrics: { like_count: 5 }, + }, ], includes: { users: [ { id: "42", - username: "sam", + username: "alice", name: "New Sam", public_metrics: { followers_count: 250 }, }, + { + id: "43", + username: "sam", + name: "Current Sam", + public_metrics: { followers_count: 500 }, + }, ], }, meta: {}, @@ -232,10 +246,36 @@ describe("live home timeline sync", () => { expect( db .prepare( - "select display_name, followers_count from profiles where id = 'profile_user_42'", + "select id, handle, display_name, followers_count from profiles where id in ('profile_user_42', 'profile_user_43') order by id", ) - .get(), - ).toEqual({ display_name: "New Sam", followers_count: 250 }); + .all(), + ).toEqual([ + { + id: "profile_user_42", + handle: "alice", + display_name: "New Sam", + followers_count: 250, + }, + { + id: "profile_user_43", + handle: "sam", + display_name: "Current Sam", + followers_count: 500, + }, + ]); + + resetDatabaseForTests(); + vi.stubEnv("BIRDCLAW_DEPLOYMENT_READ_ONLY", "1"); + const readOnlyCached = await syncHomeTimeline({ + mode: "xurl", + limit: 5, + refresh: false, + }); + expect(readOnlyCached).toMatchObject({ + ok: true, + source: "cache", + count: 1, + }); }); it("honors config preference and does not reuse another auto preference's cache", async () => { diff --git a/src/lib/x-profile.ts b/src/lib/x-profile.ts index a073353b..5800b9d4 100644 --- a/src/lib/x-profile.ts +++ b/src/lib/x-profile.ts @@ -199,12 +199,42 @@ function upsertProfileFromXUserInTransaction( } const profileId = buildExternalProfileId(externalUserId); + if (options.preserveExisting) { + const existingCanonical = db + .prepare( + ` + select id, handle, display_name, bio, followers_count, following_count, avatar_hue, avatar_url, + location, url, verified_type, entities_json, created_at + from profiles + where id = ? + limit 1 + `, + ) + .get(profileId) as Record | undefined; + if (existingCanonical) { + const existingHandle = String(existingCanonical.handle ?? ""); + const existingDisplayName = String(existingCanonical.display_name ?? ""); + if ( + !existingHandle.startsWith("birdclaw_stub_") && + !existingDisplayName.startsWith("birdclaw_stub_") + ) { + return { + profile: profileFromDbRow(existingCanonical), + externalUserId: String(user.id), + }; + } + } + } + const reconciliation = reconcileCanonicalXProfileIdentity({ db, externalUserId, canonicalProfileId: profileId, incomingHandle: username, provenLegacyProfileIds: options.provenLegacyProfileIds, + ...(options.preserveExisting + ? { canReassignHandleCollision: () => false } + : {}), }); const storedHandle = reconciliation.blockedHandleProfileIds.length > 0 @@ -213,31 +243,18 @@ function upsertProfileFromXUserInTransaction( const existingRow = db .prepare( ` - select id, handle, display_name, bio, followers_count, following_count, avatar_hue, avatar_url, - location, url, verified_type, entities_json, created_at + select id from profiles where id = ? limit 1 `, ) - .get(profileId) as Record | undefined; + .get(profileId) as { id: string } | undefined; if (existingRow) { - const existingHandle = String(existingRow.handle ?? ""); - const existingDisplayName = String(existingRow.display_name ?? ""); - if ( - options.preserveExisting && - !existingHandle.startsWith("birdclaw_stub_") && - !existingDisplayName.startsWith("birdclaw_stub_") - ) { - return { - profile: profileFromDbRow(existingRow), - externalUserId: String(user.id), - }; - } return updateExistingProfileFromUser( db, - String(existingRow.id), + existingRow.id, user, storedHandle, ); diff --git a/src/routes/blocks.test.tsx b/src/routes/blocks.test.tsx index 7274ff93..d24fb3a5 100644 --- a/src/routes/blocks.test.tsx +++ b/src/routes/blocks.test.tsx @@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { renderWithQueryClient as render } from "#/test/render"; import { BlocksRouteView as BlocksRoute } from "./blocks"; -import { validateBlocksSearch } from "#/lib/route-search"; describe("blocks route", () => { beforeEach(() => { @@ -15,68 +14,6 @@ describe("blocks route", () => { vi.unstubAllGlobals(); }); - it.each([false, true])( - "uses the stored default unless the account was explicit=%s", - async (explicit) => { - const fetchMock = vi.fn(async (input: RequestInfo | URL) => { - const url = String(input); - if (url.endsWith("/api/status")) - return new Response( - JSON.stringify({ - stats: { home: 0, mentions: 0, dms: 0, needsReply: 0, inbox: 0 }, - transport: { statusText: "local" }, - archives: [], - accounts: [ - { - id: "acct_studio", - handle: "@studio", - name: "Studio", - isDefault: 1, - }, - { - id: "acct_primary", - handle: "@primary", - name: "Primary", - isDefault: 0, - }, - ], - }), - ); - if (url.includes("/api/blocks")) - return new Response(JSON.stringify({ items: [], matches: [] })); - if (url.endsWith("/api/action")) - return new Response( - JSON.stringify({ ok: true, transport: { ok: true } }), - ); - throw new Error("Unexpected fetch " + url); - }); - vi.stubGlobal("fetch", fetchMock); - const onSearchChange = vi.fn(); - render( - , - ); - await screen.findByRole("option", { name: "@studio" }); - const expectedChanges = explicit - ? [] - : [[{ account: "acct_studio", q: "" }, { replace: true }]]; - await waitFor(() => - expect(onSearchChange.mock.calls).toEqual(expectedChanges), - ); - await waitFor(() => - expect( - fetchMock.mock.calls.some(([input]) => - String(input).includes("account=acct_primary"), - ), - ).toBe(explicit), - ); - }, - ); - it("preserves a newer draft across stale controlled navigation responses", async () => { vi.stubGlobal( "fetch", @@ -519,9 +456,7 @@ describe("blocks route", () => { JSON.stringify({ stats: { home: 3, mentions: 1, dms: 4, needsReply: 2, inbox: 3 }, transport: { statusText: "xurl available" }, - accounts: [ - { id: "acct_primary", handle: "@primary", name: "Primary" }, - ], + accounts: [], archives: [], }), );