Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 38x 38x 38x 1x 31x 31x 31x 31x 31x 1x 4x 4x 4x 4x 4x 4x 4x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 8x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 1x 9x 9x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 8x 8x 10x 6x 6x 6x 6x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 1x 1x 7x 7x 7x 6x 5x 7x 5x 5x 5x 5x 7x 6x 6x 7x 4x 7x 1x 1x 7x 1x 1x 7x 7x 1x 1x 28x 28x 28x 28x 19x 17x 19x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 7x 7x 8x 8x 3x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 36x 36x 36x 36x 36x 36x 36x 36x 36x 34x 34x 34x 34x 34x 34x 34x 34x 34x 33x 7x 7x 7x 34x 27x 27x 34x 34x 34x 34x 34x 34x 34x 32x 34x 2x 2x 34x 36x 36x 36x 35x 36x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 36x 2x 36x 1x 1x 36x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 36x 4x 4x 4x 4x 4x 4x 2x 2x 4x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 27x 27x 36x 25x 25x 17x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 25x 8x 8x 25x 22x 22x 22x 22x 22x 22x 22x 22x 22x 36x 9x 9x 22x 22x 22x 22x 22x 22x 36x 36x 36x 19x 13x 13x 13x 13x 13x 13x 13x 36x 2x 2x 2x 36x 2x 2x 13x 13x 13x 13x 13x 13x 13x 13x 13x 26x 36x 36x 9x 9x 9x 9x 9x 9x 9x 9x 9x 36x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 2x 2x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 7x 7x 7x | import { canonicalize } from "../lib/canonicalUrl";
import {
extractPage,
deriveJsonLdFields,
MAIN_TEXT_CAP,
MIN_TEXT_CHARS,
} from "../lib/pageExtractor";
import type { RawPageExtract } from "../lib/pageExtractor";
import { pasteIdentity } from "../lib/pasteIdentity";
import { boundViolation } from "../lib/textBounds";
import { postJobAnalysis } from "./jobAnalysisClient";
import { jobStorage } from "./jobStorage";
import { learnedSelectors } from "./learnedSelectors";
import { getCached, setCached } from "./jobAnalysisCache";
import { getProfile, profileToPromptText } from "./profileStorage";
import { MessageType } from "../types/messages";
import type {
AnalyzeJobPageMessage,
AnalyzePastedTextMessage,
AnalyzeScopedRegionMessage,
CancelAnalysisMessage,
ExtensionMessage,
} from "../types/messages";
import type {
CandidateProfile,
JobAnalysis,
JobErrorCode,
JobPanelError,
PageExtract,
SavedJob,
} from "../types/job";
/**
* Most-recently-active candidate content tabs, newest first. Only ids are
* kept: URLs observed at track time go stale (and a brand-new tab is briefly
* an unreadable about:blank), so candidates are re-validated with a fresh
* lookup at resolve time instead.
*/
const MAX_TRACKED_TABS = 5;
let recentContentTabs: number[] = [];
/**
* Last successfully extracted URL per tab, kept in session storage so it
* survives service-worker restarts. The activeTab grant dies on every tab
* switch, but a revisited tab's analysis is usually still in the saved
* library or session cache — this URL is what lets it be served without any
* page access. Cleared when the tab navigates or closes.
*/
function tabUrlKey(tabId: number): string {
return `taburl:${tabId}`;
}
async function rememberTabUrl(tabId: number, url: string): Promise<void> {
try {
await chrome.storage.session.set({ [tabUrlKey(tabId)]: url });
} catch {
// Session storage unavailable; revisits will need a toolbar click.
}
}
async function recallTabUrl(tabId: number): Promise<string | null> {
try {
const key = tabUrlKey(tabId);
const data = await chrome.storage.session.get(key);
return typeof data[key] === "string" ? (data[key] as string) : null;
} catch {
return null;
}
}
async function forgetTabUrl(tabId: number): Promise<void> {
try {
await chrome.storage.session.remove(tabUrlKey(tabId));
} catch {
// Nothing to clean up if storage is unavailable.
}
}
/**
* Tracks recent non-extension tabs so the panel's target can be resolved even
* when the panel page itself is the active tab (e.g. sidepanel.html opened in
* a tab).
*
* When `broadcast` is provided, tab switches and navigations are announced as
* ACTIVE_TAB_CHANGED so an already-open panel can follow the active tab —
* navigation revokes the activeTab grant, so whatever the panel was showing is
* stale the moment it happens.
*/
export function trackContentTabs(
broadcast?: (message: ExtensionMessage) => void
): void {
chrome.tabs.onActivated.addListener(({ tabId }) => {
void rememberTab(tabId, broadcast, "tab-switch");
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// Only navigation signals matter: "loading" fires once per page load even
// on hosts whose URL we cannot read; `url` covers SPA history updates on
// readable hosts.
const navigated =
changeInfo.status === "loading" || changeInfo.url !== undefined;
// A navigation invalidates the tab's remembered URL even in a background
// tab — whatever was analyzed there no longer describes the page.
if (navigated) void forgetTabUrl(tabId);
if (!tab.active) return;
void rememberTab(tabId, navigated ? broadcast : undefined, "navigation");
});
chrome.tabs.onRemoved.addListener((tabId) => {
void forgetTabUrl(tabId);
});
}
async function rememberTab(
tabId: number,
broadcast: ((message: ExtensionMessage) => void) | undefined,
trigger: "navigation" | "tab-switch"
): Promise<void> {
try {
const tab = await chrome.tabs.get(tabId);
if (tab.url?.startsWith("chrome-extension://") || tab.url === "about:blank")
return;
recentContentTabs = [
tabId,
...recentContentTabs.filter((id) => id !== tabId),
].slice(0, MAX_TRACKED_TABS);
broadcast?.({
type: MessageType.ACTIVE_TAB_CHANGED,
tabId,
trigger,
});
} catch {
// Tab may already be gone.
}
}
/**
* Toolbar-icon click: the only moment an activeTab grant (and thus a readable
* URL on any site) is guaranteed to exist. Opening the side panel via
* setPanelBehavior does NOT grant activeTab — Chrome deliberately withholds
* it (crbug.com/40926394) — which is why the background listens to
* action.onClicked and opens the panel itself.
*/
export function handleActionClick(
tab: chrome.tabs.Tab,
broadcast: (message: ExtensionMessage) => void
): void {
if (tab.id === undefined) return;
recentContentTabs = [
tab.id,
...recentContentTabs.filter((id) => id !== tab.id),
].slice(0, MAX_TRACKED_TABS);
broadcast({
type: MessageType.ACTIVE_TAB_CHANGED,
tabId: tab.id,
trigger: "action-click",
});
}
/**
* Resolves which tab the panel should target.
*
* `excludeTabId` is the panel page's own tab when it runs as a regular tab
* (from `sender.tab`). Extension-page URLs are NOT readable without the
* "tabs" permission, so the id — not the URL — is what prevents the panel
* from resolving to (and then analyzing) itself.
*/
export async function resolveActiveTab(
excludeTabId: number | null = null
): Promise<{ tabId: number | null }> {
let tab: chrome.tabs.Tab | undefined;
try {
[tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
} catch {
tab = undefined;
}
if (
!tab ||
tab.id === excludeTabId ||
tab.url?.startsWith("chrome-extension://")
) {
// Walk the tracked candidates newest-first, re-validating each: a tab
// tracked while it was still about:blank may have since become the panel
// page itself, and any candidate may have been closed.
for (const tabId of recentContentTabs) {
if (tabId === excludeTabId) continue;
try {
const fresh = await chrome.tabs.get(tabId);
if (fresh.url?.startsWith("chrome-extension://")) continue;
return { tabId };
} catch {
// Tab closed since it was tracked.
}
}
return { tabId: null };
}
return { tabId: tab.id ?? null };
}
/** FR-011/FR-012 stored-result lookup: saved library first, then session cache. */
async function lookupStored(
canonicalUrl: string
): Promise<{ analysis: JobAnalysis; saved: SavedJob | null } | null> {
const saved = await jobStorage.get(canonicalUrl);
if (saved) return { analysis: saved.analysis, saved };
const cached = await getCached(canonicalUrl);
if (cached) return { analysis: cached, saved: null };
return null;
}
/**
* A stored analysis is fit-stale when recomputing is the only way the current
* fit UI ever appears — the default lookup never reaches the backend again:
* - fit is null but the profile was created/updated after the analysis ran;
* - fit predates the breakdown fields (matching/missing/…), a one-time
* upgrade per stored analysis (fresh results always carry the breakdown,
* so this cannot loop).
*/
async function needsFitRefresh(analysis: JobAnalysis): Promise<boolean> {
if (analysis.fit && analysis.fit.matching !== undefined) return false;
try {
const profile = await getProfile();
if (profile === null) return false;
if (analysis.fit) return true;
return Date.parse(analysis.analyzedAt) < Date.parse(profile.updatedAt);
} catch {
// Can't tell — serve the stored copy rather than fail the revisit.
return false;
}
}
/**
* Per-tab cancellation generation (spec FR-006, FR-006b).
*
* Extraction now spends up to 6 s waiting for the page inside the injected
* function, and that wait cannot be interrupted from here — the loop lives in
* the page's isolated world. What we can guarantee is the part the user cares
* about: a cancelled attempt sends no analysis request, spends no allowance,
* and broadcasts nothing. The abandoned injection resolves into a generation
* check that discards it; its observer is disconnected as it returns, so it
* holds nothing open.
*
* A counter rather than a boolean because of FR-006b: cancel, then immediately
* re-analyze. A flag would have to be cleared by the next request and would
* race with the abandoned one; a generation makes the stale result identifiable
* no matter when it lands.
*/
const cancelGenerations = new Map<number, number>();
/** Panel → background: abandon whatever is in flight for this tab. */
export function cancelAnalysis(message: CancelAnalysisMessage): void {
cancelGenerations.set(message.tabId, (cancelGenerations.get(message.tabId) ?? 0) + 1);
}
export async function analyzeJobPage(
message: AnalyzeJobPageMessage,
broadcast: (m: ExtensionMessage) => void
): Promise<void> {
const generation = cancelGenerations.get(message.tabId) ?? 0;
const cancelled = (): boolean => (cancelGenerations.get(message.tabId) ?? 0) !== generation;
let raw: RawPageExtract | undefined;
if (!message.cachedOnly) {
// The learned selector must be resolved from storage and handed to
// extractPage as an argument — the injected function is serialized and
// can neither read chrome.storage itself nor import learnedSelectors.ts
// (plan.md Constraints). A host we can't resolve ahead of extraction
// (permission not yet granted, tab already gone) just means no learned
// selector is tried — never a hard failure.
let learnedSelector: string | undefined;
try {
const tab = await chrome.tabs.get(message.tabId);
if (tab.url) {
const learned = await learnedSelectors.get(new URL(tab.url).hostname);
learnedSelector = learned?.selector;
}
} catch {
learnedSelector = undefined;
}
try {
const [injection] = await chrome.scripting.executeScript({
target: { tabId: message.tabId },
func: extractPage,
args: [{ learnedSelector }],
});
raw = injection?.result as RawPageExtract | undefined;
} catch {
raw = undefined;
}
}
// The readiness wait is the window a cancel most plausibly lands in.
if (cancelled()) return;
if (!raw) {
// No page access: either this is a cachedOnly probe, or executeScript
// failed because the activeTab grant is missing (it only exists after a
// toolbar-icon click and dies on navigation) or the page is one Chrome
// never allows extensions to read (chrome://, Web Store). A revisited tab
// can still be served from the library/cache via its remembered URL.
if (!message.bypassCache) {
const rememberedUrl = await recallTabUrl(message.tabId);
if (rememberedUrl) {
const canonicalUrl = canonicalize(rememberedUrl);
try {
const stored = await lookupStored(canonicalUrl);
if (stored) {
broadcast({
type: MessageType.JOB_ANALYSIS_RESULT,
analysis: stored.analysis,
canonicalUrl,
sourceUrl: rememberedUrl,
multiplePostings: false,
cached: true,
saved: stored.saved,
});
return;
}
} catch {
// Storage unreachable — fall through to the error (or silence).
}
}
}
if (message.cachedOnly) return; // Silent probe: leave the panel as-is.
broadcast({
type: MessageType.JOB_ANALYSIS_ERROR,
error: {
code: "no-access",
message: "The extension doesn't have permission to read this page.",
action:
"Click the extension icon in the Chrome toolbar to grant access " +
"and re-run the analysis. Chrome's own pages and the Web Store " +
"can't be analyzed.",
retryable: false,
},
fallback: null,
canonicalUrl: null,
sourceUrl: null,
});
return;
}
const canonicalUrl = canonicalize(raw.url);
const extract: PageExtract = { ...raw, canonicalUrl };
void rememberTabUrl(message.tabId, raw.url);
// Both storage writes live here, never inside the injected function
// (plan.md Constraints); recordMiss fires once per extraction, never per
// readiness attempt — calling it per attempt would retire a learned
// selector on a slow SPA within two page loads (FR-029, contracts
// "Interaction with readiness").
try {
const host = new URL(raw.url).hostname;
if (raw.provenance?.strategy === "learned-selector") {
void learnedSelectors.touch(host);
} else if (raw.provenance?.learnedSelectorMissed) {
void learnedSelectors.recordMiss(host);
}
} catch {
// Malformed URL — nothing to record against.
}
// Thin content now keys on body text alone. Structured data no longer
// rescues a page from this check: JSON-LD with an empty body was the silent
// degradation 3/6 corpus fixtures took — the model received structured
// fields and no posting, and the user was never told (spec FR-004a).
//
// Since extraction only returns early once text clears the minimum, text
// below it means the readiness budget expired. The two messages describe two
// genuinely different situations and suggest different next actions
// (contracts/extraction-payload.md §3); the code and retryability are
// unchanged, so JobErrorCode does not grow.
if (extract.mainText.length < MIN_TEXT_CHARS) {
const stillLoading = extract.provenance?.budgetExpired === true;
broadcast({
type: MessageType.JOB_ANALYSIS_ERROR,
error: {
code: "thin-content",
message: stillLoading
? "The page was still loading when we tried to read it."
: "Not enough page content to analyze.",
action: stillLoading
? "Wait for the page to finish loading, then re-analyze."
: "Open the full job posting page, then re-analyze.",
retryable: true,
},
fallback: null,
canonicalUrl,
sourceUrl: raw.url,
});
return;
}
// FR-011/FR-012 lookup order: saved library → session cache → backend.
if (!message.bypassCache) {
try {
const stored = await lookupStored(canonicalUrl);
if (stored && !(await needsFitRefresh(stored.analysis))) {
broadcast({
type: MessageType.JOB_ANALYSIS_RESULT,
analysis: stored.analysis,
canonicalUrl,
sourceUrl: raw.url,
multiplePostings: extract.jsonLd.length > 1,
cached: true,
saved: stored.saved,
strategy: raw.provenance?.strategy,
});
return;
}
} catch {
// Storage unreachable — fall through to a fresh analysis.
}
}
try {
// FR-007: the profile leaves the browser only inside analysis requests.
// The profile is an enhancement: when it cannot be fetched, analyze
// without it (fit stays null and refreshes on a later revisit) instead
// of failing the whole analysis.
let profile: CandidateProfile | null = null;
try {
profile = await getProfile();
} catch {
profile = null;
}
// Last check before the request: this is the line FR-006 is about — a
// cancelled analysis must not spend the user's monthly allowance.
if (cancelled()) return;
const analysis = await postJobAnalysis({
extract,
profile: profile ? profileToPromptText(profile) : undefined,
assumeJobPosting: message.assumeJobPosting,
});
await setCached(canonicalUrl, analysis);
// A fresh analysis of an already-saved posting replaces its snapshot
// (status/notes survive) — explicit Re-analyze and the automatic fit
// refresh both land here.
let saved: SavedJob | null = null;
try {
const existing = await jobStorage.get(canonicalUrl);
if (existing) {
await jobStorage.update(canonicalUrl, { analysis });
saved = await jobStorage.get(canonicalUrl);
}
} catch {
// Library unreachable — still deliver the analysis itself.
}
broadcast({
type: MessageType.JOB_ANALYSIS_RESULT,
analysis,
canonicalUrl,
sourceUrl: raw.url,
multiplePostings: extract.jsonLd.length > 1,
cached: false,
saved,
strategy: raw.provenance?.strategy,
});
} catch (err) {
broadcast({
type: MessageType.JOB_ANALYSIS_ERROR,
error: toJobPanelError(err),
fallback:
extract.jsonLd.length > 0 ? deriveJsonLdFields(extract.jsonLd) : null,
canonicalUrl,
sourceUrl: raw.url,
});
}
}
/**
* Story 3 — the unconditional escape hatch. Skips extraction entirely: the
* text came from the user, not a page. Validated against the same bounds as
* page text (FR-018) and reported before any request is sent, so a below-
* minimum or above-cap paste never touches the allowance. Identified by a
* content-derived `paste:<sha256>` (FR-021), not a page URL — repeat pastes
* of the same text resolve to the same identity, so this goes through the
* same saved-library/session-cache lookup as a page analysis (FR-019).
*/
export async function analyzePastedText(
message: AnalyzePastedTextMessage,
broadcast: (m: ExtensionMessage) => void
): Promise<void> {
const violation = boundViolation(
message.text.length,
MIN_TEXT_CHARS,
MAIN_TEXT_CAP,
"Paste more of the posting before analyzing.",
"Trim it to the posting itself before analyzing."
);
if (violation) {
broadcast({
type: MessageType.PASTE_ANALYSIS_ERROR,
error: {
code: "thin-content",
message: violation.message,
action: violation.action,
retryable: false,
},
});
return;
}
const canonicalUrl = await pasteIdentity(message.text);
try {
const stored = await lookupStored(canonicalUrl);
if (stored && !(await needsFitRefresh(stored.analysis))) {
broadcast({
type: MessageType.PASTE_ANALYSIS_RESULT,
analysis: stored.analysis,
canonicalUrl,
saved: stored.saved,
strategy: "paste",
});
return;
}
} catch {
// Storage unreachable — fall through to a fresh analysis.
}
const extract: PageExtract = {
url: canonicalUrl,
canonicalUrl,
title: "",
jsonLd: [],
mainText: message.text.slice(0, MAIN_TEXT_CAP),
extractedAt: new Date().toISOString(),
};
try {
let profile: CandidateProfile | null = null;
try {
profile = await getProfile();
} catch {
profile = null;
}
const analysis = await postJobAnalysis({
extract,
profile: profile ? profileToPromptText(profile) : undefined,
assumeJobPosting: message.assumeJobPosting,
});
await setCached(canonicalUrl, analysis);
let saved: SavedJob | null = null;
try {
const existing = await jobStorage.get(canonicalUrl);
if (existing) {
await jobStorage.update(canonicalUrl, { analysis });
saved = await jobStorage.get(canonicalUrl);
}
} catch {
// Library unreachable — still deliver the analysis itself.
}
broadcast({
type: MessageType.PASTE_ANALYSIS_RESULT,
analysis,
canonicalUrl,
saved,
strategy: "paste",
});
} catch (err) {
broadcast({
type: MessageType.PASTE_ANALYSIS_ERROR,
error: toJobPanelError(err),
});
}
}
/**
* Story 4 — a hand-scoped region (picker or selection, FR-023c) re-runs the
* analysis of the CURRENT page, identified by its canonical URL, never a
* synthetic identity (FR-026). This is a separate path from
* `analyzeJobPage`'s lookup order specifically so it can never call
* `lookupStored`: FR-026a requires bypassing the saved-library/session-cache
* lookup entirely, or a scoped correction on a page that already has a
* stored analysis would silently return that stale result and the user's
* correction would appear to do nothing (plan.md Risks — the cache-bypass
* trap).
*/
export async function analyzeScopedRegion(
message: AnalyzeScopedRegionMessage,
broadcast: (m: ExtensionMessage) => void
): Promise<void> {
let tabUrl: string;
try {
const tab = await chrome.tabs.get(message.tabId);
if (!tab.url) throw new Error("no readable url");
tabUrl = tab.url;
} catch {
broadcast({
type: MessageType.JOB_ANALYSIS_ERROR,
error: {
code: "no-access",
message: "The extension doesn't have permission to read this page.",
action:
"Click the extension icon in the Chrome toolbar to grant access and re-run the analysis.",
retryable: false,
},
fallback: null,
canonicalUrl: null,
sourceUrl: null,
});
return;
}
const canonicalUrl = canonicalize(tabUrl);
// FR-034: refused with the same wording/number as the paste-side refusal
// (FR-018a) — a bound violation is one rule, not two.
const violation = boundViolation(
message.text.length,
MIN_TEXT_CHARS,
MAIN_TEXT_CAP,
"Pick or select a larger part of the page.",
"Pick or select a smaller part of the page."
);
if (violation) {
broadcast({
type: MessageType.JOB_ANALYSIS_ERROR,
error: {
code: "thin-content",
message: violation.message,
action: violation.action,
retryable: true,
},
fallback: null,
canonicalUrl,
sourceUrl: tabUrl,
});
return;
}
const extract: PageExtract = {
url: tabUrl,
canonicalUrl,
title: "",
jsonLd: [],
mainText: message.text.slice(0, MAIN_TEXT_CAP),
extractedAt: new Date().toISOString(),
};
try {
let profile: CandidateProfile | null = null;
try {
profile = await getProfile();
} catch {
profile = null;
}
const analysis = await postJobAnalysis({
extract,
profile: profile ? profileToPromptText(profile) : undefined,
assumeJobPosting: message.assumeJobPosting,
});
await setCached(canonicalUrl, analysis);
let saved: SavedJob | null = null;
try {
const existing = await jobStorage.get(canonicalUrl);
if (existing) {
await jobStorage.update(canonicalUrl, { analysis });
saved = await jobStorage.get(canonicalUrl);
}
} catch {
// Library unreachable — still deliver the analysis itself.
}
let host: string | undefined;
try {
host = new URL(tabUrl).hostname;
} catch {
host = undefined;
}
broadcast({
type: MessageType.JOB_ANALYSIS_RESULT,
analysis,
canonicalUrl,
sourceUrl: tabUrl,
multiplePostings: false,
cached: false,
saved,
strategy: message.mechanism,
scopedRegion: host ? { selector: message.selector, host } : undefined,
});
} catch (err) {
broadcast({
type: MessageType.JOB_ANALYSIS_ERROR,
error: toJobPanelError(err),
fallback: null,
canonicalUrl,
sourceUrl: tabUrl,
});
}
}
/** ApiError codes (storage API) mapped onto the panel's error vocabulary. */
const API_ERROR_CODES: Record<string, JobErrorCode> = {
NOT_CONFIGURED: "not-configured",
NETWORK_ERROR: "network-error",
UNAUTHENTICATED: "no-access",
NOT_AUTHORIZED: "no-access",
SERVICE_ERROR: "service-error",
};
function toJobPanelError(err: unknown): JobPanelError {
if (
typeof err === "object" &&
err !== null &&
"code" in err &&
"message" in err &&
"retryable" in err
) {
const e = err as {
code: string;
message: string;
retryable: boolean;
action?: string;
usage?: JobPanelError["usage"];
};
// Rebuild as a plain object: on an Error subclass (e.g. ApiError),
// `message` is non-enumerable and would be dropped by the JSON
// serialization in chrome.runtime.sendMessage, leaving a blank error box.
return {
code: API_ERROR_CODES[e.code] ?? (e.code as JobErrorCode),
message: e.message,
action: e.action ?? "Try again.",
retryable: e.retryable,
...(e.usage ? { usage: e.usage } : {}),
};
}
return {
code: "unknown",
message: "An unexpected error occurred.",
action: "Try again.",
retryable: true,
};
}
|