Skip to content

fix: await IDLE loop in email channel disconnect to prevent resource leak#22

Merged
mcheemaa merged 3 commits intoghostwright:mainfrom
jeffklassen:fix/email-idle-loop-resource-leak
Apr 5, 2026
Merged

fix: await IDLE loop in email channel disconnect to prevent resource leak#22
mcheemaa merged 3 commits intoghostwright:mainfrom
jeffklassen:fix/email-idle-loop-resource-leak

Conversation

@jeffklassen
Copy link
Copy Markdown
Contributor

Summary

  • Track the IDLE loop promise so disconnect() can await it before calling logout()
  • Move connectionState = "disconnected" before the abort so the loop's while condition exits immediately
  • Fix the mock IDLE in tests to respond to AbortSignal, matching real ImapFlow behavior
  • Add two tests: disconnect-awaits-loop and rapid disconnect/reconnect doesn't leak

Without this fix, a quick disconnect() + connect() can spawn a second IDLE loop that competes for the INBOX mailbox lock with the first.

Test plan

  • All 824 tests pass (822 existing + 2 new)
  • Lint clean
  • Manual: connect email channel, disconnect, reconnect rapidly — verify single IDLE loop in logs

jeffklassen and others added 3 commits April 1, 2026 09:02
…leak

startIdleLoop() was fire-and-forget, so disconnect() could return
before the loop released the mailbox lock. A rapid disconnect/reconnect
cycle could spawn concurrent IDLE loops competing for the same lock.

Track the loop promise and await it in disconnect(), and set
connectionState before aborting so the loop exits immediately.
@mcheemaa mcheemaa self-requested a review April 5, 2026 03:46
@mcheemaa mcheemaa merged commit cb857d2 into ghostwright:main Apr 5, 2026
1 check passed
mutusfa pushed a commit to mutusfa/phantom that referenced this pull request Apr 14, 2026
…p-resource-leak

fix: await IDLE loop in email channel disconnect to prevent resource leak
imonlinux added a commit to imonlinux/phantom that referenced this pull request Apr 24, 2026
Complete security review and implementation of fixes for Nextcloud Talk
integration based on comprehensive security audit findings.

HIGH PRIORITY fixes (security-critical):
- ghostwright#1: Implement replay attack protection with LRU cache (5-minute TTL)
- ghostwright#2: Add 64KB request size limit before body buffering
- ghostwright#4: Replace Date.now() with crypto.randomUUID() for unique IDs
- ghostwright#7: Fix JSON unwrap logic for ActivityStreams Note objects
- ghostwright#11: Replace 'Error:' text sniffing with runtime error events

Logic and security fixes:
- ghostwright#3: Fix msgId/msg name collision in error handling
- ghostwright#5: Improve parseConversationId to handle colons in tokens
- ghostwright#6: Reject webhooks without target.id instead of silent fallback
- ghostwright#8: Normalize emoji to avoid variation selector validation issues
- ghostwright#9: Handle 404/409 reaction responses as success conditions
- ghostwright#10: Make setReaction return boolean for proper error handling
- ghostwright#12: Improve bot loop guard with actorId checking

