Skip to content

[Prototype, do not merge] feat(samples): add inbox decision rules and Gemini recommendations - #4382

Closed
josemontespg wants to merge 1 commit into
inbox/1-datafrom
inbox/2-decisions
Closed

josemontespg wants to merge 1 commit into
inbox/1-datafrom
inbox/2-decisions

Conversation

@josemontespg

Copy link
Copy Markdown
Collaborator

Internal M1 proof-of-concept sample for @a2ui/embed (A2UI in MCP Apps), not meant to merge. Builds on #4334.

Summary

Second of four PRs for the inbox decisions sample. This one decides what the card shows: which emails need the person, what the agent recommends for each, and what applying a choice does.

Selection is deterministic so the demo stays stable. Gemini only recommends and drafts, in one batched call with a time budget, and rule-based picks cover every type when there is no key, the call fails or an item comes back invalid.

Changes

  • src/decisions/select.ts: rules over labels, senders, headers and markup that pick 12 of the 30 threads and collect the evidence each decision shows (a calendar conflict, a bill's change since last month, an open rate, phishing red flags, free slots).
  • src/decisions/fallback.ts: a rule-based pick, reason and consequence for each of the 8 decision types.
  • src/decisions/plan.ts: the confirm step's plan, its one-sentence summary and the key that ties a confirmation to what was previewed.
  • src/ai/recommend.ts: the Gemini call (gemini-flash-latest, JSON). A tool call waits at most 32 s; a slower answer keeps running and fills a per-decision cache. Email text goes in <untrusted_email> tags it can't close, and a pick that waves through flagged phishing is replaced by "Report phishing". Drafts keep their paragraph breaks.
  • src/mail/store.ts: applies decisions to an in-memory copy of the mailbox (nothing is sent) and undoes them one by one.
  • src/compose/events.ts: action and follow-up schemas.

Verification

  • yarn install --immutable in samples/community, then yarn build and yarn lint pass.
  • yarn test: 35 tests pass, including prompt injection in an email body and a model that falls for it.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new inbox embed MCP sample (a2ui-embed-inbox) that provides deterministic email decision selection, a rule-based fallback recommendation system, and a Gemini-backed recommender with lenient JSON parsing. The feedback highlights several robustness and correctness improvements: handling structured error objects in transient error checks, making retry delays responsive to abort signals, using DST-safe date arithmetic for calendar calculations, and formatting Zod validation errors to avoid exposing raw JSON strings in logs.

Comment on lines +45 to +47
export function isTransient(error: unknown): boolean {
return /\b(429|503)\b|UNAVAILABLE|RESOURCE_EXHAUSTED/.test(String(error));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If error is a structured object (such as a gRPC error or a custom API error) that does not override toString(), String(error) will return "[object Object]". This prevents the regex from matching transient status codes or error messages.

Consider checking the status, statusCode, and message properties of the error object explicitly to make the transient error detection more robust.

export function isTransient(error: unknown): boolean {
  const errObj = error as Record<string, unknown> | null | undefined;
  const status = errObj?.status ?? errObj?.statusCode;
  if (status === 429 || status === 503) return true;
  const message = errObj?.message ?? String(error);
  return /\b(429|503)\b|UNAVAILABLE|RESOURCE_EXHAUSTED/.test(String(message));
}

Comment on lines +50 to +64
export async function withRetries<T>(
request: () => Promise<T>,
signal?: AbortSignal,
delays: readonly number[] = [1000, 3000],
): Promise<T> {
for (let attempt = 0; ; attempt++) {
try {
return await request();
} catch (error) {
const delay = delays[attempt];
if (delay === undefined || !isTransient(error) || signal?.aborted) throw error;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If the signal is aborted while waiting in the setTimeout delay, the promise will not reject immediately. Instead, it will wait for the full delay duration to elapse before checking signal?.aborted in the next iteration.

To ensure responsive cancellation, make the delay abortable by listening to the abort event on the signal.

export async function withRetries<T>(
  request: () => Promise<T>,
  signal?: AbortSignal,
  delays: readonly number[] = [1000, 3000],
): Promise<T> {
  for (let attempt = 0; ; attempt++) {
    try {
      return await request();
    } catch (error) {
      const delay = delays[attempt];
      if (delay === undefined || !isTransient(error) || signal?.aborted) throw error;
      await new Promise<void>((resolve, reject) => {
        const onAbort = () => {
          clearTimeout(timer);
          reject(signal.reason || new Error('Aborted'));
        };
        const timer = setTimeout(() => {
          signal?.removeEventListener('abort', onAbort);
          resolve();
        }, delay);
        signal?.addEventListener('abort', onAbort);
      });
    }
  }
}

Comment on lines +188 to +189
for (const shift of [-1, 1, -2, 2, -3, 3]) {
const from = new Date(Date.parse(start) + shift * 86_400_000);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Adding multiples of 86_400_000 milliseconds assumes that every day is exactly 24 hours. During Daylight Saving Time (DST) transitions, days can be 23 or 25 hours long, which will cause the calculated local time of day to shift (e.g., from 1:00 PM to 12:00 PM or 2:00 PM).

To perform DST-safe date arithmetic, use setDate on a Date instance instead of adding raw milliseconds.

  for (const shift of [-1, 1, -2, 2, -3, 3]) {
    const from = new Date(start);
    from.setDate(from.getDate() + shift);

Comment on lines +335 to +338
for (const entry of z.object({items: z.array(z.unknown())}).parse(answer).items) {
const parsed = ModelItemSchema.safeParse(entry);
if (parsed.success) items.set(parsed.data.key, parsed.data);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When parsing the model response, throwing a raw ZodError directly can expose raw JSON strings to the user or logs. Instead, use safeParse and format any validation errors into a human-readable list of paths and messages.

Suggested change
for (const entry of z.object({items: z.array(z.unknown())}).parse(answer).items) {
const parsed = ModelItemSchema.safeParse(entry);
if (parsed.success) items.set(parsed.data.key, parsed.data);
}
const parsedAnswer = z.object({items: z.array(ModelItemSchema)}).safeParse(answer);
if (!parsedAnswer.success) {
const formattedErrors = parsedAnswer.error.errors
.map(err => err.path.join('.') + ': ' + err.message)
.join(', ');
throw new Error('Validation failed: ' + formattedErrors);
}
const items = parsedAnswer.data.items;
References
  1. Format Zod validation errors into a human-readable list of paths and messages instead of throwing the raw ZodError message, which is a raw JSON string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant