diff --git a/docs/x-capture/capture-walk-20260914.md b/docs/x-capture/capture-walk-20260914.md index fd0ae658..8de121ed 100644 --- a/docs/x-capture/capture-walk-20260914.md +++ b/docs/x-capture/capture-walk-20260914.md @@ -58,7 +58,6 @@ the first cursor. - [ ] Open the permalink of the post with four images - [ ] Open the permalink of the video post - [ ] Open the permalink of the poll -- [ ] Open the permalink of the long-form post, if one was seeded - [ ] Open the permalink of the link-card post - [ ] Open the permalink of the retweet whose original was deleted — if it is not on the timeline at all, that is the finding, and the decoded type diff --git a/scripts/x-capture/README.md b/scripts/x-capture/README.md index fc8958d0..c453ac0f 100644 --- a/scripts/x-capture/README.md +++ b/scripts/x-capture/README.md @@ -122,15 +122,13 @@ post. `--count N` overrides how many filler posts, likes, and bookmarks to make; the default is 61 each, which clears three pages of twenty. The default follow count is 21, enough for the following list to page once. -Two steps stop and ask you to do them in the open browser window, then -continue: +One step stops and asks you to do it in the open browser window, then +continues: -- **The long-form post** needs a premium account and X's own long-form - composer, which the ordinary composer will not stand in for. - **The orphaned retweet** needs two accounts: retweet a post from the second test account, then delete it from that account. -Both are recorded as manual steps rather than as selector failures, so they do +It is recorded as a manual step rather than as a selector failure, so it does not pollute the selector evidence. ### When it stops @@ -275,9 +273,8 @@ Two shapes were deliberately **not** promoted: so there is no JSON body to promote. The status and the `x-rate-limit-*` headers are what a test needs, and they are in `GraphQLResponses.rateLimitError`. -- **The long-form post, and a rate limit disguised as a success.** Neither was - observed, so neither has a fixture. Inventing one would assert a shape this - capture cannot vouch for. +- **A rate limit disguised as a success.** Never observed, so it has no + fixture. Inventing one would assert a shape this capture cannot vouch for. `src/renderer/src/view_models/XViewModel/test_fixtures.test.ts` asserts what each fixture shows, so the findings do not drift away from the files. diff --git a/scripts/x-capture/lib/seed_plan.test.ts b/scripts/x-capture/lib/seed_plan.test.ts index 68500756..1e4cc0c3 100644 --- a/scripts/x-capture/lib/seed_plan.test.ts +++ b/scripts/x-capture/lib/seed_plan.test.ts @@ -104,7 +104,6 @@ describe("kinds", () => { }); test("names the kinds a person has to do", () => { - expect(isManualKind("longform")).toBe(true); expect(isManualKind("retweet-to-orphan")).toBe(true); expect(isManualKind("post")).toBe(false); }); @@ -115,7 +114,6 @@ describe("buildSeedPlan", () => { const counts = summarizePlan(buildSeedPlan(options())); expect(counts.thread).toBe(1); expect(counts.poll).toBe(1); - expect(counts.longform).toBe(1); expect(counts.link).toBe(1); expect(counts.quote).toBe(1); expect(counts.retweet).toBe(1); diff --git a/scripts/x-capture/lib/seed_plan.ts b/scripts/x-capture/lib/seed_plan.ts index 9d1f4407..7b95282a 100644 --- a/scripts/x-capture/lib/seed_plan.ts +++ b/scripts/x-capture/lib/seed_plan.ts @@ -14,7 +14,6 @@ export type SeedActionKind = | "thread" | "poll" | "media" - | "longform" | "link" | "quote" | "retweet" @@ -32,10 +31,10 @@ export const BULK_KINDS: SeedActionKind[] = [ ]; /** - * Kinds no script can do on its own: the long-form composer needs premium, and - * an orphaned retweet needs a second account to delete the original from. + * Kinds no script can do on its own: an orphaned retweet needs a second + * account to delete the original from. */ -export const MANUAL_KINDS: SeedActionKind[] = ["longform", "retweet-to-orphan"]; +export const MANUAL_KINDS: SeedActionKind[] = ["retweet-to-orphan"]; export function isBulkKind(kind: SeedActionKind): boolean { return BULK_KINDS.includes(kind); @@ -167,23 +166,6 @@ function awkwardShapes(options: SeedPlanOptions): SeedAction[] { note: "Post with a link card", text: `Cyd seed link card ${dateStamp}: https://cyd.social/`, }, - { - id: "longform-001", - kind: "longform", - note: "Long-form post. Posted by hand: X's long-form composer needs premium, and the ordinary composer will not take it", - text: [ - `Cyd seed long-form post ${dateStamp}.`, - "", - "This post exists to exercise the long-form note shape, where the body is", - "carried outside the ordinary post text field and the timeline entry is", - "truncated. It has to be long enough that X treats it as long-form rather", - "than an ordinary post, so it runs past the usual character limit and keeps", - "going for several paragraphs.", - "", - "Everything here is seeded test content on a test account and is safe to", - "delete at any point during the capture walk.", - ].join("\n"), - }, ]; targetUrls.slice(0, 2).forEach((targetUrl, index) => { @@ -305,7 +287,6 @@ export const SHAPE_MARKERS: { label: string; pattern: RegExp }[] = [ { label: "Poll", pattern: /Cyd seed poll/ }, { label: "Link card", pattern: /Cyd seed link card/ }, { label: "Quote post", pattern: /Cyd seed quote post/ }, - { label: "Long-form", pattern: /Cyd seed long-form/ }, ]; /** The shape a timeline entry is, or null if it is not a seeded shape. */ diff --git a/scripts/x-capture/lib/walk_plan.test.ts b/scripts/x-capture/lib/walk_plan.test.ts index 07948114..33c152c8 100644 --- a/scripts/x-capture/lib/walk_plan.test.ts +++ b/scripts/x-capture/lib/walk_plan.test.ts @@ -28,7 +28,7 @@ describe("parsePermalinks", () => { test("skips shapes that were never found", () => { const markdown = [ "- [ ] Poll: https://x.com/someone/status/1", - "- [ ] Long-form: **not found on the timeline**", + "- [ ] Link card: **not found on the timeline**", ].join("\n"); expect(parsePermalinks(markdown)).toHaveLength(1); }); diff --git a/scripts/x-capture/lib/x_page.ts b/scripts/x-capture/lib/x_page.ts index 9c5be45f..cc486aef 100644 --- a/scripts/x-capture/lib/x_page.ts +++ b/scripts/x-capture/lib/x_page.ts @@ -13,6 +13,12 @@ import type { Page } from "playwright-core"; export const SELECTORS = { // Composing composerTextarea: '[data-testid="tweetTextarea_0"]', + // X opens /compose/post as a modal over the home timeline, whose own inline + // composer carries the same test identifier. Waiting on the unscoped + // selector re-resolves to that inline composer the moment the modal closes, + // so it never reports detached and every successful post looks like a + // failure. Waiting for the modal's own field is what says the post landed. + composerDialogTextarea: '[role="dialog"] [data-testid="tweetTextarea_0"]', composerTextareaNth: (index: number) => `[data-testid="tweetTextarea_${index}"]`, composerFileInput: 'input[data-testid="fileInput"]', @@ -215,7 +221,7 @@ async function submitComposer(page: Page) { } const composerClosed = page - .locator(SELECTORS.composerTextarea) + .locator(SELECTORS.composerDialogTextarea) .first() .waitFor({ state: "detached", timeout: 20000 }) .then(() => "closed" as const) @@ -348,31 +354,49 @@ async function clickNthAfterScrolling( await assertNotBlocked(page); const buttons = page.locator(selector); - for (let attempt = 0; attempt < 8; attempt++) { + // Every fifteen actions the seeder reloads the feed, which puts it back at + // the top — above everything it has already acted on. Finding the next post + // to act on then means scrolling past all of them, so how far this has to + // reach grows with the count. An image-heavy feed makes that worse: a single + // photo post runs to most of a screen, so forty already-liked posts can sit + // tens of thousands of pixels down. Reaching short of them looks exactly + // like a selector X has changed. + for (let attempt = 0; attempt < 40; attempt++) { if ((await buttons.count()) > index) { await buttons.nth(index).scrollIntoViewIfNeeded(); await buttons.nth(index).click(); return; } - await page.mouse.wheel(0, 2000); + await page.mouse.wheel(0, 4000); await page.waitForTimeout(1500); } throw new SelectorMissingError(selector); } -export async function actOnNextPost( - page: Page, - action: "like" | "bookmark", - alreadyDone: number, -) { +/** + * Acts on the first post still offering the action, rather than counting how + * many have been done and reaching for that index. + * + * X virtualizes the timeline, dropping posts out of the DOM once they are + * scrolled well past, so the number rendered stays roughly flat however far + * down the feed you are. A liked post also leaves the `like` selector + * entirely, since its test identifier flips to `unlike`. Counting upwards + * against that meant the index climbed while the count did not, and past + * eight or so actions it could never be reached. + * + * The first match is always the next one to act on, for the same reason: what + * has been done is no longer in the set. + */ +export async function actOnNextPost(page: Page, action: "like" | "bookmark") { await clickNthAfterScrolling( page, action === "like" ? SELECTORS.like : SELECTORS.bookmark, - alreadyDone, + 0, ); } -export async function followNextAccount(page: Page, alreadyDone: number) { - await clickNthAfterScrolling(page, SELECTORS.follow, alreadyDone); +/** The first account still offering Follow, for the reason above. */ +export async function followNextAccount(page: Page) { + await clickNthAfterScrolling(page, SELECTORS.follow, 0); } diff --git a/scripts/x-capture/seed.ts b/scripts/x-capture/seed.ts index 5a9b7559..d4d5c53c 100644 --- a/scripts/x-capture/seed.ts +++ b/scripts/x-capture/seed.ts @@ -211,9 +211,6 @@ function requireTarget(action: SeedAction): string { } interface FeedState { - liked: number; - bookmarked: number; - followed: number; actionsSinceReload: number; } @@ -247,35 +244,28 @@ async function runAction( case "retweet": await retweetPost(page, requireTarget(action)); break; - case "longform": case "retweet-to-orphan": // Handled above, before the switch. break; case "like": if (feed.actionsSinceReload === 0) { await page.goto(feedUrl, { waitUntil: "domcontentloaded" }); - feed.liked = 0; } - await actOnNextPost(page, "like", feed.liked); - feed.liked += 1; + await actOnNextPost(page, "like"); break; case "bookmark": if (feed.actionsSinceReload === 0) { await page.goto(feedUrl, { waitUntil: "domcontentloaded" }); - feed.bookmarked = 0; } - await actOnNextPost(page, "bookmark", feed.bookmarked); - feed.bookmarked += 1; + await actOnNextPost(page, "bookmark"); break; case "follow": if (feed.actionsSinceReload === 0) { await page.goto("https://x.com/i/connect_people", { waitUntil: "domcontentloaded", }); - feed.followed = 0; } - await followNextAccount(page, feed.followed); - feed.followed += 1; + await followNextAccount(page); break; } } @@ -350,12 +340,7 @@ async function main() { return; } - const feed: FeedState = { - liked: 0, - bookmarked: 0, - followed: 0, - actionsSinceReload: 0, - }; + const feed: FeedState = { actionsSinceReload: 0 }; for (const action of plan) { if (progress.isDone(action.id)) { diff --git a/src/account_x/__tests__/integration/controller.indexing.integration.test.ts b/src/account_x/__tests__/integration/controller.indexing.integration.test.ts index 147b23ac..cf627ef7 100644 --- a/src/account_x/__tests__/integration/controller.indexing.integration.test.ts +++ b/src/account_x/__tests__/integration/controller.indexing.integration.test.ts @@ -493,9 +493,8 @@ test("indexParseTweets() reads the rate limit reset from the response headers", test("indexParseTweets() saves the rest when one entry cannot be read", async () => { // No fixture can show a retweet whose original was deleted — the entry is - // simply gone from the timeline (findings 5) — and a long-form post was - // never observed either. What both would cost, if X ever returns one Cyd - // cannot read, is the rest of the archive. They do not. + // simply gone from the timeline (findings 5). What that would cost, if X + // ever returns one Cyd cannot read, is the rest of the archive. It does not. const body = JSON.parse( fs.readFileSync( path.join( diff --git a/src/account_x/x_account_controller.ts b/src/account_x/x_account_controller.ts index 0aba486f..eba56b9c 100644 --- a/src/account_x/x_account_controller.ts +++ b/src/account_x/x_account_controller.ts @@ -9,6 +9,7 @@ import { Agent } from "@atproto/api"; import { Record as BskyPostRecord } from "@atproto/api/dist/client/types/app/bsky/feed/post"; import { getAccountDataPath } from "../util"; +import { RequestLog } from "../request_log"; import { XAccount, XJob, @@ -82,6 +83,8 @@ export class XAccountController extends BaseAccountController { private blueskyService: BlueskyService | null = null; + private requestLog: RequestLog; + constructor(accountID: number, mitmController: IMITMController) { super(accountID, mitmController); // Initialize progress with X-specific type @@ -89,7 +92,23 @@ export class XAccountController extends BaseAccountController { // Monitor web request metadata for X-specific functionality const ses = session.fromPartition(`persist:account-${this.accountID}`); + + // Off unless CYD_REQUEST_LOG says otherwise. See src/request_log.ts. + this.requestLog = new RequestLog(this.accountID); + if (this.requestLog.enabled) { + log.info( + `XAccountController: recording requests for account ${this.accountID} to ${process.env.CYD_REQUEST_LOG}`, + ); + } + ses.webRequest.onCompleted((details) => { + this.requestLog.record({ + method: details.method, + url: details.url, + statusCode: details.statusCode, + fromCache: details.fromCache, + }); + // Learn the operation identifiers X is using right now this.observeGraphqlOperation(details.url); diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 2a427f53..27caa520 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -372,6 +372,7 @@ "youJustSaved": "You just saved:", "youJustArchived": "You just archived:", "youJustDeleted": "You just deleted:", + "youJustTombstoned": "You just tombstoned your account:", "youJustMigrated": "You just migrated:" }, "premium": { diff --git a/src/renderer/src/view_models/XViewModel/jobs_tombstone.test.ts b/src/renderer/src/view_models/XViewModel/jobs_tombstone.test.ts index a0bf11c9..0c259ae4 100644 --- a/src/renderer/src/view_models/XViewModel/jobs_tombstone.test.ts +++ b/src/renderer/src/view_models/XViewModel/jobs_tombstone.test.ts @@ -89,6 +89,7 @@ describe("jobs_tombstone.ts", () => { expect(vm.waitForSelector).toHaveBeenCalledWith( '[data-testid="applyButton"]', "https://x.com/settings/profile", + 8000, ); expect(vm.scriptClickElement).toHaveBeenCalledWith( '[data-testid="applyButton"]', @@ -163,6 +164,127 @@ describe("jobs_tombstone.ts", () => { expect(events[0].type).toBe("change"); }); + it("should wait for the profile to render its banner before reading it", async () => { + // X renders the header photo after the load finishes. Reading straight + // away got "" from both the before and the after read, which match, so a + // banner that had been saved was reported as one that never changed. + answerWith( + ["https://pbs.twimg.com/old", "https://pbs.twimg.com/new"], + [], + ); + + await TombstoneJobs.runJobTombstoneUpdateBanner(vm, 0); + + expect(vm.waitForSelector).toHaveBeenCalledWith( + 'a[href$="/header_photo"] img', + "https://x.com/testuser", + 10000, + ); + }); + + it("should read a profile that renders no banner as having none", async () => { + // An account with no banner never grows that element, so the wait + // running out is an answer rather than something to throw over. + const { TimeoutError } = await import("../automation_failures"); + vi.spyOn(vm, "waitForSelector").mockImplementation( + async (selector: string) => { + if (selector === 'a[href$="/header_photo"] img') { + throw new TimeoutError(selector); + } + }, + ); + + const result = await TombstoneJobs.runJobTombstoneUpdateBanner(vm, 0); + + // Nothing was there before and nothing after, which is a real failure — + // but reported as one, rather than thrown out of the job. + expect(result).toBe(false); + expect(vm.error).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ reason: "the banner did not change" }), + ); + }); + + it("should wait out the old banner the profile shows before the new one", async () => { + // Recorded on a real run: the save returns 200, then the profile page + // fetches the banner it already had and replaces it 200ms later. Reading + // once catches the old URL and calls a save that worked unchanged, which + // is why this failed four times and then passed with nothing altered. + answerWith( + [ + "https://pbs.twimg.com/profile_banners/1/1789501624/1080x360", + "https://pbs.twimg.com/profile_banners/1/1789501624/1080x360", + "https://pbs.twimg.com/profile_banners/1/1789502153/1080x360", + ], + [], + ); + + const result = await TombstoneJobs.runJobTombstoneUpdateBanner(vm, 0); + + expect(result).toBe(true); + expect(vm.finishJob).toHaveBeenCalledWith(0); + expect(vm.error).not.toHaveBeenCalled(); + }); + + it("should put the banner on again when X offers no crop step", async () => { + // Recorded from Cyd's own session: with no crop step the image still + // uploads, INIT through FINALIZE, and update_profile_banner.json is + // never called at all. Apply is what stages the upload as the banner, + // so a run that never sees one saves nothing. + const { TimeoutError } = await import("../automation_failures"); + let cropWaits = 0; + vi.spyOn(vm, "waitForSelector").mockImplementation( + async (selector: string) => { + if (selector === '[data-testid="applyButton"]') { + cropWaits += 1; + if (cropWaits === 1) { + throw new TimeoutError(selector); + } + } + }, + ); + answerWith( + ["https://pbs.twimg.com/old", "https://pbs.twimg.com/new"], + [], + ); + + const result = await TombstoneJobs.runJobTombstoneUpdateBanner(vm, 0); + + expect(cropWaits).toBeGreaterThan(1); + expect(vm.scriptClickElement).toHaveBeenCalledWith( + '[data-testid="applyButton"]', + ); + expect(result).toBe(true); + expect(vm.error).not.toHaveBeenCalled(); + }); + + it("should say the banner was never staged rather than save without it", async () => { + const { TimeoutError } = await import("../automation_failures"); + vi.spyOn(vm, "waitForSelector").mockImplementation( + async (selector: string) => { + if (selector === '[data-testid="applyButton"]') { + throw new TimeoutError(selector); + } + }, + ); + answerWith(["https://pbs.twimg.com/old"], []); + + const result = await TombstoneJobs.runJobTombstoneUpdateBanner(vm, 0); + + expect(result).toBe(false); + // Clicking Save without the crop uploads the image and attaches nothing, + // then reports a banner that did not change, which explains none of it. + expect(vm.scriptClickElement).not.toHaveBeenCalledWith( + 'button[data-testid="Profile_Save_Button"]', + ); + expect(vm.error).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + reason: "X never offered its crop step, so the banner was not staged", + }), + ); + }); + it("should report a banner it could not set rather than claiming success", async () => { vi.spyOn(vm.getWebview()!, "executeJavaScript").mockResolvedValue(false); @@ -237,6 +359,30 @@ describe("jobs_tombstone.ts", () => { expect(vm.error).not.toHaveBeenCalled(); }); + it("should save the new bio, so the wizard stops offering the old one", async () => { + // The tombstone page pre-fills from the bio Cyd has saved, which is + // written at login and nowhere else. Leaving it stale meant coming back + // to the page and being offered the bio the tombstone had replaced. + vm.account.xAccount!.bio = "Seeded test account."; + answerWith([], ["Gone to Bluesky"]); + + const result = await TombstoneJobs.runJobTombstoneUpdateBio(vm, 0); + + expect(result).toBe(true); + expect(vm.account.xAccount!.bio).toBe("Gone to Bluesky"); + expect(window.electron.database.saveAccount).toHaveBeenCalled(); + }); + + it("should leave the saved bio alone when the change did not land", async () => { + vm.account.xAccount!.bio = "Seeded test account."; + answerWith([], ["Seeded test account."]); + + const result = await TombstoneJobs.runJobTombstoneUpdateBio(vm, 0); + + expect(result).toBe(false); + expect(vm.account.xAccount!.bio).toBe("Seeded test account."); + }); + it("should report a bio that did not change rather than finishing", async () => { answerWith([], ["Seeded test account."]); diff --git a/src/renderer/src/view_models/XViewModel/jobs_tombstone.ts b/src/renderer/src/view_models/XViewModel/jobs_tombstone.ts index ce999bcf..a01c8600 100644 --- a/src/renderer/src/view_models/XViewModel/jobs_tombstone.ts +++ b/src/renderer/src/view_models/XViewModel/jobs_tombstone.ts @@ -2,6 +2,7 @@ import type { XViewModel } from "./view_model"; import { PlausibleEvents } from "../../types"; import { AutomationErrorType } from "../../automation_errors"; import { tombstoneUpdateBioCreditCydText } from "./types"; +import { TimeoutError } from "../automation_failures"; const PROFILE_SETTINGS_URL = "https://x.com/settings/profile"; @@ -10,11 +11,33 @@ const PROFILE_SETTINGS_URL = "https://x.com/settings/profile"; // so it is reached by position among the matches rather than by the selector. const FILE_INPUT_SELECTOR = 'input[data-testid="fileInput"]'; -// The crop step X shows after a file is chosen +// The crop step X sometimes shows after a file is chosen const APPLY_BUTTON_SELECTOR = '[data-testid="applyButton"]'; +// Long enough for X to open its crop step, short enough that a delivery which +// did not produce one can be made again without a long wait first. +const CROP_STEP_TIMEOUT = 8000; + +// How many times to put the banner on the file input before giving up on X +// offering a crop for it. +const BANNER_DELIVERY_TRIES = 3; + const SAVE_BUTTON_SELECTOR = 'button[data-testid="Profile_Save_Button"]'; +// The banner on the profile page, which is what says whether a save landed. +const BANNER_IMAGE_SELECTOR = 'a[href$="/header_photo"] img'; + +// How long to give the profile page to render its banner. An account with no +// banner never renders one, so running this out is an answer rather than a +// failure. +const BANNER_RENDER_TIMEOUT = 10000; + +// The page draws the banner it already had and swaps the new one in a moment +// later, so the banner is read until it turns over rather than sampled once. +// Recorded on a real run, the swap landed 200ms after the first paint. +const BANNER_CHANGE_TRIES = 30; +const BANNER_POLL_INTERVAL = 500; + const AUDIENCE_SETTINGS_URL = "https://x.com/settings/audience_and_tagging"; // The "Protect your posts" box is the first checkbox on the audience settings @@ -48,20 +71,86 @@ async function clickSaveProfile( } /** The banner X serves on the profile, which is the only answer that counts. */ -async function readBannerURL(vm: XViewModel): Promise { - await vm.loadURLWithRateLimit( - `https://x.com/${vm.account.xAccount?.username ?? ""}`, - ); +/** The banner the page is showing at this instant. */ +async function readBannerSrc(vm: XViewModel): Promise { return ( (await vm.getWebview()?.executeJavaScript(` (() => { - const image = document.querySelector('a[href$="/header_photo"] img'); + const image = document.querySelector('${BANNER_IMAGE_SELECTOR}'); return image ? image.src : ""; })(); `)) ?? "" ); } +/** + * Opens the profile and waits for it to draw a banner at all. + * + * Returns false when it never draws one, which is what an account with no + * banner looks like and is an answer rather than a failure. + */ +async function openProfileWithBanner(vm: XViewModel): Promise { + const profileURL = `https://x.com/${vm.account.xAccount?.username ?? ""}`; + await vm.loadURLWithRateLimit(profileURL); + + // X renders the header photo after the page load finishes, so asking + // straight away gets nothing back and reads as "no banner". When both the + // before and the after read that way they match, and a banner that was in + // fact saved gets reported as one that never changed. + // + // A profile with no banner never grows this element, so running the timeout + // out is an answer, not a failure. + try { + await vm.waitForSelector( + BANNER_IMAGE_SELECTOR, + profileURL, + BANNER_RENDER_TIMEOUT, + ); + } catch (error) { + if (!(error instanceof TimeoutError)) { + throw error; + } + vm.log("openProfileWithBanner", "the profile rendered no banner"); + return false; + } + return true; +} + +async function readBannerURL(vm: XViewModel): Promise { + if (!(await openProfileWithBanner(vm))) { + return ""; + } + return await readBannerSrc(vm); +} + +/** + * Reads the banner back after a save, giving the page time to turn it over. + * + * The profile draws the banner it already had and replaces it a moment later, + * so asking once catches the old URL and reports a save that worked as one + * that changed nothing. Watching until it differs makes the answer the page + * settles on the one that counts, rather than whichever it happened to be + * showing when asked. + */ +async function readBannerURLAfterSave( + vm: XViewModel, + bannerBefore: string, +): Promise { + if (!(await openProfileWithBanner(vm))) { + return ""; + } + + let latest = ""; + for (let attempt = 0; attempt < BANNER_CHANGE_TRIES; attempt++) { + latest = await readBannerSrc(vm); + if (latest !== bannerBefore) { + return latest; + } + await vm.sleep(BANNER_POLL_INTERVAL); + } + return latest; +} + /** The bio X serves back into the profile dialog. */ async function readBioText(vm: XViewModel): Promise { await vm.loadURLWithRateLimit(PROFILE_SETTINGS_URL); @@ -157,22 +246,65 @@ export async function runJobTombstoneUpdateBanner( // Load the profile page await vm.loadURLWithRateLimit(PROFILE_SETTINGS_URL); - // Wait for the file input, and set the banner on it + // Put the banner on the file input, and wait for X to offer its crop. + // + // The crop is not decoration that X sometimes shows: Apply is what stages + // the uploaded image as the banner. Recorded from Cyd's own session, a + // delivery that draws no crop still uploads the file — INIT, APPEND and + // FINALIZE all succeed — and then update_profile_banner.json is never called + // at all, so Save writes the name and bio and leaves the banner alone. + // + // A delivery that draws no crop has therefore staged nothing, and is worth + // making again rather than carrying on from. await vm.waitForSelector(FILE_INPUT_SELECTOR, PROFILE_SETTINGS_URL); - const wasSet = await vm - .getWebview() - ?.executeJavaScript(setBannerScript(bannerDataURL)); - if (!wasSet) { + + let cropOffered = false; + for ( + let attempt = 0; + attempt < BANNER_DELIVERY_TRIES && !cropOffered; + attempt++ + ) { + const wasSet = await vm + .getWebview() + ?.executeJavaScript(setBannerScript(bannerDataURL)); + if (!wasSet) { + await vm.error( + AutomationErrorType.x_runJob_tombstoneUpdateBanner_FailedToSetBanner, + {}, + ); + return false; + } + + try { + await vm.waitForSelector( + APPLY_BUTTON_SELECTOR, + PROFILE_SETTINGS_URL, + CROP_STEP_TIMEOUT, + ); + cropOffered = true; + } catch (error) { + if (!(error instanceof TimeoutError)) { + throw error; + } + vm.log("runJobTombstoneUpdateBanner", [ + "X offered no crop step, putting the banner on again", + attempt + 1, + ]); + } + } + + if (!cropOffered) { + // Saving from here uploads the image, attaches nothing, and comes back + // reporting a banner that did not change, which explains none of it. await vm.error( - AutomationErrorType.x_runJob_tombstoneUpdateBanner_FailedToSetBanner, - {}, + AutomationErrorType.x_runJob_tombstoneUpdateBanner_FailedToSave, + { reason: "X never offered its crop step, so the banner was not staged" }, ); return false; } - // Confirm the crop X offers, then save. Both clicks go through the element's - // own click(), because the dialog keeps a mask that swallows pointer events. - await vm.waitForSelector(APPLY_BUTTON_SELECTOR, PROFILE_SETTINGS_URL); + // The click goes through the element's own click(), because the dialog keeps + // a mask that swallows pointer events. if (!(await vm.scriptClickElement(APPLY_BUTTON_SELECTOR))) { await vm.error( AutomationErrorType.x_runJob_tombstoneUpdateBanner_FailedToSave, @@ -192,7 +324,7 @@ export async function runJobTombstoneUpdateBanner( // Read the banner back. A save that clicked cleanly and changed nothing is // exactly the failure this job kept reporting as success. - const bannerAfter = await readBannerURL(vm); + const bannerAfter = await readBannerURLAfterSave(vm, bannerBefore); if (bannerAfter === bannerBefore) { vm.log("runJobTombstoneUpdateBanner", ["banner unchanged", bannerBefore]); await vm.error( @@ -269,6 +401,15 @@ export async function runJobTombstoneUpdateBio( return false; } + // Cyd's saved copy of the bio is written at login and nowhere else, and the + // tombstone page pre-fills from it. Left stale, that page comes back + // offering the bio this job just replaced. The value read back off X is the + // one worth keeping, since it is what X actually holds. + if (vm.account.xAccount) { + vm.account.xAccount.bio = savedBio; + await window.electron.database.saveAccount(JSON.stringify(vm.account)); + } + await vm.finishJob(jobIndex); return true; } diff --git a/src/renderer/src/views/x/wizard/XWizardFinished.test.ts b/src/renderer/src/views/x/wizard/XWizardFinished.test.ts index 95ec7c89..427a3415 100644 --- a/src/renderer/src/views/x/wizard/XWizardFinished.test.ts +++ b/src/renderer/src/views/x/wizard/XWizardFinished.test.ts @@ -236,6 +236,85 @@ describe("XWizardFinished", () => { }); }); + describe("basic rendering - tombstone mode", () => { + it("should render finished page for tombstone mode", async () => { + const { getJobsType } = await import("../../../util"); + (getJobsType as ReturnType).mockReturnValue("tombstone"); + + const mockModel = createMockModel( + { + xAccount: { + tombstoneUpdateBanner: true, + tombstoneUpdateBio: true, + tombstoneLockAccount: true, + }, + }, + {}, + ); + + wrapper = mount(XWizardFinished, { + props: { + model: mockModel as XViewModel, + failureStateIndexTweets_FailedToRetryAfterRateLimit: false, + failureStateIndexLikes_FailedToRetryAfterRateLimit: false, + }, + global: { + plugins: [i18n], + config: { + globalProperties: { + emitter: mockEmitter, + } as Record, + }, + }, + }); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(wrapper.text()).toContain("You just tombstoned your account:"); + expect(wrapper.text()).toContain("Updated your banner"); + expect(wrapper.text()).toContain("Updated your bio"); + expect(wrapper.text()).toContain("Locked your account"); + }); + + it("should list only the tombstone actions that were turned on", async () => { + const { getJobsType } = await import("../../../util"); + (getJobsType as ReturnType).mockReturnValue("tombstone"); + + const mockModel = createMockModel( + { + xAccount: { + tombstoneUpdateBanner: false, + tombstoneUpdateBio: true, + tombstoneLockAccount: false, + }, + }, + {}, + ); + + wrapper = mount(XWizardFinished, { + props: { + model: mockModel as XViewModel, + failureStateIndexTweets_FailedToRetryAfterRateLimit: false, + failureStateIndexLikes_FailedToRetryAfterRateLimit: false, + }, + global: { + plugins: [i18n], + config: { + globalProperties: { + emitter: mockEmitter, + } as Record, + }, + }, + }); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + expect(wrapper.text()).toContain("Updated your bio"); + expect(wrapper.text()).not.toContain("Updated your banner"); + expect(wrapper.text()).not.toContain("Locked your account"); + }); + }); + describe("basic rendering - archive mode", () => { it("should render finished page for archive mode", async () => { const { getJobsType } = await import("../../../util"); diff --git a/src/renderer/src/views/x/wizard/XWizardFinished.vue b/src/renderer/src/views/x/wizard/XWizardFinished.vue index 187970c3..6513f5f9 100644 --- a/src/renderer/src/views/x/wizard/XWizardFinished.vue +++ b/src/renderer/src/views/x/wizard/XWizardFinished.vue @@ -301,6 +301,26 @@ onMounted(async () => { +
+
+

