Public authentication completion document
Standalone Calendar renders its existing/verify-token, /en/verify-token and
/vi/verify-token completion screen as a public SSR document for GET and HEAD
requests with no token query parameter. The default is English; an explicit
supported locale prefix, then NEXT_LOCALE, then browser language resolves the
document language. These documents do not redirect solely to canonicalize the
locale prefix, and their page model does not resolve an actor or workspace data.
On the Next route tree, which has only /[locale]/verify-token, the unprefixed
path is served in place from its resolved-locale route; the browser URL stays
/verify-token.
The normal Calendar auth proxy, auth-cookie cleanup and response security policy
still apply. Rendering this screen does not create or prove an authenticated
session; the existing client completion flow normalizes its next destination.
This rule applies only to these exact Calendar paths and document methods. A
present token parameter, including an empty value, retains the existing shared
server verification and safe redirect behavior. Token-bearing success propagates
verifier cookies; failure retains the safe fallback and cookie cleanup. Other
methods, protected pages, shared auth defaults and other satellite apps are
unchanged. Web and mobile Calendar surfaces are outside this rule’s scope.
Web owns the session at tuturuuu.com/calendar. A signed-out mounted page
redirects to Web’s /login with
https://tuturuuu.com/calendar/verify-token?nextUrl=<Calendar path and query>
as its returnUrl. The mounted verifier checks Web’s shared session and
resumes the Calendar destination for GET or HEAD. This follows the
one-origin login return decision.
The proxy selects the shared session from the routed HTTPS apex URL and the
/calendar base. The subdomain keeps its app-session refresh, token verifier
and central auth proxy. Calendar’s plan-panel preference passes through the
mount and writes a host-only cookie at Path=/calendar.
The production Worker uses TTR_ONE_ORIGIN_CALENDAR to control activation.
shadow serves both hosts. After the apex is verified, on moves browser
document navigations (GET/HEAD, by Sec-Fetch-Mode: navigate or an HTML
Accept without Fetch Metadata) to the corresponding path and query under the
apex with a 301. Fetches, prefetches, upgrades and every other method keep
serving on the subdomain, as do API, server-function and legacy completion
paths. runtime/root-cutover.test.ts covers both sides of that boundary. Google and Microsoft
connections started at the apex navigate to their registered subdomain flow.
Microsoft keeps its HttpOnly PKCE cookie on that host through its callback.
Moving these callbacks to the apex requires registration with both providers.
/serwist/sw.js answers with a worker that clears the subdomain’s caches,
unregisters itself and reloads open tabs, so browsers that installed the old
worker reach the mount. Calendar’s proxy.mounted-auth.test.ts covers completion
and runtime/one-origin.test.ts covers the serving modes and provider navigation.
The Next build serves the app under the /calendar base path on its own host.
Next prefixes the proxy matchers with the base path, so the proxy only sees
prefixed paths; its root matcher / covers the bare /calendar. Unprefixed
document paths answer a same-host 307 that keeps the query string, and their
sources also declare Cache-Control: private, no-store: / goes to
/calendar, and any other path goes to /calendar/<path> unless its first
segment is calendar, api, _next, _vercel, serwist, monitoring or
.well-known. Next’s built-in 308 removes a trailing slash first.
On Vercel, unprefixed /api/* is served in place. A routes entry in
apps/calendar/vercel.json rewrites it to /calendar/api/* with
continue: true ahead of Next’s routes, so every method and body pass through
and the proxy API guard and owner rewrites apply as on the prefixed path. A
vercel.json rewrites entry cannot do this: it compiles to a check route that
leaves the phase before Next’s proxy route. Next alone cannot serve an
unprefixed path in place, so without that entry the Google and Microsoft OAuth
callbacks and /api/build-info redirect to their prefixed paths and other
unprefixed API paths are not found. apps/calendar/src/lib/legacy-root-routes.ts
holds the Next rule; apps/calendar/next.config.test.ts and
apps/calendar/vercel-config.test.ts cover both.
apps/calendar/src/runtime/public-completion.test.ts covers the real proxy,
shared token consumer, locale resolution, anonymous page model, security policy,
cookie cleanup and token-bearing/protected negative controls. The emitted Worker
suite separately requires 200 EN/VI HTML, hydration assets and framing protection;
source tests do not establish hosted or restored-artifact acceptance.
Browser language fallback
Standalone Calendar filters wildcard and invalid BCP 47 language ranges before matching browser preferences. A wildcard-only, zero-quality-only or otherwise empty usable language list falls back to English. Remaining valid ranges retain Negotiator’s quality ordering and the existing English/Vietnamese best-fit matching, including regional tags. An explicit supported path locale takes precedence over a validNEXT_LOCALE cookie, followed by browser preferences.
This applies to Calendar document/native-function locale resolution and the
browser-language default used by its existing login middleware. Token
verification, authenticated routes and callback redirects retain their existing
authentication contracts. Web, mobile and other apps use their own locale rules.
apps/calendar/src/runtime/request-locale.test.ts and
apps/calendar/src/runtime/public-completion.test.ts cover wildcard/malformed
ranges, regional and quality preferences, precedence, the real public proxy and
login locale middleware. Hosted request headers and Worker acceptance require
separate evidence.
Calendar editor timezone
Calendar display and the built-in event editor use the same resolved Calendar settings. Explicit personal timezone takes precedence over workspace timezone; when neither is explicit, the canonical resolver detects the browser timezone. The editor’s date/time picker inherits those settings instead of resolving its own browser timezone. This applies to the shared Calendar surface in Web and the standalone Calendar app. It does not change saved user or workspace settings. Timed edits represent an instant and serialize as UTC ISO timestamps. A date-only all-day choice represents midnight in the resolved calendar timezone with an exclusive end boundary. A browser in another timezone must still display the chosen calendar date, including when its local date is the previous day. Existing Google-backed events are patched immediately using their stored external event identifier. Imported recurring occurrences retain the provider’s instance identifier; changing an occurrence must preserve that identifier and calendar source. The patch sends updates to guests. Verify the stored event and the same Google occurrence independently after an edit; a local toast is not provider read-back evidence. The current Google write mapper usesdateTime
fields and does not provide native Google date-only all-day writes. Native
Tuturuuu all-day events do not require that provider path.
Event location
A calendar event’slocation is the meeting place. It is separate from the
working-location strip (Home, Office, School). Web reads and edits the string
on the event, and a non-empty value can open Google Maps.
Mobile uses that same field. The agenda, the timed event card, and the event
detail show it. Create and update send it, including an empty string when the
editor clears it. The editor accepts at most 500 characters, the calendar
update schema limit. The detail action opens Maps through the mobile link
launcher. Import deduplication treats a different location as a different
event. Coverage lives in the mobile calendar location tests.
Event dialog
The web create and edit event dialog (decided 2026-11-22) leads with a large, borderless title, then icon rows for When (start, end, an All day switch and the time zone the times are in), Calendar (source with its colour, plus a compact event-colour swatch), Location, Description and, for new events on a supported provider, guests. Quick entry and AI generate are tabs in the header; editing shows Quick entry only. Header and footer stay fixed while the fields scroll, so nothing is clipped; on phones the dialog opens full screen. The footer keeps the lock toggle (and Delete when editing) on the left and Cancel and Create event or Save changes on the right. Keyboard: the title takes focus when the dialog opens; Enter in the title or location saves; Cmd+Enter (macOS) or Ctrl+Enter saves from any field, the description included, and runs Generate or Save on the AI tabs; Escape closes. While an input method is composing (for example Vietnamese Telex), Enter never saves and Escape only cancels the candidate. Repeated keypresses while a save, delete or generation is pending are ignored. Saving, the source choice, provider colours, guests, all-day ranges, the AI prompt (text, voice and image) and the draft recovery notice behave as before. Every string the dialog shows, including its notifications, date and overlap warnings and AI suggestions, is in English and Vietnamese (calendar.event_dialog). Coverage: event-dialog/event-dialog-keys.test.ts,
event-dialog/event-dialog-frame.test.tsx and
event-dialog/event-quick-entry.test.tsx under
packages/ui/src/components/ui/legacy/calendar/.
Default calendar view
Standalone Calendar and the Tasks calendar open in week view on tablet and desktop and in agenda view on phones (viewports narrower than 768px). The Default view setting under Settings › Calendar › General can instead pick day, week, month or agenda, or reopen the last view used. A multi-day time grid chosen for a phone opens as agenda. The choice is saved to the account (CALENDAR_DEFAULT_VIEW user config) and mirrored in the browser whenever the
setting is saved or opened there, so a calendar opens without waiting for a
request. A browser that has not yet opened the setting uses the device default.
packages/ui/src/hooks/calendar-default-view.test.ts covers the resolution
rules.
Plan panel
The calendar’s plan panel holds the task list and habits in two tabs, with the time tracker in its header. From 1280px wide it sits beside the grid at 280px (320px from 1536px) and remembers whether it was open; below 1280px its rail opens it as a sheet over the grid so the week keeps its width. Phones show no rail.packages/tasks-ui/src/calendar/components/sidebar/calendar-sidebar.test.tsx
covers the rail, inline and sheet states.
Tasks and Calendar planning
Calendar and Tasks keep cross-product API calls on the active browser origin so host-only app cookies remain available. TheirbeforeFiles rewrites forward only
the other product’s API families, before Tasks’ API catch-all can intercept them.
The source proxy refreshes the host session and forwards its signed bearer token;
Calendar routes explicitly accept Calendar and Tasks audiences while retaining
workspace membership and permission checks. Do not route these APIs through Web:
Web no longer owns the Calendar events or Tasks endpoints.
Tasks’ session verifier also accepts Calendar for routes that explicitly accept
Tasks, including labels, projects, task detail dependencies, and workspace task
preferences. It preserves required scopes and does not widen unrelated app
audiences. Calendar forwards /api/v1/users/me/workspaces/:wsId/configs/* to
Tasks so those preferences use the verified planning actor and membership guard.
Collection rewrites must have an exact path before their /:path* variant.
Vercel can retain a trailing slash when the wildcard is empty, causing the owning
app to return a 308 to the same browser URL and loop. Verify both collection and
nested resource requests on the deployed host.
Both satellite apps expose local planning views without changing workspace or
requiring a cross-app login handoff:
The shared sidebar retains locale and personal/internal workspace aliases,
including on mobile. Calendar also serves
/tasks/boards,
/tasks/boards/{boardId}, and /tasks/{taskId} within the workspace. Task views
hide the calendar-only mini-month sidebar to leave more room for task work.
Tasks’ embedded calendar uses the shared scheduling, connection, event, and task
controls and enforces manage_calendar. Each host resolves its own app-session
actor. Keep the task route context and dialog manager prefix aligned: Tasks uses
an empty prefix, while Calendar and Web use /tasks. Tasks already owns a dialog
provider, so its embedded calendar disables the additional dialog wrapper.
When validating this integration, check both locales, personal and team workspace
links, board/task detail return paths, and mobile navigation with the sidebar
closed. Mutations continue through the existing protected product APIs.
Overview
apps/calendar and the Calendar experience inside apps/web are paired
Calendar hosts. They must stay 1:1 for product features, data behavior,
mutations, permissions, and user-facing workflow updates.
- Calendar UI and logic should live in shared packages, primarily
@tuturuuu/ui/calendar-app/*, with app route files acting as thin auth and workspace-context wrappers. - Task-aware Calendar controls (task creation, task scheduling, habits, and
task time tracking) live in
@tuturuuu/tasks-ui/calendar/*. The generic Calendar shell accepts those controls through typed component seams, keeping@tuturuuu/uiindependent from task-only code and preserving narrow Turbo rebuilds. apps/calendarowns its standalone workspace shell, local/login, and local/verify-tokencompletion route.apps/web /{wsId}/calendarrenders the same shared Calendar product surface inside the normal platform dashboard shell.- Dashboard navigation in
apps/webshould link to the local/{wsId}/calendarroute, not to the standalone Calendar origin.
Auth Model
Calendar does not create local Supabase Auth sessions. It uses centralapps/web login plus a Calendar app-session cookie:
/logininapps/calendarnormalizes a safenextpath.- If both the Calendar app-session cookie and Web-issued app-session cookie are
already present,
/loginredirects to that localnextpath immediately. - Otherwise
/loginredirects toapps/web /loginwith a return URL pointing back to Calendar/verify-token?nextUrl=.... /verify-tokenposts the handoff token to the Calendar-local verifier, which validates through central Web and sets host-local app-session cookies.
sb-*-auth-token cookies. A valid
Calendar session is represented by Tuturuuu app-session cookies, not by a local
Supabase browser session.
Calendar timezone boundaries
Event start/end values are UTC instants. Display and picker controls resolve personal calendar timezone first, workspace timezone second, and device timezone when both inherit withauto. A browser-local Date used by a date-only calendar
widget is a calendar-day carrier, not an event instant: project its year, month
and day in the resolved timezone before passing selection, today or bounds.
Compare end-time options on that same calendar day and derive minimum/maximum
clock values in the same timezone. This matters when the browser and calendar
are on different dates, for example Los Angeles and Ho Chi Minh City.
Quick previews use the same resolved timezone and clock format as the event
form, localized to the current locale. Date/time edits must round-trip the requested wall time; nonexistent
DST times must not silently normalize into another hour. Reselecting an unchanged
ambiguous time or date preserves the original UTC instant. Tests cover these
boundaries; they do not establish exhaustive correctness for every IANA history
or changed ambiguous-time choice.
Native all-day persistence and the outer calendar Today/header date contract
remain separate concerns. Do not infer all-day intent solely from a 24-hour
elapsed duration, and do not publish a DST duration helper in isolation from the
persistence/rendering contract. Imported recurring provider events require
exact-instance and neighboring-instance readback after an authorized UI edit.
Never use real user calendar screenshots as public regression fixtures.
API Ownership
apps/calendar owns the Calendar product APIs. Its local handlers cover events
and calendars, categories and preferences, hours and default sources,
scheduling and sync, Calendar connections, Google and Microsoft provider OAuth,
Calendar media/generation helpers, and Calendar-owned cron work. Host-local
auth/session and build-info routes are local as well.
- Exact local handlers win before the fallback
/api/:path*rewrite. The fallback remains for cross-product routes that Calendar uses but does not own, including workspace encryption and task, board, habit, and time-tracking families; typed task helpers may target the Tasks app directly. - Central platform login, social-provider callbacks, and cross-app token issuance remain Web-owned. Calendar-provider OAuth initiation and callbacks are Calendar-local, even though their configured redirect origins retain Web compatibility for existing provider registrations.
- Calendar-only routes use
targetApp: 'calendar'. Shared cross-product routes must name the exact accepted app audiences, such astargetApp: ['calendar', 'tasks'], rather than accepting generic satellite sessions. - Keep workspace membership checks and Calendar/task permissions on the owning route before admin-backed reads or writes. The Calendar proxy guard and app-session refresh do not replace route-level authorization.
- Prefer typed
packages/internal-apihelpers. Browser calls remain same-origin so Calendar-local handlers are selected first; server calls to a different owning app must use its configured API base URL with forwarded authentication.
Calendar settings authorization
Personal/workspace settings use shared validation and explicit workspace edit permissions. Native preferences default directly to Web; Calendar browser clients and older mobile gateway clients retain their existing adapters. See Native Calendar preferences for the product decision, quotas, exceptions and regression evidence.OAuth Token Safety
Calendar OAuth credentials live incalendar_auth_tokens. RLS restricts
selects to user_id = auth.uid(), but admin/service-role reads bypass RLS.
Calendar server pages must therefore:
- Check
manage_calendarbefore loading calendar integration state. - Scope token reads to both
ws_idand the authenticateduser_id. - Never pass
access_tokenorrefresh_tokeninto client components. SSR props should use the sharedfetchUserWorkspaceCalendarGoogleTokenForClient()helper from@tuturuuu/utils/calendar-auth-token, which projects only connection metadata (id, account email/name, provider, active state, expiry). - Keep token refresh and provider API calls on Calendar-local server routes; never expose provider credentials to client components.
- Never filter a query by
access_tokenorrefresh_tokenvalue: PostgREST sends filters in the URL. Fence by id andcreated_at, or compare a fingerprint in SQL.oauth-credential-url-filter.test.tsinpackages/utilsenforces this across apps and packages.
select('*') on calendar_auth_tokens.
When adding new Calendar UI that needs protected data, update the shared
Calendar component or helper first, then wire both host wrappers in the same
change. Extend the route family in its owning app and expose a typed
packages/internal-api seam instead of creating a host-local product API fork
or adding direct client Supabase reads.
Calendar OAuth And Connections
Google Calendar OAuth initiation and callback handlers are owned byapps/calendar. Connect and reconnect from the production mount return to
https://tuturuuu.com/calendar/api/v1/calendar/auth/callback. Register that URI
alongside https://calendar.tuturuuu.com/api/v1/calendar/auth/callback so
in-flight subdomain flows can finish on their original host. The Worker uses
its trusted mount match to choose the callback. A subdomain flow uses
GOOGLE_REDIRECT_URI or the Calendar BASE_URL.
Valid local development callback URLs such as
http://localhost:7803/api/v1/calendar/auth/callback may still be configured
through GOOGLE_REDIRECT_URI, but wildcard listener URLs must never be emitted
as Google redirect_uri values or browser redirects.
Google and Microsoft connections share these security rules (regression
coverage lives beside the routes under apps/calendar/src/app/api/v1/calendar/auth/
and in apps/calendar/src/lib/calendar/calendar-oauth-*.test.ts):
- The OAuth
stateis signed, expires after 10 minutes, and binds the flow to the initiating user and workspace. Callbacks reject forged, swapped, expired, other-user and non-member states before exchanging the authorization code. - Each state is single-use. The callback consumes its nonce through the
service-role-only RPC
private.consume_calendar_oauth_state_nonce, which inserts intoprivate.calendar_oauth_state_nonces(RLS forced, no client policies or grants) and treats an existing row as a replay. The same call purges at most 100 rows that expired over an hour ago. If the ledger is unavailable (for example the migration has not been applied), the callback fails closed with503before exchanging the code. - Google uses S256 PKCE derived from the signed state and the browser’s existing session on the initiating origin. Microsoft uses S256 PKCE with an HttpOnly verifier cookie.
- After connecting (or on a provider error), the browser is redirected to the
Calendar app’s workspace page, under
/calendar/{wsId}for mounted Google connections or{BASE_URL}/{wsId}on the subdomain, which is where the Calendar satellite serves each workspace calendar.BASE_URL(apps/calendar/src/constants/common.ts) resolvesCALENDAR_APP_URLorNEXT_PUBLIC_CALENDAR_APP_URLagainst the registered Calendar domain and otherwise defaults tohttps://calendar.tuturuuu.comin production. The origin is never taken from the request URL, Host or forwarded headers. Without a verified workspace the redirect goes to the origin root. - Calendar logs the rejection category for an invalid or reused state without logging the state or signed-in user. The mounted Google route tests cover redirect URI selection, the signed state and PKCE round trip, and reconnect account binding. The Web-origin and forwarded-header fallbacks apply only outside production, for local proxies.
- No environment variables beyond the existing provider credentials are required. The nonce ledger ships as a migration through the gated production migration workflow.
PATCHandDELETEon/api/v1/calendar/connectionsonly change a connection inside the caller’s workspace. The route resolves the connection’s workspace, requires the caller’s membership there (403otherwise), and the write itself filters by bothidandws_id. APATCHwhosewsIddoes not match the connection returns404. ADELETEthat matches no row in the authorized workspace, such as after a stale lookup, affects nothing and returns404(regression coverage:apps/calendar/src/app/api/v1/calendar/connections/route.workspace-scope.test.ts).
apps/calendar with
CALENDAR_OAUTH_NONCE_IT_SUPABASE_URL, CALENDAR_OAUTH_NONCE_IT_SERVICE_ROLE_KEY
and CALENDAR_OAUTH_NONCE_IT_USER_ID (a synthetic local auth user):
bunx vitest run src/lib/calendar/calendar-oauth-nonce-store.integration.test.ts.
It is skipped when those variables are absent. Never point it at a shared or
remote project.
Normal Google Calendar connect and reconnect URLs request
access_type=offline and include_granted_scopes=true, but they must not force
prompt=consent by default. Google may return a refresh token only during the
first authorization, so the callback must preserve an existing stored
refresh_token when a reconnect returns only a new access token. If neither the
callback nor the existing token row has a refresh token, the flow must fail
before saving an active Google connection because provider sync cannot refresh
offline.
Standalone apps/calendar also exposes the shared Calendar connections manager
inside its settings dialog under Calendar -> Integrations. It should fetch the
initial connection state through @tuturuuu/internal-api/calendar and render the
shared Calendar connections UI inside CalendarSyncProvider rather than
forking host-local connection controls.
CI And Deployment
Calendar deploys to Cloudflare through.github/workflows/calendar-cloudflare.yaml.
Previews are Worker versions uploaded at a 0% stage; see the native Start migration runbook. apps/calendar/vercel.json keeps git.deploymentEnabled and
github.enabled set to false, so Vercel never builds Calendar from GitHub.
Vercel hosts the Calendar schedules in apps/admin/vercel.json. Infrastructure authenticates the scheduler and forwards through the private Calendar gateway; Calendar validates the scheduler credential again.
After qualification, collect native-emitted-config-calendar.json even on failure. Keep the actual source HEAD separate from the
event SHA. Retain pointer and config hashes and a redacted key-shape inventory, never raw configs, resource identifiers, or secret
values. Unavailable or overflow diagnostics remain failures. The receipt provides no acceptance, allowlist approval, or rollback
proof. Inspect the actual receipt before qualifying unexpected queues or configPath fields. Preserve the strict resource,
saved-pointer, native-relative-base, restore, and deployment gates.
Provider Sync
Infrastructure hosts the provider-sync schedule (*/15 * * * *). Both apps’
proxies recognize validated cron credentials independently of browser sessions;
invalid credentials still fail authentication. If hosted runs return 401 before
Calendar logs a request, check the Infrastructure proxy and matching production
CRON_SECRET configuration before investigating provider tokens.
The Calendar cron wrapper invokes Calendar’s workspace sync handler
locally, preserving cron authentication, running locks, cooldown behavior and
calendar_sync_dashboard audit rows. It must not send sync requests to the former
Web owner through INTERNAL_WEB_API_ORIGIN or a protected preview URL.
Both Tasks and Calendar show Sync needs attention beside the calendar
picker when sync stalls, data becomes stale, a provider account needs action,
or the status check fails. The Calendar header popover and the Accounts tab
identify the affected account. Reconnect Google renews a rejected grant
for that account. Grant access requests missing permissions. For a
provider outage or failed status check, Check again reloads the status.
Contact support appears if that retry fails. Remove account asks for confirmation
when the provider reports that an account is gone. Stored events remain
available after removal and during provider outages. Google automatically
refreshes normally expiring access tokens.
Each affected account appears with its status and one recovery action. A
confirmed expired or revoked Google credential offers Reconnect Google.
A missing OAuth configuration or an unidentified failure offers a retry.
The status endpoint verifies workspace membership before reading server-owned
sync history. If a status section is unavailable, the response retains the
sections that succeeded, and the Accounts tab keeps each account’s own provider
status and recovery action. The foreground poll waits for a complete status
before starting sync. The service logs the failed read category and database
error code, while the browser receives only the unavailable section names.
For a failed provider account check, use the X-Calendar-Request-Id response
header to find the matching warning in Workers Observability. The warning
includes a hashed account row, an allowlisted error name and provider code,
upstream HTTP status, and a transport category when known. The route keeps
successful accounts available and offers the matching recovery action for an
expired grant, missing scope, or a temporary provider error.
Calendar Settings loads Hours and Category Colors through the shared typed
client. Under the apex mount, the client targets /calendar/api/ for these
Calendar-owned endpoints and for sync status. Web-owned calendar preferences
stay on Web’s /api/. The calendar-mounted-api regression test checks the
browser URLs against the local route registry. The provider-account-status
and calendar-sync-recovery tests cover classification and recovery actions.
Sync health polls every 30 seconds (every 5 seconds during a run or cooldown).
A running entry older than five minutes is stalled; a successful sync older than
45 minutes is stale. Partial provider failures are recorded as failed runs rather
than successful syncs. Successful runs use the database’s completed status;
completion writes must be checked so a constraint failure cannot leave a run
stuck at running. Provider rate limits and transient outages offer retry,
while authentication failures offer reconnection. Operators should inspect the
Calendar cron execution and dashboard run when retries continue to fail.
Bounded cron execution and revoked consent
The provider cron returns HTTP 200 when dispatch completes, including recorded provider failures. Inspectok, failed, deferred, and workspace summaries;
HTTP 200 alone does not establish successful synchronization. Authentication and
workspace-enumeration failures retain their 401/500 responses. Dashboard rows
use failed only for actual provider failures; successful admitted work is
completed even when summaries report deferred accounts or connections.
A permanently rejected credential is quarantined, not deleted; see
Self-healing OAuth credentials. Sibling
calendars skip further calls in that run; healthy accounts continue.
Calendar-scoped Microsoft errors retain failure diagnostics while sibling
calendars continue; auth and rate-limit errors stop that account. Deletion runs
only after successful fetching, reconciliation and upsert. These rules apply to
manual and background inbound sync; stored events remain visible.
Background runs admit at most 10 workspaces, 20 Google connections and 20
Microsoft connections per workspace, with a rotating selection across ticks.
Workspace enumeration stops at 10,000 active token rows and fails visibly if the
scan is incomplete. Tokens without enabled inbound connections do not dispatch
workspace sync. Google snapshots stop at 20 pages without applying an incomplete
snapshot; Microsoft retains its existing pagination guards. Excess work is
reported as deferred, rather than counted as synchronized or failed. The scan
accepts exactly 10,000 rows and probes one additional row to reject overflow.
A shared 210-second cancellation signal bounds provider work below the private
Infrastructure gateway’s 240-second timeout and the function’s 300-second limit.
Provider and database requests have a 10-second transport timeout; completion
writes use a separate five-second budget so cancellation can still record a
failed run. Queued workspaces and unattempted Google connections are deferred on
cancellation; an in-flight Google failure remains failed. Microsoft stops without
creating provider-failure entries for aborted calendars and defers the unfinished
account plus later accounts. Earlier observed calendar failures remain failed.
Google, Graph and Microsoft refresh transport do not retry internally; the
credential check retries a transient refresh failure twice with jittered backoff
inside the same budget, and the 15-minute schedule owns later attempts. Never
substitute a detached promise timeout that leaves provider work running, and do
not log provider error objects, headers, tokens, or event payloads.
Regression coverage lives in the provider cron route tests, the workspace sync
route tests, and google-inbound-sync, microsoft-inbound-sync,
provider-sync-budget, and provider-sync-network tests under Calendar. Use
ttr resources run -- bun run --cwd apps/calendar test <focused-test-paths>;
local verification does not require building workspace dependencies. Require the
Calendar build, tests, lint and type checks in CI for the submitted commit before
release. This policy does not change the cron cadence or authorize a native
Worker cutover.
Self-healing OAuth credentials
Product decision (26 Oct 2026). Applies to Google and Microsoft accounts in every workspace, for manual sync, the provider cron and interactive provider requests. Nobody repairs a rejected credential by hand.- Classification. Each refresh failure is permanent, transient or
systemic. Permanent: Google
invalid_grant,access_deniedorunauthorized_client(a credential from an earlier client); Microsoftinvalid_grant,interaction_required, consent revoked (AADSTS65001) or a tenant that removed or disabled our app (AADSTS700016, 7000112); andunknown_permanentfor a token-endpoint 400/401 code not seen before. Transient (5xx, 429, throttling, timeouts, network) retries and never deactivates. Systemic means our OAuth client is wrong for everyone (invalid_client,deleted_client,disabled_client, bad or expired client secrets); it never deactivates. - Quarantine. A permanent failure sets
is_active = falsewithdeactivated_reasonanddeactivated_atthroughquarantine_calendar_auth_token. The update matches only the active row whose credential fingerprint (sha256, compared in SQL) andcreated_atare unchanged, so a concurrent reconnect wins. It is idempotent and deletes nothing. Credentials never appear in URLs, logs or responses. - Breaker. From the third distinct account with the same reason, counting
rows still quarantined within the last 24 hours, quarantine holds
(
consensus_hold): nothing is written, the account stays active and is still shown as needing reconnect, and the spike alert fires. A misconfigured client therefore cannot drain accounts. - Isolation. The scheduler reads
okand a bounded provider-degradation signal from a body of at most 64 KiB, and five failed or unreadable runs stop the job for everyone. Sookreports whether the run worked, not whether every account synced: a run that completed returnsok: truewithpartialFailure, per-workspacefailurescodes,tokens.countsand at most 50 non-oktokens.attentionentries (hashed account, provider, outcome, reason); complete detail is in the per-outcome logs. The run fails (ok: false) only when, for one provider, at least three accounts failed with an explicit client-wide diagnosis (systemic), or every evaluated account for that provider did, and none obtained a fresh credential (HTTP 500), when no workspace sync completed, or on the existing enumeration/dispatch failures. Breaker holds of any reason, revocations and one tenant removing our app never fail the job.cron-control’scalendar-provider-sync-contract.test.tsdrives these responses through the scheduler’s real reader and ledger. - Transient provider outages. A nonempty provider sample where every evaluated
account failed transiently returns
ok: true,degraded: trueandtransientProviders(at most Google and Microsoft). A healthy account in the same provider prevents that flag; a healthy sibling provider does not hide it. Cron Control recordslastOutcome: degradeddurably without spending the fatal failure budget, including a single blip and repeated outages. This completed nonfatal run resets the fatal streak but preserves the timestamp of the last productive completion. Healthy later runs restorelastOutcome: ok. Holds and revocations retain their existing nonfatal behavior, and explicit systemic failures still take priority. Coverage: the real dispatch/ledgercalendar-provider-sync-contract.test.tsandledger.test.ts. - Recovery. The calendar sync warning is the durable signal: it lists
quarantined accounts (by email, or name when there is none) with the
provider’s Reconnect action. The owner also gets at most one
account_updatenotification per quarantine (codecalendar_reconnect_required), delivered through their notification preferences (web, email and push); breaker holds send none. Web and every app that ships the shared notification popover render it in English or Vietnamese by code; email, push and mobile show the stored English text. - Reconnect. A successful reconnect updates the same row, reactivates it and
clears both quarantine fields in one statement. While any of the user’s
Google rows in the workspace is quarantined, every Google connect there shows
the consent screen so Google issues a fresh refresh token; the Reconnect
actions in the warning and in calendar settings ask for consent too, which
covers held accounts. When Google returns no new refresh token, the stored one
is reused only through a guarded update that matches a row still active,
unquarantined and unchanged since the callback read it; otherwise (including
a quarantined row) the callback keeps the quarantine and sends the user
through consent again instead of reviving the rejected credential. Automatic
consent restarts are capped at one per account/user/workspace in each fixed
ten-minute window, shared across instances and newly initiated OAuth flows by
the existing single-use nonce ledger. Window boundaries can admit two close
attempts, but never an unbounded loop. A repeated missing refresh token returns
localized HTTP 429 with
Retry-After; an unavailable ledger returns HTTP 503 and never starts another consent flow. Neither response changes the token row. A genuinely fresh refresh token bypasses this restart cap and can complete recovery. Explicit user-initiated reconnects retain their consent behavior; ordinary connects stay consent-free. Coverage:google-consent-restart.test.tsand the Google callback route tests. - Consent restart diagnostics. Limited and unavailable automatic restarts
emit callback-only
consent_restart_limitedandconsent_restart_unavailableevents undercalendar.oauth.token_outcome, with a hashed account handle. These events do not enter provider-sync counters. Restart ledger expiry is at least one minute ahead of the app clock to tolerate modest database clock skew at a window boundary. HTTP 429 and 503 retain explicit localized JSON errors andRetry-After; Calendar has no consumer for a post-auth error parameter, so redirecting to its normal workspace page would hide the recovery error. - Observability. One
calendar.oauth.token_outcomelog line per outcome carries the route template, provider, outcome, reason, provider code and a hashed account id.calendar.oauth.deactivation_spikefires on five or more quarantines, any deferred quarantine, any breaker hold or any systemic outcome. The provider cron also sends due spikes to the existingcreate_notificationdelivery queue as high-priority account updates, with bilingual English/Vietnamese operator copy and aggregate counts only. ConfigureCALENDAR_OAUTH_ALERT_RECIPIENTSas a comma-separated operator email list on Calendar. Each address must resolve to a confirmed auth account that is a currentMEMBERof the root workspace;GUESTmemberships are excluded. The notification is addressed only by that account id, never by a copied email address. At most five distinct valid configured addresses are processed per run. No affected provider account identity, credential or provider payload enters the notification content. Recurring holds/deferrals/systemic and all-transient provider alerts are due only in the first quarter-hour of each hour; five newly quarantined accounts alert immediately. The response exposesalerts.statusand queued/failed/unknown/unresolved/suppressed counts; missing recipients are explicitlyunconfigured. Unresolved or unconfirmed non-operator addresses make no notification write; an account preference that suppresses creation is reported assuppressed. A transport result without an HTTP response (status: 0) is an unknown write, while HTTP errors are failures. A queue failure stays visible in logs and the response while holds and revocations remain nonfatal. There are at most three metadata reads and one notification-write attempt per configured address, sharing one five-second transport deadline. Recipient metadata reads are not retried, and an unknown notification write is never replayed in the same run. Queue acceptance does not prove recipient delivery; verify the existing notification sender and operator receipt during release. Coverage:oauth-spike-notification.test.tsand provider cron route tests. The five-or-more-deactivations branch is not hourly-gated: the normal fifteen-minute schedule permits at most four due runs and twenty notification rows per hour. A re-dispatch can repeat an alert; there is no cross-run idempotency key. Recipient preferences and existing batching still apply. - Degradation scope. The provider degradation signal covers OAuth token
refresh outcomes. A single transient account degrades the job when it is the
only evaluated account for that provider, even beside many healthy accounts
from another provider. A still-valid token counted as
okprevents that provider’s all-transient signal. Events API 5xx/quota failures with valid tokens can therefore still return plain schedulerokand advancelastCompletedAt; per-workspace failure diagnostics remain the signal for those failures. Degraded runs preserve the last productive completion time even if another provider synced successfully. The hourly spike sink includes the all-transient provider signal, including one-account samples. The default minimum sample is one because single-account workspaces need outage visibility. The normal fifteen-minute schedule alerts only on the hourly due run for this branch, and a healthy account in the same provider suppresses it. This bounded hourly noise is intentional; the signal never spends the fatal failure budget. Direct re-dispatch can repeat an alert as described above. Coverage:oauth-token-health.test.tspins the one-account hourly and healthy-mixed cases;oauth-spike-notification.test.tsexcludes root guests. - Exception. Before the quarantine columns reach a database, quarantine is deferred and accounts keep failing as before.
oauth-failure, oauth-token-quarantine,
credential-health, token-refresh, google-inbound-sync and
microsoft-inbound-sync tests; the provider cron route tests (mixed batch,
spike, systemic); the Google and Microsoft auth callback, auth URL and accounts
route tests; the calendar-sync-recovery component test; and the
calendar-auth-token-deactivation.sql pgTAP fixture.
Recovering individual calendar failures
The warning names each failed Google calendar after a sync attempt. Pause sync for this calendar turns off only its inbound import; it preserves its saved events and visibility, and does not disconnect the account or affect other calendars. This action is available during the manual retry cooldown. Restore provider access when applicable, then re-enable inbound sync from the calendar’s sync controls. Sync now retries the remaining enabled calendars. The sync handler stores sanitized version-1failedCalendars diagnostics in the
existing calendar_sync_dashboard.error_stack_trace text field. Each entry has
only connectionId, calendarName, and a classified code. Never store OAuth
credentials, provider response payloads, or headers there. The status API parses
this format, filters disabled/paused connections, and returns failedCalendars;
it never returns the raw diagnostic field. Older unstructured errors still show
an aggregate warning and gain calendar-specific details on the next attempt.
Per-calendar failure diagnostics and the pause shortcut currently cover Google inbound sync. Microsoft failures retain account-level reconnect/retry guidance; individual Microsoft calendar failure identification is not yet available.
Calendar views and behavior
Calendar integration and runtime
Opt-in UI SDK category ordering pilot
CategoryOrderPilot at
@tuturuuu/ui/legacy/calendar/settings/category-order-pilot is a separate,
reorder-only companion with the existing category editor’s value/onChange
shape. No live editor or satellite enables it by default. Existing category
editing, pointer dragging and server-backed satellite persistence stay owned by
their current implementations; this pilot does not establish parity with them.
The pilot uses @ui-sdk/core@0.1.0-beta.1 for roving focus, keyboard draft
ordering, cancellation, focus retention and localized live announcements.
Arrows navigate; Space/Enter picks up and drops; arrows and Home/End move a
picked-up item. Escape or Tab cancels the draft without calling onChange.
Only a changed drop calls onChange; the parent owns persistence. Unique,
nonempty category names are stable identities for this variant. Ambiguous
names show an error and cannot reorder. English and Vietnamese messages ship
with the shared UI consumers.
Regression coverage is in
packages/ui/src/components/ui/legacy/calendar/settings/category-order-pilot.test.tsx:
roles, one tab stop, arrow/Home/End focus, draft/commit timing, cancellation,
modified-key rejection and duplicate identity rejection, under StrictMode.
These DOM checks do not establish browser/screen-reader, SSR/hydration or bundle
acceptance. Exact-commit CI and manual accessibility review are required before
any live enablement. No agent bridge, adapter package or global SDK CSS is used.
Contacts attendees proposal
Contacts attendee selection is under development for new events on supported connected Google calendars. The shared picker reads only workspace-authorized, visible contact/member names and email addresses. Selecting a person adds a guest chip; it does not create a workspace member or send an invitation immediately. Saving the event uses the existing invitation API and its provider authorization. The first slice offers guests only after a successful capability read confirms a writable Google source with an organizer email, a timezone and disabled Google provider-color write operations. Unknown, failed or changing capability reads, native calendars, Outlook calendars and provider-color event commands do not offer attendee selection. If a draft already has guests when its source becomes unsupported, the guests stay visible and removable, and save refuses the unsupported invitation. Outlook capability support remains unimplemented. Guest data is carried through the modal, recovery snapshot and actual create payload. An uncertain submission retains its original UUIDv7 and immutable guest list for an explicit retry; editing a pending draft cannot replace the original operation. There is no automatic invitation retry. The server reauthorizes the request and applies its existing idempotency and provider-saga restrictions. Existing-event attendee editing remains unsupported and is rejected rather than silently discarded. No migration or new invitation-delivery service is added. Regression coverage is inpackages/ui/src/hooks/calendar-event-create-payload.test.ts, alongside the
existing event-save, draft-recovery and draft-save suites. Source checks alone
do not establish sent-invitation or provider acceptance; exact-source validation
and signed-in runtime proof are required before marking this slice delivered.