Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Forwarding an email with only an FYI note no longer opens a waiting-on-them loop (GST-2899) (#9577)

Garry Tan8f4f48d8e35c
diff --git a/behavior-changes.d/forward_fyi_no_loop_gst2899.md b/behavior-changes.d/forward_fyi_no_loop_gst2899.md
new file mode 100644
index 0000000000..5a772d9ece
--- /dev/null
+++ b/behavior-changes.d/forward_fyi_no_loop_gst2899.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+A forwarded email whose own note asks nothing ("FYI, see below.") no longer opens a waiting-on-them loop just because the forwarded message contains a question. Since #8941 a forward keeps its whole body, and the loop detector read a question mark anywhere in it as your ask; it now reads only the note above the forward separator (Gmail's "Forwarded message" line or Apple Mail's "Begin forwarded message:"). The same rule applies to mail sent to you, so your "Thanks!" to someone's FYI forward counts as the reply again. A forward whose note does ask ("Can you take this one?") still opens a loop, and forwards still keep their full content in the brain. A loop that opened this way before the upgrade stays open until the other person replies or you close it yourself with gbrain loops drop <id> (gbrain waiting lists it).
diff --git a/changelog.d/capy-forward-fyi-no-loop.md b/changelog.d/capy-forward-fyi-no-loop.md
new file mode 100644
index 0000000000..f4ce720a23
--- /dev/null
+++ b/changelog.d/capy-forward-fyi-no-loop.md
@@ -0,0 +1,8 @@
+**Forwarding an email with only an FYI note no longer opens a "waiting on them" loop.**
+
+### Fixed
+- A forward whose own note asks nothing ("FYI, see below.") over someone else's question opened an `unanswered_outbound` loop, against the rule in docs/guides/open-loops.md that an FYI or forward without a question opens nothing. Since #8941 a forward keeps its whole body, and the loop detector counted a question mark anywhere in that body. It now reads only the note above the forward separator (Gmail's "Forwarded message" line or Apple Mail's "Begin forwarded message:"). A forward whose note does ask still opens a loop, and forwards still keep their full content.
+- The same reading applies to mail sent to you, so a "Thanks!" reply to someone's FYI forward counts as the reply again instead of leaving a reply-owed loop open.
+- A loop that already opened this way is not closed by the upgrade. It closes when the other person replies, or with `gbrain loops drop <id>`.
+
+<!-- behavior-change: forward_fyi_no_loop_gst2899 -->
diff --git a/docs/architecture/key-files/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.md
index f2cbca9ed8..8948f8d5e0 100644
--- a/docs/architecture/key-files/open-loops-engine.md
+++ b/docs/architecture/key-files/open-loops-engine.md
@@ -9,7 +9,7 @@ close semantics). The Gmail sweep that feeds both lanes is in
- `src/core/google/loops-exclusion.ts` — the user's own label exclusion for the open-loop engine (#5445). `excludedLabelTokens` reads the source's `g_loops_exclude_labels`, else the brain-wide `loops.extraction_exclude_labels` (no merge); `resolveExcludedLabels` matches tokens against the account's label catalog (id verbatim, name case-insensitively; with no catalog only id-shaped tokens resolve) into a `LoopsExclusionPolicy { tokens, ids, unresolved }`, where a non-empty `unresolved` means FAIL CLOSED for new paid extraction. `resolveSweepExclusion` (`loops-enqueue.ts`) runs it once per Gmail sweep (one `GmailClient.getLabels` call when anything is configured), logs each unresolved name, and `storeLoopsExclusion` keeps the resolution in `op_checkpoints` (op `loops-exclusion`, keyed like the loop outcomes) so `loadLoopsExclusionPolicy` can apply the policy without a Gmail client at the two late sites: `runLoopsExtract` (skips `excluded_label`, throws retryable `excluded_label_unresolved`) and `openDueGraceHold` (`'excluded'` drops the hold, `'deferred'` keeps it). A stored resolution is reused only for the same token list; changed tokens fall back to id-only until the next sweep. The policy gates `loopExtractionEligibility` right after SPAM/TRASH and before the owner override (reasons `excluded_label` / `excluded_label_unresolved` in the sweep's counters), `withLabelExclusion` strips the opens from a `detectThreadLoop` verdict (closes untouched), `recordGraceVerdict` records no hold for an excluded thread, `runLoopsCatchup` skips with `excluded_label_unresolved`, and `enqueueLoopsExtraction` reports the same `skipped_reason` ahead of `no_candidates`. The leaf is `excluded` from connector identity. Tests: `test/loops-exclusion.test.ts`, `test/google-source-reconcile.test.ts` ("label exclusion (#5445)"), `test/loops-extract-run.serial.test.ts` ("#5445 execution-time").
- `src/core/google/loops-spend.ts` — the daily spend cap on loop extraction (wave 14 P4.6b): `loops.extraction_max_usd_per_day` (default $2.00, validated at `config set` by `validateLoopsSpendConfigValue`; a stored value is `user`-sourced). `loopsSpendGate` is what both enqueue sites call: it reads the cap and the day's group spend (`readGroupSpend` on `group:<day group>`) and returns the `SpendAuthorization` to stamp (`loopsExtractSpendAuthorization`: kind `authorized`, command `loops_extract`, via `preapproval`, one deterministic UUID per UTC day from `loopsSpendGroupId`) or the reason to queue nothing (`daily_spend_cap` at the cap, `spend_cap_zero` at 0). The sweep's `enqueueLoopsExtraction` and the catch-up's enqueue pass that record through `MinionQueue.add`'s trusted `spendAuthorization` option, so the worker runs each job under `runWithJobSpend` (spend-authorization.ts): every provider attempt reserves against the group and settles its usage; refusal before the call is `cost_cap_exceeded`, recorded on the row. An unreadable meter admits the enqueue (the worker still enforces). Tests: `test/loops-extract-spend-cap.test.ts`.
- `src/core/google/counterparty.ts` — where a loop's counterparty page is (#5504, wave 14 P4.1). `resolveCounterparty(engine, sourceId, { name, email })` tries the loop's OWN source first through `resolveEntitySlugWithSource` (name, then email; never the slugify fallback), and only then crosses a source boundary by identity: an `entity_identities` canonical member in another source (`identity_canonical`, which also redirects an own-source stub to its canonical twin) or the exact email as a `page_aliases` row on exactly one live page in exactly one other source (`email_alias`). A display name never crosses, a tie (two other sources) stays unresolved and the loop keeps a NULL counterparty rather than a guess. Both writers (`loop-detect.ts` `upsertThreadLoop`, `loops-extract.ts`) stamp the result into `open_loops.counterparty_source_id` and point the `owes_to` / `awaiting_reply_from` edge at the page's source; the commitment fact stays in the connector source. Readers confine with `COALESCE(counterparty_source_id, source_id)` (`COUNTERPARTY_SOURCE_SQL`): a row written before v236 reads as its own source. `src/core/loops/loops-schema.ts` is the leaf the migration and the store share (column DDL + the partial index `open_loops_counterparty_source_idx`).
-- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops; positively automated mail (`isPositivelyAutomated`) and, with the opt-in `LoopDetectPolicy.ownerWroteTo`, `CATEGORY_UPDATES` mail from someone the owner never wrote to return `withheld: {reason, counterpartyEmail}` instead of an open (#5012; closes are unaffected) — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions. `applyThreadLoopVerdict` builds the policy through `ownerWroteToFor` and settles a mute re-check thread (`settleMuteRecheck`) whose verdict neither opened nor closed its queued loops; `invalidateSuppressionCache` drops the per-engine suppression cache after a mute or unmute.
+- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7) and reads only the note above a forward separator (`textAboveForward` in `google-render.ts`), so the message a forward carries never counts as the sender's question; each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops; positively automated mail (`isPositivelyAutomated`) and, with the opt-in `LoopDetectPolicy.ownerWroteTo`, `CATEGORY_UPDATES` mail from someone the owner never wrote to return `withheld: {reason, counterpartyEmail}` instead of an open (#5012; closes are unaffected) — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions. `applyThreadLoopVerdict` builds the policy through `ownerWroteToFor` and settles a mute re-check thread (`settleMuteRecheck`) whose verdict neither opened nor closed its queued loops; `invalidateSuppressionCache` drops the per-engine suppression cache after a mute or unmute.
- `src/core/google/loops-reciprocity.ts` — the opt-in Updates reciprocity rule (#5012): key `loops.updates_require_reciprocity` (default false; `validateLoopsReciprocityConfigValue` at `config set`). `ownerWroteToFor(engine, source, myAddresses)` returns null when off; on, the addresses in `participants` of the source's email pages whose `senders` include an owner address, cached per engine and source for 10 minutes. Tests: `test/loops-noise-5012.test.ts`, `test/loops-noise-5012-store.test.ts` (+ Postgres twin).
- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>` of thread, direction and the normalized verbatim quote, the text only when no quote verified; same-quote items in one response collapse, and a row already recorded for the quote keeps its key, #7289), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code; a failed facts write is logged with slug, source, the refusal code and a bounded error, never the commitment text, and the loop row still lands; on a strict source a counterparty with no page under an exact page rule, or whose access rules cannot be read, is such a refusal, `git_home_required` or `access_policy_pending`, whose message names the entity's page, GST-2635), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, `Auto-Submitted`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.
- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. `openedAt` sets `opened_at` (default now()); an open row keeps the earlier of its stored and incoming value, a reopened row takes the incoming one. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `listOpenLoops` takes an optional `id` that composes with the status/type/counterparty filters and never replaces the source scope; `counterpartySourceId` narrows a `counterparty` slug match to the source the page lives in (`COALESCE(counterparty_source_id, source_id)`), leaving an email match untouched (#5504). `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing and returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success). #5012: `closeMutedLoops` closes (or, without apply, lists) the open reply-owed loops a mute covers as `dropped` / `closed_by: muted`, and the upsert never updates a `muted` row for the same counterparty; `requeueMutedLoops` hands an unmuted loop no other suppression covers to `closed_by: mute_recheck` (no thread: `unmuted`, reported `unverifiable`), which the upsert reopens and `closeThreadLoops` closes on the re-check's verdict, and `settleMuteRecheck` marks `unmuted` when neither happens; `muteRecheckThreads` feeds `loadSuppressions().recheckThreads` and the sweep seed; `listSenderInboundLoops` backs `loops drop sender`.
diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.md
index 40e9dc5b30..ed5bcacf02 100644
--- a/docs/guides/open-loops.md
+++ b/docs/guides/open-loops.md
@@ -29,6 +29,14 @@ zero LLM, free, always on). For every synced Gmail thread:
keeps running. "Will do" counts as a reply.
- a question mark inside a link (`https://docs.example.com/view?id=42`) is
not a question, so an FYI that only shares a link opens nothing.
+- a forward is judged by the note above the forwarded message. "FYI, see
+ below." over someone else's question asks nothing, so it opens no loop (and
+ a "Thanks!" answers one sent to you); "Can you take this one?" above the
+ same forward is an ask. The note ends at Gmail's "Forwarded message" line
+ or Apple Mail's "Begin forwarded message:"; a forward in any other format
+ (a translated separator) is still judged by its whole body. A classic
+ Outlook forward is stored only up to its "Original Message" line, so it
+ is judged by its note too.
- "unanswered" is measured from the oldest unanswered message since the
last turn flip (the first one addressed to you, or your first question),
so a nudge or follow-up never restarts the clock — a request that waited
diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.ts
index 7038004e63..3545ba0d89 100644
--- a/src/core/google/google-render.ts
+++ b/src/core/google/google-render.ts
@@ -176,6 +176,21 @@ export function htmlToText(html: string): string {
return t.trim();
}
+function isForwardSeparator(trimmedLine: string): boolean {
+ return /^-{2,}\s*Forwarded message\s*-{2,}$/i.test(trimmedLine) || /^Begin forwarded message:$/i.test(trimmedLine);
+}
+
+/**
+ * The sender's own words in a stored message body: the text above the first
+ * forward separator. `trimQuotedReply` keeps what follows it (#8719), and
+ * that part was written by someone else.
+ */
+export function textAboveForward(text: string): string {
+ const lines = text.split('\n');
+ const at = lines.findIndex((l) => isForwardSeparator(l.trim()));
+ return at < 0 ? text : lines.slice(0, at).join('\n');
+}
+
/**
* Trim quoted-reply tails: trailing '>'-quoted runs and the "On ... wrote:"
* marker line and everything after it. Conservative — only the TAIL is cut,
@@ -189,7 +204,7 @@ export function trimQuotedReply(text: string): string {
let cut = lines.length;
for (let i = 0; i < lines.length; i++) {
const l = lines[i].trim();
- if (/^-{2,}\s*Forwarded message\s*-{2,}$/i.test(l) || /^Begin forwarded message:$/i.test(l)) return text.trim();
+ if (isForwardSeparator(l)) return text.trim();
if (/^On .{4,80} wrote:$/.test(l) || /^-{2,}\s*Original Message\s*-{2,}$/i.test(l)) {
cut = i;
break;
diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.ts
index 57e5a45963..827ef6f0bb 100644
--- a/src/core/google/loop-detect.ts
+++ b/src/core/google/loop-detect.ts
@@ -25,7 +25,8 @@
* - self-threads (all participants are my addresses) never open loops
* - CC-only inbound does not owe a reply (must be in To:)
* - outbound without a question mark is FYI, not an ask; a question mark
- * inside a link (?id=42) is not a question
+ * inside a link (?id=42) is not a question, and neither is one in the
+ * message a forward carries: only the note above the separator counts
* - my acknowledgement-only reply ("Thanks!", "Got it") to a question is
* not an answer: it neither closes the reply-owed loop nor flips the turn
* ("Will do" is a commitment and still counts as the reply)
@@ -49,7 +50,7 @@ import {
type SuppressionSet,
} from '../loops/loops-store.ts';
import { resolveCounterparty, type ResolvedCounterparty } from './counterparty.ts';
-import { isCalendarSystemMail, isNoiseSender, isPositivelyAutomated } from './google-render.ts';
+import { isCalendarSystemMail, isNoiseSender, isPositivelyAutomated, textAboveForward } from './google-render.ts';
export { isPositivelyAutomated } from './google-render.ts';
import { hasBulkCategory } from './gmail-categories.ts';
import { isExcludedByLabels, NO_EXCLUSION, pageLabelIds, type LoopsExclusionPolicy } from './loops-exclusion.ts';
@@ -114,9 +115,13 @@ function ageHours(ms: number, now: Date): number {
const URL_RE = /\b(?:https?:\/\/|www\.)\S+/gi;
-/** A question mark outside any link. */
+/**
+ * A question mark outside any link, in the sender's own words: the message a
+ * forward carries below its separator is someone else's, so its question is
+ * not this sender's ask.
+ */
export function asksQuestion(text: string): boolean {
- return text.replace(URL_RE, '').includes('?');
+ return textAboveForward(text).replace(URL_RE, '').includes('?');
}
const ACK_ONLY_RE =
diff --git a/test/google-loop-detect.test.ts b/test/google-loop-detect.test.ts
index 737cf4a7db..c14dac77b2 100644
--- a/test/google-loop-detect.test.ts
+++ b/test/google-loop-detect.test.ts
@@ -23,6 +23,7 @@ import {
import type { SuppressionSet } from '../src/core/loops/loops-store.ts';
import { BULK_CATEGORY_LABELS } from '../src/core/google/gmail-categories.ts';
import { BULK_CATEGORY_LABELS as EXTRACT_LANE_BULK_CATEGORY_LABELS } from '../src/core/google/loops-extract.ts';
+import { trimQuotedReply } from '../src/core/google/google-render.ts';
import type { GmailMessageMeta, GmailThreadData } from '../src/core/google/types.ts';
// Frozen clock — every age below is relative to this instant, so the corpus
@@ -990,3 +991,93 @@ describe('#5012 positively automated mail and the opt-in Updates reciprocity rul
expect(v.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);
});
});
+
+describe('forwarded mail is judged by the note above the forward (#8941 keeps the forwarded body)', () => {
+ // Bodies go through the same trim the Gmail client applies, so these rows
+ // pin both halves: the forward keeps its whole body, and only the sender's
+ // own note decides whether it asks anything.
+ const GMAIL_FORWARD = [
+ '---------- Forwarded message ---------',
+ 'From: Carol Example <[email protected]>',
+ 'Date: Mon, Aug 17, 2026 at 9:00 AM',
+ 'Subject: Venue for the offsite',
+ 'To: Me Example <[email protected]>',
+ '',
+ 'Which venue did we settle on for the offsite? I need a headcount by Friday.',
+ ].join('\n');
+ const APPLE_FORWARD = [
+ 'Begin forwarded message:',
+ '',
+ 'From: Carol Example <[email protected]>',
+ 'Subject: Venue for the offsite',
+ '',
+ 'Which venue did we settle on for the offsite?',
+ ].join('\n');
+ const forwardBody = (note: string, forwarded = GMAIL_FORWARD) => trimQuotedReply(note ? `${note}\n\n${forwarded}` : forwarded);
+ const myForward = (note: string, ageHours = 96, forwarded = GMAIL_FORWARD) =>
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours, sent: true, subject: 'Fwd: Venue for the offsite', body: forwardBody(note, forwarded) });
+
+ test('the forward keeps the forwarded message in its body', () => {
+ expect(forwardBody('FYI, see below.')).toContain('Which venue did we settle on');
+ expect(forwardBody('See below.', APPLE_FORWARD)).toContain('Which venue did we settle on');
+ });
+
+ for (const [name, m] of [
+ ['a Gmail forward with an FYI note over someone else\'s question', myForward('FYI, see below.')],
+ ['an Apple Mail forward with a "See below." note', myForward('See below.', 96, APPLE_FORWARD)],
+ ['a forward with no note at all', myForward('')],
+ ['an FYI note that only shares a link', myForward('FYI, context here: https://docs.example.com/view?id=42')],
+ ] as const) {
+ test(`${name} opens no waiting-on-them loop`, () => {
+ const v = detectThreadLoop(thread([m]), MY, NOW);
+ expect(v.open).toEqual([]);
+ expect(v.held).toBeUndefined();
+ });
+ }
+
+ test('a forward whose own note asks a question still opens the loop', () => {
+ const v = detectThreadLoop(thread([myForward('Can you take this one?')]), MY, NOW);
+ expect(v.open).toHaveLength(1);
+ expect(v.open[0].loopType).toBe('unanswered_outbound');
+ expect(v.open[0].counterpartyEmail).toBe('[email protected]');
+ });
+
+ test('my question after an FYI forward opens at the question, not at the forward', () => {
+ const ask = msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 80, sent: true, body: 'Did you get a chance to look?' });
+ const v = detectThreadLoop(thread([myForward('FYI, see below.', 400), ask]), MY, NOW);
+ expect(v.open).toHaveLength(1);
+ expect(v.open[0].openedMs).toBe(ask.internalDateMs);
+ });
+
+ test('their FYI forward to me is answered by my "Thanks!"', () => {
+ const v = detectThreadLoop(
+ thread([
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, subject: 'Fwd: Venue for the offsite', body: forwardBody('FYI, see below.') }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' }),
+ ]),
+ MY,
+ NOW,
+ );
+ expect(v.open).toEqual([]);
+ expect(v.close).toEqual(['unanswered_inbound']);
+ });
+
+ test('their forward that asks me in its note still owes a real answer', () => {
+ const v = detectThreadLoop(
+ thread([
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, subject: 'Fwd: Venue for the offsite', body: forwardBody('Can you answer Carol?') }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Thanks!' }),
+ ]),
+ MY,
+ NOW,
+ );
+ expect(v.open).toHaveLength(1);
+ expect(v.open[0].loopType).toBe('unanswered_inbound');
+ });
+
+ test('asksQuestion reads only the text above a forward separator', () => {
+ expect(asksQuestion(forwardBody('FYI, see below.'))).toBe(false);
+ expect(asksQuestion(forwardBody('Thoughts?'))).toBe(true);
+ expect(asksQuestion('Is "---------- Forwarded message ---------" the separator Gmail writes?')).toBe(true);
+ });
+});