Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: join a Google Calendar meeting from the event drawer (#6289)
[._.]/ Adam Eivyad3aafaf304d
diff --git a/client/src/components/calendar/EventDetail.jsx b/client/src/components/calendar/EventDetail.jsxindex 50a47ab259..69f9f54a62 100644--- a/client/src/components/calendar/EventDetail.jsx+++ b/client/src/components/calendar/EventDetail.jsx@@ -1,5 +1,6 @@-import { MapPin, Clock, Users, Repeat, CalendarDays } from 'lucide-react';+import { MapPin, Clock, Users, Repeat, CalendarDays, Video } from 'lucide-react';import { formatEventDateTime } from '../../utils/formatters';+import { isHttpUrl } from '../../utils/urlNormalize';import Drawer from '../Drawer';const RSVP_STYLES = {@@ -10,6 +11,19 @@ const RSVP_STYLES = {};export default function EventDetail({ event, onClose }) {+ // Re-check the scheme at render time as well as at sync time: a cached event+ // predates today's write-side validation, so a stored `javascript:` URL must+ // never reach an href. A meeting you cancelled or declined gets no join+ // action; a past one still does, since people rejoin recordings and overruns.+ //+ // The cancelled/declined terms are NOT redundant with the list filter: the+ // four parent views read `GET /api/calendar/events`, which drops those+ // events, but `GET /api/calendar/events/:accountId/:eventId` serves them+ // unfiltered — so any deep link or future single-event fetch reaches here+ // with them intact.+ const canJoin =+ isHttpUrl(event.meetingUrl) && !event.isCancelled && event.myStatus !== 'declined';+return (<Drawer open onClose={onClose} title={event.title} closeLabel="Close"><div className="space-y-4">@@ -35,6 +49,19 @@ export default function EventDetail({ event, onClose }) {</div></div>+ {/* Join meeting */}+ {canJoin && (+ <a+ href={event.meetingUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center justify-center gap-2 min-h-[44px] px-4 rounded-lg bg-port-accent/20 text-port-accent border border-port-accent/40 text-sm font-medium hover:bg-port-accent/30 transition-colors"+ >+ <Video size={16} />+ Join meeting+ </a>+ )}+{/* Location */}{event.location && (<div className="flex items-start gap-3">diff --git a/client/src/components/calendar/EventDetail.test.jsx b/client/src/components/calendar/EventDetail.test.jsxindex 7fbc80f99d..4029e4fbbd 100644--- a/client/src/components/calendar/EventDetail.test.jsx+++ b/client/src/components/calendar/EventDetail.test.jsx@@ -28,3 +28,84 @@ describe('EventDetail', () => {expect(onClose).toHaveBeenCalledTimes(1);});});++// #6289: the drawer's only meeting action. Its two failure modes are opposite —+// hiding a link the user has (the feature silently doesn't exist) and rendering+// one it must not (an unsafe scheme, or a meeting that isn't happening).+describe('EventDetail — Join meeting action (#6289)', () => {+ const withMeeting = (overrides = {}) => ({+ ...baseEvent,+ meetingUrl: 'https://meet.example.com/room-abc',+ ...overrides,+ });++ const joinLink = () => screen.queryByRole('link', { name: /join meeting/i });++ // Querying by the `link` role is also the keyboard-accessibility assertion:+ // it matches only a real <a href>, which is natively focusable and+ // Enter-activatable, where a div-with-onClick would not match at all.+ it('renders a safe, separately-opening link for an event with a meeting URL', () => {+ render(<EventDetail event={withMeeting()} onClose={() => {}} />);++ const link = joinLink();+ expect(link).toBeTruthy();+ expect(link.getAttribute('href')).toBe('https://meet.example.com/room-abc');+ expect(link.getAttribute('target')).toBe('_blank');+ // noopener keeps the opened tab from reaching back into PortOS via window.opener.+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');+ expect(link.className).toContain('min-h-[44px]');+ });++ it('opening the meeting neither closes the drawer nor changes the selected event', () => {+ const onClose = vi.fn();+ render(<EventDetail event={withMeeting()} onClose={onClose} />);++ // Swallow the navigation the anchor would otherwise perform: happy-dom+ // would try to actually fetch the URL, turning a unit test into a DNS+ // lookup. React still sees the bubbled click, which is what's under test.+ const swallow = (e) => e.preventDefault();+ document.addEventListener('click', swallow);+ fireEvent.click(joinLink());+ document.removeEventListener('click', swallow);++ expect(onClose).not.toHaveBeenCalled();+ // The drawer is still mounted with the same event.+ expect(screen.getByText('Standup')).toBeTruthy();+ expect(joinLink()).toBeTruthy();+ });++ // `canJoin` deliberately carries no time term — people rejoin overruns and+ // recordings — so this guards against a later change narrowing it to upcoming.+ it('shows the action for a meeting that has already started', () => {+ render(<EventDetail+ event={withMeeting({ startTime: '2020-01-01T15:00:00.000Z', endTime: '2020-01-01T15:30:00.000Z' })}+ onClose={() => {}}+ />);++ expect(joinLink()).toBeTruthy();+ });++ it.each([+ ['no meeting URL', { meetingUrl: null }],+ ['an unsafe scheme', { meetingUrl: 'javascript:alert(1)' }],+ ['a cancelled meeting', { meetingUrl: 'https://meet.example.com/room-abc', isCancelled: true }],+ ['a declined meeting', { meetingUrl: 'https://meet.example.com/room-abc', myStatus: 'declined' }],+ ])('renders no join action for %s', (_label, overrides) => {+ render(<EventDetail event={{ ...baseEvent, ...overrides }} onClose={() => {}} />);+ expect(joinLink()).toBeNull();+ });++ it('never renders a link built from the location or description', () => {+ render(<EventDetail+ event={{+ ...baseEvent,+ location: 'https://meet.example.com/from-location',+ description: 'Dial in at https://meet.example.com/from-description',+ }}+ onClose={() => {}}+ />);++ expect(joinLink()).toBeNull();+ expect(screen.queryAllByRole('link')).toHaveLength(0);+ });+});diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex a94d00f3d0..89768caf5e 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -132,7 +132,7 @@ Capture thoughts, build personal memory graphs, model your identity and taste, p| **Third-Party Import** | `/brain/import` | Ingests ChatGPT and OpenAI export archives into structured Brain memory. | — || **Activity Timeline** | `/timeline` | Unified chronological human activity ledger aggregating events from iMessage, Signal, WhatsApp, Spotify, Discord, YouTube, and Calendar. | — || **Tribe Relationship Manager** | `/tribe` | Dunbar-number social network management, relationship health scores, care cadence reminders, and contact resolution. | — |-| **Multi-Scale Calendar** | `/calendar/*` | Time management across Agenda, Day, Week, Month, and Lifetime perspectives, periodic reflection reviews, and external sync (iCal/CalDAV/Google). | — |+| **Multi-Scale Calendar** | `/calendar/*` | Time management across Agenda, Day, Week, Month, and Lifetime perspectives, periodic reflection reviews, external sync (iCal/CalDAV/Google), and a one-click **Join meeting** action on event details for Google Calendar events that carry a conference link. | — || **Digital Twin Profile & Identity** | `/digital-twin/overview`, `/digital-twin/identity`, `/digital-twin/autobiography`, `/digital-twin/personas`, `/digital-twin/taste`, `/digital-twin/goals` | Core identity attributes, autobiography, dynamic personas (professional, casual, creative), quantified aesthetic taste, and personal goals. | [Digital Twin](./digital-twin.md), [Identity System](./identity-system.md) || **Twin Presence & Avatars** | `/digital-twin/appearance`, `/digital-twin/avatar-bio`, `/digital-twin/voice` | Visual appearance reference photos, live avatar bios (HeyGen, Tavus, Simli, ElevenLabs), and comparative spoken-vs-written voice fingerprinting. | [Digital Twin](./digital-twin.md) || **Personality & Assessment** | `/digital-twin/personality`, `/digital-twin/test` | Big Five (OCEAN) quantitative trait scoring, values hierarchy, model sycophancy comparison radar, and automated behavioral test suites. | [Digital Twin](./digital-twin.md), [Soul System](./soul-system.md) |diff --git a/scripts/migrations/343-calendar-meeting-url.js b/scripts/migrations/343-calendar-meeting-url.jsnew file mode 100644index 0000000000..15cde96b95--- /dev/null+++ b/scripts/migrations/343-calendar-meeting-url.js@@ -0,0 +1,81 @@+/**+ * Stamp `meetingUrl: null` onto the Google events already sitting in each+ * account's calendar cache.+ *+ * `normalizeGoogleEvent` now selects a join link out of Google's+ * `conferenceData.entryPoints` / `hangoutLink` and caches it as `meetingUrl`+ * (#6289), which the event drawer renders as a "Join meeting" action. Events+ * cached before that change simply lack the key.+ *+ * This is a SHAPE normalization, not a behavior change, and deliberately so.+ * Nothing reads the cached key's presence: the drawer gates on the value being+ * a usable http(s) URL, and the sync path's preserve-vs-clear decision reads+ * the RAW incoming Google event, never the cached one. So a missing key is+ * already handled correctly everywhere, and this migration exists to stop the+ * cache from carrying two shapes for one state — every Google event a current+ * install writes has the key, and after this every Google event it has ever+ * written does too. That keeps a hand-inspected cache, a future consumer, and+ * a diff between two installs from having to re-derive which absence means+ * what.+ *+ * It is additive and offline. It never fetches, never contacts Google, and+ * never overwrites an existing `meetingUrl` — a re-run, or an install that+ * already synced under the new code, is a no-op. Non-Google events (the+ * iCal/CalDAV/Outlook paths, which have no conference metadata to project) are+ * left exactly as they are. A missing cache directory is a fresh install:+ * nothing is created. An unreadable or wrong-shaped cache file is left+ * untouched rather than rewritten from a guess, since the next real sync+ * repairs it and a partial rewrite here would not. Rolling back is safe in+ * both directions: older code never touches the field.+ */++import { join } from 'path';+import { readdir } from 'fs/promises';+import { atomicWrite, readJSONFileStrict } from '../../server/lib/fileUtils.js';++const CACHE_REL = join('data', 'calendar', 'cache');+const GOOGLE_SOURCE = 'google-calendar';++export default {+ async up({ rootDir }) {+ const cacheDir = join(rootDir, CACHE_REL);+ const files = await readdir(cacheDir).catch(() => null);+ if (files === null) return { stamped: 0, files: 0, skipped: 0, reason: 'no calendar cache directory' };++ let stampedEvents = 0;+ let rewrittenFiles = 0;+ let skippedFiles = 0;++ for (const file of files.filter((f) => f.endsWith('.json'))) {+ const path = join(cacheDir, file);+ const { ok, value: cache } = await readJSONFileStrict(path, null);+ // Unreadable, absent, or not the `{ events: [...] }` shape this migration+ // knows how to walk — leave it for the next sync to rebuild.+ if (!ok || !cache || !Array.isArray(cache.events)) {+ skippedFiles++;+ continue;+ }++ let changed = 0;+ for (const event of cache.events) {+ if (!event || typeof event !== 'object') continue;+ if (event.source !== GOOGLE_SOURCE) continue;+ if ('meetingUrl' in event) continue;+ event.meetingUrl = null;+ changed++;+ }++ if (changed === 0) continue;+ // `atomicWrite` serializes the object itself; every other field, the+ // event ids, and `syncCursor` ride through untouched.+ await atomicWrite(path, cache);+ stampedEvents += changed;+ rewrittenFiles++;+ }++ if (stampedEvents > 0) {+ console.log(`📅 Stamped meetingUrl on ${stampedEvents} cached Google events across ${rewrittenFiles} account caches`);+ }+ return { stamped: stampedEvents, files: rewrittenFiles, skipped: skippedFiles };+ },+};diff --git a/scripts/migrations/343-calendar-meeting-url.test.js b/scripts/migrations/343-calendar-meeting-url.test.jsnew file mode 100644index 0000000000..1cebbc6b3a--- /dev/null+++ b/scripts/migrations/343-calendar-meeting-url.test.js@@ -0,0 +1,113 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './343-calendar-meeting-url.js';++const ACCOUNT_A = '44444444-4444-4444-4444-444444444444';++describe('migration 343 — stamp meetingUrl onto cached Google events', () => {+ let rootDir;+ let cacheDir;++ const cachePath = (accountId) => join(cacheDir, `${accountId}.json`);+ const writeCache = (accountId, cache) => {+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(cachePath(accountId), `${JSON.stringify(cache, null, 2)}\n`);+ };+ const readCache = (accountId) => JSON.parse(readFileSync(cachePath(accountId), 'utf8'));++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-343-'));+ cacheDir = join(rootDir, 'data', 'calendar', 'cache');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('is a no-op on a fresh install with no calendar cache directory', async () => {+ await expect(migration.up({ rootDir })).resolves.toMatchObject({+ stamped: 0,+ reason: 'no calendar cache directory',+ });+ // It must not conjure cache data an install never had.+ expect(() => readFileSync(cachePath(ACCOUNT_A), 'utf8')).toThrow();+ });++ it('stamps null on Google events lacking the field, preserving every other value', async () => {+ writeCache(ACCOUNT_A, {+ syncCursor: 'cursor-token-1',+ events: [{+ id: 'evt-1',+ externalId: 'gcal-aaaaaaaaaaaa',+ apiId: 'upstream-1',+ title: 'Design review',+ description: 'Bring mockups',+ location: 'Room 2',+ startTime: '2026-03-02T10:00:00Z',+ endTime: '2026-03-02T11:00:00Z',+ isAllDay: false,+ isCancelled: false,+ organizer: { name: 'Alice Example', email: '[email protected]' },+ attendees: [{ name: 'Bob Example', email: '[email protected]', status: 'accepted' }],+ subcalendarId: '[email protected]',+ source: 'google-calendar',+ syncMethod: 'push',+ }],+ });++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ stamped: 1, files: 1 });++ const cache = readCache(ACCOUNT_A);+ expect(cache.syncCursor).toBe('cursor-token-1');+ expect(cache.events[0]).toMatchObject({+ id: 'evt-1',+ externalId: 'gcal-aaaaaaaaaaaa',+ title: 'Design review',+ organizer: { name: 'Alice Example', email: '[email protected]' },+ attendees: [{ name: 'Bob Example', email: '[email protected]', status: 'accepted' }],+ meetingUrl: null,+ });+ });++ it('leaves an existing link intact and skips non-Google events', async () => {+ writeCache(ACCOUNT_A, {+ syncCursor: null,+ events: [+ { id: 'evt-linked', source: 'google-calendar', meetingUrl: 'https://meet.example.com/room-abc' },+ { id: 'evt-ical', source: 'ical', title: 'Imported' },+ { id: 'evt-plain', source: 'google-calendar', title: 'Needs stamping' },+ ],+ });++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ stamped: 1 });++ const events = readCache(ACCOUNT_A).events;+ expect(events[0].meetingUrl).toBe('https://meet.example.com/room-abc');+ expect('meetingUrl' in events[1]).toBe(false);+ expect(events[2].meetingUrl).toBeNull();+ });++ it('is idempotent — a second run stamps nothing and rewrites no file', async () => {+ writeCache(ACCOUNT_A, { syncCursor: null, events: [{ id: 'evt-1', source: 'google-calendar' }] });++ await migration.up({ rootDir });+ const afterFirst = readFileSync(cachePath(ACCOUNT_A), 'utf8');++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ stamped: 0, files: 0 });+ expect(readFileSync(cachePath(ACCOUNT_A), 'utf8')).toBe(afterFirst);+ });++ it('leaves a malformed or wrong-shaped cache file byte-identical', async () => {+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(cachePath(ACCOUNT_A), '{ this is not json');+ const wrongShape = '55555555-5555-5555-5555-555555555555';+ writeCache(wrongShape, { syncCursor: null, events: 'not-an-array' });+ const malformedBefore = readFileSync(cachePath(ACCOUNT_A), 'utf8');+ const wrongShapeBefore = readFileSync(cachePath(wrongShape), 'utf8');++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ stamped: 0, skipped: 2 });++ expect(readFileSync(cachePath(ACCOUNT_A), 'utf8')).toBe(malformedBefore);+ expect(readFileSync(cachePath(wrongShape), 'utf8')).toBe(wrongShapeBefore);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex ddf1f3975d..a640a1a0b2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -159,6 +159,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. || `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). || `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |+| `meetingUrl.js` | Selects the one cacheable join URL (`selectMeetingUrl`) out of a raw Google Calendar event — first http(s) `video` entry point, else `hangoutLink` — and owns the shared `MEETING_URL_MAX` bound. Three-state: `undefined` = the producer never described conferencing, `null` = described with none usable. || `minimaxH3Memory.js` | The declared weight-placement table for the three MiniMax H3 entries (#5420) — H3 is the one video model family whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. || `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. || `videoPromptLinter.js` | Deterministic lint pass for continuous-video clip prompts (part of #6217, independent of `scriptVideoCompiler.js` #6225 by interface — lints already-built prompt strings plus caller-supplied framing/reference metadata rather than a compiler-shaped clip). `lintClipPrompt(clip, {bible, maxLength})` checks a single clip: a `cutType: 'continue'` clip must open with `"Hard cut to <framing>:"` and use a framing distinct from `previousFraming`; every `references` entry (`{kind: 'cast'|'locations', id}`) must resolve to a bible descriptor present VERBATIM in the prompt (never paraphrased); the prompt must not contain the banned cross-clip referents (same/still/again/continues/as before), negatives (no/without/never), or UI-overlay terms (text/caption/overlay), matched on word boundaries so substrings like "against" or "context" don't false-positive; and the prompt must be `<= MAX_CLIP_PROMPT_LENGTH` (800) characters. Returns `{pass, reasons[]}`, never throws. `lintClips(clips, {bible, maxLength})` lints an ordered chain, deriving each clip's `previousFraming` from the preceding array element's `framing` when not set explicitly. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 5914496e6f..90c6e9444d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -153,6 +153,7 @@ export * from './installLogger.js';export * from './kimi.js';export * from './mediaModelBuckets.js';export * from './mediaModels.js';+export * from './meetingUrl.js';export * from './minimaxH3Memory.js';export * from './videoContinuity.js';export * from './videoDisclosure.js';diff --git a/server/lib/meetingUrl.js b/server/lib/meetingUrl.jsnew file mode 100644index 0000000000..7028d8e651--- /dev/null+++ b/server/lib/meetingUrl.js@@ -0,0 +1,102 @@+/**+ * Selection of the ONE join link worth caching out of a raw Google Calendar+ * event, plus the bound both the HTTP ingress and the selector enforce.+ *+ * Pure and dependency-light on purpose: the push route (`routes/calendar.js`)+ * needs `MEETING_URL_MAX` at schema-construction time, and the sync service+ * (`services/calendarGoogleSync.js`) needs the selector — so a single copy has+ * to live somewhere neither one's test suite mocks. Route suites factory-mock+ * the sync service wholesale, which would leave an imported bound `undefined`+ * before Zod ever saw it; nothing mocks `server/lib/`.+ */++import { isSafeHref } from './isSafeHref.js';++/**+ * Upper bound for a conference URL, enforced at the HTTP boundary (a longer one+ * fails route validation) and again at selection (a longer one is not chosen).+ * Google's own join links sit two orders of magnitude below this; the cap+ * exists so a hostile or malformed payload can't push an unbounded string into+ * the local event cache.+ */+export const MEETING_URL_MAX = 1300;++/**+ * Pick the join URL to cache for a raw Google event.+ *+ * `conferenceData.entryPoints` is the modern shape — it also carries `phone`,+ * `sip` and `more` entries plus dial-in PINs and conference passwords, so only+ * a `video` entry's `uri` is considered and nothing else from that object is+ * returned. `hangoutLink` is the legacy field and the fallback. `htmlLink` is+ * deliberately NOT a candidate: it opens the calendar event, not the meeting.+ *+ * THREE-STATE by design, following the repo's sentinel convention — the caller+ * must be able to tell "this producer never described conferencing" from "this+ * producer described it and there is none", or every legacy push would read as+ * "the meeting lost its link" and wipe a working Join action:+ *+ * `undefined` — the event carried NEITHER raw field. An older or partial+ * producer; preserve whatever is already cached.+ * `null` — conferencing WAS described, and nothing usable came of it+ * (absent, empty, unsafe scheme, or over-long). Clear the link.+ * `string` — a validated http(s) URL to cache.+ *+ * A DEFINED value on either raw field is what separates the first two, so an+ * explicit `null` from the producer still counts as "described" — which is+ * exactly why the direct-API mapper emits nulls rather than omitting the keys.+ * (A JS caller passing a literal `undefined` therefore reads as "not+ * described", the same as omitting it; across the JSON boundary every real+ * producer crosses, the two are indistinguishable anyway.)+ *+ * @param {object} event raw Google Calendar event+ * @returns {string|null|undefined}+ */+export function selectMeetingUrl(event) {+ const hangoutLink = event?.hangoutLink;+ const conferenceData = event?.conferenceData;+ if (hangoutLink === undefined && conferenceData === undefined) return undefined;++ const entryPoints = Array.isArray(conferenceData?.entryPoints) ? conferenceData.entryPoints : [];+ for (const entryPoint of entryPoints) {+ if (!isVideoEntry(entryPoint?.entryPointType)) continue;+ const url = usableMeetingUrl(entryPoint.uri);+ if (url) return url;+ }+ return usableMeetingUrl(hangoutLink) ?? null;+}++/**+ * Is this the `video` entry type, ignoring surrounding whitespace and case?+ *+ * Matched leniently on purpose. A producer that sends `" video "` plainly means+ * the video entry, and an exact-match test would skip it and silently fall back+ * to the legacy `hangoutLink` — a DIFFERENT meeting, not merely a missing one.+ * It also keeps the three ingress paths agreeing: the push route trims its+ * strings, so a strict match here would make the same event resolve one way+ * over HTTP and another over the API/MCP relays.+ */+function isVideoEntry(entryPointType) {+ return typeof entryPointType === 'string' && entryPointType.trim().toLowerCase() === 'video';+}++/**+ * A trimmed, bounded, http(s) URL in NORMALIZED form — or null when the+ * candidate is unusable.+ *+ * The normalization is what keeps the write side and the read side agreeing.+ * `isSafeHref` parses with `new URL()`, which accepts scheme-relative forms+ * like `https:meet.example.com` that resolve fine in a browser; the client's+ * render-time re-check (`isHttpUrl` in `client/src/utils/urlNormalize.js`) is a+ * `^https?://` prefix regex that does not. Storing `new URL(url).href` — which+ * is always `scheme://host/…` — means anything this function accepts is+ * something the drawer will render, instead of a link silently cached and then+ * hidden. The cap is applied to the stored form for the same reason.+ */+function usableMeetingUrl(candidate) {+ if (typeof candidate !== 'string') return null;+ const trimmed = candidate.trim();+ if (trimmed.length === 0 || trimmed.length > MEETING_URL_MAX) return null;+ if (!isSafeHref(trimmed)) return null;+ const normalized = new URL(trimmed).href;+ return normalized.length > MEETING_URL_MAX ? null : normalized;+}diff --git a/server/routes/calendar.js b/server/routes/calendar.jsindex eee4696a59..6409b08bb0 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -3,6 +3,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, parsePagination } from '../lib/validation.js';import { UUID_RE } from '../lib/fileUtils.js';+import { MEETING_URL_MAX } from '../lib/meetingUrl.js';import * as calendarAccounts from '../services/calendarAccounts.js';import * as calendarSync from '../services/calendarSync.js';import * as calendarGoogleSync from '../services/calendarGoogleSync.js';@@ -16,6 +17,14 @@ import { localDayWindowUtc } from '../lib/timezone.js';const router = express.Router();+/** A string bounded by its TRIMMED length, so padding can't fail an otherwise fine value. */+const trimmedString = (max) =>+ z.preprocess((v) => (typeof v === 'string' ? v.trim() : v), z.string().max(max));++/** An array CAPPED at `max` rather than rejected past it, so a valid leading item survives. */+const cappedArray = (max, element) =>+ z.preprocess((v) => (Array.isArray(v) ? v.slice(0, max) : v), z.array(element));+// === Validation Schemas ===const createAccountSchema = z.object({name: z.string().min(1),@@ -71,7 +80,52 @@ const pushSyncSchema = z.object({location: z.string().optional().default(''),description: z.string().optional().default(''),status: z.string().optional().default('confirmed'),- htmlLink: z.string().optional()+ htmlLink: z.string().optional(),+ // Conference metadata feeds the cached `meetingUrl` join link (#6289).+ // OPTIONAL with no default, and nullable: `selectMeetingUrl` distinguishes+ // a producer that omitted them (preserve the cached link) from one that+ // explicitly sent none (clear it), so a default here would make every+ // legacy push wipe a working Join action. Non-video entry types are+ // accepted and ignored downstream, so ordinary phone/SIP metadata can't+ // reject an otherwise valid event; Zod strips the conference passwords and+ // dial-in codes Google ships alongside them, and the length bound comes+ // from the selector's own module so the two can't drift.+ //+ // The bounds FAIL SOFT via `.catch`, at THREE granularities, because what+ // a malformed value should cost depends on how much of the payload it+ // implicates. Throwing costs the most: `validateRequest` 400s the WHOLE+ // batch, so one 1301-character `uri` — even on a `phone` entry the+ // selector ignores — silently stops the user's entire calendar from+ // syncing, while an unbounded `description` sails through.+ //+ // per ENTRY → a bad entry becomes `{}`, which the selector skips. This+ // is the granularity that matters: a malformed phone entry+ // must not erase the usable video link sitting beside it.+ // per FIELD → a bad `hangoutLink` / `conferenceData` becomes null, i.e.+ // "described, nothing usable came of it" — exactly true.+ // per EVENT → nothing. Every other event in the batch still syncs.+ //+ // Omission short-circuits ahead of every catch, so an older client that+ // sends neither field still reads as "not described" and keeps its link.+ // The bounds also NORMALIZE before measuring, so this ingress is not+ // needlessly stricter than the selector it feeds — anything it rejects+ // reads downstream as "this meeting has no conference" and CLEARS a link+ // the API and MCP paths keep for the same input. Untrimmed padding counted+ // toward the length cap (1300 leading spaces sank a URL the selector trims+ // and accepts), and an over-long array was rejected outright rather than+ // capped, losing a valid leading video entry to its junk siblings.+ //+ // Truncation past 100 entries is the one place a bound can still drop a+ // usable candidate, and it is the deliberate residue of having any bound at+ // all: Google emits a handful of entry points, so 100 is ~20x headroom, and+ // capping strictly beats rejecting the whole array as it used to.+ hangoutLink: trimmedString(MEETING_URL_MAX).nullable().optional().catch(null),+ conferenceData: z.object({+ entryPoints: cappedArray(100, z.object({+ entryPointType: trimmedString(32).nullable().optional(),+ uri: trimmedString(MEETING_URL_MAX).nullable().optional()+ }).catch(() => ({}))).nullable().optional().catch(null)+ }).nullable().optional().catch(null)}))});diff --git a/server/routes/calendar.test.js b/server/routes/calendar.test.jsindex cd348decfd..f57764bb67 100644--- a/server/routes/calendar.test.js+++ b/server/routes/calendar.test.js@@ -274,3 +274,187 @@ describe('Calendar Routes — normalized error handling', () => {});});});++// #6289: the push route is the HTTP ingress for Google conference metadata.+// Zod strips whatever a schema doesn't name, so the regression this pins is the+// route silently dropping the conference fields before the service can project+// them — the join link would then never reach the cache from a push sync.+describe('Calendar Routes — push sync carries Google conference metadata (#6289)', () => {+ let app;++ const push = (events) =>+ request(app).post(`/api/calendar/sync/${ACCOUNT_ID}/push`).send({+ calendarId: '[email protected]',+ calendarName: 'Work',+ events,+ });++ const pushedEvents = () => calendarGoogleSync.pushSyncEvents.mock.calls.at(-1)[3];++ const baseEvent = {+ id: 'upstream-1',+ summary: 'Design review',+ start: { dateTime: '2026-03-02T10:00:00Z' },+ end: { dateTime: '2026-03-02T11:00:00Z' },+ };++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/calendar', calendarRoutes);+ vi.clearAllMocks();+ calendarGoogleSync.pushSyncEvents.mockResolvedValue({ newEvents: 1, updated: 0, pruned: 0, total: 1 });+ });++ it('forwards conferenceData entry points and hangoutLink to the service', async () => {+ const response = await push([{+ ...baseEvent,+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: {+ entryPoints: [+ { entryPointType: 'phone', uri: 'tel:+15550100' },+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ ],+ },+ }]);++ expect(response.status).toBe(200);+ expect(pushedEvents()[0]).toMatchObject({+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: {+ entryPoints: [+ { entryPointType: 'phone', uri: 'tel:+15550100' },+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ ],+ },+ });+ });++ it('strips conference passwords and dial-in PINs riding alongside the URI', async () => {+ await push([{+ ...baseEvent,+ conferenceData: {+ conferenceId: 'abc-defg-hij',+ entryPoints: [{ entryPointType: 'video', uri: 'https://meet.example.com/video-xyz', password: 'hunter2', pin: '987654' }],+ },+ }]);++ const forwarded = pushedEvents()[0];+ expect(forwarded.conferenceData.entryPoints[0]).toEqual({+ entryPointType: 'video',+ uri: 'https://meet.example.com/video-xyz',+ });+ expect(JSON.stringify(forwarded)).not.toContain('hunter2');+ expect(JSON.stringify(forwarded)).not.toContain('987654');+ });++ it('preserves the OMISSION of both fields rather than defaulting them', async () => {+ await push([baseEvent]);++ const forwarded = pushedEvents()[0];+ // The service reads key PRESENCE to tell an intentional clear from a legacy+ // producer, so a default here would make every legacy push wipe cached links.+ expect('hangoutLink' in forwarded).toBe(false);+ expect('conferenceData' in forwarded).toBe(false);+ });++ it('passes an explicit null through as the clear signal', async () => {+ await push([{ ...baseEvent, hangoutLink: null, conferenceData: null }]);++ expect(pushedEvents()[0]).toMatchObject({ hangoutLink: null, conferenceData: null });+ });++ // The bounds FAIL SOFT. Throwing would 400 the whole batch, so one malformed+ // event — even on an entry-point type the selector ignores — would silently+ // stop the user's entire calendar from syncing. Collapsing to null instead+ // says "conferencing was described, nothing usable came of it", which is+ // true, and every other event in the payload still lands.+ it('collapses an over-long entry point without erasing a usable sibling', async () => {+ // The granularity that matters: a malformed `phone` entry the selector+ // would ignore anyway must not take the usable video link down with it.+ const response = await push([{+ ...baseEvent,+ conferenceData: {+ entryPoints: [+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ { entryPointType: 'phone', uri: `tel:${'1'.repeat(1300)}` },+ ],+ },+ }]);++ expect(response.status).toBe(200);+ const entryPoints = pushedEvents()[0].conferenceData.entryPoints;+ expect(entryPoints[0]).toEqual({ entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' });+ // The bad entry survives only as an inert placeholder the selector skips.+ expect(entryPoints[1]).toEqual({});+ });++ it('collapses a genuinely over-long hangoutLink to null without failing the batch', async () => {+ const response = await push([{+ ...baseEvent,+ hangoutLink: `https://meet.example.com/${'a'.repeat(1300)}`,+ }]);++ expect(response.status).toBe(200);+ expect(pushedEvents()[0]).toMatchObject({ hangoutLink: null });+ });++ // This ingress must not be needlessly STRICTER than the selector it feeds:+ // anything it rejects that the selector would have accepted reads downstream+ // as "this meeting has no conference" and CLEARS a link the API and MCP paths+ // keep for the identical input. These two pin the cases where a naive bound+ // did exactly that. (Truncation past 100 entries can still drop a candidate —+ // the deliberate residue of having any bound; see the schema's comment.)+ it('keeps a padded URL the selector would trim and accept', async () => {+ const response = await push([{ ...baseEvent, hangoutLink: `${' '.repeat(1300)}https://meet.example.com/room` }]);++ expect(response.status).toBe(200);+ expect(pushedEvents()[0].hangoutLink).toBe('https://meet.example.com/room');+ });++ it('caps an over-long entry-point array instead of discarding the valid lead entry', async () => {+ const response = await push([{+ ...baseEvent,+ conferenceData: {+ entryPoints: [+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ ...Array.from({ length: 100 }, () => null),+ ],+ },+ }]);++ expect(response.status).toBe(200);+ const entryPoints = pushedEvents()[0].conferenceData.entryPoints;+ expect(entryPoints).toHaveLength(100);+ expect(entryPoints[0]).toEqual({ entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' });+ });++ it('bounds an unbounded entry-point array at 100 entries', async () => {+ const response = await push([{+ ...baseEvent,+ conferenceData: {+ entryPoints: Array.from({ length: 500 }, () => ({ entryPointType: 'more', uri: 'https://meet.example.com/x' })),+ },+ }]);++ expect(response.status).toBe(200);+ expect(pushedEvents()[0].conferenceData.entryPoints).toHaveLength(100);+ });++ it('keeps the rest of a batch syncing when one event has malformed conference data', async () => {+ const response = await push([+ { ...baseEvent, id: 'bad', conferenceData: 'not-an-object' },+ {+ ...baseEvent,+ id: 'good',+ conferenceData: { entryPoints: [{ entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' }] },+ },+ ]);++ expect(response.status).toBe(200);+ const forwarded = pushedEvents();+ expect(forwarded).toHaveLength(2);+ expect(forwarded[0].conferenceData).toBeNull();+ expect(forwarded[1].conferenceData.entryPoints[0].uri).toBe('https://meet.example.com/video-xyz');+ });+});diff --git a/server/services/calendarGoogleApiSync.js b/server/services/calendarGoogleApiSync.jsindex aaae0a9173..b18aedb6ea 100644--- a/server/services/calendarGoogleApiSync.js+++ b/server/services/calendarGoogleApiSync.js@@ -51,7 +51,25 @@ export async function apiSyncAccount(accountId, io) {status: item.status || 'confirmed',// Attendee/organizer identities feed Tribe touchpoint auto-logging (#2033).organizer: item.organizer || null,- attendees: item.attendees || []+ attendees: item.attendees || [],+ // Conference metadata feeds the cached `meetingUrl` join link (#6289).+ // Both keys are emitted UNCONDITIONALLY — an explicit null is what makes+ // a direct API response authoritative enough to clear a stale link,+ // where an omitted key would (correctly) preserve it. Only the entry+ // type + URI are carried forward; Google's conference passwords and+ // dial-in codes are dropped here rather than travelling any further.+ hangoutLink: item.hangoutLink || null,+ conferenceData: item.conferenceData+ ? {+ // Passed through unflattened — `selectMeetingUrl` owns every+ // "is this usable?" decision, so this layer only decides what is+ // allowed to travel at all.+ entryPoints: (item.conferenceData.entryPoints || []).map(ep => ({+ entryPointType: ep.entryPointType ?? null,+ uri: ep.uri ?? null+ }))+ }+ : null})));pageToken = response.data.nextPageToken;} while (pageToken);diff --git a/server/services/calendarGoogleApiSync.test.js b/server/services/calendarGoogleApiSync.test.jsnew file mode 100644index 0000000000..f83c3fbf1f--- /dev/null+++ b/server/services/calendarGoogleApiSync.test.js@@ -0,0 +1,140 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// The direct Google API path projects each `events.list` item into a smaller+// object before handing it to `pushSyncEvents`. That projection is a real+// stripping boundary: a field it forgets can never reach the cache, however+// well the normalizer downstream handles it. These tests pin the conference+// metadata's survival across it, and the explicit-null contract that makes an+// API response authoritative enough to clear a stale join link (#6289).+vi.mock('@googleapis/calendar', () => ({ calendar: vi.fn() }));++vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: vi.fn() }));++vi.mock('./calendarAccounts.js', () => ({+ getAccount: vi.fn(),+ updateSubcalendars: vi.fn(async () => ({})),+ mergeDiscoveredSubcalendars: vi.fn((existing, discovered) => discovered),+}));++vi.mock('./calendarGoogleSync.js', () => ({+ pushSyncEvents: vi.fn(async () => ({ newEvents: 1, updated: 0, pruned: 0, total: 1 })),+ getSyncDateRange: vi.fn(() => ({ pastDate: new Date('2026-03-01T00:00:00Z'), futureDate: new Date('2026-04-01T00:00:00Z') })),+}));++import { apiSyncAccount } from './calendarGoogleApiSync.js';+import { calendar } from '@googleapis/calendar';+import { getAuthenticatedClient } from './googleAuth.js';+import { getAccount } from './calendarAccounts.js';+import { pushSyncEvents } from './calendarGoogleSync.js';++const ACCOUNT_ID = '33333333-3333-3333-3333-333333333333';+const CAL_ID = '[email protected]';++const account = () => ({+ id: ACCOUNT_ID,+ name: 'Example Account',+ type: 'google-calendar',+ subcalendars: [{ calendarId: CAL_ID, name: 'Work', enabled: true, dormant: false }],+});++const apiItem = (overrides = {}) => ({+ id: 'upstream-1',+ summary: 'Design review',+ start: { dateTime: '2026-03-02T10:00:00Z' },+ end: { dateTime: '2026-03-02T11:00:00Z' },+ status: 'confirmed',+ ...overrides,+});++/** Stub one `events.list` page holding the given raw API items. */+const mockListPage = (items) => {+ const list = vi.fn(async () => ({ data: { items, nextPageToken: undefined } }));+ calendar.mockReturnValue({ events: { list } });+ return list;+};++/** The raw events the API mapper handed to the shared sync service. */+const syncedEvents = () => pushSyncEvents.mock.calls.at(-1)[3];++describe('apiSyncAccount conference-metadata projection (#6289)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getAccount.mockResolvedValue(account());+ getAuthenticatedClient.mockResolvedValue({});+ pushSyncEvents.mockResolvedValue({ newEvents: 1, updated: 0, pruned: 0, total: 1 });+ });++ it('carries the video entry point and hangoutLink through to the cache write', async () => {+ mockListPage([apiItem({+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: {+ entryPoints: [+ { entryPointType: 'phone', uri: 'tel:+15550100' },+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ ],+ },+ })]);++ await apiSyncAccount(ACCOUNT_ID, null);++ expect(syncedEvents()[0]).toMatchObject({+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: {+ entryPoints: [+ { entryPointType: 'phone', uri: 'tel:+15550100' },+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ ],+ },+ });+ });++ it('drops conference passwords and dial-in PINs at the projection boundary', async () => {+ mockListPage([apiItem({+ conferenceData: {+ conferenceId: 'abc-defg-hij',+ notes: 'Ask the host for the passcode',+ entryPoints: [{ entryPointType: 'video', uri: 'https://meet.example.com/video-xyz', password: 'hunter2', pin: '987654' }],+ },+ })]);++ await apiSyncAccount(ACCOUNT_ID, null);++ const forwarded = syncedEvents()[0];+ expect(forwarded.conferenceData).toEqual({+ entryPoints: [{ entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' }],+ });+ expect(JSON.stringify(forwarded)).not.toContain('hunter2');+ expect(JSON.stringify(forwarded)).not.toContain('987654');+ });++ it('emits EXPLICIT nulls for an event with no conference metadata', async () => {+ mockListPage([apiItem()]);++ await apiSyncAccount(ACCOUNT_ID, null);++ // Not omission: a direct API response is the authoritative snapshot, and an+ // explicit null is what lets it clear a link the meeting no longer has.+ expect(syncedEvents()[0]).toMatchObject({ hangoutLink: null, conferenceData: null });+ });++ it('paginates the full event range before writing the cache once per calendar', async () => {+ const list = vi.fn()+ .mockResolvedValueOnce({ data: { items: [apiItem({ id: 'page-1' })], nextPageToken: 'more' } })+ .mockResolvedValueOnce({ data: { items: [apiItem({ id: 'page-2' })], nextPageToken: undefined } });+ calendar.mockReturnValue({ events: { list } });++ const result = await apiSyncAccount(ACCOUNT_ID, null);++ expect(list).toHaveBeenCalledTimes(2);+ expect(syncedEvents().map((e) => e.id)).toEqual(['page-1', 'page-2']);+ expect(pushSyncEvents).toHaveBeenCalledTimes(1);+ expect(result.status).toBe('success');+ });++ it('refuses to sync without configured OAuth rather than writing an empty cache', async () => {+ getAuthenticatedClient.mockResolvedValue(null);++ await expect(apiSyncAccount(ACCOUNT_ID, null)).rejects.toMatchObject({ status: 401 });+ expect(pushSyncEvents).not.toHaveBeenCalled();+ });+});diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.jsindex 5553db6667..6e43ff7a81 100644--- a/server/services/calendarGoogleSync.js+++ b/server/services/calendarGoogleSync.js@@ -6,6 +6,7 @@ import { getAllProviders } from './providers.js';import { getSettings } from './settings.js';import { pickCliProvider, runCliProviderPrompt } from '../lib/cliProviderRun.js';import { safeJSONParse } from '../lib/fileUtils.js';+import { selectMeetingUrl } from '../lib/meetingUrl.js';import { ServerError } from '../lib/errorHandler.js';// Google Calendar sync is driven through an MCP-capable CLI provider — the@@ -49,6 +50,11 @@ export function normalizeGoogleEvent(event, subcalendarId, subcalendarName) {endTime: endDateTime || (endDate ? `${endDate}T00:00:00` : null),isAllDay,isCancelled: event.status === 'cancelled',+ // Three-state (see `lib/meetingUrl.js`): a string to cache, `null` to+ // clear, or `undefined` when this producer never described conferencing at+ // all. Only the chosen URL is ever retained — never the surrounding+ // conference object, its passwords, or its dial-in codes (#6289).+ meetingUrl: selectMeetingUrl(event),organizer: event.organizer? { name: event.organizer.displayName || '', email: event.organizer.email || '' }: null,@@ -118,10 +124,18 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEveexisting.organizer = event.organizer;existing.attendees = event.attendees;existing.myStatus = event.myStatus;+ // `undefined` means this producer never described the event's+ // conferencing — a legacy push, or an MCP payload predating the field —+ // so the cached link stands. Anything else is the current snapshot:+ // replace it, or clear it to null when the meeting no longer has one.+ // Without this gate an older client silently drops a working Join action.+ if (event.meetingUrl !== undefined) existing.meetingUrl = event.meetingUrl;existing.syncedAt = event.syncedAt;updatedCount++;} else {- cache.events.push(event);+ // A newly cached event always carries the key, so `meetingUrl` is absent+ // from the cache only for records written before this shipped.+ cache.events.push({ ...event, meetingUrl: event.meetingUrl ?? null });newCount++;}}@@ -166,6 +180,27 @@ export async function pushSyncEvents(accountId, calendarId, calendarName, rawEvereturn { newEvents: newCount, updated: updatedCount, pruned, total: cache.events.length, status };}+/**+ * Make an MCP-relayed raw event AUTHORITATIVE about its conferencing (#6289).+ *+ * The MCP prompt asks for Google's `events.list` items verbatim, and Google+ * simply OMITS `hangoutLink` / `conferenceData` on an event that has no+ * conference. Relayed unchanged, that omission hits `selectMeetingUrl` as "this+ * producer never described conferencing" and the cached link is preserved — so+ * a meeting whose organizer removed the video call would keep a dead Join+ * button forever, with no sync able to clear it. Stamping explicit nulls says+ * what a complete Google response actually means, matching what the direct-API+ * mapper emits for the same reason.+ *+ * Only a COMPLETE payload earns this. A partial one (the CLI died mid-stream)+ * is relayed untouched, so a truncated event that lost its conference fields+ * reads as "unknown" rather than "cleared" — the same rule that already stops a+ * partial payload from driving a prune. Clearing a link is destructive too.+ */+function withExplicitConferenceFields(event) {+ return { ...event, hangoutLink: event?.hangoutLink ?? null, conferenceData: event?.conferenceData ?? null };+}+const mcpSyncLock = new Map();export async function mcpSyncAccount(accountId, io) {@@ -197,7 +232,7 @@ For EACH calendar, call gcal_list_events with the calendarId, timeMin, and timeMAfter fetching ALL calendars, output ONLY a single JSON object (no markdown fences, no explanation) with this exact structure:{"calendars":[{"calendarId":"...","calendarName":"...","events":[...raw events from gcal_list_events response...]}]}-Include the full events arrays as returned by gcal_list_events. Output NOTHING else — just the JSON.`;+Include the full events arrays as returned by gcal_list_events, with every field each event carries — do NOT abbreviate, summarize, or drop fields. In particular keep "conferenceData" and "hangoutLink" exactly as returned, and omit them only when the event itself does not have them. Output NOTHING else — just the JSON.`;const runSync = async () => {const result = await runConfiguredMcp(prompt, io, accountId);@@ -229,7 +264,7 @@ Include the full events arrays as returned by gcal_list_events. Output NOTHING eaccountId,cal.calendarId,cal.calendarName || cal.calendarId,- cal.events,+ partial ? cal.events : cal.events.map(withExplicitConferenceFields),null,{ prune: !partial, status },);diff --git a/server/services/calendarGoogleSync.test.js b/server/services/calendarGoogleSync.test.jsindex 88955565c4..f9aa898ef6 100644--- a/server/services/calendarGoogleSync.test.js+++ b/server/services/calendarGoogleSync.test.js@@ -27,7 +27,7 @@ vi.mock('./calendarSync.js', () => ({vi.mock('./providers.js', () => ({ getAllProviders: vi.fn(async () => ({ providers: {} })) }));vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));-import { mcpSyncAccount, mcpDiscoverCalendars } from './calendarGoogleSync.js';+import { mcpSyncAccount, mcpDiscoverCalendars, pushSyncEvents } from './calendarGoogleSync.js';import { runCliProviderPrompt } from '../lib/cliProviderRun.js';import { getAccount, updateSyncStatus, updateSubcalendars } from './calendarAccounts.js';import { loadCache, saveCache } from './calendarSync.js';@@ -177,3 +177,228 @@ describe('mcpDiscoverCalendars CLI exit-status agreement (#5302)', () => {expect(updateSubcalendars).not.toHaveBeenCalled();});});++// #6289: a Google event's join link is projected into a single cached+// `meetingUrl`. The regressions these pin are (a) caching something that is not+// a usable video link, and (b) an older producer that omits the conference+// fields silently wiping a working Join action off an already-cached event.+describe('meetingUrl projection (#6289)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getAccount.mockResolvedValue(account());+ loadCache.mockResolvedValue({ events: [] });+ });++ const resync = async (raw) => {+ runCliProviderPrompt.mockResolvedValue({+ text: JSON.stringify({ calendars: [{ calendarId: CAL_ID, calendarName: 'Work', events: [raw] }] }),+ exitCode: 0,+ partial: false,+ stderrTail: '',+ });+ return mcpSyncAccount(ACCOUNT_ID, null);+ };++ const syncOne = async (raw) => {+ await resync(raw);+ return savedCache().events.at(-1);+ };++ it('prefers a structured video entry point over the legacy hangoutLink', async () => {+ const event = await syncOne({+ ...rawEvent('upstream-video', 'Design review'),+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: {+ entryPoints: [+ { entryPointType: 'phone', uri: 'tel:+15550100,,987654#' },+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz' },+ { entryPointType: 'more', uri: 'https://meet.example.com/more-xyz' },+ ],+ },+ });++ expect(event.meetingUrl).toBe('https://meet.example.com/video-xyz');+ });++ it('matches the video entry type leniently rather than falling back to a DIFFERENT meeting', async () => {+ // An exact-match test would skip a ` video ` entry and silently serve the+ // legacy link instead — the wrong meeting, not merely a missing one. It also+ // keeps the ingress paths agreeing, since the push route trims its strings.+ const event = await syncOne({+ ...rawEvent('upstream-padded-type', 'Padded entry type'),+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: { entryPoints: [{ entryPointType: ' Video ', uri: 'https://meet.example.com/video-xyz' }] },+ });++ expect(event.meetingUrl).toBe('https://meet.example.com/video-xyz');+ });++ it('falls back to hangoutLink when no usable video entry point exists', async () => {+ const event = await syncOne({+ ...rawEvent('upstream-legacy', 'Legacy sync'),+ hangoutLink: 'https://meet.example.com/legacy-abc',+ conferenceData: { entryPoints: [{ entryPointType: 'phone', uri: 'tel:+15550100' }] },+ });++ expect(event.meetingUrl).toBe('https://meet.example.com/legacy-abc');+ });++ it('caches only the chosen URL — never passwords, PINs or the raw conference object', async () => {+ const event = await syncOne({+ ...rawEvent('upstream-secrets', 'Sensitive'),+ conferenceData: {+ conferenceId: 'abc-defg-hij',+ entryPoints: [+ { entryPointType: 'video', uri: 'https://meet.example.com/video-xyz', password: 'hunter2' },+ { entryPointType: 'phone', uri: 'tel:+15550100', pin: '987654' },+ ],+ },+ });++ expect(event.meetingUrl).toBe('https://meet.example.com/video-xyz');+ expect(event.conferenceData).toBeUndefined();+ expect(JSON.stringify(event)).not.toContain('hunter2');+ expect(JSON.stringify(event)).not.toContain('987654');+ });++ it('caches a normalized URL the client-side render check will accept', async () => {+ // `isSafeHref` (new URL) accepts scheme-relative forms that the drawer's+ // `^https?://` re-check rejects, so storing the raw string would cache a+ // link and then hide it. Normalizing on write keeps the two sides agreeing.+ const event = await syncOne({+ ...rawEvent('upstream-relative', 'Odd but resolvable'),+ hangoutLink: 'https:meet.example.com/room-abc',+ });++ expect(event.meetingUrl).toBe('https://meet.example.com/room-abc');+ expect(/^https?:\/\//i.test(event.meetingUrl)).toBe(true);+ });++ it('rejects a non-http(s) candidate rather than caching a script URL', async () => {+ const event = await syncOne({+ ...rawEvent('upstream-xss', 'Hostile'),+ conferenceData: { entryPoints: [{ entryPointType: 'video', uri: 'javascript:alert(1)' }] },+ });++ expect(event.meetingUrl).toBeNull();+ });++ it('rejects an over-long candidate rather than caching an unbounded string', async () => {+ const event = await syncOne({+ ...rawEvent('upstream-long', 'Too long'),+ hangoutLink: `https://meet.example.com/${'a'.repeat(1300)}`,+ });++ expect(event.meetingUrl).toBeNull();+ });++ it('never treats htmlLink or a URL in the description as a join link', async () => {+ const event = await syncOne({+ ...rawEvent('upstream-html', 'No conference'),+ htmlLink: 'https://calendar.example.com/event?eid=abc',+ description: 'Dial in at https://meet.example.com/from-description',+ location: 'https://meet.example.com/from-location',+ });++ expect(event.meetingUrl).toBeNull();+ });++ // Seed the cache the honest way: run one sync and keep what it wrote, so the+ // externalId derivation stays production's business rather than the test's.+ const seedCached = async (raw) => {+ await syncOne(raw);+ const seeded = savedCache().events.at(-1);+ vi.clearAllMocks();+ getAccount.mockResolvedValue(account());+ loadCache.mockResolvedValue({ events: [seeded] });+ return seeded;+ };++ const withOldRoom = () => ({+ ...rawEvent('upstream-move', 'Weekly sync'),+ conferenceData: { entryPoints: [{ entryPointType: 'video', uri: 'https://meet.example.com/old-room' }] },+ });++ it('replaces an existing link, keeping the cached event id stable', async () => {+ const seeded = await seedCached(withOldRoom());++ const result = await resync({+ ...rawEvent('upstream-move', 'Weekly sync'),+ conferenceData: { entryPoints: [{ entryPointType: 'video', uri: 'https://meet.example.com/new-room' }] },+ });++ expect(result.updated).toBe(1);+ const events = savedCache().events;+ expect(events).toHaveLength(1);+ expect(events[0].id).toBe(seeded.id);+ expect(events[0].meetingUrl).toBe('https://meet.example.com/new-room');+ });++ it('clears the link when the producer says the meeting no longer has one', async () => {+ await seedCached(withOldRoom());++ const result = await resync({ ...rawEvent('upstream-move', 'Weekly sync'), hangoutLink: null, conferenceData: null });++ expect(result.updated).toBe(1);+ expect(savedCache().events[0].meetingUrl).toBeNull();+ });++ it('CLEARS the link when a complete MCP sync stops mentioning the conference', async () => {+ await seedCached(withOldRoom());++ // Google OMITS both fields on an event that has no conference, and the MCP+ // prompt relays its events verbatim — so on a complete payload, omission+ // means "the organizer removed the video call", not "unknown". Without the+ // authoritative stamp the dead Join button could never be cleared by any+ // sync.+ const result = await resync(rawEvent('upstream-move', 'Weekly sync'));++ expect(result.updated).toBe(1);+ expect(savedCache().events[0].meetingUrl).toBeNull();+ });++ it('PRESERVES the link when a PARTIAL MCP payload stops mentioning the conference', async () => {+ await seedCached(withOldRoom());++ // The CLI died mid-stream, so a missing field may just be truncation.+ // Clearing a link is destructive, and the same rule that stops a partial+ // payload from pruning stops it from clearing.+ runCliProviderPrompt.mockResolvedValue({+ text: JSON.stringify({+ calendars: [{ calendarId: CAL_ID, calendarName: 'Work', events: [rawEvent('upstream-move', 'Weekly sync')] }],+ }),+ exitCode: 1,+ partial: true,+ stderrTail: 'stream aborted',+ });++ const result = await mcpSyncAccount(ACCOUNT_ID, null);++ expect(result.status).toBe('partial');+ expect(savedCache().events[0].meetingUrl).toBe('https://meet.example.com/old-room');+ });++ it('PRESERVES the link when a legacy PUSH client omits both conference fields', async () => {+ // The HTTP push route is the one ingress whose omission is genuinely+ // ambiguous — an older client simply doesn't know the fields exist — so it+ // reaches pushSyncEvents unstamped and must not read as "link removed".+ const seeded = await seedCached(withOldRoom());+ loadCache.mockResolvedValue({ events: [seeded] });++ const result = await pushSyncEvents(+ ACCOUNT_ID, CAL_ID, 'Work', [rawEvent('upstream-move', 'Weekly sync')], null,+ );++ expect(result.updated).toBe(1);+ expect(savedCache().events[0].meetingUrl).toBe('https://meet.example.com/old-room');+ });++ it('writes an explicit null key on a newly cached event that named no link', async () => {+ // The selector returns `undefined` here (this producer described no+ // conferencing at all); the insert path pins it to null so a fresh record+ // never carries the sentinel into the cache.+ const event = await syncOne(rawEvent('upstream-plain', 'No conference'));+ expect('meetingUrl' in event).toBe(true);+ expect(event.meetingUrl).toBeNull();+ });+});