Best practices and polish:
- ghostwright#13: Make port configurable instead of hardcoded 3200
- ghostwright#14: Move webhookPath default normalization to constructor
- ghostwright#15: Fix health check path precedence (check webhook first)
- ghostwright#16: Add exponential backoff retry for 5xx/429 responses
- ghostwright#17: Add URL validation and encoding for talkServer config
- ghostwright#18: Document HMAC signing asymmetry (inbound vs outbound)
- ghostwright#20: Import randomUUID explicitly from node:crypto
- ghostwright#21: Add reactions: true to channel capabilities
- ghostwright#22: Namespace environment variables with NEXTCLOUD_ prefix

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
mcheemaa added a commit that referenced this pull request May 2, 2026
…k DM renderer (Slice 15a) (#122)

The agent's first action on a fresh tenant is now do_first_hour_of_work,
a single-Sonnet-turn scaffold-driven runner that fires from main()
after the intro DM lands. By the time the user finishes setup, their
named persona has already pulled their morning, drafted their replies,
and DMed them with one click to approve.

Architect: phantom-cloud-deploy/local/2026-05-03-slice-15-first-hour-
of-work-architect.md.

What ships in this PR:

- src/persona/work-plans.ts: code-vendored TypeScript mirror of the
  canonical persona-work-plans.json fixture (slice 15d-fixture, PR
  #22 on phantom-cloud-deploy). Seven personas locked: sdr-lilian,
  eng-cos-marcus, am-sloane, bdr-theo, sales-vp-priya, gtm-eng-ryan,
  founder-asst-adrian. Byte-equal with the canonical for persona_id
  literals and required_integrations arrays.
- src/persona/types.ts: FirstHourOfWorkInput/Output, DraftKind,
  ReasonCode (11-code taxonomy locked at architect §7.2).
- src/persona/scaffold-prompt.ts: the verbatim 4-step prompt from
  architect §1.4 with persona-driven substitutions.
- src/persona/runner.ts: end-to-end orchestrator. Resolves grants
  via the env reader, filters required-integrations against the
  resolved set, builds the prompt scaffold, races the LLM call
  against a 60s AbortController, parses the JSON envelope, persists
  drafts, sends the Block Kit DM, emits the five audit events.
- src/persona/llm-caller.ts: production LlmTurnCaller wrapping
  runtime.handleMessage with a first-hour: session id prefix and
  the JSON envelope parser.
- src/persona/failure-modes.ts: per-persona DM bodies for the six
  failure modes (no_integrations_granted, all_pulls_zero_data,
  llm_error_mid_flow, zero_drafts_from_nonzero_data, integration_
  auth_expired, sixty_second_cap_hit). Verbatim from architect §6.
- src/persona/draft-store.ts: SQLite helpers for the firstboot ledger
  and phantom_drafts table. Status transitions pending -> approved
  -> sent.
- src/persona/firstboot-hook.ts: the index.ts entry point. NO-OP
  when PHANTOM_PERSONA_ID is unset; idempotent on the firstboot
  ledger.
- src/integrations/grants.ts: env-based reader of PHANTOM_GRANTED_
  INTEGRATIONS with slack always granted (the wizard's slot 10
  install is firstboot-baked).
- src/channels/slack/render-first-hour-dm.ts: Block Kit renderer
  for the standard, fallback, and partial DM variants. Action_id
  pattern phantom:draft:{draft_id}:{action} per architect §5.4.
- src/channels/slack/edit-modal.ts: views.open payload for the
  draft edit modal.
- src/db/schema.ts: additive migrations (52-58) for firstboot_state
  ledger columns and the new phantom_drafts table. Idempotent per
  the migration-safety contract.
- src/channels/slack-actions.ts: Bolt regex handler for the
  phantom:draft:{id}:{action} action_id pattern; per-draft buttons
  flip to context blocks on click.
- src/channels/slack.ts: extends sendDm to accept optional Block Kit
  blocks (the HTTP transport already accepted them; Socket Mode
  catches up).
- src/index.ts: fires the firstboot hook after the intro DM lands.
- .github/workflows/ci.yml: persona-work-plans drift verifier step.
  Runs the cross-repo guard from phantom-cloud-deploy in strict mode
  once the canonical fixture lands on main.
- CLAUDE.md: First hour of work invariant section covering the
  contract, idempotency, the action_id wire pattern, and the 60s
  hard cap.

Coverage:

- 111 new tests across work-plans, scaffold-prompt, runner, failure-
  modes, llm-caller, render-first-hour-dm, edit-modal, draft-store,
  firstboot-hook, grants. Snapshot pins on the Block Kit JSON for
  Lilian's full DM and the per-persona header/footer text shape.
- Happy path: drafts persist, DM lands, all five audit events fire
  in order (start, pulls, drafts, dm, finish).
- Each of the six failure modes covered by its own runner test:
  no_integrations_granted, all_pulls_zero_data, llm_error_mid_flow,
  zero_drafts_from_nonzero_data, integration_auth_expired, sixty_
  second_cap_hit. Plus slack_post_failed and persona_unknown.
- Defense-in-depth: a happy-path cycle across all seven personas
  pinning that none degrades to a fallback DM.

Pre-push gate: bun typecheck clean, bun test 2537 pass / 0 fail
(+111 from this slice), bun lint clean.
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.

2 participants