{{ t("finished.youJustTombstoned") }}

+
    +
  • + + Updated your banner +
  • +
  • + + Updated your bio +
  • +
  • + + Locked your account +
  • +
+
+
+

{{ t("finished.youJustMigrated") }}

diff --git a/src/request_log.test.ts b/src/request_log.test.ts new file mode 100644 index 00000000..c96832fe --- /dev/null +++ b/src/request_log.test.ts @@ -0,0 +1,111 @@ +import fs from "fs"; +import os from "os"; +import path from "path"; + +import { describe, test, expect, beforeEach, afterEach } from "vitest"; + +import { RequestLog } from "./request_log"; + +describe("RequestLog", () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-request-log-")); + }); + + afterEach(() => { + delete process.env.CYD_REQUEST_LOG; + fs.rmSync(dir, { recursive: true, force: true }); + }); + + test("records nothing unless the environment asks for it", () => { + const requestLog = new RequestLog(1); + + expect(requestLog.enabled).toBe(false); + + requestLog.record({ + method: "POST", + url: "https://upload.x.com/i/media/upload.json", + statusCode: 201, + fromCache: false, + }); + + expect(fs.readdirSync(dir)).toEqual([]); + }); + + test("appends one line per request, so a crash keeps what came before", () => { + process.env.CYD_REQUEST_LOG = dir; + const requestLog = new RequestLog(7); + + expect(requestLog.enabled).toBe(true); + + requestLog.record({ + method: "POST", + url: "https://upload.x.com/i/media/upload.json", + statusCode: 201, + fromCache: false, + }); + requestLog.record({ + method: "POST", + url: "https://api.x.com/1.1/account/update_profile_banner.json", + statusCode: 200, + fromCache: false, + }); + + const lines = fs + .readFileSync(path.join(dir, "account-7.jsonl"), "utf8") + .trim() + .split("\n"); + + expect(lines).toHaveLength(2); + expect(JSON.parse(lines[0])).toMatchObject({ + method: "POST", + url: "https://upload.x.com/i/media/upload.json", + statusCode: 201, + }); + expect(JSON.parse(lines[1])).toMatchObject({ + url: "https://api.x.com/1.1/account/update_profile_banner.json", + statusCode: 200, + }); + expect(JSON.parse(lines[0]).at).toEqual(expect.any(String)); + }); + + test("keeps one account's traffic out of another's", () => { + process.env.CYD_REQUEST_LOG = dir; + + new RequestLog(1).record({ + method: "GET", + url: "https://x.com/one", + statusCode: 200, + fromCache: false, + }); + new RequestLog(2).record({ + method: "GET", + url: "https://x.com/two", + statusCode: 200, + fromCache: false, + }); + + expect(fs.readdirSync(dir).sort()).toEqual([ + "account-1.jsonl", + "account-2.jsonl", + ]); + }); + + test("a directory it cannot write to stops the log, not the run", () => { + process.env.CYD_REQUEST_LOG = path.join(dir, "file-in-the-way"); + fs.writeFileSync(path.join(dir, "file-in-the-way"), ""); + + const requestLog = new RequestLog(1); + + expect(requestLog.enabled).toBe(false); + expect(() => + requestLog.record({ + method: "GET", + url: "https://x.com/", + statusCode: 200, + fromCache: false, + }), + ).not.toThrow(); + }); +}); diff --git a/src/request_log.ts b/src/request_log.ts new file mode 100644 index 00000000..6b22760d --- /dev/null +++ b/src/request_log.ts @@ -0,0 +1,76 @@ +/** + * Records the requests a platform's session makes, so a run that has already + * failed can still be worked out afterwards. + * + * The capture tooling in `scripts/x-capture/` answers questions by driving a + * separate Chromium, which means its findings are about Chromium. When the app + * behaves differently from the probe — a banner that uploads under Playwright + * and does not under Electron — there is nothing to compare, because only one + * of the two is being watched. This watches the other one. + * + * Off unless `CYD_REQUEST_LOG` names a directory to write to: + * + * CYD_REQUEST_LOG=/tmp/cyd-requests npm start + * + * What it records is the traffic of a signed-in session, so it stays where + * whoever is debugging put it. It is never attached to an error report and + * never leaves the machine. To keep it that way it holds no bodies, no + * headers, and no cookies — a method, a URL, and a status say whether a call + * was made and what came back, which is the question worth asking, and none of + * them carry the session. + */ + +import fs from "fs"; +import path from "path"; + +import log from "electron-log/main"; + +export interface RequestLogEntry { + method: string; + url: string; + statusCode: number; + fromCache: boolean; +} + +export class RequestLog { + private logPath: string | null = null; + + constructor(accountID: number) { + const dir = process.env.CYD_REQUEST_LOG; + if (dir === undefined || dir.trim() === "") { + return; + } + + try { + fs.mkdirSync(dir, { recursive: true }); + this.logPath = path.join(dir, `account-${accountID}.jsonl`); + } catch (error) { + // A debugging aid that cannot write is worth a line in the log and + // nothing more. It must not take the run down with it. + log.error("RequestLog: could not open the request log:", error); + } + } + + get enabled(): boolean { + return this.logPath !== null; + } + + /** + * Appended a line at a time, because the runs worth reading this back for + * are the ones that did not reach the end. + */ + record(entry: RequestLogEntry): void { + if (this.logPath === null) { + return; + } + + try { + fs.appendFileSync( + this.logPath, + `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`, + ); + } catch (error) { + log.error("RequestLog: could not record a request:", error); + } + } +}