diff --git a/CLAUDE.md b/CLAUDE.md
index e9291c9..67605a5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -105,9 +105,10 @@ Each macro (protein, carbs, fat, alcohol) is added as a separate "Quick Add" foo
4. Click "Add Food..." in context menu
5. Search for the macro (e.g. "Quick Add, Protein")
6. Click SEARCH, select the result
-7. Enter serving size in grams
-8. Click "ADD TO DIARY"
-9. Repeat for each macro
+7. Wait (up to 10s) for the food details to load inside the dialog; if the dialog closes early or stalls, re-open and re-select (up to 3 attempts)
+8. Enter serving size in grams (inputs and buttons are scoped to the Add Food dialog, never the diary behind it)
+9. Click "ADD TO DIARY" and confirm a new diary entry appeared (existing entries of the same macro are never edited)
+10. Repeat for each macro
**Date navigation note:** Cronometer's GWT hash routing does not support `?date=` query params. Date changes use prev-day arrow clicks (same approach as `diary` and `weight` commands), capped at 90 days back.
diff --git a/src/automation/runner.ts b/src/automation/runner.ts
index e142e61..fa5a8bf 100644
--- a/src/automation/runner.ts
+++ b/src/automation/runner.ts
@@ -26,7 +26,7 @@ import type {
WeightData,
} from "./types.js";
-const QUICK_ADD_SECONDS_PER_MACRO = 60;
+const QUICK_ADD_SECONDS_PER_MACRO = 150;
const QUICK_ADD_SETUP_TIMEOUT_SEC = 60;
const QUICK_ADD_SECONDS_PER_DATE_STEP = 2;
const MAX_QUICK_ADD_DATE_STEPS = 90;
@@ -37,9 +37,10 @@ const AUTO_LOGIN_TIMEOUT_SEC = 120;
* 60-second timeout can therefore save the first macro and abort while adding
* the next one, leaving a partial (and unsafe to retry) diary entry.
*
- * Allow one minute to load and prepare the diary, one minute per macro, plus
- * the two-second delay used for each previous day navigation step in
- * buildQuickAddCode.
+ * Allow one minute to load and prepare the diary, two and a half minutes per
+ * macro (each macro may re-open the Add Food dialog up to three times if it
+ * closes before the food details load), plus the two-second delay used for
+ * each previous day navigation step in buildQuickAddCode.
*/
export function getQuickAddTimeoutSec(
entry: MacroEntry,
diff --git a/src/kernel/client.ts b/src/kernel/client.ts
index 01c35b4..92c8098 100644
--- a/src/kernel/client.ts
+++ b/src/kernel/client.ts
@@ -21,22 +21,22 @@ import { getCredential } from "../credentials.js";
* Client-side HTTP timeout for Kernel API requests.
*
* The SDK defaults to 60s, but automations are dispatched with `timeout_sec`
- * values up to 480s (see multi-macro retroactive quick-add). When the client gives up first the
+ * values up to 840s (see multi-macro retroactive quick-add). When the client gives up first the
* browser keeps going, so Cronometer commits the change while crono reports
* failure — and a retry then duplicates the data. Keep this comfortably above
* the largest `timeout_sec` used by any automation.
*/
-const KERNEL_REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
+const KERNEL_REQUEST_TIMEOUT_MS = 20 * 60 * 1000;
/**
* Lifetime of a remote browser session.
*
* A single command can spend up to 120s logging in before a multi-macro quick-add
- * starts. Quick-add may need up to 480s for setup, four macros, and 90 date
+ * starts. Quick-add may need up to 840s for setup, four macros, and 90 date
* steps, so
* leave enough room for both login and the operation.
*/
-const BROWSER_SESSION_TIMEOUT_SEC = 900;
+const BROWSER_SESSION_TIMEOUT_SEC = 1200;
export type KernelClient = AutomationClient;
export type {
diff --git a/src/kernel/food-dialog.ts b/src/kernel/food-dialog.ts
index abdac53..33d92e6 100644
--- a/src/kernel/food-dialog.ts
+++ b/src/kernel/food-dialog.ts
@@ -8,8 +8,53 @@ export interface FoodDialogOptions {
alwaysUpdateServingSize?: boolean;
updateServingSize?: boolean;
verifyDialogDismissed?: boolean;
+ /**
+ * After adding, fail unless the food's diary entry count increased. Guards
+ * against edits landing on an existing entry. (The pre-add count is always
+ * taken so dialog retries never duplicate an entry.)
+ */
+ verifyNewEntry?: boolean;
}
+/** How many times to re-open the Add Food dialog if it closes or stalls. */
+export const ADD_FOOD_DIALOG_ATTEMPTS = 3;
+/** How long to wait for the selected food's details to load in the dialog. */
+export const DETAILS_LOAD_TIMEOUT_MS = 10000;
+/** How long the dialog must stay gone before it is treated as closed. */
+export const DIALOG_CLOSED_GRACE_MS = 1500;
+/** How long to wait for a newly added entry to render in the diary. */
+export const NEW_ENTRY_TIMEOUT_MS = 10000;
+
+/**
+ * In-page helper that locates the visible "Add Food to Diary" dialog root.
+ * Interpolated into every page.evaluate() that touches dialog controls so
+ * serving-size inputs and the "Add to Diary" button are never resolved
+ * against the diary behind the dialog (which would edit an existing entry).
+ */
+const FIND_ADD_FOOD_DIALOG = `
+ const isShown = (el) => !!el && el.getClientRects().length > 0;
+ const findAddFoodDialog = () => {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
+ acceptNode: (node) =>
+ node.textContent && node.textContent.trim() === 'Add Food to Diary'
+ ? NodeFilter.FILTER_ACCEPT
+ : NodeFilter.FILTER_REJECT,
+ });
+ let node;
+ while ((node = walker.nextNode())) {
+ const title = node.parentElement;
+ if (!isShown(title)) continue;
+ const root = title.closest('.gwt-DialogBox, .gwt-PopupPanel, .gwt-DecoratedPopupPanel, [role="dialog"]');
+ if (root) return root;
+ let el = title.parentElement;
+ for (let i = 0; i < 8 && el && el !== document.body; i++) {
+ if (el.querySelector('input')) return el;
+ el = el.parentElement;
+ }
+ }
+ return null;
+ };`;
+
export function buildFoodDialogCode(options: FoodDialogOptions = {}): string {
const foodNameVar = options.foodNameVar ?? "foodName";
const mealLabelVar = options.mealLabelVar ?? "mealLabel";
@@ -20,6 +65,7 @@ export function buildFoodDialogCode(options: FoodDialogOptions = {}): string {
const alwaysUpdateServingSize = options.alwaysUpdateServingSize ?? false;
const updateServingSize = options.updateServingSize ?? false;
const verifyDialogDismissed = options.verifyDialogDismissed ?? false;
+ const verifyNewEntry = options.verifyNewEntry ?? false;
const mealCategoryError = errorPrefix
? `${errorPrefix}could not find meal category "`
: 'Could not find meal category "';
@@ -46,6 +92,8 @@ export function buildFoodDialogCode(options: FoodDialogOptions = {}): string {
? `'${addToDiaryError}'`
: `'${addToDiaryError} for "' + ${itemNameVar} + '"'`;
+ const dialogClosedError = `'${errorPrefix}Add Food dialog closed before details loaded after selecting "' + ${foodNameVar} + '"'`;
+
return `
// Helper: right-click an element from a list of selectors
async function rightClickFirst(selectors, description) {
@@ -61,171 +109,305 @@ export function buildFoodDialogCode(options: FoodDialogOptions = {}): string {
return false;
}
- // Right-click meal category with retry (GWT context menus can be flaky
- // and meal labels may not render immediately)
- let menuVisible = false;
- for (let attempt = 0; attempt < 3 && !menuVisible; attempt++) {
- if (attempt > 0) {
+ // Helper: report whether the Add Food dialog is closed, still loading the
+ // selected food's details, or ready for an amount to be entered.
+ async function probeAddFoodDialog(requireServingSize) {
+ return page.evaluate(({ requireServingSize }) => {
+${FIND_ADD_FOOD_DIALOG}
+ const dialog = findAddFoodDialog();
+ if (!dialog) return 'closed';
+ const hasServingInput = Array.from(dialog.querySelectorAll('*')).some((el) =>
+ el.children.length === 0 &&
+ el.textContent && el.textContent.trim() === 'Serving Size' &&
+ isShown(el) &&
+ (() => {
+ let container = el.parentElement;
+ for (let i = 0; i < 5 && container && dialog.contains(container); i++) {
+ const input = container.querySelector('input');
+ if (input && isShown(input)) return true;
+ container = container.parentElement;
+ }
+ return false;
+ })()
+ );
+ const hasAddButton = Array.from(dialog.querySelectorAll('button')).some((btn) =>
+ btn.textContent && btn.textContent.trim().toLowerCase() === 'add to diary' && isShown(btn)
+ );
+ if (requireServingSize ? hasServingInput : hasAddButton) return 'ready';
+ return 'loading';
+ }, { op: 'probeAddFoodDialog', requireServingSize });
+ }
+
+ // Helper: wait until the selected food's details have loaded in the dialog.
+ // GWT can briefly re-render the dialog, so it only counts as closed after
+ // staying gone for a grace period.
+ async function waitForFoodDetails(requireServingSize) {
+ const deadline = Date.now() + ${DETAILS_LOAD_TIMEOUT_MS};
+ let closedSince = null;
+ while (true) {
+ const state = await probeAddFoodDialog(requireServingSize);
+ if (state === 'ready') return 'ready';
+ if (state === 'closed') {
+ if (closedSince === null) closedSince = Date.now();
+ if (Date.now() - closedSince >= ${DIALOG_CLOSED_GRACE_MS}) return 'closed';
+ } else {
+ closedSince = null;
+ }
+ if (Date.now() >= deadline) return state;
+ await page.waitForTimeout(250);
+ }
+ }
+${buildCountDiaryEntriesCode()}
+ // Snapshot existing entries so a retry never re-adds a food that an early
+ // dialog close already logged
+ const entriesBefore = await countDiaryEntries(${foodNameVar});
+ console.log('[crono food-dialog] existing diary entries for ' + ${foodNameVar} + ': ' + entriesBefore);
+ let detailsLoaded = false;
+ let dialogError = '';
+ for (let dialogAttempt = 0; dialogAttempt < ${ADD_FOOD_DIALOG_ATTEMPTS} && !detailsLoaded; dialogAttempt++) {
+ if (dialogAttempt > 0) {
+ console.log('[crono food-dialog] retrying Add Food dialog (attempt ' + (dialogAttempt + 1) + ') after: ' + dialogError);
+ // Close any half-open dialog and clear diary selection before re-opening
await page.keyboard.press('Escape');
+ await page.waitForSelector('text="Add Food to Diary"', { state: 'hidden', timeout: 3000 })
+ .then(() => true).catch(() => false);
await page.mouse.click(1, 1);
- await page.waitForTimeout(2000);
+ await page.waitForTimeout(1500);
+ // If the early close logged the food anyway, re-adding would duplicate it
+ const entriesNow = await countDiaryEntries(${foodNameVar});
+ if (entriesNow !== entriesBefore) {
+ return { success: false, error: '${errorPrefix}Add Food dialog closed early and the diary changed for "' + ${foodNameVar} + '" (' + entriesBefore + ' -> ' + entriesNow + ' entries); not retrying to avoid a duplicate' };
+ }
}
- const clicked = await rightClickFirst([
- 'td:text("' + ${mealLabelVar} + '")',
- 'div:text("' + ${mealLabelVar} + '")',
- 'text="' + ${mealLabelVar} + '"',
- ], 'meal category');
- if (!clicked) {
- if (attempt < 2) {
+
+ // Right-click meal category with retry (GWT context menus can be flaky
+ // and meal labels may not render immediately)
+ let menuVisible = false;
+ for (let attempt = 0; attempt < 3 && !menuVisible; attempt++) {
+ if (attempt > 0) {
+ await page.keyboard.press('Escape');
+ await page.mouse.click(1, 1);
await page.waitForTimeout(2000);
- continue;
}
- return { success: false, error: '${mealCategoryError}' + ${mealLabelVar} + '" in diary' };
+ const clicked = await rightClickFirst([
+ 'td:text("' + ${mealLabelVar} + '")',
+ 'div:text("' + ${mealLabelVar} + '")',
+ 'text="' + ${mealLabelVar} + '"',
+ ], 'meal category');
+ if (!clicked) {
+ if (attempt < 2) {
+ await page.waitForTimeout(2000);
+ continue;
+ }
+ return { success: false, error: '${mealCategoryError}' + ${mealLabelVar} + '" in diary' };
+ }
+ menuVisible = await page.waitForSelector('text="Add Food..."', { timeout: 3000 })
+ .then(() => true)
+ .catch(() => page.waitForSelector('text="Add Food"', { timeout: 2000 }).then(() => true).catch(() => false));
}
- menuVisible = await page.waitForSelector('text="Add Food..."', { timeout: 3000 })
+ if (!menuVisible) {
+ return { success: false, error: '${contextMenuError}' + ${mealLabelVar} + '"' };
+ }
+
+ // Click "Add Food..." in context menu
+ const addFoodClicked = await clickFirst([
+ 'text="Add Food..."',
+ 'text="Add Food\\u2026"',
+ 'text="Add Food"',
+ '[role="menuitem"]:has-text("Add Food")',
+ ], 'Add Food menu item');
+ if (!addFoodClicked) {
+ return { success: false, error: '${addFoodError}' };
+ }
+ await page.waitForTimeout(200);
+
+ // Wait for "Add Food to Diary" dialog
+ const dialogAppeared = await page.waitForSelector('text="Add Food to Diary"', { timeout: 5000 })
.then(() => true)
- .catch(() => page.waitForSelector('text="Add Food"', { timeout: 2000 }).then(() => true).catch(() => false));
- }
- if (!menuVisible) {
- return { success: false, error: '${contextMenuError}' + ${mealLabelVar} + '"' };
- }
+ .catch(() => false);
+ if (!dialogAppeared) {
+ dialogError = '${errorPrefix}Add Food to Diary dialog did not appear';
+ continue;
+ }
+ await page.waitForTimeout(300);
- // Click "Add Food..." in context menu
- const addFoodClicked = await clickFirst([
- 'text="Add Food..."',
- 'text="Add Food\\u2026"',
- 'text="Add Food"',
- '[role="menuitem"]:has-text("Add Food")',
- ], 'Add Food menu item');
- if (!addFoodClicked) {
- return { success: false, error: '${addFoodError}' };
- }
- await page.waitForTimeout(200);
+ // Search for the food
+ const searchSelectors = [
+ 'input[placeholder*="Search all foods" i]',
+ 'input[placeholder*="Search" i]',
+ 'input[placeholder*="food" i]',
+ 'input.gwt-TextBox',
+ 'input[type="text"]',
+ 'input[type="search"]',
+ ];
+ let searched = false;
+ for (const sel of searchSelectors) {
+ try {
+ const el = page.locator(sel).filter({ visible: true });
+ if (await el.count() > 0) {
+ await el.first().click({ timeout: 3000 });
+ await page.waitForTimeout(200);
+ await el.first().fill('', { timeout: 3000 });
+ await page.keyboard.type(${foodNameVar}, { delay: 50 });
+ searched = true;
+ break;
+ }
+ } catch {}
+ }
+ if (!searched) {
+ dialogError = '${searchBarError}';
+ continue;
+ }
+ await page.waitForTimeout(300);
- // Wait for "Add Food to Diary" dialog
- try {
- await page.waitForSelector('text="Add Food to Diary"', { timeout: 5000 });
- } catch {
- return { success: false, error: '${errorPrefix}Add Food to Diary dialog did not appear' };
- }
- await page.waitForTimeout(300);
+ // Click SEARCH
+ await clickFirst([
+ 'button:has-text("SEARCH")',
+ 'button:has-text("Search")',
+ 'text="SEARCH"',
+ ], 'SEARCH button');
- // Search for the food
- const searchSelectors = [
- 'input[placeholder*="Search all foods" i]',
- 'input[placeholder*="Search" i]',
- 'input[placeholder*="food" i]',
- 'input.gwt-TextBox',
- 'input[type="text"]',
- 'input[type="search"]',
- ];
- let searched = false;
- for (const sel of searchSelectors) {
- try {
- const el = page.locator(sel).filter({ visible: true });
- if (await el.count() > 0) {
- await el.first().click({ timeout: 3000 });
- await page.waitForTimeout(200);
- await el.first().fill('', { timeout: 3000 });
- await page.keyboard.type(${foodNameVar}, { delay: 50 });
- searched = true;
- break;
- }
- } catch {}
- }
- if (!searched) {
- return { success: false, error: '${searchBarError}' };
- }
- await page.waitForTimeout(300);
+ // Wait for search results to appear
+ const resultsAppeared = await page.getByText(${foodNameVar}, { exact: true })
+ .filter({ visible: true }).first().waitFor({ state: 'visible', timeout: 8000 })
+ .then(() => true)
+ .catch(() => false);
+ if (!resultsAppeared) {
+ return { success: false, error: '${noFoodError}' + ${foodNameVar} + '"' };
+ }
+ await page.waitForTimeout(2000);
- // Click SEARCH
- await clickFirst([
- 'button:has-text("SEARCH")',
- 'button:has-text("Search")',
- 'text="SEARCH"',
- ], 'SEARCH button');
-
- // Wait for search results to appear
- const resultsAppeared = await page.getByText(${foodNameVar}, { exact: true })
- .filter({ visible: true }).first().waitFor({ state: 'visible', timeout: 8000 })
- .then(() => true)
- .catch(() => false);
- if (!resultsAppeared) {
- return { success: false, error: '${noFoodError}' + ${foodNameVar} + '"' };
- }
- await page.waitForTimeout(2000);
+ // Select the first visible result row whose Description cell exactly
+ // matches the requested food. Cronometer renders duplicate result rows, so
+ // iterate them and click the first good row. Only consider rows with exactly
+ // 2 cells (Description + Source columns in search results), not diary entry
+ // rows (8+ cells). We scan ALL
elements because the search results table
+ // is distinct from the diary table shown in the background.
+ const allRows = page.locator('tr');
+ let resultClicked = false;
+ const allRowCount = await allRows.count();
+ console.log('[crono food-dialog] scanning ' + allRowCount + ' total rows');
- // Select the first visible result row whose Description cell exactly
- // matches the requested food. Cronometer renders duplicate result rows, so
- // iterate them and click the first good row. Only consider rows with exactly
- // 2 cells (Description + Source columns in search results), not diary entry
- // rows (8+ cells). We scan ALL
elements because the search results table
- // is distinct from the diary table shown in the background.
- const allRows = page.locator('tr');
- let resultClicked = false;
- const allRowCount = await allRows.count();
- console.log('[crono food-dialog] scanning ' + allRowCount + ' total rows');
-
- for (let i = 0; i < allRowCount; i++) {
- const row = allRows.nth(i);
- const visible = await row.isVisible().catch(() => false);
- if (!visible) continue;
-
- // Only consider rows with exactly 2 cells (search results table)
- const cellCount = await row.locator('td').count();
- if (cellCount !== 2) continue;
-
- const description = (await row.locator('td').first().textContent().catch(() => '') || '').trim();
- if (description !== ${foodNameVar}) continue;
-
- console.log('[crono food-dialog] found matching search result at row ' + i + ': ' + description);
- // GWT rows don't respond to click(), need to focus and press Enter
- await row.focus({ timeout: 3000 });
- await page.waitForTimeout(300);
- await page.keyboard.press('Enter');
- resultClicked = true;
- break;
- }
+ for (let i = 0; i < allRowCount; i++) {
+ const row = allRows.nth(i);
+ const visible = await row.isVisible().catch(() => false);
+ if (!visible) continue;
- if (!resultClicked) {
- return { success: false, error: '${noExactResultError}' + ${foodNameVar} + '"' };
- }
- await page.waitForTimeout(1000);
+ // Only consider rows with exactly 2 cells (search results table)
+ const cellCount = await row.locator('td').count();
+ if (cellCount !== 2) continue;
+
+ const description = (await row.locator('td').first().textContent().catch(() => '') || '').trim();
+ if (description !== ${foodNameVar}) continue;
+
+ console.log('[crono food-dialog] found matching search result at row ' + i + ': ' + description);
+ // GWT rows don't respond to click(), need to focus and press Enter
+ await row.focus({ timeout: 3000 });
+ await page.waitForTimeout(300);
+ await page.keyboard.press('Enter');
+ resultClicked = true;
+ break;
+ }
- const dialogStillOpen = await page.waitForSelector('text="Add Food to Diary"', { timeout: 1000 })
- .then(() => true)
- .catch(() => false);
- if (!dialogStillOpen) {
- return { success: false, error: 'Add Food dialog closed before details loaded after selecting "' + ${foodNameVar} + '"' };
+ if (!resultClicked) {
+ return { success: false, error: '${noExactResultError}' + ${foodNameVar} + '"' };
+ }
+
+ // Wait for the selected food's details (serving size) to load inside the
+ // dialog before entering any amount; re-open and re-select if it closes.
+ const detailsState = await waitForFoodDetails(${requireServingSize});
+ if (detailsState === 'ready') {
+ detailsLoaded = true;
+ } else if (detailsState === 'closed') {
+ dialogError = ${dialogClosedError};
+ } else {
+ dialogError = '${errorPrefix}Add Food dialog details did not load after selecting "' + ${foodNameVar} + '"';
+ }
+ }
+ if (!detailsLoaded) {
+ return { success: false, error: dialogError + ' (after ${ADD_FOOD_DIALOG_ATTEMPTS} attempts)' };
}
console.log('[crono food-dialog] selected search result and dialog stayed open: ' + ${foodNameVar});
${buildServingSizeCode({ errorPrefix, foodNameVar, itemNameVar, requireServingSize, servingCountVar, alwaysUpdateServingSize, updateServingSize })}
- // Click "Add to Diary" button - wait for panel to render, then find button using evaluate
+ // Click "Add to Diary" button - wait for panel to render, then find the
+ // button inside the Add Food dialog only
await page.waitForTimeout(2000);
- // Find and click the button using page.evaluate
const buttonClicked = await page.evaluate(() => {
- const buttons = document.querySelectorAll('button');
+${FIND_ADD_FOOD_DIALOG}
+ const dialog = findAddFoodDialog();
+ if (!dialog) return false;
+ const buttons = dialog.querySelectorAll('button');
for (const btn of buttons) {
- if (btn.textContent && btn.textContent.trim().toLowerCase() === 'add to diary' && btn.offsetParent !== null && !btn.disabled) {
+ if (btn.textContent && btn.textContent.trim().toLowerCase() === 'add to diary' && isShown(btn) && !btn.disabled) {
btn.click();
return true;
}
}
return false;
- });
+ }, { op: 'clickAddToDiary' });
if (!buttonClicked) {
return { success: false, error: ${addToDiaryErrorCode} };
}
- console.log('[crono food-dialog] found and clicked Add to Diary button for: ' + ${itemNameVar});
console.log('[crono food-dialog] clicked Add to Diary for: ' + ${itemNameVar});
${buildDialogDismissedCode({ itemNameVar, verifyDialogDismissed })}
+${verifyNewEntry ? buildVerifyNewEntryCode({ errorPrefix, foodNameVar, itemNameVar }) : ""}
`;
}
+/**
+ * In-page diary entry counter. Counts visible elements outside the Add Food
+ * dialog that directly hold a text node exactly matching the food name, which
+ * is independent of how Cronometer lays out diary rows. Only the delta matters.
+ */
+function buildCountDiaryEntriesCode(): string {
+ return `
+ async function countDiaryEntries(name) {
+ return page.evaluate(({ name }) => {
+${FIND_ADD_FOOD_DIALOG}
+ const dialog = findAddFoodDialog();
+ const matches = new Set();
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
+ acceptNode: (node) =>
+ node.textContent && node.textContent.trim() === name
+ ? NodeFilter.FILTER_ACCEPT
+ : NodeFilter.FILTER_REJECT,
+ });
+ let node;
+ while ((node = walker.nextNode())) {
+ const el = node.parentElement;
+ if (!el || (dialog && dialog.contains(el)) || !isShown(el)) continue;
+ matches.add(el);
+ }
+ return matches.size;
+ }, { op: 'countDiaryEntries', name });
+ }
+`;
+}
+
+function buildVerifyNewEntryCode(options: {
+ errorPrefix: string;
+ foodNameVar: string;
+ itemNameVar: string;
+}): string {
+ return `
+ // Confirm a NEW entry was created rather than an existing one being edited
+ const entryDeadline = Date.now() + ${NEW_ENTRY_TIMEOUT_MS};
+ let entriesAfter = await countDiaryEntries(${options.foodNameVar});
+ while (entriesAfter <= entriesBefore && Date.now() < entryDeadline) {
+ await page.waitForTimeout(500);
+ entriesAfter = await countDiaryEntries(${options.foodNameVar});
+ }
+ if (entriesAfter <= entriesBefore) {
+ return { success: false, error: '${options.errorPrefix}Add to Diary did not create a new "' + ${options.foodNameVar} + '" entry for ' + ${options.itemNameVar} + ' (' + entriesBefore + ' before, ' + entriesAfter + ' after); an existing entry may have been modified' };
+ }
+ console.log('[crono food-dialog] new diary entry confirmed for ' + ${options.itemNameVar} + ' (' + entriesBefore + ' -> ' + entriesAfter + ')');
+`;
+}
+
function buildServingSizeCode(options: {
errorPrefix: string;
foodNameVar: string;
@@ -261,9 +443,13 @@ function buildServingSizeCode(options: {
if (${servingCondition}) {
let servingFilled = false;
try {
- servingFilled = await page.evaluate((count) => {
+ servingFilled = await page.evaluate(({ count }) => {
+${FIND_ADD_FOOD_DIALOG}
+ // Only ever edit the Add Food dialog's serving input, never a diary entry
+ const dialog = findAddFoodDialog();
+ if (!dialog) return false;
const walker = document.createTreeWalker(
- document.body,
+ dialog,
NodeFilter.SHOW_TEXT,
{ acceptNode: (node) =>
node.textContent && node.textContent.trim() === 'Serving Size'
@@ -275,7 +461,7 @@ function buildServingSizeCode(options: {
if (!textNode) return false;
let container = textNode.parentElement;
- for (let i = 0; i < 5 && container; i++) {
+ for (let i = 0; i < 5 && container && dialog.contains(container); i++) {
const input = container.querySelector('input');
if (input) {
input.focus();
@@ -291,7 +477,7 @@ function buildServingSizeCode(options: {
container = container.parentElement;
}
return false;
- }, ${options.servingCountVar});
+ }, { op: 'fillServingSize', count: ${options.servingCountVar} });
} catch {}
if (!servingFilled) {
diff --git a/src/kernel/quick-add.ts b/src/kernel/quick-add.ts
index 0377e2b..a401466 100644
--- a/src/kernel/quick-add.ts
+++ b/src/kernel/quick-add.ts
@@ -119,6 +119,7 @@ ${buildFoodDialogCode({
alwaysUpdateServingSize: true,
updateServingSize: true,
verifyDialogDismissed: true,
+ verifyNewEntry: true,
})}
}
diff --git a/tests/automation/runner.test.ts b/tests/automation/runner.test.ts
index a33d83f..10606dc 100644
--- a/tests/automation/runner.test.ts
+++ b/tests/automation/runner.test.ts
@@ -15,25 +15,25 @@ import type { AutomationRuntime } from "../../src/automation/types.js";
describe("getQuickAddTimeoutSec", () => {
const now = new Date("2026-09-02T12:00:00");
- it("allows setup time plus one minute for a single macro", () => {
- expect(getQuickAddTimeoutSec({ protein: 45 }, now)).toBe(120);
+ it("allows setup time plus the per-macro budget for a single macro", () => {
+ expect(getQuickAddTimeoutSec({ protein: 45 }, now)).toBe(210);
});
it("scales the timeout for every macro dialog", () => {
expect(
getQuickAddTimeoutSec({ protein: 45, carbs: 90, fat: 55 }, now)
- ).toBe(240);
+ ).toBe(510);
});
it("includes the delay for previous-day navigation", () => {
expect(getQuickAddTimeoutSec({ fat: 55, date: "2026-08-30" }, now)).toBe(
- 126
+ 216
);
});
it("caps date navigation at the same 90 steps as the automation", () => {
expect(getQuickAddTimeoutSec({ protein: 1, date: "2025-01-01" }, now)).toBe(
- 300
+ 390
);
});
});
@@ -60,7 +60,7 @@ describe("quick-add automation timeouts", () => {
await client.addQuickEntry({ protein: 45, carbs: 90, fat: 55 });
- expect(execute.mock.calls.map((call) => call[1])).toEqual([30, 120, 240]);
+ expect(execute.mock.calls.map((call) => call[1])).toEqual([30, 120, 510]);
expect(close).toHaveBeenCalledOnce();
});
});
diff --git a/tests/kernel/quick-add-dialog-retry.test.ts b/tests/kernel/quick-add-dialog-retry.test.ts
new file mode 100644
index 0000000..09e7159
--- /dev/null
+++ b/tests/kernel/quick-add-dialog-retry.test.ts
@@ -0,0 +1,269 @@
+import { describe, expect, it, vi, afterEach } from "vitest";
+import { buildQuickAddCode } from "../../src/kernel/quick-add.js";
+import { buildFoodDialogCode } from "../../src/kernel/food-dialog.js";
+
+type DialogState = "closed" | "loading" | "ready";
+
+interface FakeDiaryOptions {
+ /** Dialog states returned after each search-result selection, one list per dialog attempt. */
+ attempts: DialogState[][];
+ /** Existing diary entries for the searched food before the run. */
+ existingEntries?: number;
+ /** Whether clicking "Add to Diary" creates a new diary entry. */
+ addCreatesEntry?: boolean;
+ /** Diary entries added as a side effect of the dialog closing early. */
+ entriesAddedOnEarlyClose?: number;
+}
+
+/**
+ * Minimal fake Playwright page that drives the generated quick-add code.
+ * Time only advances through page.waitForTimeout so polling loops are
+ * deterministic and fast.
+ */
+function createFakePage(options: FakeDiaryOptions) {
+ let now = 1_000_000;
+ vi.spyOn(Date, "now").mockImplementation(() => now);
+
+ let entries = options.existingEntries ?? 0;
+ let attempt = -1;
+ let probeIndex = 0;
+ const ops: string[] = [];
+ const servingCounts: unknown[] = [];
+
+ const resultRow = {
+ isVisible: vi.fn().mockResolvedValue(true),
+ focus: vi.fn().mockResolvedValue(undefined),
+ locator: vi.fn(() => ({
+ count: vi.fn().mockResolvedValue(2),
+ first: () => ({
+ textContent: vi.fn().mockResolvedValue("Quick Add, Fat"),
+ }),
+ })),
+ };
+
+ const rightClick = vi.fn();
+ const genericLocator = () => {
+ const loc = {
+ filter: () => loc,
+ first: () => loc,
+ count: vi.fn().mockResolvedValue(1),
+ click: vi.fn(async (opts?: { button?: string }) => {
+ if (opts?.button === "right") {
+ rightClick();
+ attempt++;
+ probeIndex = 0;
+ }
+ }),
+ fill: vi.fn().mockResolvedValue(undefined),
+ };
+ return loc;
+ };
+
+ const page = {
+ goto: vi.fn().mockResolvedValue(undefined),
+ waitForLoadState: vi.fn().mockResolvedValue(undefined),
+ url: () => "https://cronometer.com/#diary",
+ waitForTimeout: vi.fn(async (ms: number) => {
+ now += ms;
+ }),
+ waitForSelector: vi.fn().mockResolvedValue(undefined),
+ locator: vi.fn((sel: string) =>
+ sel === "tr"
+ ? { count: vi.fn().mockResolvedValue(1), nth: () => resultRow }
+ : genericLocator()
+ ),
+ getByText: vi.fn(() => ({
+ filter: () => ({
+ first: () => ({ waitFor: vi.fn().mockResolvedValue(undefined) }),
+ }),
+ })),
+ keyboard: {
+ press: vi.fn().mockResolvedValue(undefined),
+ type: vi.fn().mockResolvedValue(undefined),
+ },
+ mouse: { click: vi.fn().mockResolvedValue(undefined) },
+ evaluate: vi.fn(async (_fn: unknown, arg?: Record) => {
+ const op = (arg?.op as string) ?? "unknown";
+ ops.push(op);
+ if (op === "countDiaryEntries") return entries;
+ if (op === "probeAddFoodDialog") {
+ const states = options.attempts[attempt] ?? ["closed"];
+ const state = states[Math.min(probeIndex, states.length - 1)];
+ probeIndex++;
+ if (state === "closed" && probeIndex === 1) {
+ entries += options.entriesAddedOnEarlyClose ?? 0;
+ }
+ return state;
+ }
+ if (op === "fillServingSize") {
+ servingCounts.push(arg?.count);
+ return true;
+ }
+ if (op === "clickAddToDiary") {
+ if (options.addCreatesEntry ?? true) entries++;
+ return true;
+ }
+ throw new Error(`unexpected evaluate op: ${op}`);
+ }),
+ };
+
+ return { page, ops, servingCounts, rightClick };
+}
+
+async function runQuickAdd(page: unknown, fat = 5) {
+ const code = buildQuickAddCode({ fat, meal: "Lunch" });
+ const execute = new Function(
+ "page",
+ `return (async () => { ${code} })()`
+ ) as (page: unknown) => Promise<{ success: boolean; error?: string }>;
+ return execute(page);
+}
+
+describe("quick-add Add Food dialog reliability", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("waits for food details to load before entering the amount", async () => {
+ const fake = createFakePage({
+ attempts: [["loading", "loading", "closed", "loading", "ready"]],
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ await expect(runQuickAdd(fake.page)).resolves.toEqual({ success: true });
+
+ expect(fake.rightClick).toHaveBeenCalledTimes(1);
+ const firstFill = fake.ops.indexOf("fillServingSize");
+ const lastProbe = fake.ops.lastIndexOf("probeAddFoodDialog");
+ expect(lastProbe).toBeLessThan(firstFill);
+ expect(fake.servingCounts).toEqual([5]);
+ });
+
+ it("re-opens and re-selects the food when the dialog closes early", async () => {
+ const fake = createFakePage({
+ attempts: [["closed"], ["loading", "ready"]],
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ await expect(runQuickAdd(fake.page)).resolves.toEqual({ success: true });
+
+ expect(fake.rightClick).toHaveBeenCalledTimes(2);
+ expect(
+ fake.page.keyboard.press.mock.calls.filter(([k]) => k === "Enter")
+ ).toHaveLength(2);
+ expect(fake.servingCounts).toEqual([5]);
+ });
+
+ it("retries when the details never load, then reports after the last attempt", async () => {
+ const fake = createFakePage({
+ attempts: [["loading"], ["closed"], ["closed"]],
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ const result = await runQuickAdd(fake.page);
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain(
+ 'Add Food dialog closed before details loaded after selecting "Quick Add, Fat"'
+ );
+ expect(result.error).toContain("after 3 attempts");
+ expect(fake.rightClick).toHaveBeenCalledTimes(3);
+ expect(fake.ops).not.toContain("fillServingSize");
+ expect(fake.ops).not.toContain("clickAddToDiary");
+ });
+
+ it("does not retry (and duplicate) when an early close already changed the diary", async () => {
+ const fake = createFakePage({
+ attempts: [["closed"], ["ready"]],
+ existingEntries: 1,
+ entriesAddedOnEarlyClose: 1,
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ const result = await runQuickAdd(fake.page);
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("not retrying to avoid a duplicate");
+ expect(fake.rightClick).toHaveBeenCalledTimes(1);
+ expect(fake.ops).not.toContain("clickAddToDiary");
+ });
+
+ it("adds a new entry alongside an existing quick-add entry of the same macro", async () => {
+ const fake = createFakePage({
+ attempts: [["ready"]],
+ existingEntries: 1,
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ await expect(runQuickAdd(fake.page, 15)).resolves.toEqual({
+ success: true,
+ });
+ expect(fake.servingCounts).toEqual([15]);
+ });
+
+ it("fails when adding did not create a new entry (existing entry replaced)", async () => {
+ const fake = createFakePage({
+ attempts: [["ready"]],
+ existingEntries: 1,
+ addCreatesEntry: false,
+ });
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ const result = await runQuickAdd(fake.page, 15);
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain(
+ 'Add to Diary did not create a new "Quick Add, Fat" entry for fat'
+ );
+ expect(result.error).toContain("1 before, 1 after");
+ });
+});
+
+describe("Add Food dialog scoping", () => {
+ const code = buildFoodDialogCode({
+ updateServingSize: true,
+ alwaysUpdateServingSize: true,
+ verifyNewEntry: true,
+ });
+
+ it("only edits the serving size input inside the Add Food dialog", () => {
+ const fill = code.slice(code.indexOf("op: 'fillServingSize'") - 2500);
+ expect(fill).toContain("const dialog = findAddFoodDialog();");
+ expect(fill).toMatch(/createTreeWalker\(\s*dialog,/);
+ expect(fill).toContain("dialog.contains(container)");
+ expect(code).not.toMatch(
+ /createTreeWalker\(\s*document\.body,\s*NodeFilter\.SHOW_TEXT,\s*\{\s*acceptNode: \(node\) =>\s*node\.textContent && node\.textContent\.trim\(\) === 'Serving Size'/
+ );
+ });
+
+ it("only clicks the Add to Diary button inside the Add Food dialog", () => {
+ expect(code).toContain("dialog.querySelectorAll('button')");
+ expect(code).not.toContain("document.querySelectorAll('button')");
+ });
+
+ it("only verifies new entries when requested", () => {
+ expect(code).toContain("did not create a new");
+ expect(buildFoodDialogCode()).not.toContain("did not create a new");
+ });
+
+ it("always guards retries against duplicating an early-committed entry", () => {
+ const logCode = buildFoodDialogCode({ updateServingSize: true });
+ expect(logCode).toContain("const entriesBefore = await countDiaryEntries");
+ expect(logCode).toContain("not retrying to avoid a duplicate");
+ });
+
+ it("prefixes the dialog-closed error", () => {
+ const prefixed = buildFoodDialogCode({ errorPrefix: "Food created but " });
+ expect(prefixed).toContain(
+ "'Food created but Add Food dialog closed before details loaded"
+ );
+ });
+
+ it("counts diary entries via text nodes instead of every element", () => {
+ const counter = code.slice(
+ code.indexOf("async function countDiaryEntries")
+ );
+ expect(counter).toContain("NodeFilter.SHOW_TEXT");
+ expect(counter).not.toContain("querySelectorAll('*')");
+ });
+});