* chore: remove legacy orchestrator, trading and one-off script leftovers The repository still carried the pre-evOo prototype: a Python orchestrator, the old HTML "evoo-platform" cockpit (whose test ran in the root unit suite), an apex-trading package, the hot-reload deploy.sh for it, a permissions manifest, an architecture note with local file links, agent handoff notes, a Steve Jobs persona template and about ninety one-off scripts that probe a developer database with hard-coded local URLs. None of it is used by the product, CI or the real deploy in ops/evo-deploy. Delete those files, drop the evoo-platform test glob from the root vitest config, the Cockpit section from .env.example and the dead biome and gitignore entries, and update the docs that listed the removed tools. scripts/start-tmux.sh no longer starts the removed sentinel and resolves the checkout from its own location instead of a machine-specific path; scripts/seed-ollama.ts requires DATABASE_URL instead of falling back to a local URL with a username. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * fix(web): drop trading and persona prompts from the conversation shell The web shell still showed leftovers from the trading prototype: composer chips with German trading and "Steve Jobs" prompts, trading suggestion chips under the empty conversation line, a German trading hero for the empty transcript, and a German "data protection" status panel in the sidebar. They suggested actions the product does not have and added persistent chrome. Remove the composer chips and their helper, the empty-state chips and the hero (the empty conversation keeps its existing one-line start hint), the sidebar trading indicator and the data trust panel. The new-bot E2E now asserts the plain empty state; the sidebar spec no longer expects the trading status, and the placeholder Steve Jobs spec with no assertions is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * refactor: remove the trading bot status integration With the sidebar trading indicator gone, the only remaining consumer of the trading bot status was a banner in General settings that reused the same component. evOo is a personal assistant; a status proxy and poller for one external trading service, configured through service-specific TRADING_BOT_URL and VITE_TRADING_BOT_URL variables, does not belong in the core product. Remove the settings banner and its prop plumbing, the web poller, the indicator component, the /api/trading-bot/status proxy, the shared core contract, the env loading and both variables from .env.example, together with their tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * chore: remove one-off database scripts and a stale review note packages/db carried four hand-run scripts outside the package build that query or seed a developer database with a hard-coded connection string, one of them for a specific account. docs/VOICE-FIRST-REVIEW.md was a one-time verification note for a workflow that no longer exists and named private machines and local paths. Nothing references them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(memory): remember appends dated notes instead of replacing memory The remember tool rewrote the bot's whole MEMORY.md with each call, so every new fact erased the earlier ones unless the model re-sent the full document. - MemoryCommitRequest gains mode "append" (the store joins the note onto the current content inside the same serializable transaction and still writes a revision row) and every commit is capped at 16 KB per document. - remember appends a dated bullet ("- YYYY-MM-DD: ...", the user's local date) by default and rewrites only with mode "replace"; a full document returns an error that tells the bot to condense it. Retries of the same tool call stay single appends through the existing effect record. - Scripted runtime memory entries can append too; the scripted "remember" script now appends instead of overwriting the bot's memory. - When memory does not fit the run's 32 KB budget, the prompt keeps a document's newest lines instead of its oldest. - memory.update maps an oversized save to BAD_REQUEST. - docs/PRODUCT.md records that UserFact is the cross-space user model and the space MEMORY.md stays space notes (no migration). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(coach): goals, habits, check-ins, daily briefs and check-in rhythm The main agent should coach the user, but nothing stored what the user wants to achieve or keep doing, and no routine ever checked in. This adds the data model and the interfaces the onboarding intake and the coach tools build on. - Schema: UserGoal, Habit, CheckIn (one per habit, goal or day and date) and DailyBrief, all keyed to the user's local calendar date, plus a coachKey on Routine that marks the main bot's coach check-ins. - Contracts (coach.ts): CoachRhythm, Goal, Habit, CheckIn, DailyBrief and CoachToday DTOs and the RPC inputs. - Repository (@rakazo/db coach.ts): goal, habit and check-in CRUD with per-user limits, upsertDailyBrief and loadCoachToday with streaks in the user's time zone. - coach-rhythm.ts: setCoachRhythm/getCoachRhythm keep up to three main bot routines (morning brief, evening check-in, weekly review) in the main conversation in step with the user's chosen times. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(notifications): add push subscriptions, notification settings and web push interfaces Push could only reach one mobile device per user (a token file), quiet hours did not exist, and the web app had no service worker, so a closed tab never heard about finished work. This lands the shared interfaces first so onboarding can build on them: - push_subscriptions (web push endpoints and Expo tokens, one row per device) and user_notification_settings (quiet hours as minutes in the profile time zone, nudges, a per-day nudge counter), with CHECK constraints. - NotificationSettingsSchema and web push contracts, notifications.settings.get/update and notifications.webPush.config/subscribe/unsubscribe (owner-scoped, https endpoints only). - getNotificationSettings/updateNotificationSettings plus the policy and nudge-cap helpers. - VAPID keys from VAPID_PUBLIC_KEY/VAPID_PRIVATE_KEY or generated once and stored encrypted, and an SSRF-guarded web push sender built on the web-push package. - The web app links its manifest, registers a push-only service worker where supported (secure context, not the desktop app) and exposes webPushSupported/webPushEnabled/enableWebPush/ disableWebPush. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * chore: replace machine-specific paths and addresses with placeholders ORIGIN.md pinned the intended checkout to an absolute path under a personal home directory, docs/LOCAL-SETUP.md listed folders on one developer's machine, and two tests used what looks like a real tailnet address. Use a home-relative path, drop the machine-specific folder list, and use 100.100.100.100 in the tests; it is still inside 100.64.0.0/10, so both tests check the same thing as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(coach): repository, streak and rhythm suites Covers what the coach interfaces promise before anything builds on them: goal and habit ownership and limits, one check-in per habit, goal and day dated in the user's time zone, streaks across weekends and weeks, and a rhythm that keeps exactly one main-bot routine per check-in and is idempotent when set again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * refactor(contracts): share one clock-time schema The coach rhythm and the quiet hours both parse "HH:MM" wall-clock times and each defined its own ClockTimeSchema, which the contracts index cannot export twice. Both now import it from one module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(onboarding): ask the onboarding questions in the main conversation The wizard asked for the account name again and a "Tell us about yourself" form, and the focus answer in the main conversation was never saved. The main bot now gets to know the user in the main conversation instead, one card after each answer. - UserOnboarding keeps the pending step, the focus and when onboarding finished. - onboarding-intake.ts declares the steps (focus, goal, rhythm, quiet hours, notifications) as cards plus what their answers change; onboarding.ts commits an answer, the focus app suggestions and the next card or the closing line in one transaction. - The choice block gains a step, an optional text input and the typed answer; choose takes the step, the text and whether the device can still turn push on. - The focus answer becomes a goals fact; the goal, rhythm and quiet-hours effects and the push seam are placeholders until the coach and notification modules are merged. - The wizard drops the preferences step and fills time zone, locale and language from the browser; the main bot's prompt notes open onboarding cards; agent history shows a card's question and answer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(notifications): fan push out to every device, honour quiet hours, add notify_user Run notifications reached at most one phone and nothing could hold them back at night. - PushNotificationProvider sends each notification to all of the user's registered devices (web push and Expo), skips everything during quiet hours in the profile time zone, drops devices the push service reports gone (404/410, DeviceNotRegistered), records lastUsedAt and links each push to its conversation. - Expo tokens move from DATA_DIR/push-tokens files into push_subscriptions: the API imports and deletes the legacy files at start; notifications.registerPush/unregisterPush keep their contract for the mobile app (tokens must look like Expo tokens). - NotificationMessage gains the nudge kind, and the main bot gets notify_user: a short push to the main conversation that respects the nudge switch, quiet hours and a cap of three per day. It is withheld from shared messaging channels and from runs answering another owner's agent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(coach): main-bot coach tools and goals in its prompt The main agent had no way to record what the user wants to achieve or how their day went, and its prompt never showed their goals or habits. - update_goal, update_habit, log_check_in and write_daily_brief, main-bot only and, like update_user_profile, withheld from shared channels and from runs that answer another owner's agent. Goals and habits can be named by id or exact title. - The main bot's own runs list active goals and habits (with ids, done state and streak) in the <user> block; the basics-only block and every other bot never see them. The main agent role adds a short coaching stance and names each coach tool only when the run has it, so the check-in routine prompts stay tool-agnostic. - The scripted runtime understands a few coach commands and the morning check-in, so tests can drive the tools end to end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * fix(web): use English Lingui sources for German UI text Several web surfaces hard-coded German (the project card, roster and activity status labels, the sidebar "Heute" label) or used German text as the Lingui source message (sidebar sections, project timeline, bot picker, voice entry, group stage, copy and read-aloud buttons). English users saw German, and because production builds keep only message ids, none of these strings could be translated per locale. Convert them to English source messages, keeping the meaning: - ProjectCreatedCard: Lingui Trans/Plural instead of literals. - agent-activity: labels go through i18n._ with literal ids so the module stays importable from plain unit tests; the extractor still collects them. - Shell, ProjectSessionTimeline, bot-picker, StageVoiceEntry, OoStage: English sources, reusing existing messages where one already fit ("just now", "{n}m ago", "Search", "No bots match", "Set up voice", "Group conversation", "Transcript"). - The conversation picker matches its create entry against the translated label instead of a fixed German string. The German wording returns through the de catalog in the next commit. Unit and E2E tests now assert the English labels. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(web): keep Lingui catalogs complete and in sync The committed catalogs were last extracted weeks ago: about 330 source messages were missing from every locale, and production builds keep only message ids, so those strings rendered as hash ids (sidebar sections, privacy settings, profile, timeline, ...). German also had 226 empty entries, and every extraction rewrote the files because references carried line numbers. - lingui.config.ts: po references without line numbers, and a stable sort that breaks Lingui's ordering ties (explicit ids, equal text) by id, so the output no longer depends on file-system order. - Re-extract all catalogs with --clean (drops 25-44 obsolete entries per locale; no existing translation changed). - Translate every German entry (du form, consistent with the existing catalog). Other locales keep empty entries and fall back to English. - i18n-catalog-sync.test.ts extracts into a copy of the catalogs and fails when the committed files differ or a German entry is empty, so stale catalogs fail the unit test job (offline, about 5 s). Adds @lingui/format-po (already installed through @lingui/cli) as a direct dev dependency to configure the formatter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * refactor(memory): derive the run's memory budget from the document limit The prompt budget was a separate 32 KB constant; it is now twice the per-document limit, so a full bot document and a full space document keep fitting if either number changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(profile): edit facts in place in About you About you could only confirm or delete what the bots know about the user, so a fact that was slightly wrong or filed under the wrong category had to be deleted and taught again, and a fact could not be limited to some spaces from the app even though the profile supports it. - Each fact gets an Edit button that turns its row into an inline editor: wording, category, and (when the user has more than one space, or the fact is already limited) which spaces it shows in. Escape or Cancel leaves it unchanged; only changed fields are sent through profile.update editFacts. - A limited fact names its spaces next to its source. - The repository validates edits like new facts: a wording whose normalized form is empty or equals another fact of the user is refused, all edits of one update apply atomically, and the stored embedding is only dropped when the wording really changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(inbox): list and answer items from all of the user's spaces The inbox in the main conversation only showed asks, approvals, takeovers and unread threads of the current space. The main conversation lives in the home space, so anything a bot needed in a project space never reached it. - inbox.list now covers every space the user belongs to (except spaces being deleted), still only the user's own bots, runs and threads. Items from another space carry that space's id and name. - The web inbox shows the space name next to the bot for those items, answers them with that space's header so the existing thread procedures check membership and ownership for that space, and opens their thread in it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(coach): coach RPCs for goals, habits, check-ins, today and rhythm The web app needs to show and change the user's coach data, and the check-in times need a way to change after onboarding. - coach.today, coach.goals.*, coach.habits.*, coach.checkIns.* and coach.rhythm.get/set, owner-only and not space-scoped; another user's ids read as not found, invalid input as a bad request. - coach-rhythm reuses the shared clock-time helpers. - Tests: an API suite covering ownership and validation for every procedure, the coach tools driven through the main bot (and refused for a specialist), and a morning check-in routine that fires in the main conversation and writes today's brief; the unauthenticated authorization sweep lists the new procedures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(onboarding): save goal, check-in rhythm, quiet hours and push from the cards With the coach and notification modules merged, the onboarding answers now take effect: - the goal card creates a goal (source onboarding) through createGoal; - the rhythm card sets the main bot's check-in routines through setCoachRhythm, and the closing line names the first check-in from the routines that were saved; - the quiet-hours card updates the notification settings; - the choice card tells the server whether this browser can still turn push on, so the notifications card is offered only there, and "Turn on" subscribes before answering. The thread lock becomes NO KEY UPDATE so a rhythm routine, which references the thread, can be written while the answer holds the lock. The goal answer is capped at the coach title length. A Postgres suite walks the questions end to end: answers, skips, a dismissed card, a stale and a doubled answer, another bot's focus card, and another user's access. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(notifications): cover quiet hours, delivery, nudges and the notification RPCs The quiet-hours CHECK accepted a row with only one bound set, because a NULL comparison made the whole condition NULL; it now requires both bounds explicitly. The migration has not shipped yet, so it is corrected in place. - Unit: quiet-hours math across midnight, time zones and daylight saving; VAPID key handling (configured, generated once and shared, invalid); the web push sender (encrypted VAPID-signed request, gone on 404/410, no private or non-https endpoints); the fan-out with fake senders. - PostgreSQL: settings and subscription repositories (constraints, per-user removal, endpoint hand-over, device cap, concurrent nudge cap, cascade on account deletion), delivery and notify_user against a real main conversation, and every notification RPC through the API including cross-user isolation and endpoint validation. - .env.example documents the optional VAPID keys and VAPID_SUBJECT. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(web): notification settings, and sign-out stops this browser's push Users had no way to turn on push for a browser, set quiet hours or opt out of nudges. Settings gains a compact Notifications section: a switch for push on this device (only where web push works: a secure context outside the desktop app), quiet hours with from/to times (22:00-07:00 when first turned on) and a switch for nudges. Changes save in order as they are made. A browser that blocked notifications says so instead of offering a dead switch. Logging out unregisters the browser first, so a shared computer stops receiving the account's pushes. The E2E stubs the Push API (headless Chromium has no push service), walks all three controls, checks they survive a reload and captures the notification-settings screenshot. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * fix(profile): keep the fact editor's Save label visible Small buttons in ui-web merge their text-ui-label size over the default variant's text color, so the small Save button rendered ink on ink. The editor now uses default-size controls, with the category select at the same height. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * refactor(notifications): keep the push sender contract next to the fan-out The payload, target and outcome types are shared by the Expo and web push senders, so they now live with PushSender in push-notifications.ts instead of in the web push adapter. The settings E2E also stubs the Notification permission (headless Chromium reports it as denied even when granted), and the quiet-hours inputs are wide enough for 12-hour times. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * fix(core): load child_process normally in the git checkout reader readGitCheckout loaded node:child_process through require(), which does not exist in the ESM API runtime. Linking a project space to a folder that is a git checkout therefore failed after the space was created. The lazy load is no longer needed: the reader is only reachable through the server-only "@rakazo/core/git-checkout" subpath, never through the package entry the web app bundles. Import spawn at the top instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(onboarding): ask before discovering projects and let the user choose The onboarding scan started on its own, discarded what it found, claimed to read email and calendars, simulated progress for everyone who could not scan, and its project creation always failed (wrong Space fields and a space lookup by title across tenants). Discovery now asks first and creates nothing without a choice: - The scan step appears only for the deployment owner when ONBOARDING_SCAN_HOME is set; everyone else skips it. The simulated scan is gone. - It shows the folder and asks. Only directory listings are read: git projects up to four levels deep, their languages and a few tools (Docker, GitHub Actions, Terraform). Symlinks are never followed and each chosen folder is resolved again before use, so nothing outside the folder is reached. Results stay with the account that scanned. - Found projects are a checklist (none preselected); found languages and tools are facts (preselected). "Add" creates one project space per chosen project with createSpaceForMember and wireProjectWorkspace in the user's own organization, reusing the user's own space already linked to that folder, and saves the chosen facts as onboarding facts under the profile lock and fact limit. - When a connection becomes connected (direct connect, authorization round trip, or catalog reconciliation), "Uses <App>" is remembered as a tools fact from the connector. Revoking keeps it. The E2E harness now points ONBOARDING_SCAN_HOME at a fixture folder and starts without a deployment owner, so owner-only onboarding steps appear only in specs that take the seat through /__e2e/deployment-owner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(web): coach on the Heute page Heute only listed runs and linked to a hard-coded local Mission Control address, so the coach's work had nowhere to show. - Today's brief at the top, habits with a check-off and their streak, and active goals, each only when there is something to show; then the existing needs-you, doing and done lists. - One icon button opens the check-in times (morning, evening, weekly), loaded when opened and saved on every change. - The page reads coach.today, refreshes it when a run finishes or the tab becomes visible, and checks habits off optimistically; the date header uses the user's time zone from the profile. - Removes the Mission Control link and its constant. - Tests: helper unit tests and a web E2E that writes the brief through the main bot, checks a habit off across a reload and sets check-in times (screenshots heute-coach and heute-rhythm). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(onboarding): walk the onboarding questions end to end; mobile reads cards as text - onboarding-intake.spec walks focus, goal (after typing into the composer, which still works), check-ins, quiet hours and the notifications card when the browser offers it, with the onboarding-intake-goal, -rhythm and -done screenshots. - completeOnboarding and the wizard specs drop the preferences step; the scan step is optional (skipped when it asks, otherwise it advances by itself). - The user-profile spec now checks the browser-filled profile and the focus fact; the conversation spec checks the shorter app suggestion and the following goal question. - The hover spec measures a reply that fills its row (a bot row's rail sits at the row's end, so the old long onboarding line was what made it pass) and scopes Send to the composer, since an open goal card has its own. - Mobile shows a choice card as its question and answer instead of an empty bubble. - The focus options drop their unused summary. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(web): stub the Notification permission without a static-only class Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(web): find the sidebar Today button by its English label The shell contrast test added on main looks up the sidebar button by the old German source text, which this branch replaces with "Today". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * feat(onboarding): show the onboarding cards and check-in names in the user's language The onboarding cards, the closing line and the coach routine names were English server text for every user. The server keeps the state and an English fallback; the web now words them through Lingui, so there is one translation source. - Choice cards: the web says the question, the option labels and the placeholder from the step and option ids, and keeps the server text for anything it does not know (quiet-hour ranges are already written in the user's locale). Another bot's focus card is recognized by its option ids. Mobile and agent history keep the server text. - The "Got it. … are a good place to start." line is gone: the app cards speak for themselves, and with no cards nothing is said. - The closing line becomes an intake_note block (note "done", nextCheckInAt, English text). The web words it with the first check-in in the user's clock; mobile blockText and blocksToAgentHistoryText read its text through their generic fallback. - Routines carry coachKey. The routine list and editor show a check-in under its label in the UI language until the user renames it; saving an untouched label keeps the stored name. The English names move to contracts (COACH_ROUTINE_NAMES); prompts stay English. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * style: use top-level type imports in the coach changes AGENTS.md asks for top-level `import type` instead of inline `type` specifiers; this applies it to the import statements the coach work added or changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * chore(web): extract catalogs and translate the coach strings to German Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(web): look for the bot reply in the transcript only The main conversation's sidebar row now previews the latest reply, so the unscoped text lookup matched the sidebar too and failed in strict mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(web): drop the trading status from the shell contrast test main's contrast test now waits for the sidebar trading status before measuring; this branch removes that status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(onboarding): link the foreign folder while its tenant owns the deployment Since #112 only the deployment owner can link a host folder, so the discovery test creates the other tenant's linked space while that tenant holds the deployment, then hands the deployment to the scanning owner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * chore(web): extract catalogs and translate the in-app browser strings Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test: look up the home main conversation in the scheduling journey Since every project has its own main conversation, the journey that schedules for a specialist found the user's main conversation with findFirst over all of them. With the Lab project's conversation also matching, it picked either one, so the check failed about one run in three. The lookup now names the home space, where the specialist joined and the routine is created. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test: expect the home main conversation's ask in another space's inbox Every project now has a main conversation of its own, so an ask waiting in the home main conversation is not visible from a project and its inbox lists it, answered in the home space. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * fix(coach): move check-ins when the user's time zone changes The coach check-ins are main-bot routines scheduled in the profile time zone, but a later zone change (About you, onboarding, the main bot's update_user_profile tool, or forgetting the whole profile) left them in the old zone until the rhythm was saved again, so they fired at the wrong local time. syncCoachTimeZone, next to the rhythm code, moves the main bot's coach routines that are not in the current profile zone into it, recomputes the next run of armed ones and re-arms their wakeup. Paused check-ins move but stay paused, routines the user made are never touched, users without check-ins get none, and a save that leaves the zone as it is changes nothing. The profile update and forget RPCs and the profile tool call it whenever they write the zone. Quiet hours, the daily nudge cap and coach dates are evaluated in the profile zone when they are used, so they need no migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * fix(web): word the main conversation preview in the user's language during onboarding While onboarding wrote the main conversation, its sidebar row, project rows and Heute showed the server preview: nothing for a pending card (a card has no text of its own, so the row fell back to "Ready") and the English fallback of the closing note, even for a German user. Groups now carry `previewBlock` next to `preview`: the latest message when it is an onboarding card or note, validated with the same block schemas the messages use (now named exports). The web words it with the helpers that render the card and the note, so no copy is duplicated: the question while a card waits, the answer once given, and the closing note in the user's language and clock. A dismissed card keeps the plain preview, as the conversation no longer shows it. The field is left out for every other message, and mobile keeps using the plain `preview`. The chosen-answer lookup moves from the card into onboarding-copy so the card and the preview share it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u * test(web): look for the focus question in the conversation, not the sidebar The main conversation's sidebar row now shows the pending intake question, so a page-wide text match finds it twice (strict mode) or never reaches zero. The specs mean the card in the open conversation, so they look there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u --------- Co-authored-by: Claude <noreply@anthropic.com>
1164 lines
40 KiB
TypeScript
1164 lines
40 KiB
TypeScript
import type {
|
||
Bot,
|
||
BotSection,
|
||
ComputerMode,
|
||
Group,
|
||
Me,
|
||
MessageBlock,
|
||
ModelCatalogEntry,
|
||
ModelCredential,
|
||
Space,
|
||
SpaceNavigation,
|
||
} from "@rakazo/contracts";
|
||
import type { ThreadHistory } from "@rakazo/core";
|
||
import {
|
||
aiConsentTarget,
|
||
aiDataUsesForProcedure,
|
||
cancelResponseBody,
|
||
ensureAiDataConsent,
|
||
isRunTerminalEvent,
|
||
mergeThreadHistory,
|
||
prependThreadHistoryPage,
|
||
progressMessageId,
|
||
readBoundedJsonResponse,
|
||
reduceLiveMessageBlocks,
|
||
runFailureError,
|
||
signupRequiresEmailVerification,
|
||
takeLiveMessage,
|
||
updateCloudAgentMessages,
|
||
upsertMessageById,
|
||
} from "@rakazo/core";
|
||
import * as SecureStore from "expo-secure-store";
|
||
import { promptAiConsent } from "./ai-consent";
|
||
import type { EndpointResult } from "./endpoint";
|
||
import { defaultApiBase, normalizeApiBase } from "./endpoint";
|
||
import { t } from "./i18n";
|
||
import { resumeLiveNotifications } from "./live-notifications";
|
||
import {
|
||
clearSessionToken,
|
||
loadSessionToken,
|
||
restoreSessionToken,
|
||
saveSessionToken,
|
||
snapshotSessionToken,
|
||
tokenFromAuthResponse,
|
||
} from "./session";
|
||
|
||
const ENDPOINT_KEY = "rakazo.api_base";
|
||
const SPACE_KEY = "rakazo.space_id";
|
||
const SPACE_ROLLBACK_KEY = "rakazo.space_rollback";
|
||
const RPC_TIMEOUT_MS = 8_000;
|
||
export const MAX_MOBILE_AUTH_RESPONSE_BYTES = 256 * 1024;
|
||
export const MAX_MOBILE_RPC_RESPONSE_BYTES = 16 * 1024 * 1024;
|
||
/** Inbox bootstrap reads safe to replay without a Space header during auth recovery. */
|
||
const SPACE_AUTH_RECOVERY_SAFE_PROCS = new Set(["spaces/list", "me"]);
|
||
|
||
let cachedApiBase: string | undefined;
|
||
let cachedSpaceId = "";
|
||
/** Bumped on every in-memory Space selection change so a delayed response
|
||
* cannot treat a later reselection of the same Space id as its own. */
|
||
let spaceSelectionGeneration = 0;
|
||
|
||
function bumpSpaceSelectionGeneration(): void {
|
||
spaceSelectionGeneration += 1;
|
||
}
|
||
|
||
function responseErrorMessage(body: unknown, fallback: string): string {
|
||
return typeof body === "object" && body && "message" in body
|
||
? String((body as { message?: string }).message ?? fallback)
|
||
: fallback;
|
||
}
|
||
|
||
export function currentApiBase() {
|
||
const parsed = normalizeApiBase(cachedApiBase ?? defaultApiBase());
|
||
if (!parsed.ok) throw new Error(parsed.error);
|
||
return parsed.url;
|
||
}
|
||
|
||
export async function loadApiBase() {
|
||
let apiBase = defaultApiBase();
|
||
try {
|
||
const stored = await SecureStore.getItemAsync(ENDPOINT_KEY);
|
||
if (stored) {
|
||
const parsed = normalizeApiBase(stored);
|
||
if (parsed.ok) {
|
||
apiBase = parsed.url;
|
||
}
|
||
}
|
||
} catch {
|
||
// SecureStore is unavailable in some test / web hosts.
|
||
}
|
||
cachedApiBase = apiBase;
|
||
try {
|
||
const storedSpace = (await SecureStore.getItemAsync(SPACE_KEY)) ?? "";
|
||
cachedSpaceId = storedSpace;
|
||
bumpSpaceSelectionGeneration();
|
||
// A deletion fallback must override the now-invalid saved Space even when
|
||
// the device failed to replace that value before the previous process exited.
|
||
await recoverSpaceRollback(cachedApiBase);
|
||
} catch {
|
||
// Keep any in-memory selection when SecureStore is temporarily unavailable.
|
||
}
|
||
return cachedApiBase;
|
||
}
|
||
|
||
export async function selectSpace(id: string) {
|
||
if (!(await clearStoredValue(SPACE_ROLLBACK_KEY))) return false;
|
||
// Claim memory before persisting: recovery paths reconcile against the
|
||
// in-memory selection, so a durable write must never precede its owner.
|
||
const previousSpaceId = cachedSpaceId;
|
||
cachedSpaceId = id;
|
||
bumpSpaceSelectionGeneration();
|
||
// Generation ownership distinguishes A→B→A from "we still own this claim":
|
||
// an ID-only check would treat a later same-id selection as ours.
|
||
const claimGeneration = spaceSelectionGeneration;
|
||
try {
|
||
await SecureStore.setItemAsync(SPACE_KEY, id);
|
||
// Our write may have landed stale behind a newer overlapping selection's
|
||
// write. Re-assert the live selection best-effort so durable converges
|
||
// to it; each selector heals at most once, so overlapping chains settle
|
||
// on the latest claim. Never delete here: a missing memory owner means
|
||
// another path (recovery, sign-out) owns cleanup.
|
||
const liveSpaceId = cachedSpaceId;
|
||
if (liveSpaceId && liveSpaceId !== id) {
|
||
await writeStoredValue(SPACE_KEY, liveSpaceId);
|
||
}
|
||
} catch {
|
||
// Roll back the claim and heal durable state: a concurrent recovery may
|
||
// have persisted the rolled-back id after reading it, which would leave
|
||
// restart opening a Space the live session is not using. A newer
|
||
// overlapping selection owns both by now, so only heal a claim we hold.
|
||
if (cachedSpaceId === id && spaceSelectionGeneration === claimGeneration) {
|
||
cachedSpaceId = previousSpaceId;
|
||
bumpSpaceSelectionGeneration();
|
||
if (previousSpaceId) await writeStoredValue(SPACE_KEY, previousSpaceId);
|
||
}
|
||
return false;
|
||
}
|
||
await resumeLiveNotifications(currentApiBase(), await loadSessionToken(), id).catch(
|
||
() => undefined,
|
||
);
|
||
return true;
|
||
}
|
||
|
||
export function selectedSpaceId(): string | null {
|
||
return cachedSpaceId || null;
|
||
}
|
||
|
||
/** Keep requests usable after the server deleted the selected Space but native
|
||
* storage could not replace it. Neutralize any same-endpoint rollback before
|
||
* writing the replacement selection so a cleanup failure cannot leave the new
|
||
* id beside a stale record that recoverSpaceRollback would prefer on restart. */
|
||
export async function adoptDeletedSpaceFallback(id: string): Promise<boolean> {
|
||
cachedSpaceId = id;
|
||
bumpSpaceSelectionGeneration();
|
||
// Neutralize any same-endpoint rollback before writing SPACE_KEY. Writing the
|
||
// selection first can leave it beside a stale record that recoverSpaceRollback
|
||
// would prefer on restart if later cleanup fails.
|
||
const rollbackNeutralized =
|
||
(await clearStoredValue(SPACE_ROLLBACK_KEY)) || (await saveSpaceRollback(id));
|
||
if (rollbackNeutralized && (await writeStoredValue(SPACE_KEY, id))) {
|
||
// SPACE_KEY is authoritative; drop a rollback we may have written only to
|
||
// overwrite a stale record (best-effort).
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
await resumeLiveNotifications(currentApiBase(), await loadSessionToken(), id).catch(
|
||
() => undefined,
|
||
);
|
||
return true;
|
||
}
|
||
// Clear before saving recovery: an empty selection lets startup resolve the
|
||
// server default even when the recovery record cannot be written.
|
||
const staleSelectionCleared = await clearStoredValue(SPACE_KEY);
|
||
const recoverySaved = await saveSpaceRollback(id);
|
||
await resumeLiveNotifications(currentApiBase(), await loadSessionToken(), id).catch(
|
||
() => undefined,
|
||
);
|
||
// Only treat a cleared selection as durable success when no same-endpoint
|
||
// rollback remains to override it after restart.
|
||
return recoverySaved || (staleSelectionCleared && (await clearStoredValue(SPACE_ROLLBACK_KEY)));
|
||
}
|
||
|
||
export async function selectInitialSpace(id: string) {
|
||
if (selectedSpaceId()) return true;
|
||
return selectSpace(id);
|
||
}
|
||
|
||
async function clearSpace(): Promise<boolean> {
|
||
const spaceCleared = await clearStoredValue(SPACE_KEY);
|
||
const rollbackCleared = await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
if (!spaceCleared || !rollbackCleared) return false;
|
||
cachedSpaceId = "";
|
||
bumpSpaceSelectionGeneration();
|
||
return true;
|
||
}
|
||
|
||
async function clearStoredValue(key: string): Promise<boolean> {
|
||
try {
|
||
await SecureStore.deleteItemAsync(key);
|
||
return true;
|
||
} catch {
|
||
return writeStoredValue(key, "");
|
||
}
|
||
}
|
||
|
||
async function writeStoredValue(key: string, value: string): Promise<boolean> {
|
||
try {
|
||
await SecureStore.setItemAsync(key, value);
|
||
return true;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
async function snapshotSpace(): Promise<{ ok: true; value: string } | { ok: false }> {
|
||
if (cachedSpaceId) return { ok: true, value: cachedSpaceId };
|
||
try {
|
||
return { ok: true, value: (await SecureStore.getItemAsync(SPACE_KEY)) ?? "" };
|
||
} catch {
|
||
return { ok: false };
|
||
}
|
||
}
|
||
|
||
/** Clears session + space for an endpoint change. Restores both if either wipe fails. */
|
||
async function clearCredentialsForEndpointChange(): Promise<
|
||
{ ok: true; previousToken: string; previousSpace: string } | { ok: false; result: EndpointResult }
|
||
> {
|
||
const previousToken = await snapshotSessionToken();
|
||
const previousSpace = await snapshotSpace();
|
||
if (!previousToken.ok || !previousSpace.ok) {
|
||
return {
|
||
ok: false,
|
||
result: { ok: false, error: t("Could not clear the previous server session") },
|
||
};
|
||
}
|
||
const rollbackReady = previousSpace.value
|
||
? await saveSpaceRollback(previousSpace.value)
|
||
: await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
if (!rollbackReady) {
|
||
return {
|
||
ok: false,
|
||
result: { ok: false, error: t("Could not clear the previous server session") },
|
||
};
|
||
}
|
||
const sessionCleared = await clearSessionToken();
|
||
cachedSpaceId = "";
|
||
bumpSpaceSelectionGeneration();
|
||
const spaceCleared = await clearStoredValue(SPACE_KEY);
|
||
if (sessionCleared && spaceCleared) {
|
||
return { ok: true, previousToken: previousToken.value, previousSpace: previousSpace.value };
|
||
}
|
||
|
||
await restoreCredentials(previousToken.value, previousSpace.value);
|
||
return {
|
||
ok: false,
|
||
result: { ok: false, error: t("Could not clear the previous server session") },
|
||
};
|
||
}
|
||
|
||
async function restoreCredentials(previousToken: string, previousSpace: string) {
|
||
if (previousToken) await restoreSessionToken(previousToken);
|
||
if (previousSpace) {
|
||
cachedSpaceId = previousSpace;
|
||
bumpSpaceSelectionGeneration();
|
||
try {
|
||
await SecureStore.setItemAsync(SPACE_KEY, previousSpace);
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
} catch {
|
||
// The endpoint-bound rollback record restores this selection after restart.
|
||
}
|
||
}
|
||
if (previousToken) {
|
||
await resumeLiveNotifications(currentApiBase(), previousToken, previousSpace).catch(
|
||
() => undefined,
|
||
);
|
||
}
|
||
}
|
||
|
||
async function saveSpaceRollback(spaceId: string): Promise<boolean> {
|
||
return writeStoredValue(
|
||
SPACE_ROLLBACK_KEY,
|
||
JSON.stringify({ apiBase: currentApiBase(), spaceId }),
|
||
);
|
||
}
|
||
|
||
async function recoverSpaceRollback(apiBase: string) {
|
||
const stored = await SecureStore.getItemAsync(SPACE_ROLLBACK_KEY);
|
||
if (!stored) return;
|
||
let parsed: unknown;
|
||
try {
|
||
parsed = JSON.parse(stored);
|
||
} catch {
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
return;
|
||
}
|
||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
return;
|
||
}
|
||
const rollback = parsed as { apiBase?: unknown; spaceId?: unknown };
|
||
if (rollback.apiBase !== apiBase || typeof rollback.spaceId !== "string" || !rollback.spaceId) {
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
return;
|
||
}
|
||
cachedSpaceId = rollback.spaceId;
|
||
bumpSpaceSelectionGeneration();
|
||
if (await writeStoredValue(SPACE_KEY, rollback.spaceId)) {
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
return;
|
||
}
|
||
// Could not replace the selection yet. Drop the deleted id so startup RPCs
|
||
// are not scoped to an inaccessible Space; keep the recovery record.
|
||
await clearStoredValue(SPACE_KEY);
|
||
}
|
||
|
||
export async function saveApiBase(input: string): Promise<EndpointResult> {
|
||
const parsed = normalizeApiBase(input);
|
||
if (!parsed.ok) return parsed;
|
||
if (parsed.url === defaultApiBase()) return resetApiBase();
|
||
const previous = currentApiBase();
|
||
let cleared: { previousToken: string; previousSpace: string } | undefined;
|
||
if (parsed.url !== previous) {
|
||
const result = await clearCredentialsForEndpointChange();
|
||
if (!result.ok) return result.result;
|
||
cleared = result;
|
||
}
|
||
try {
|
||
await SecureStore.setItemAsync(ENDPOINT_KEY, parsed.url);
|
||
} catch {
|
||
if (cleared) await restoreCredentials(cleared.previousToken, cleared.previousSpace);
|
||
return { ok: false, error: t("Could not save the server URL") };
|
||
}
|
||
cachedApiBase = parsed.url;
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
return parsed;
|
||
}
|
||
|
||
export async function resetApiBase(): Promise<EndpointResult> {
|
||
const previous = currentApiBase();
|
||
const url = defaultApiBase();
|
||
let cleared: { previousToken: string; previousSpace: string } | undefined;
|
||
if (url !== previous) {
|
||
const result = await clearCredentialsForEndpointChange();
|
||
if (!result.ok) return result.result;
|
||
cleared = result;
|
||
}
|
||
try {
|
||
await SecureStore.deleteItemAsync(ENDPOINT_KEY);
|
||
} catch {
|
||
if (cleared) {
|
||
await restoreCredentials(cleared.previousToken, cleared.previousSpace);
|
||
return { ok: false, error: t("Could not clear the custom server URL") };
|
||
}
|
||
}
|
||
cachedApiBase = url;
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
return { ok: true, url };
|
||
}
|
||
|
||
export async function authHeaders(
|
||
spaceId: string | null = selectedSpaceId(),
|
||
): Promise<Record<string, string>> {
|
||
const token = await loadSessionToken();
|
||
return {
|
||
...(token ? { authorization: `Bearer ${token}` } : {}),
|
||
...(spaceId ? { "x-rakazo-space-id": spaceId } : {}),
|
||
};
|
||
}
|
||
|
||
export type ApiRequestContext = {
|
||
apiBase: string;
|
||
headers: Record<string, string>;
|
||
};
|
||
|
||
export async function captureApiRequestContext(): Promise<ApiRequestContext> {
|
||
const apiBase = currentApiBase();
|
||
const headers = await authHeaders(selectedSpaceId());
|
||
if (apiBase !== currentApiBase()) {
|
||
throw new Error(t("The server changed while starting the request"));
|
||
}
|
||
return { apiBase, headers };
|
||
}
|
||
|
||
async function authenticateWithEmail(
|
||
action: "sign-in" | "sign-up",
|
||
input: { email: string; password: string; name?: string },
|
||
) {
|
||
const { response, body } = await fetchMobileJson<unknown>(
|
||
`${currentApiBase()}/api/auth/${action}/email`,
|
||
{
|
||
method: "POST",
|
||
headers: { "content-type": "application/json", origin: "rakazo://" },
|
||
body: JSON.stringify(input),
|
||
},
|
||
{},
|
||
);
|
||
if (!response.ok) {
|
||
throw new Error(responseErrorMessage(body, `Could not ${action.replace("-", " ")}`));
|
||
}
|
||
const token = tokenFromAuthResponse(response, body);
|
||
if (action === "sign-up" && signupRequiresEmailVerification(body))
|
||
return { verificationRequired: true };
|
||
if (!token)
|
||
throw new Error(
|
||
t(
|
||
action === "sign-in"
|
||
? "Sign-in did not return a session"
|
||
: "Sign-up did not return a session",
|
||
),
|
||
);
|
||
if (!(await clearSpace())) throw new Error(t("Could not clear the previous space"));
|
||
await saveSessionToken(token);
|
||
return { verificationRequired: false };
|
||
}
|
||
|
||
export function signIn(email: string, password: string) {
|
||
return authenticateWithEmail("sign-in", { email, password });
|
||
}
|
||
|
||
export function signUp(email: string, password: string, name: string) {
|
||
return authenticateWithEmail("sign-up", { email, password, name });
|
||
}
|
||
|
||
export type PasswordResetCapabilities = { passwordReset: boolean; resetUrl: string | null };
|
||
|
||
export async function passwordResetCapabilities(): Promise<PasswordResetCapabilities> {
|
||
const { response, body } = await fetchMobileJson<PasswordResetCapabilities>(
|
||
`${currentApiBase()}/api/auth/capabilities`,
|
||
{ headers: { origin: "rakazo://" } },
|
||
{ passwordReset: false, resetUrl: null },
|
||
);
|
||
if (!response.ok) throw new Error("Could not load password recovery settings");
|
||
return body;
|
||
}
|
||
|
||
export async function requestPasswordReset(email: string, redirectTo: string): Promise<void> {
|
||
const { response, body } = await fetchMobileJson<unknown>(
|
||
`${currentApiBase()}/api/auth/request-password-reset`,
|
||
{
|
||
method: "POST",
|
||
headers: { "content-type": "application/json", origin: "rakazo://" },
|
||
body: JSON.stringify({ email, redirectTo }),
|
||
},
|
||
{},
|
||
);
|
||
if (!response.ok) throw new Error(responseErrorMessage(body, t("Could not send reset email")));
|
||
}
|
||
|
||
export async function changePassword(currentPassword: string, newPassword: string): Promise<void> {
|
||
const { response, body } = await fetchMobileJson<unknown>(
|
||
`${currentApiBase()}/api/auth/change-password`,
|
||
{
|
||
method: "POST",
|
||
headers: {
|
||
"content-type": "application/json",
|
||
origin: "rakazo://",
|
||
...(await authHeaders()),
|
||
},
|
||
body: JSON.stringify({ currentPassword, newPassword, revokeOtherSessions: true }),
|
||
},
|
||
{},
|
||
);
|
||
if (!response.ok) throw new Error(responseErrorMessage(body, t("Could not change password")));
|
||
}
|
||
|
||
async function fetchMobileJson<T>(
|
||
input: Parameters<typeof fetch>[0],
|
||
init: RequestInit,
|
||
invalidJsonFallback?: T,
|
||
): Promise<{ response: Response; body: T }> {
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(new Error("Request timed out")), RPC_TIMEOUT_MS);
|
||
try {
|
||
const response = await withAbort(
|
||
fetch(input, { ...init, signal: controller.signal }),
|
||
controller.signal,
|
||
);
|
||
try {
|
||
const body = await readBoundedJsonResponse<T>(
|
||
response,
|
||
MAX_MOBILE_AUTH_RESPONSE_BYTES,
|
||
controller.signal,
|
||
);
|
||
return { response, body };
|
||
} catch (error) {
|
||
if (invalidJsonFallback !== undefined && error instanceof SyntaxError) {
|
||
return { response, body: invalidJsonFallback };
|
||
}
|
||
throw error;
|
||
}
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
export async function signOut() {
|
||
await rpc("notifications/unregisterPush").catch(() => undefined);
|
||
const headers = await authHeaders();
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(), RPC_TIMEOUT_MS);
|
||
try {
|
||
await withAbort(
|
||
fetch(`${currentApiBase()}/api/auth/sign-out`, {
|
||
method: "POST",
|
||
headers: { "content-type": "application/json", origin: "rakazo://", ...headers },
|
||
signal: controller.signal,
|
||
}),
|
||
controller.signal,
|
||
).catch(() => undefined);
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
const sessionCleared = await clearSessionToken();
|
||
const spaceCleared = await clearSpace();
|
||
if (!sessionCleared || !spaceCleared) throw new Error(t("Could not clear the local session"));
|
||
}
|
||
|
||
function withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
||
if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Request timed out"));
|
||
return new Promise<T>((resolve, reject) => {
|
||
const onAbort = () => reject(signal.reason ?? new Error("Request timed out"));
|
||
signal.addEventListener("abort", onAbort, { once: true });
|
||
promise.then(
|
||
(value) => {
|
||
signal.removeEventListener("abort", onAbort);
|
||
resolve(value);
|
||
},
|
||
(error: unknown) => {
|
||
signal.removeEventListener("abort", onAbort);
|
||
reject(error);
|
||
},
|
||
);
|
||
});
|
||
}
|
||
|
||
export async function deleteAccount(password: string) {
|
||
await rpc("notifications/unregisterPush").catch(() => undefined);
|
||
const { response, body } = await fetchMobileJson<unknown>(
|
||
`${currentApiBase()}/api/auth/delete-user`,
|
||
{
|
||
method: "POST",
|
||
headers: {
|
||
"content-type": "application/json",
|
||
origin: "rakazo://",
|
||
...(await authHeaders()),
|
||
},
|
||
body: JSON.stringify({ password }),
|
||
},
|
||
{},
|
||
);
|
||
if (!response.ok) {
|
||
throw new Error(responseErrorMessage(body, t("Could not delete account")));
|
||
}
|
||
await clearSessionToken();
|
||
await clearSpace();
|
||
}
|
||
|
||
export async function rpc<T>(
|
||
proc: string,
|
||
body: unknown = {},
|
||
options: {
|
||
signal?: AbortSignal;
|
||
timeoutMs?: number | null;
|
||
requestContext?: ApiRequestContext;
|
||
skipSpaceAuthRecovery?: boolean;
|
||
} = {},
|
||
): Promise<T> {
|
||
const requestSpaceGeneration = spaceSelectionGeneration;
|
||
const uses = aiDataUsesForProcedure(proc, body);
|
||
const consentContext =
|
||
options.requestContext ?? (uses.length ? await captureApiRequestContext() : undefined);
|
||
await ensureAiDataConsent({
|
||
uses,
|
||
status: () =>
|
||
rpc(
|
||
"aiConsent/status",
|
||
{ uses, ...aiConsentTarget(body) },
|
||
{ requestContext: consentContext },
|
||
),
|
||
prompt: promptAiConsent,
|
||
allow: (input) => rpc("aiConsent/allow", input, { requestContext: consentContext }),
|
||
});
|
||
// Abort with an explicit reason so every consumer of the signal (the fetch, the bounded body
|
||
// read, and nested recovery calls that share this signal) reports the same cause.
|
||
const controller = new AbortController();
|
||
const cancel = () => controller.abort(options.signal?.reason ?? new Error("Request canceled"));
|
||
if (options.signal?.aborted) cancel();
|
||
else options.signal?.addEventListener("abort", cancel, { once: true });
|
||
const timer =
|
||
options.timeoutMs === null
|
||
? undefined
|
||
: setTimeout(
|
||
() => controller.abort(new Error("Request timed out")),
|
||
options.timeoutMs ?? RPC_TIMEOUT_MS,
|
||
);
|
||
const abortReason = (error: unknown) =>
|
||
controller.signal.aborted ? (controller.signal.reason ?? error) : error;
|
||
// Bind recovery to the Space + selection epoch this request was sent with:
|
||
// a 401 arriving after the user switched Spaces — including A → B → A —
|
||
// belongs to a stale request and must not touch the current selection.
|
||
const requestHeaders = consentContext?.headers ?? (await authHeaders());
|
||
const requestSpaceId = requestHeaders["x-rakazo-space-id"];
|
||
try {
|
||
let res: Response;
|
||
try {
|
||
res = await fetch(`${consentContext?.apiBase ?? currentApiBase()}/rpc/${proc}`, {
|
||
method: "POST",
|
||
headers: {
|
||
"content-type": "application/json",
|
||
origin: "rakazo://",
|
||
...requestHeaders,
|
||
},
|
||
body: JSON.stringify({ json: body }),
|
||
signal: controller.signal,
|
||
});
|
||
} catch (error) {
|
||
// The native fetch reports an aborted request with an implementation detail
|
||
// ("FetchRequestCanceledException"); say what happened instead.
|
||
throw abortReason(error);
|
||
}
|
||
if (proc === "aiConsent/status" && res.status === 404) {
|
||
cancelResponseBody(res);
|
||
throw new Error(t("Update your server to use AI data sharing in this mobile version."));
|
||
}
|
||
const parsed = await readBoundedJsonResponse<{ json?: T; error?: { message?: string } }>(
|
||
res,
|
||
MAX_MOBILE_RPC_RESPONSE_BYTES,
|
||
controller.signal,
|
||
).catch((error: unknown) => {
|
||
throw abortReason(error);
|
||
});
|
||
if (!res.ok || parsed.error) {
|
||
const message = parsed.error?.message ?? `rpc ${proc} failed`;
|
||
const unauthorized = res.status === 401 || /unauthorized/i.test(message);
|
||
// After a delete where SecureStore could not clear the stale id, restart
|
||
// reloads it and the first RPCs 401. Probe once without a Space header:
|
||
// success means the selection was inaccessible (clear it); failure means
|
||
// the session itself is bad (restore the selection so a later sign-in
|
||
// keeps the user's Space). Never replay a mutation against the default
|
||
// Space — only safe reads may retry as themselves; other procs probe
|
||
// with spaces/list, then fail the original call.
|
||
const previousSpaceId = selectedSpaceId();
|
||
// Clear stale selection records, then re-persist a Space selected while
|
||
// cleanup was in flight: check-then-clear cannot be atomic on
|
||
// SecureStore, so reconcile afterwards instead of trusting the check.
|
||
const clearStaleSpaceSelection = async () => {
|
||
await clearStoredValue(SPACE_KEY);
|
||
await clearStoredValue(SPACE_ROLLBACK_KEY);
|
||
const reselected = selectedSpaceId();
|
||
if (!reselected) return;
|
||
// Own the reconcile write by generation: a newer selection that
|
||
// persists between snapshot and write must not be overwritten by
|
||
// this stale id, and a write that lands stale heals once to live.
|
||
const writeGeneration = spaceSelectionGeneration;
|
||
await writeStoredValue(SPACE_KEY, reselected);
|
||
if (spaceSelectionGeneration !== writeGeneration) {
|
||
const live = selectedSpaceId();
|
||
if (live) await writeStoredValue(SPACE_KEY, live);
|
||
}
|
||
};
|
||
if (
|
||
unauthorized &&
|
||
previousSpaceId &&
|
||
requestSpaceId &&
|
||
selectedSpaceId() === requestSpaceId &&
|
||
spaceSelectionGeneration === requestSpaceGeneration &&
|
||
!options.requestContext &&
|
||
!options.skipSpaceAuthRecovery
|
||
) {
|
||
cachedSpaceId = "";
|
||
bumpSpaceSelectionGeneration();
|
||
const retrySameProc = SPACE_AUTH_RECOVERY_SAFE_PROCS.has(proc);
|
||
// Share the original deadline/cancellation with recovery calls instead
|
||
// of starting a second full timeout behind the first request.
|
||
const recoveryOptions: {
|
||
signal?: AbortSignal;
|
||
timeoutMs?: number | null;
|
||
requestContext?: ApiRequestContext;
|
||
skipSpaceAuthRecovery?: boolean;
|
||
} = {
|
||
...options,
|
||
timeoutMs: null,
|
||
signal: controller.signal,
|
||
skipSpaceAuthRecovery: true,
|
||
};
|
||
try {
|
||
if (retrySameProc) {
|
||
const result = await rpc<T>(proc, body, recoveryOptions);
|
||
// A Space selected while the retry was in flight already owns both
|
||
// the in-memory and durable selection; leave it alone.
|
||
if (!selectedSpaceId()) await clearStaleSpaceSelection();
|
||
return result;
|
||
}
|
||
await rpc("spaces/list", {}, recoveryOptions);
|
||
} catch (retryError) {
|
||
if (!selectedSpaceId()) {
|
||
cachedSpaceId = previousSpaceId;
|
||
bumpSpaceSelectionGeneration();
|
||
}
|
||
throw retryError;
|
||
}
|
||
if (!selectedSpaceId()) await clearStaleSpaceSelection();
|
||
throw new Error(message);
|
||
}
|
||
throw new Error(message);
|
||
}
|
||
return parsed.json as T;
|
||
} finally {
|
||
if (timer) clearTimeout(timer);
|
||
options.signal?.removeEventListener("abort", cancel);
|
||
}
|
||
}
|
||
|
||
export type MobileBot = Pick<
|
||
Bot,
|
||
| "id"
|
||
| "name"
|
||
| "preview"
|
||
| "title"
|
||
| "color"
|
||
| "notifyOnFinish"
|
||
| "threadId"
|
||
| "pinned"
|
||
| "status"
|
||
| "sectionId"
|
||
| "archivedAt"
|
||
| "unread"
|
||
| "updatedAt"
|
||
| "computerMode"
|
||
| "modelProvider"
|
||
| "modelId"
|
||
| "thinkingLevel"
|
||
> &
|
||
Partial<Pick<Bot, "parentBotId" | "spaceId" | "kind">>;
|
||
|
||
export type MobileBotSection = BotSection;
|
||
|
||
export type MobileMe = Pick<
|
||
Me,
|
||
| "name"
|
||
| "email"
|
||
| "spaceId"
|
||
| "defaultProvider"
|
||
| "defaultModel"
|
||
| "needsModel"
|
||
| "avatarStyle"
|
||
| "isDeploymentOwner"
|
||
>;
|
||
|
||
export type MobileModel = ModelCatalogEntry;
|
||
|
||
export type MobileModelCredential = ModelCredential;
|
||
|
||
export type MobileMessage = {
|
||
id: string;
|
||
threadId?: string;
|
||
seq?: number;
|
||
runId?: string;
|
||
role: "user" | "bot" | "system";
|
||
botId?: string;
|
||
replyToMessageId?: string;
|
||
replyQuote?: string;
|
||
createdAt?: string;
|
||
blocks: MessageBlock[];
|
||
};
|
||
|
||
export type MobileGroup = Pick<
|
||
Group,
|
||
| "id"
|
||
| "name"
|
||
| "preview"
|
||
| "pinned"
|
||
| "sectionId"
|
||
| "archivedAt"
|
||
| "unread"
|
||
| "updatedAt"
|
||
| "members"
|
||
> &
|
||
Partial<Pick<Group, "spaceId">>;
|
||
|
||
export type MobileSpace = Space;
|
||
export type MobileSpaceNavigation = SpaceNavigation;
|
||
|
||
export type MobileSnapshot = {
|
||
botId?: string;
|
||
groupId?: string;
|
||
groupName?: string;
|
||
threadId: string;
|
||
cursor?: number;
|
||
messages: MobileMessage[];
|
||
olderCursor: number | null;
|
||
run: { id: string; botId?: string; status: string; error?: string | null } | null;
|
||
activeRuns?: Array<{ id: string; botId?: string; status: string }>;
|
||
members?: MobileGroup["members"];
|
||
computer?: {
|
||
kind?: string;
|
||
state: string;
|
||
controlHolder: string;
|
||
screenAvailable: boolean;
|
||
takeoverRequested?: boolean;
|
||
mode: ComputerMode;
|
||
busyBotName: string | null;
|
||
};
|
||
};
|
||
|
||
export function shouldApplyMobileThreadRefresh(input: {
|
||
requestEpoch: number;
|
||
currentEpoch: number;
|
||
targetBotId: string | undefined;
|
||
targetGroupId: string | undefined;
|
||
activeBotId: string | undefined;
|
||
activeGroupId: string | undefined;
|
||
}) {
|
||
return (
|
||
input.requestEpoch === input.currentEpoch &&
|
||
input.targetBotId === input.activeBotId &&
|
||
input.targetGroupId === input.activeGroupId
|
||
);
|
||
}
|
||
|
||
export type MobileMessagePage = ThreadHistory<MobileMessage>;
|
||
|
||
export function mergeMobileSnapshot(
|
||
prev: MobileSnapshot | null,
|
||
next: MobileSnapshot,
|
||
preserveLoadedHistory = false,
|
||
): MobileSnapshot {
|
||
return mergeThreadHistory(prev, next, preserveLoadedHistory);
|
||
}
|
||
|
||
export function prependMobileMessagePage(
|
||
prev: MobileSnapshot | null,
|
||
page: MobileMessagePage,
|
||
): MobileSnapshot | null {
|
||
return prependThreadHistoryPage(prev, page);
|
||
}
|
||
|
||
const MESSAGING_PROVIDER_LABELS: Record<string, string> = {
|
||
sendblue: "iMessage",
|
||
slack: "Slack",
|
||
whatsapp: "WhatsApp",
|
||
telegram: "Telegram",
|
||
lark: "Feishu",
|
||
};
|
||
|
||
export function messagingProviderLabel(provider: string, transport?: string): string {
|
||
if (provider === "sendblue" && ["iMessage", "SMS", "RCS"].includes(transport ?? "")) {
|
||
return transport!;
|
||
}
|
||
return MESSAGING_PROVIDER_LABELS[provider] ?? provider;
|
||
}
|
||
|
||
export function copyableMobileMessageText(message: MobileMessage): string {
|
||
return message.blocks
|
||
.map((block) => {
|
||
if (block.kind === "channel_message") {
|
||
return `${messagingProviderLabel(block.provider, block.transport)} · ${block.fromLabel}: ${block.text}`;
|
||
}
|
||
if (block.kind === "text" || block.kind === "progress" || block.kind === "ask")
|
||
return block.text;
|
||
return "";
|
||
})
|
||
.filter(Boolean)
|
||
.join("\n")
|
||
.trim();
|
||
}
|
||
|
||
export function blockText(message: MobileMessage) {
|
||
return message.blocks
|
||
.map((block) => {
|
||
if (block.kind === "channel_message") {
|
||
return `${messagingProviderLabel(block.provider, block.transport)} · ${block.fromLabel}: ${block.text}`;
|
||
}
|
||
if (block.kind === "cloud_agent")
|
||
return `${block.title}: ${block.status}${block.prUrl ? ` ${block.prUrl}` : ""}`;
|
||
if (block.kind === "subagent") {
|
||
return `${block.name ?? "subagent"}: ${block.result || block.progress || block.task || ""}`;
|
||
}
|
||
if (block.kind === "child_bot") {
|
||
return `${block.status === "archived" ? "Archived" : block.status === "deleted" ? "Deleted" : "Bot"} ${block.name ?? ""}`;
|
||
}
|
||
// Choice cards are answered on the web; here they read as the question and its answer.
|
||
if (block.kind === "choice") {
|
||
const answer =
|
||
block.answerText ?? block.options.find((option) => option.id === block.answerId)?.label;
|
||
return answer ? `${block.question}\n${answer}` : block.question;
|
||
}
|
||
if (block.kind === "chart") return `[chart: ${block.name ?? "chart"}]`;
|
||
if (block.kind === "image") return `[image: ${block.name ?? "attachment"}]`;
|
||
if (block.kind === "file") {
|
||
return `[file: ${block.name ?? "attachment"}${block.size ? ` (${block.size} bytes)` : ""}]`;
|
||
}
|
||
if (block.kind === "steps") {
|
||
return (block.steps ?? [])
|
||
.map((step) => `${step.label}${step.count > 1 ? ` ×${step.count}` : ""}`)
|
||
.join(" · ");
|
||
}
|
||
return ("text" in block ? block.text : "state" in block ? block.state : "") ?? "";
|
||
})
|
||
.filter(Boolean)
|
||
.join("\n");
|
||
}
|
||
|
||
type ThreadEvent = {
|
||
id?: string;
|
||
botId?: string;
|
||
type: string;
|
||
seq?: number;
|
||
runId?: string;
|
||
createdAt?: string;
|
||
payload?: Record<string, unknown>;
|
||
};
|
||
|
||
export async function subscribeThread(
|
||
target: { botId: string } | { groupId: string },
|
||
cursor: number,
|
||
onEvent: (event: ThreadEvent) => void,
|
||
signal: AbortSignal,
|
||
) {
|
||
const res = await fetch(`${currentApiBase()}/rpc/threads/subscribe`, {
|
||
method: "POST",
|
||
headers: {
|
||
"content-type": "application/json",
|
||
accept: "text/event-stream",
|
||
origin: "rakazo://",
|
||
...(await authHeaders()),
|
||
},
|
||
body: JSON.stringify({ json: { ...target, cursor } }),
|
||
signal,
|
||
});
|
||
if (!res.ok || !res.body) throw new Error(`rpc threads/subscribe failed (${res.status})`);
|
||
const reader = res.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffer = "";
|
||
while (!signal.aborted) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
buffer += decoder.decode(value, { stream: true });
|
||
const chunks = buffer.split("\n\n");
|
||
buffer = chunks.pop() ?? "";
|
||
for (const chunk of chunks) {
|
||
const data = chunk
|
||
.split("\n")
|
||
.filter((line) => line.startsWith("data:"))
|
||
.map((line) => line.slice(5).trim())
|
||
.join("");
|
||
if (!data || data === "[DONE]") continue;
|
||
try {
|
||
const parsed = JSON.parse(data) as { json?: ThreadEvent; error?: { message?: string } };
|
||
if (parsed.json?.type) onEvent(parsed.json);
|
||
} catch {
|
||
// ignore keepalives and partial frames
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
export function applyMobileThreadEvent(
|
||
prev: MobileSnapshot | null,
|
||
event: ThreadEvent,
|
||
): MobileSnapshot | null {
|
||
if (!prev) return prev;
|
||
if (event.type === "thread.cleared") {
|
||
return {
|
||
...prev,
|
||
cursor: event.seq,
|
||
messages: [],
|
||
olderCursor: null,
|
||
run: null,
|
||
activeRuns: [],
|
||
};
|
||
}
|
||
if (event.type === "run.waiting_input" || event.type === "computer.takeover.requested") {
|
||
const status = event.type === "run.waiting_input" ? "waiting_input" : "waiting_takeover";
|
||
const progressId = progressMessageId(event);
|
||
// Waiting pauses drop live progress server-side; clear a leftover bubble so
|
||
// the waiting footer is not hidden behind a stale "Working…" row.
|
||
const messages = prev.messages.filter((message) => message.id !== progressId);
|
||
const progressCleared = messages.length !== prev.messages.length;
|
||
const runId = event.runId;
|
||
const knownInRun = Boolean(runId && prev.run?.id === runId);
|
||
const knownInActive = Boolean(
|
||
runId && prev.activeRuns?.some((candidate) => candidate.id === runId),
|
||
);
|
||
// Peer bot_message runs are omitted from snapshots while busy; the first wait
|
||
// event is how an open thread learns they need ask/takeover UI.
|
||
const needsInsert = Boolean(runId) && !knownInRun && !knownInActive;
|
||
const runChanged = Boolean(knownInRun && prev.run && prev.run.status !== status);
|
||
const activeRunChanged = Boolean(
|
||
knownInActive &&
|
||
prev.activeRuns?.some((candidate) => candidate.id === runId && candidate.status !== status),
|
||
);
|
||
const computer =
|
||
event.type === "computer.takeover.requested" && prev.computer?.busyBotName
|
||
? { ...prev.computer, busyBotName: null }
|
||
: prev.computer;
|
||
const computerChanged = computer !== prev.computer;
|
||
const cursor = event.seq ?? prev.cursor;
|
||
if (!runChanged && !activeRunChanged && !progressCleared && !needsInsert && !computerChanged) {
|
||
return cursor === prev.cursor ? prev : { ...prev, cursor };
|
||
}
|
||
if (needsInsert && runId) {
|
||
const waitingRun = {
|
||
id: runId,
|
||
status,
|
||
...(event.botId ? { botId: event.botId } : {}),
|
||
};
|
||
const baseActive = prev.activeRuns ?? (prev.run ? [prev.run] : []);
|
||
const activeRuns = [...baseActive.filter((candidate) => candidate.id !== runId), waitingRun];
|
||
const promoteWaiting =
|
||
!prev.run ||
|
||
(prev.run.status !== "waiting_input" && prev.run.status !== "waiting_takeover");
|
||
return {
|
||
...prev,
|
||
cursor,
|
||
messages,
|
||
computer,
|
||
run: promoteWaiting ? waitingRun : prev.run,
|
||
activeRuns,
|
||
};
|
||
}
|
||
const run = runChanged && prev.run ? { ...prev.run, status } : prev.run;
|
||
const activeRuns = activeRunChanged
|
||
? prev.activeRuns?.map((candidate) =>
|
||
candidate.id === runId ? { ...candidate, status } : candidate,
|
||
)
|
||
: prev.activeRuns;
|
||
return { ...prev, cursor, run, activeRuns, messages, computer };
|
||
}
|
||
if (isRunTerminalEvent(event)) {
|
||
const activeRuns = prev.activeRuns?.filter((candidate) => candidate.id !== event.runId);
|
||
const failure = runFailureError(event);
|
||
const primaryEnded = prev.run?.id === event.runId ? prev.run : null;
|
||
// A group member run can fail while another is displayed; see reduceThreadSnapshot.
|
||
const endedRun =
|
||
primaryEnded ?? prev.activeRuns?.find((candidate) => candidate.id === event.runId) ?? null;
|
||
return {
|
||
...prev,
|
||
cursor: event.seq ?? prev.cursor,
|
||
messages: prev.messages.filter((message) => message.id !== progressMessageId(event)),
|
||
// A failed run stays in run so the thread can say why it stopped (see reduceThreadSnapshot).
|
||
run:
|
||
endedRun && failure
|
||
? { ...endedRun, status: "failed", error: failure }
|
||
: primaryEnded
|
||
? (activeRuns?.[0] ?? null)
|
||
: prev.run,
|
||
activeRuns,
|
||
};
|
||
}
|
||
if (event.type === "thread.progress") {
|
||
const progressId = progressMessageId(event);
|
||
const { previous, remaining } = takeLiveMessage(prev.messages, progressId);
|
||
const streaming: MobileMessage = {
|
||
id: progressId,
|
||
role: "bot",
|
||
blocks: reduceLiveMessageBlocks((previous?.blocks ?? []) as MessageBlock[], {
|
||
type: "progress",
|
||
payload: event.payload,
|
||
}),
|
||
...(event.botId ? { botId: event.botId } : {}),
|
||
...(event.runId ? { runId: event.runId } : {}),
|
||
};
|
||
return {
|
||
...prev,
|
||
cursor: event.seq ?? prev.cursor,
|
||
messages: [...remaining, streaming],
|
||
};
|
||
}
|
||
if (event.type === "agent.tool.called") {
|
||
const progressId = progressMessageId(event);
|
||
const { previous, remaining } = takeLiveMessage(prev.messages, progressId);
|
||
const streaming: MobileMessage = {
|
||
id: progressId,
|
||
role: "bot",
|
||
blocks: reduceLiveMessageBlocks((previous?.blocks ?? []) as MessageBlock[], {
|
||
type: "tool",
|
||
name: String(event.payload?.name ?? ""),
|
||
}),
|
||
...(event.botId ? { botId: event.botId } : {}),
|
||
...(event.runId ? { runId: event.runId } : {}),
|
||
};
|
||
return {
|
||
...prev,
|
||
cursor: event.seq ?? prev.cursor,
|
||
messages: [...remaining, streaming],
|
||
};
|
||
}
|
||
if (event.type === "agent.tool.completed" || event.type === "thread.computer") {
|
||
return { ...prev, cursor: event.seq ?? prev.cursor };
|
||
}
|
||
if (event.type === "thread.subagent") {
|
||
const agentId = String(event.payload?.agentId ?? event.id ?? "live");
|
||
const status = event.payload?.status;
|
||
const streaming: MobileMessage = {
|
||
id: `subagent:${agentId}`,
|
||
role: "bot",
|
||
...(event.botId ? { botId: event.botId } : {}),
|
||
...(event.runId ? { runId: event.runId } : {}),
|
||
blocks: [
|
||
{
|
||
kind: "subagent",
|
||
agentId,
|
||
name: String(event.payload?.name ?? "subagent"),
|
||
task: String(event.payload?.task ?? ""),
|
||
status: status === "completed" || status === "failed" ? status : "running",
|
||
progress: event.payload?.progress ? String(event.payload.progress) : undefined,
|
||
result: event.payload?.result ? String(event.payload.result) : undefined,
|
||
},
|
||
],
|
||
};
|
||
return {
|
||
...prev,
|
||
cursor: event.seq ?? prev.cursor,
|
||
messages: [...prev.messages.filter((message) => message.id !== streaming.id), streaming],
|
||
};
|
||
}
|
||
if (event.type === "thread.cloud_agent") {
|
||
return {
|
||
...prev,
|
||
cursor: event.seq ?? prev.cursor,
|
||
messages: updateCloudAgentMessages(prev.messages, event.payload ?? {}),
|
||
};
|
||
}
|
||
if (event.type === "thread.message.created" || event.type === "thread.message.updated") {
|
||
const { remaining } = takeLiveMessage(prev.messages, progressMessageId(event));
|
||
const next: MobileMessage = {
|
||
id: String(event.payload?.messageId ?? event.id ?? `msg:${event.seq ?? 0}`),
|
||
runId: event.runId ? String(event.runId) : undefined,
|
||
role: (event.payload?.role as MobileMessage["role"]) ?? "bot",
|
||
blocks: (event.payload?.blocks as MobileMessage["blocks"]) ?? [],
|
||
botId: event.botId ?? (event.payload?.botId ? String(event.payload.botId) : undefined),
|
||
replyToMessageId: event.payload?.replyToMessageId
|
||
? String(event.payload.replyToMessageId)
|
||
: undefined,
|
||
replyQuote: event.payload?.replyQuote ? String(event.payload.replyQuote) : undefined,
|
||
};
|
||
return {
|
||
...prev,
|
||
cursor: event.seq ?? prev.cursor,
|
||
messages: upsertMessageById(
|
||
remaining.filter(
|
||
(message) =>
|
||
!(
|
||
message.id.startsWith("subagent:") &&
|
||
next.blocks.some(
|
||
(block) => block.kind === "subagent" && message.id === `subagent:${block.agentId}`,
|
||
)
|
||
),
|
||
),
|
||
next,
|
||
),
|
||
};
|
||
}
|
||
return prev;
|
||
}
|
||
|
||
export {
|
||
apiBaseWarning,
|
||
defaultApiBase,
|
||
displayApiHost,
|
||
normalizeApiBase,
|
||
probeApiBase,
|
||
usesCustomApiBase,
|
||
} from "./endpoint";
|
||
export { loadSessionToken };
|