diff --git a/AGENTS.md b/AGENTS.md index 603e6743..ff68b78d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,10 +35,10 @@ change in both repos. `HermesWorkspaceStore` of its own (`separateStore()`), so the shell's Projects never move. - Everyday controls must never live only behind Advanced options. - **One place for each thing.** - - There's one ☰ menu (`BighelpMenu`) and one Settings, the same tree in every mode (`SettingsView`). Its first + - There's one Settings (`SettingsView`), and the person's circle in the header opens it from every tab. Its first screen is a short list of rows that each open one page, in groups: the person's row, Usage and, while a share waits, Shared with bighelp; Your bots (Models, Apps & skills, Voice, Personality and the Teamwork switch); This - app (Appearance, Chat, Notifications, Modes); on Vision Pro the agent in the room; Your computers (one row per + app (Appearance, Chat, Notifications); on Vision Pro the agent in the room; Your computers (one row per computer, Add a computer, Show every computer, Time zone, and with two or more, Update every computer); then Help & feedback and the Advanced options switch. - Settings copy follows DESIGN.md › Simplicity means hierarchy. A row's title is one to three words and its second @@ -53,41 +53,67 @@ change in both repos. credential vault) and, with Advanced options, MCP servers and Toolsets. Models (`ModelsSettingsView`) is the providers and each bot's default model on one page. Each computer has one page (`BighelpConfiguredHostView`: Use this computer, Updates, Restart, This computer, Access, its Advanced groups, Remove this computer), and - Update every computer (`FleetSettingsView`) updates and restarts them together. Modes holds the mode switches, - Appearance the companion pet, and Help & feedback the usage-sharing switch and the Apple Watch's status. The + Update every computer (`FleetSettingsView`) updates and restarts them together. Appearance holds the + companion pet, and Help & feedback the usage-sharing switch and the Apple Watch's status. The old Hermes tools list (`WorkspaceHubView`) and Settings › System are gone: their pages open from where they belong (skills, plugins, messaging apps, MCP servers and toolsets in Apps & skills; logs, webhooks, tool backends, the computer voice test, diagnostics, backups, config.yaml, shell hooks and Kanban boards on a computer's page; Clean up chats and Archived chats in Chat; Toolsets and Manage bots in a bot's Advanced Options › For experts). - Don't add a second menu, drawer or settings copy for a feature. Add a row where people already look. - - People choose the bottom bar (Chat plus up to three, around New chat in the middle) and ☰'s order in - Appearance › App layout - (`BighelpAppLayout`). ☰ lists every place the bar doesn't hold, so nothing is out of reach, and Agents - and Settings always (`staysInMenu`): quick screens hide the bar. A new place - in ☰ is a `BighelpPlace` case; a page that can be pinned also needs an `AppTab` and a root in `rootTabs`. - Sessions' tab (`AppTab.sessionList`) is the Chat tab's own list: `selectedTab` stays `.sessions`, and only - the bar lights Sessions (`selectedBarTab`). - - Long-stay screens (Chat, Agents, Projects, Kanban, Workflows, Scheduled tasks) open from ☰ as screens of - their own, with ☰ in the corner (`AppTab.isLongStay`). Quick ones (Usage; Feed, Ideas, Goals and Files when - the bar doesn't hold them) slide in over where you are, with Back. Settings is a sheet: Back steps through - it, Done closes it. Whatever the bar holds is a tab. Headers drawn by the app place ☰ with - `bighelpHeaderButtonsPlacement()`, so it sits where the top bar puts it on every screen - (`MenuButtonPlacementUITests`). - - Main screens look the same whichever tab you came from (`SearchPlacementUITests`). Their title is the - bar's small one (a large title kept the size of the tab before). The bottom bar never moves. Search is - a `BighelpSearchField` as the first row under the title (`bighelpListSearchRow()`), filter chips below - it; never `.searchable` on a screen with the bar (iOS 26 puts it along the bottom, on the bar). + - There are no modes. One home has three places, the same for everyone: the first shows the Bots view + (`SimpleBotsHomeView`) or the Chats view (`ChatsInboxView`), then Today (`TodayView`) and Work (`WorkView`). The + first tab takes the name of the person's default view (`settings.homeView`), and the header's Bots | Chats + switch (`HomeViewSwitchPill`) changes the view for this run only. `HomeSelection` (`appState.home`, one for the + whole app; `AppState()` in tests and previews makes its own) holds the tab, the view, New chat's picks + (`NewChatSession`) and Today's layout and boards, so they stay when the computer in use changes. A tab is a root: `AppState.select(_:)` closes whatever was pushed, and + `select(_:thenOpen:)` shows a page over a tab for links, widgets and alerts (`showOverWork`, `showOverToday`). + - The app opens on Settings › Chat › Opens on (Bots, Chats, Today or Work: `settings.homeLanding`, read once per + launch as `launchHomeLanding` and applied by `HomeSelection.land`). With Today or Work, Chat › First tab shows + picks the first tab's view. No chat opens by itself. `HomeSettingsMigration` reads the old settings once + (marker `bighelp.home.migrated-v1`; it renames no key and removes none): Bots mode opens on Bots, Code mode as + the launch home opens on Work, an old Opens on screen maps to its place, the all-hosts view and Multi-gateway + become Show every computer, and a mode edge swipe becomes the edge's default (Bots mode's own swipes are + written down as the swipes they were). + - The bar is the same for everyone (`HomeTabBar`): the three places in a glass capsule, and the round New chat + button beside it. It shows on roots only, so a pushed page, a chat included, has Back instead, and the keyboard + hides it. Vision Pro puts the places in an ornament (`HomeTabOrnament`), and the iPhone Duo's side strip holds + them as toolbar items (`HomeStripTabs`). Today's dot on the bar means Needs you has an entry. + - Every root hides the navigation bar and draws one header (`HomeHeaderBar`, from a `HomeHeaderContext`): the + person's circle, which opens Settings, then the Bots | Chats switch or the title (Today, Work), search (a + button that opens a search page, or a field on a row under the buttons: `HomeHeaderSearch`), the computer menu + (Today and Work, with two or more computers; a computer that doesn't answer gives the selection back, as + everywhere: `selectFleetHost`), the root's own control (Today's Edit) and +. Place the header's + buttons with `bighelpHeaderButtonsPlacement()`, so they sit where a top bar puts them on every screen + (`MenuButtonPlacementUITests`). When the switch or the title doesn't fit beside the buttons (large text), it + moves to a row of its own instead of being cut. + - Search is a `BighelpSearchField` as the first row under the header (`bighelpListSearchRow()`), filter chips + below it; never `.searchable` on a screen with the bar (iOS 26 puts it along the bottom, on the bar). + - iPhone has no menu and no sidebar. iPad at regular width has a slide-in sidebar behind a header button + (`HomeMenuPresentation`). The Mac and Vision Pro have the sidebar column (`BighelpSideMenu` hosts + `HomeSidebar`, drawn again from the stores by `BighelpLiveColumn`). It lists the three places, Settings, New + chat, up to eight recent chats with See all, and More: Needs you while something waits, Shared with bighelp + while a share waits, Usage and, on Vision Pro, Simple mode. A new place goes where people already look (a Work + door, a Settings row), not in More. + - Every chat is a pushed page (`AppRoute.chat`) with one header (`ChatPushedHeader`, from + `AgentHomeChrome.pushedChat`): Back, the bot and ⋯. The bot opens its bot page (`openBotPage(fromChat:)` pushes + one run-loop turn later: a push straight from the header's tap was dropped about one time in three). ⋯ ends + with Bot page, the same push. No bar sits under a chat. + - Work's four doors (Projects, Tasks, Workflows, Schedules) open Projects, Kanban, Workflows and Scheduled tasks as + pushed pages, each only where the computer has it. Usage is a pushed page too (Settings' first group, the + sidebar's More). Settings is a sheet: Back steps through it, Done closes it. - Never show "bighelp account" or "Link" wording. That pairing system is retired. - Needs you (`NeedsYouDeckView`) is the one place a waiting approval, question or workflow sign-off is - answered outside its own card: a chat's prompts open it (`ChatAttentionPresenter`), and ☰ has its row - only while something waits. Each entry is read from where it lives (`RootShellView.needsYouEntries`): + answered outside its own card: a chat's prompts open it (`ChatAttentionPresenter`), Today's Needs you card + opens it, and the sidebar's More has its row, both only while something waits. Each entry is read from where it lives (`RootShellView.needsYouEntries`): prompts on open chats' connections, the Dashboard's list for chats that aren't open, one entry per prompt ID (`DashboardAttentionItem.promptID`; Hermes' prompts reach the app both ways), and - `WorkflowsStore.waiting`. A bot whose chat isn't open gets only an Open chat row. A long command or + `WorkflowsStore.waiting` (the store is made and read as soon as the computer says it has Workflows, so a + sign-off shows on Today before Work is ever opened). A bot whose chat isn't open gets only an Open chat row. A long command or sign-off file opens in full before Approve works. Prompts answer through `DirectHermesPromptResponseView` (its `deck` look), the same code as the card in the chat. There is no Activity screen: an alert that names no - chat opens Needs you while something waits (`AppState.openNeedsYou()`), else the home chat. A bot's Dashboard + chat opens Needs you while something waits (`AppState.openNeedsYou()`; the request is kept in `HomeSelection`, so + the shell on screen gets it whichever computer's `AppState` took it), else Today. A bot's Dashboard tab and its Activities list stay. - A blueprint is filled in in the message box, nowhere else: a pick anywhere (a board's Blueprints, an empty board's starters, a bot's Dashboard) leaves it for the chat with `fillsBlanks` @@ -103,43 +129,86 @@ change in both repos. Discuss puts it in the message box (`ChatModel.boardCardDraft`). Let's do it sends "Let's do it!" with the idea at once (`leaveComposerText(sendsAtOnce:)`, `ChatModel.sendFromOutside`), never touching the box, and the idea moves to Ideas › Completed (the plugin's `answer`, `answeredAt`). - - Code mode is a second home, not a second app: ☰ gets a mode switch on top and Code's places while it's - the home (`AppTab.code`, `appState.homeTab`). Chat stays the out-of-box home. - - The modes are Bots, Chat and Code (`BighelpMode`; `settings.switchMode`). Settings › Modes has one picker - for the home a launch opens in (`settings.homeMode`, `selectHomeMode`; picking Code turns Code mode on) - and Code mode's own switch (`setCodeMode`), so Code can stay on beside a Chat or Bots home, or go off. - Its Header mode switcher (`unifiedModeToggleEnabled`, off by default) puts the modes in one pill - (`BighelpModePill`) at the top of each home: the Chat tab's own chat or its list, Code's home and Bots' - home (where Search and the computer filter move to a row under it). ☰ drops its Chat and Code switch - then. Edge swipes can switch modes too (Next mode, Bots, Chat, Code), also from Bots mode; on the - Mac, ⌃⌘1–⌃⌘3. - - Bots mode (Settings › Modes, `settings.simpleBotsEnabled`) is the one exception to ☰ and the bar: - its home (`SimpleBotsHomeView`) takes the Chat tab's place with neither, and the person's circle opens the - same Settings (`SettingsView`) that ☰ opens in Chat and Code; it has no Settings of its own. - Everything in it uses the same stores and chat; `Bighelp/SimpleBots/` holds its screens. It wins over the - all-hosts view and Settings › Chat › Opens on (`fleetModeOn` is off while it's on). Its Multi-gateway switch - (`simpleBotsMultiGateway`) lists every gateway's bots (`SimpleBotsGateways`, one `SimpleBotsBot` model - keyed by `FleetID`): the gateway in use live, the others from the all-hosts copies. Pins live on each - bot's own gateway; the primary bot is kept on the device (`simpleBotsMultiPrimary`). Acting on another - gateway's bot goes through `openFleet`; the home stays under the Noodle loader (`SimpleBotsOpeningOverlay`, - with Cancel) until the bot opens. A computer that doesn't answer gives the selection back to the one the tap - came from (`FleetSwitchFallback`), so neither the app nor its next launch is left on it. - - Sections are folders of bots and group chats (`Bighelp/SimpleBots/SimpleBotsSections.swift`): cards on - Bots mode's home and the Agents screen, a page of their own (`AppRoute.simpleBotsSection`, the home view - with a `sectionID`), and Code mode's agent picker lists agents by them. A bot's section is its profile's - `AgentListPlacement` (Hermes Desktop's field, saved on its own computer through `SimpleBotsSectionEditor`); - the sections list and each group chat's section, pin and hide are `FleetStore`'s, kept on the computers too - (`bots.layout`). Same-named sections on two computers are one (`FleetSectioning`). With one gateway shown, a - section whose members are all elsewhere stays off (`SimpleBotsSectioning.elsewhere`). + in Bots mode is - New Bot, New Group Chat and New Section, each only where it can work (`SimpleBotsNewItem`); the bot and - group chat menus come from `SimpleBotsMenuAction`. + - New chat is the new chat's own screen, drawn by the ordinary chat (`ChatNewChatSlot`, handed only to the chat + whose ID is `NewChatSession.conversationID`, never decided from its messages; from the first message on, staged, + sending or sent, it's an ordinary chat). Under Back and ⋯ a To row (`NewChatToRow`) holds the picked bots as + chips and a field that filters the people list (`NewChatPeopleList`, over the empty messages): one bot is a + chat, two to six (`BotModeRoom.maximumMembers`) a group chat, and a group chat the person already has can be + picked at the end of the list. With nobody picked the blank chat is the primary bot's; picking another single + bot makes the chat that bot's, replacing the blank chat in one step (`NewChatCoordinator.start(replacingBlankChat:)`). + A pick made while a chat starts waits, and the To row is read again when the start ends: the latest pick wins. + The message box's Send asks `ChatComposerActions.sendOverride` first (`NewChatSend.decide`): `.chat` sends in + this chat, `.group` makes the group chat, `.coding` and `.staged` hand the text to `CodeHomeStore` and go to + Work. Send sends everything in the box, or sends nothing, keeps the box and says why in a line under the To + row (`NewChatSend.Note`): with nobody picked it says "Pick who gets this" and puts the cursor in the To field. + A group chat and a coding session start with text only, so they are refused while the box holds an attachment + or a reference, and so is a pick that would replace the chat. A group Send keeps its text in the box until the + group chat is open (`NewChatSession.isStartingGroup` holds a second Send), so a group that can't be made loses + nothing. Text that goes with a pick to another computer rides in `HomeSelection.newChatHandoff`, dropped when + that computer doesn't open. Only a blank chat is ever taken off the stack (`AppState.dropBlankChat`). The + override holds a `NewChatSendRelay` and must not capture a view (the box keeps it while the chat is open), and + the choices row reads `ChatModel.draftShape` inside its own host view, never in the shell: a key press would + redraw the shell. + offers attachments only for a plain one-bot chat, and voice and ⋯ › Bot page show only + while the To row is exactly the chat's own bot. + - For exactly one bot on a computer that has a coding store, a single row under the message box scrolls sideways + (`NewChatChoicesRow`, `Equatable`): Project (none is an ordinary chat), then, once a project is picked, where it + runs (a new worktree or local), the branch, the mode (Hermes' Plan and YOLO, `CodeSessionMode`) and Stage. A + project makes the chat a coding session (`CodeLauncher`; see Coding sessions below). There is no Code home and no + Code message box: Work lists the coding sessions, and Work filtered to a project (`AppRoute.work(projectID:)`) + is the project's own page. + - Chats (`Bighelp/Home/Chats/`) lists every chat on every computer, newest first, with Pinned on top and the rest + by day. Once two or more computers show, one row of chips (All, each computer, Unread) sits under search. The + computer in use is read live from its catalog; the others come from their all-hosts copies (`FleetStore`) and + open through `openFleet`. Pin and Mark Read or Unread change only the computer in use's chats; another + computer's rows rename and archive. "This computer" pushes that computer's own Sessions page (projects, + imports from other apps, one bot's chats). The list is a pure function of the stores (`ChatsInboxProjection`), + kept until an input changes (`ChatsInboxCache`), so a computer's events don't redo it. + - Today (`Bighelp/Today/`) is a grid of panels under the header (`TodayPanelGrid`; Small, Wide or Tall), with the + Needs you card and the Shared with bighelp card above it while something waits, and the Make a space box + below (`TodayCreateBox`, hidden while the computer in use's plugin has no spaces). A panel is Feed, Ideas and + Goals for every bot (`TodayBoardsPanel`; See all pushes `TodayBoardPage` as `AppRoute.board`) or a space + (docs/SPACES.md). Edit changes order, hiding and size and deletes a space (`TodayPanelLayoutStore`; a space's + own layout belongs to its computer). What a panel's long press offers, VoiceOver gets from the panel's Actions + menu. A refusal (Update now too soon, a delete the computer refused) shows as one quiet line under the header + (`TodayNotice`). A read where no bot answered is not a read: the boards keep loading rather than say "Nothing + yet". One `TodayBoardsStore` and one `TodayPanelLayoutStore` live in `HomeSelection`, above the per-computer + `AppState`. + - Work (`Bighelp/Work/`) is one list of what the bots are doing, each row read from the store that holds it + (`WorkProjection`): coding sessions, chats and background work running now, workflow runs, Kanban tasks and + scheduled tasks. Chips: All, Needs you, Working, Done. Four doors lead on: Projects, Tasks, Workflows and + Schedules. Work filtered to a project has the navigation bar (Back, the project's name, ⋯ with pull requests, + worktrees and Dev Factory), not `HomeHeaderBar`. + - One bot page for every bot from every door (`SimpleBotProfileView`, `AppRoute.simpleBotProfile`): a bot's name + in a chat header, Bot Profile in a bot's long-press menu, a bot chip on a Today board. Its tabs are Dashboard, + Info, Computer, Files and Media. Info's About rows (Name, Role, Summary) edit in place, Handle is read only, and Approvals + lists what the bot asked to do. ⋯ holds what is done to the bot: New chat, Chats with this bot, Pin, Use with + Siri, Duplicate, Manage bots and Delete bot. The shell fills `SimpleBotProfileContext` in + `RootSimpleBots.simpleBotProfileContext(for:)`; a bot on another computer is pushed only once that computer + is in use (`openingComputer`). There is no profile sheet, no action sheet and no Agents screen. + - Sections are folders of bots and group chats (`Bighelp/SimpleBots/SimpleBotsSections.swift`): cards on the Bots + view and a page of their own (`AppRoute.simpleBotsSection`, the home view with a `sectionID`). A bot's section + is its profile's `AgentListPlacement` (Hermes Desktop's field, saved on its own computer through + `SimpleBotsSectionEditor`); the sections list and each group chat's section, pin and hide are `FleetStore`'s, + kept on the computers too (`bots.layout`). Same-named sections on two computers are one (`FleetSectioning`). + With one computer shown, a section whose members are all elsewhere stays off (`SimpleBotsSectioning.elsewhere`). + + on the Bots view is New Bot, New Group Chat and New Section, each only where it can work + (`SimpleBotsNewItem`); the bot and group chat menus come from `SimpleBotsMenuAction`. + - Show every computer (Settings › Your computers, `settings.showsEveryComputer`, on until turned off) puts every + computer's bots and chats in the Bots view, the Chats view and New chat's people list: the computer in use + live, the others from the all-hosts copies (`SimpleBotsGateways`, one `SimpleBotsBot` model keyed by + `FleetID`). It is the one switch behind the old all-hosts view and Multi-gateway (the saved key is the old + all-hosts one). Pins live on each bot's own computer; the primary bot is kept on the device + (`simpleBotsMultiPrimary`). Acting on another computer's bot goes through `openFleet`; the Bots view stays + under the Noodle loader (`SimpleBotsOpeningOverlay`, with Cancel) until the bot opens. A computer that + doesn't answer gives the selection back to the one the tap came from (`FleetSwitchFallback`), so neither the + app nor its next launch is left on it. While it's on, the other computers stay connected + (`keepsFleetHostsConnected`), through the background grace too, so opening on one is instant. - First run (`FirstRunOnboardingView`) is Welcome (with an optional Appearance step behind Appearance options), the AI data agreement if not given yet, Connect, the optional plugin, notifications (only once the plugin is - in), then Choose your mode (`FirstRunMode`: Bots, Chat for `.sessions`, Code). Optional steps have a small - Skip; Connect and the mode don't. `FirstRunOnboarding.afterConnectKey` keeps it on screen after host setup's own - finish. The mode cards show screenshots (`OnboardingMode*` assets); retake them when those homes change. - - While every host's data shows (all-hosts view or Multi-gateway), the other hosts stay connected - (`keepsFleetHostsConnected`), through the background grace too, so opening on one is instant. + in), then "How do you want to start?" (`FirstRunHome`: With a bot opens on Bots, Across chats on Chats; the + answer sets Opens on, which Settings › Chat changes later). Optional steps have a small Skip; Connect and the + start question don't. `FirstRunOnboarding.afterConnectKey` keeps it on screen after host setup's own finish. + The two cards draw a small sketch of the home they open (`FirstRunHomeSketch`), not a screenshot. - **Real data only.** - Avatars, activity poses and badges must come from what the agent is actually doing. - Never fake progress. @@ -170,20 +239,24 @@ change in both repos. | Path | What it is | |---|---| -| `Bighelp/App/` | App composition, `RootShellView`, routes (`AppRoute`, `RootDestinations`), ☰ menu, connection keeper, widget/Shortcut entry points | +| `Bighelp/App/` | App composition, `RootShellView` and its `Root*.swift` extensions (`RootHome` draws the three roots, the bar and the sidebar), routes (`AppRoute`, `RootDestinations`), `AppState`, `BighelpSideMenu`, connection keeper, widget/Shortcut entry points | +| `Bighelp/Home/` | The one home's parts: `HomeSelection`, `HomeHeaderBar`, `HomeTabBar` (+ `HomeTabOrnament`, `HomeStripTabs`), `HomeSidebar`, `Chats/` (the Chats view) and `NewChat/` (`NewChatSession`, the To row, the people list, the choices row, `NewChatSend`) | +| `Bighelp/Today/`, `Bighelp/Work/` | The Today and Work tabs: panel grid, layout store, boards panel and page, Needs you card; Work's list, cards and doors (`WorkProjection`) | +| `Bighelp/Spaces/` | Spaces on Today: the plugin client, stores, panels, the chat's `space_draft` card, the Make a space box ([docs/SPACES.md](docs/SPACES.md)) | +| `Bighelp/SimpleBots/` | The Bots view (`SimpleBotsHomeView`), sections, the bot page (`SimpleBotProfileView` and its tabs), creating a bot | | `Bighelp/Chat/` | Chat screen, composer, `ChatModel` (+ `ChatModel+Submission`), the native chat timeline | | `Bighelp/DirectHermes/` | The Hermes client: sign-in, WebSocket JSON-RPC, dashboard REST, plugin routes (`DirectHermesNativeContext.swift`), access credentials | | `Bighelp/Workspace/` | `WorkspaceOperation` (every host operation) and workspace stores | | `Bighelp/Settings/` | The one Settings tree (`SettingsView` and its `+Menu`, `+NerdMode`, `+Computers` pages: the groups, the Advanced options switch, Your computers) and `SettingsStore`; Models (`ModelsSettingsView`), Voice and Notifications pages. A computer's own page is `BighelpConfiguredHostView` in `Bighelp/Hosts/` | -| `Bighelp/Agents/`, `Board/`, `Companion/` | Agents, Feed/Ideas/Goals, the avatar kit renderer | +| `Bighelp/Agents/`, `Board/`, `Companion/` | The bot directory and its editors, Feed/Ideas/Goals boards, the avatar kit renderer | | `Bighelp/Kanban/` | Kanban on Hermes' Kanban plugin: board model, lanes, cards, Vision Pro window and pinch-drag | -| `Bighelp/Code/` | Code mode (Settings › Modes › Code mode): its home (`CodeHomeView`), the message box's chips (project, new worktree or local, branch), `CodeLauncher`, Changes and Ship | +| `Bighelp/Code/` | Coding sessions, started from New chat's choices row (project, new worktree or local, branch, mode, Stage) and listed on Work: `CodeHomeStore`, `CodeLauncher`, the pickers, Changes and Ship | | `BighelpShare/`, `Bighelp/ShareShared/`, `Bighelp/Share/` | The share sheet (#922): the extension saves what's shared into the app group (`PendingShareInbox`, Foundation only and shared with the app), and the app's review puts it in the message box of the chat the person picks (`PendingShareCenter`, `ChatModel.placeShare`) | | `Bighelp/Connectors/` | Settings › Apps & skills (`AppsHubView`; a bot's profile has its own Connections): Hermes' connectors as Native App Connections (the inline connect cards in chat, `connection.request`, `ConnectorCardStore`; `ConnectorAppsModel`) and Composio Apps (`Composio/`, [docs/COMPOSIO_APPS.md](docs/COMPOSIO_APPS.md)) | | `Bighelp/HTMLApps/` | Agents' HTML apps: the `html_app` card, the full-screen page and its `window.bighelp` bridge, the plugin's `html-apps` routes, the demo's sample apps | | `Bighelp/BotScreen/` | Bot Screen: an agent's Linux screen (Hermes `display.*`) and the computer's own desktop (`ComputerScreen.swift`, the plugin's VNC bridge) in its profile's Computer tab, a native RFB client (`RFB/`, with VNC passwords) and the full-screen viewer with take control and hand back | | `Bighelp/Driving/` | An agent showing the person a place (`iphone_navigation`, #662): the place catalog and its playbooks (`DriveCatalog`), the navigator that plays one (`DriveNavigator`), and the overlay (island bar, chat dock) in its own window | -| `Bighelp/Usage/` | The Usage page (☰ › Usage): plans and limits (`ProviderUsageStore`), Hermes' own analytics per agent and computer (`UsageStore`, `HostUsageLoader`), charts | +| `Bighelp/Usage/` | The Usage page (Settings' first group, the sidebar's More): plans and limits (`ProviderUsageStore`), Hermes' own analytics per agent and computer (`UsageStore`, `HostUsageLoader`), charts | | `Bighelp/Voice/` | Turn-based and live voice; on-device voices (`OnDevice/`, Phonon in `Packages/PhononTTS`) | | `Bighelp/Spatial/` | Vision Pro: the agent in the room (`SpatialAvatarModel`, its volume and voice panel, its Settings section) | | `BighelpWatch/`, `BighelpWatchShared/`, `Bighelp/Watch/` | The Watch app, the Watch–iPhone wire (`WatchWire`), and the iPhone's `WatchRelay` that answers it | @@ -233,11 +306,19 @@ change in both repos. ### UI test traps -- `BighelpUITestCase` launches with Advanced options (`settings.nerdModeEnabled`) on and `-loopdy.home.opens-chat NO`. Use its helpers: - - `openRootTab` +- `BighelpUITestCase.makeApp()` returns a `BighelpTestApplication`, which launches with Advanced options on + (`-loopdy.settings.nerd-mode YES`), `-bighelp.home.migrated-v1 YES` (the one-time settings migration is past), + `-loopdy.home.landing chats` (pin another place with `bots`, `chats`, `today` or `work`, and the first tab's view + with `-bighelp.home.view bots|chats` under today or work), `-bighelp.hosts.all-hosts NO` (the computer in use + only; a test of every computer opts in) and the bot page's swipe tutorial seen. Use its helpers: + - `openRootTab` (the old shell's tab names, through the home's doors: Chats, Bots, a Today panel, a Work door, + Settings; any other name fails) - `settingsRow` - `openChatInfo` - - `chatNewChatButton` + - `chatNewChatButton` (leaves an open chat through its Back first, then returns the bar's `home.new-chat`) + - `chatIdentity` (the pill in a chat's header) and `confirmNewChatPicker` (New chat opens with nobody + picked; it picks a bot) +- The bar's ids are `home.tab.conversations|today|work` and `home.new-chat`; a chat's Back is `chat.back`. - Launch arguments pin `@AppStorage` values for the whole run, and taps in the UI can't change them. A `NO` launch argument is a string, so read flags with `UserDefaults.bool(forKey:)`. - `app.buttons["x"]` matches accessibility identifiers. SwiftUI menu items use their title as the identifier. @@ -321,7 +402,7 @@ change in both repos. `@available`, so never raise the app's minimum for it. Its core has no visionOS or Intel slices, so only iPhone and iPad link it (the Mac DMG is universal). - **Voice mode per agent** (`AgentVoiceChoices`): Live or Take turns, and the live voice, are kept per computer - and agent on the device; Settings › Voice holds the default for agents without their own, and Bots mode's + and agent on the device; Settings › Voice holds the default for agents without their own, and a bot page's Default Voice sets an agent's. Anything that opens voice for an agent reads its effective mode. Voices and models are picked from lists (`VoiceOptions`; ElevenLabs from the account, speech plugins from the plugin's `voice-catalog`), with a typed Other only where a provider takes any value. @@ -365,7 +446,7 @@ change in both repos. each time it's read (`BighelpVisibleChats` → `ChatModel.noteRead` → `SessionCatalogStore.noteRead`): as it shows, 2 s after a turn ends on screen, and as it stops showing or the app leaves the front. A chat that isn't on screen is never marked, and one read again with nothing new isn't marked twice. Rows without `unread` mean the host - keeps none: Mark Read and Mark Unread hide (`SessionSummary.tracksUnread`). Bots mode shows Hermes' state where + keeps none: Mark Read and Mark Unread hide (`SessionSummary.tracksUnread`). The Bots view shows Hermes' state where there is one, else the marks kept on the device (`SimpleBotsReadState`). The Chats list's Draft reads the draft journal without observing it (`ChatDraftJournal.pendingDraft`). - **Archived:** the catalog lists `archived=include` and keeps rows Hermes' idle sweep archived @@ -385,16 +466,16 @@ change in both repos. the host sent something on that socket in the last 5 s (`admissionFreshness`). Coming back to the app or a network change (`verifyLiveness`) voids that until a ping sent after it is answered: frames from before can sit in a dead socket's buffer. A prompt sent on a socket that dies anyway is journaled as uncertain, never resent. -- **App state on the computer:** Bots mode's order, the sections, each group chat's section, pin and hide, Multi-gateway's - primary bot and each bot's voice, mark, pet and character are also kept for each person on their computers - (plugin `native-app-state-v1`, keys `bots.layout` and `bots.settings`; `Bighelp/AppState/`), so a reinstall +- **App state on the computer:** the Bots view's order, the sections, each group chat's section, pin and hide, the + primary bot kept for Show every computer and each bot's voice, mark, pet and character are also kept for each + person on their computers (plugin `native-app-state-v1`, keys `bots.layout` and `bots.settings`; `Bighelp/AppState/`), so a reinstall or another device gets them back. The stores stay where screens read them; `BotsAppStateSync` turns their changes into patches and puts the newest revision from every computer reached back in them. Items are named by the computer's own ID (`/`), never by this phone's host ID or sign-in scope. A value lists the computers it covers: a computer reached for the first time gets this phone's part, and a value already there wins (a fresh install never sends empty choices). Keep JSON fields the app doesn't know. The plugin refuses only values shaped like credentials; links and IDs go as they are. -- **Who's working:** Bots mode's home and the Agents screen show each agent's Bot Chat working or needing +- **Who's working:** the Bots view, the Chats view, Today and Work show each agent's Bot Chat working or needing you from the plugin's `agents/activity` (`native-agents-activity-v1`): Hermes' turn leases in any process (the app, `message_agent`, `chat -q`) and the dashboard's open prompts, for up to 64 agents in one read. `BotChatActivityStore` reads it while one of those screens shows and the app is active (3 s while something @@ -433,8 +514,8 @@ change in both repos. share with files waits in the list: its words alone would spend files never sent, and Open brings them all back, even into a box that has its words already (`PendingShareIntake` places the opened share first). The person taking a share's last file or words out of the box lets it go, kept and listed. The saved copy goes only when - Hermes takes the message carrying it, or when the person deletes it in ☰ › Shared with bighelp (or Settings' first - screen, in every mode), which lists every waiting share; never by itself. `PendingShareInboxTests`, `PendingShareLedgerTests` + Hermes takes the message carrying it, or when the person deletes it in the list of waiting shares (Today's Shared with bighelp card, Settings' first + screen or the sidebar's More), never by itself. `PendingShareInboxTests`, `PendingShareLedgerTests` and `PendingShareWaitTests` run under any Swift (no UIKit); `PendingShareComposerTests` drive the chat. - **Plugin routes:** - Each route is a `WorkspaceOperation` case plus a `Route(path:feature:isMutation:maximumResponseBytes:)` in @@ -552,7 +633,9 @@ change in both repos. `native-device-permission-request-v1`): its Turn on flips the same switch, without reopening the channel that carried the call, and the call goes on. Apple Health is read only and asks once about sharing first. The channel runs while bighelp is active, inactive or in the background grace, and in any agent's chat on a plugin with - `native-device-tools-agents-v1`; after the grace it closes as `paused` so the host waits for the phone. + `native-device-tools-agents-v1`; after the grace it closes as `paused` so the host waits for the phone. It + belongs to the chat opened last (`AppState.deviceToolConversationID`), also after Back to a list while its bot + still works; `activeConversationID` is only the chat still on the stack. A channel the host ended (its 30 s lease ran out while a slow tool ran, the plugin unloaded or started again, a lost connection) opens again by itself while the chat keeps its tools, with longer waits each time and a limit (`runReopeningWhileHeld`, `reopenWaits`); a late answer the host no longer takes loses only that answer, never @@ -569,22 +652,43 @@ change in both repos. (`ImageDraftStore`): it claims the draft on the host, journals the write (`DeviceToolFileJournal`) and reads it back, so a second tap or a relaunch never writes twice; without access it opens Apple's own editor, whose Done is the Save. In a chat that holds the person's picture the phone answers `contacts.create` and `calendar.create` with - `review_required`. Each agent's Photo actions page sits beside its Instructions in Agent Studio, and in What it - can use on a bot's profile. + `review_required`. Each agent's Photo actions page is in What it can use on a bot's profile. - **Agents' apps** ([docs/HTML_APPS.md](docs/HTML_APPS.md), plugin `native-html-apps-v1`): an agent's HTML app is an `html_app` card (title, description, Open App); the chat never draws the HTML. Open App loads the page from its own `bighelp-app:///` origin in a full-screen web view (`HTMLAppWebView`) and renders it as made: any site or - library loads, while links and new windows open outside and the camera and microphone are refused. Its only way to + library loads, while the camera and microphone are refused. Only a link the person taps, to an `http` or `https` + address, opens outside; every other way off the page is dropped (`HTMLAppNavigationPolicy`: a script's own + navigation or `window.open`, and every other scheme, bighelp's own links included). Its only way to the app is `window.bighelp` (`HTMLAppBridge`): data the plugin serves (read every 5 s while a live app is open) and `sendAnswer`, which shows the exact message and sends only on the person's Send, as their next message. +- **Spaces** ([docs/SPACES.md](docs/SPACES.md), plugin `native-spaces-v1`): a space is a live panel on Today. A bot + drafts it in a chat as a `space_draft` card (`SpaceDraftCardView`); only the person's Add to Today makes it a space, + and a routine on the computer then keeps it current. Each computer has one `SpacesStore`, kept by its cache scope + (`WorkspaceAuthority.cacheScopeID`), so a reconnect keeps it. `TodaySpacesModel` reads them all: the computer in + use and the ones Show every computer keeps connected live, the rest from the phone's copy. A read sends the card + hashes the phone has (`known`), so the computer leaves unchanged cards out. A space's size, hiding and place belong + to its computer (`TodayPanelLayoutStore.ownedChanges` → `SpacesTodayBridge`): a change shows at once + (`SpacesStore.stage`) and goes with `update`. One still waiting for its answer repeats with the same + `operationId`; a change on top of it gets a new one, because the plugin refuses an `operationId` it saw with + another body. A delete the computer hasn't finished stays off Today and repeats at each read, across launches. + Only the plugin's own context says the feature is missing ("Update the plugin"); a refused route during a + reconnect never does. A space's page opens in `HTMLAppScreen` on its own computer and never sends a message, + whatever the plugin says the page may do. Changes to one space go one at a time (`SpacesStore.send`), so the + computer ends on the last choice. A read asks about every bot the phone holds spaces for, and only the computer + saying a bot is gone takes its spaces off: a bot list that is short for a moment never does. Removing a computer + erases its spaces from the phone (`TodaySpacesModel.forget`). A bot's title and description are cut to the wire + maximums as they are read. - **Hermes versions never gate connections or features.** Older, newer, custom and absent version strings are metadata, not an allowlist. Check actual host capabilities and route responses instead. - Hosts differ, so parse leniently: ignore unknown keys and treat most parts as optional. - A missing part should hide one row, not break a screen. -### Code mode +### Coding sessions + +A coding session starts from New chat (one bot, a project picked in its choices row) and lists on Work. There is no +Code mode. -- Each Send runs `CodeLauncher`: the host's stock git makes the worktree (`/api/git/worktree/add` through +- Each Send of one runs `CodeLauncher`: the host's stock git makes the worktree (`/api/git/worktree/add` through `StockGitManaging` prepare/execute) or switches the local branch, then `session.create` starts the session in exactly that folder with a title (`createSession(agentID:folder:title:)`, no fallback folder), then the first message goes out the way Shortcuts sends (`submitWithoutWaiting`). Nothing opens, so sends can go back to back. @@ -598,26 +702,28 @@ change in both repos. - Back-to-back sends make their folders and sessions one at a time (`CodeHomeStore.setupTail`): Hermes starts one new chat per agent at a time, and each worktree changes the repository the next send reads. Sending and the agents' work still run side by side. -- Hermes doesn't remove a worktree when its session ends; ☰ › Worktrees does. Its `create-pr` route takes no - title or description (they come from the commits); "Ask the agent to open it" sends the session a message. -- Cards show only what the live chat or the session list says (`CodeChatStatusReader`): waiting prompts are - "Needs you", running work shows its tool. Demo mode uses `DemoCodeProjectSource` and `DemoCodeGit`. -- The mode button (`CodeSessionMode`) uses Hermes' own options: Plan sends the first message as `/plan …` (Hermes +- Hermes doesn't remove a worktree when its session ends; Worktrees does (a project's ⋯ on Work, and New chat's + choices row). Its `create-pr` route takes no title or description (they come from the commits); "Ask the + agent to open it" sends the session a message. +- Work's coding rows show only what the live chat, the session list or the Dashboard's waiting list says + (`CodeChatStatusReader`): waiting prompts are "Needs you", also for a session whose chat isn't open, and running + work shows its tool. Demo mode uses `DemoCodeProjectSource` and `DemoCodeGit`. +- The mode chip (`CodeSessionMode`) uses Hermes' own options: Plan sends the first message as `/plan …` (Hermes writes `.hermes/plans/-.md` and changes no code); YOLO sets the session's `yolo` config (session - scope, `setYOLO`) before the first message. A refused YOLO sends nothing and keeps the card. + scope, `setYOLO`) before the first message. A refused YOLO sends nothing and says so (`CodeStartError.yoloRefused`). - A first message that starts with `/` takes the chat's own send path, which runs it as a command (`/plan` expands to its planning prompt there); `submitWithoutWaiting` (`prompt.submit`) would send it as plain text. The `/` list loads before the session exists: `commands.catalog` with `profile` and `cwd`, no `session_id`. - Markdown files open in `MarkdownFileSheet` through Hermes' `/api/fs/read-text` and `/api/fs/write-text` (`HostTextFileAccess`; demo: `DemoHostTextFiles`). Save re-reads first and never overwrites a file that changed without asking. IDE chats link Markdown paths (`HostFileLink`, `opensHostFiles`) against the session's folder. -- Orchestration mode: Stage keeps a job with its chips (`CodeStagedJob`, saved per computer), and Send all - starts the staged jobs as one `CodeBatch` through the same one-at-a-time setup. The app combines the batch's +- Stage (the last chip of New chat's choices row) keeps a job with its chips (`CodeStagedJob`, saved per + computer), and Send all starts the staged jobs as one `CodeBatch` through the same one-at-a-time setup. The app combines the batch's sessions (`CodeBatchChatView`): a message goes to each through `sendCardReply` (it steers a running turn), and each session's answer shows under the message by time. `#` mentions route (`CodeBatchRouting`): a session mention picks it and drops out of the text; a pull request mention is spelled out with its branch and goes to the session on that branch. -- Dev Factory (☰ › Dev Factory) is Workflows with `schemaVersion: 3` recipes (plugin `native-workflows-code-v1`, +- Dev Factory (a project's ⋯ on Work) is Workflows with `schemaVersion: 3` recipes (plugin `native-workflows-code-v1`, contract in bighelp-plugin's docs/DEV_FACTORY.md; vectors in `BighelpTests/Fixtures/Workflows/*-code.json`). A recipe lists git projects; `startCodeRun` makes one run per project under a `group_id`, each in its own worktree. New stage kinds `command` and `pullRequest`, and sign-off on the changes (`signsChanges`, @@ -743,8 +849,8 @@ change in both repos. the files that use it and rebuild before chasing it. - **Live properties read outside `body`:** calling another view's computed property (a section of `SettingsView`, say) from elsewhere reads its `@Environment` and `@BighelpThemeReader` with their defaults, - the light theme, so Bots mode's pages drew white rows and light-mode grays at night. Build such a page - in the view's own `body` (`opening(_:)`, `simpleBotsPage(_:)`). + the light theme, so a page built that way drew white rows and light-mode grays at night. Build such a page + in the view's own `body`. - **Light and Dark on open sheets:** `.preferredColorScheme` gives a sheet its style when it opens and doesn't change it after, so a switch in Settings left the open sheet's text fields and pickers in the old style. `BighelpWindowAppearance` sets every window and presented controller, and each `bighelpSheet` and @@ -755,7 +861,7 @@ change in both repos. two steps. - **One long-press menu per List row:** a List row shows the first `.contextMenu` in it for every item, so a grid of tiles in one row acted on the wrong item (holding a pinned chat offered another chat's Delete). Give each tile a - `Menu(primaryAction:)` or its own gesture (`AgentPinnedGrid`). + `Menu(primaryAction:)` or its own gesture. - **Owners change on every reconnect:** `WorkspaceOwner` includes the connection generation, so returning to the app makes a new one. Keep per-computer state (like "this host has Kanban") by `cacheScopeID`, and don't turn a failed check during a reconnect into "unavailable" (`KanbanAvailability`; New Group Chat: @@ -778,8 +884,8 @@ sections can crash only on devices ("Thread stack size exceeded"). ### iPad layout -- iPad has no always-open sidebars. ☰ opens the one menu, which slides in from the leading edge - (`HomeMenuPresentation`); iPhone shows the same menu as a sheet. The bottom tab bar shows on iPad too. +- iPad has no always-open sidebar. At regular width the header's sidebar button slides `HomeSidebar` in from the + leading edge (`HomeMenuPresentation`); iPhone has no sidebar. The bottom bar (`HomeTabBar`) shows on iPad too. - The chat lane (messages, message box, status rail) is `ChatCanvasLayout.regularLaneMaximumWidth` wide on iPad and Vision Pro. Bubbles take their share of it; don't reintroduce a fixed narrow column. @@ -792,9 +898,9 @@ sections can crash only on devices ("Thread stack size exceeded"). isn't for layout). - Cover (466 × 678, or half of the open screen in Split View) and open wide (`usesSideBar`): built with the iOS 27.1 SDK, iOS lays a screen's navigation bar buttons down the 84-pt status column under its 174-pt camera area. The bar's - places are toolbar items (`BighelpStripTabs`, `.bottomBar`), so iOS stacks them there too; a column of our own - drawn over the strip lay on top of ☰ and the brand. The brand shows only the Noodle there. Chats in Bots and Code - mode, which have no bar, get `BighelpChatSwitcher` in the strip instead. + places are toolbar items (`HomeStripTabs`, `.bottomBar`), so iOS stacks them there too; a column of our own + drawn over the strip lay on top of the screen's own buttons. A chat has no bar, so + `BighelpChatSwitcher` (Settings › Chat › Chat switcher) takes the strip there. - Open wide: `BighelpSplitColumn` shows the tab's list in its own `NavigationStack` up to the fold (`splitColumnWidth`), and what it opens is pushed on the app's one stack beside it, so `path`, the active chat and every top-of-stack rule work as on iPhone. The list is the shell's own view, drawn again from its stores @@ -831,13 +937,15 @@ sections can crash only on devices ("Thread stack size exceeded"). - Present with `.bighelpSheet` and `.bighelpFullScreenCover`, never `.sheet` or `.fullScreenCover`. After a few sheets, Catalyst stops closing them: Done runs and the state says closed, but the sheet stays, stops updating and blocks the window until Esc. The bighelp versions close it through UIKit (`MacSheetPresentationTests`). -- ☰ is the window's sidebar (`BighelpSideMenu`, shared with Vision Pro): it stays open while you pick, and the Mac - remembers it. The title bar's sidebar button (`MacTitlebarItems`, on every screen), ☰ and ⌃⌘S toggle it. Drag - its divider to resize it (remembered; double-click for the default width). +- `HomeSidebar` is the window's sidebar (`BighelpSideMenu`, shared with Vision Pro): it stays open while you pick, + and the Mac remembers it. The title bar's sidebar button (`MacTitlebarItems`, on every screen), the header's + sidebar button and ⌃⌘S toggle it. Drag its divider to resize it (remembered; double-click for the default + width). The bar shows on the Mac too. - Title bar items are an `NSToolbar` on `scene.titlebar`. An `NSToolbarItem` made from a `UIBarButtonItem` fires only the button's target/action; a `primaryAction` closure never runs. - Keys: Return sends (Settings › Chat › Return sends), Shift-Return adds a line, Command-Return shows the send - choices while the agent works. ⌘N starts a chat and ⌘, opens Settings (`BighelpMenuCommands`). + choices while the agent works. ⌘N starts a chat, ⌘, opens Settings and ⌘1–⌘3 pick the three places + (`BighelpMenuCommands`). - `BighelpMac` (`BighelpMac/`) is a separate, fixture-only desktop prototype. It isn't the shipping Mac app. - Mouse and keyboard: plain buttons take clicks only where they draw, toolbar icons only on their glyph and form fields only on their line of text. Use the helpers in DESIGN.md › Mac pointer and keyboard. @@ -879,9 +987,9 @@ sections can crash only on devices ("Thread stack size exceeded"). it anyway: pass `prompt: Text("…").bighelpFieldHint(theme)`. Light-mode theme greys are darkened there too. Unselected segment labels ignore every color setting, so use `bighelpSegmentedPicker()`, which keeps a dark track there. Don't use `toolbarColorScheme` there: it overrides the appearance and turns titles white again. -- Tabs sit in a leading ornament (`VisionTabOrnament`), not a bar along the bottom by the system's window - controls. A screen covered by a pushed one hides its ornaments, so the pushed home chat carries its own. - ☰ opens as a column beside the page (`BighelpSideMenu`), not a sheet; the Mac uses the same column as its sidebar. +- The three places sit in a leading ornament (`HomeTabOrnament`), not a bar along the bottom by the system's window + controls. A screen covered by a pushed one hides its ornaments, and a pushed chat has Back instead. + The sidebar opens as a column beside the page (`BighelpSideMenu`), not a sheet; the Mac uses the same column. - Eye targets: controls are 56pt or more (`BighelpTokens.hitTarget`), header buttons 52pt glass plus margin. - Forms on visionOS: section headers don't grow to fit (Agent Studio's hero lives in a row there), a row of plain buttons can be laid out zero points tall (pin it with `.fixedSize(horizontal: false, vertical: true)`), @@ -1177,9 +1285,9 @@ New code uses Bighelp names. Don't "finish" the rename on this list. catalogs for demo mode and first launch; refresh them before a release. - Only first-party or permissively licensed art can ship in this Apache-2.0 repo. - The maintainer approves new character art before it ships. -- An agent's face (`AgentFace`, drawn by `AgentLiveAvatar`, Bots mode's `SimpleBotFace` and its pet +- An agent's face (`AgentFace`, drawn by `AgentLiveAvatar`, the Bots view's `SimpleBotFace` and its pet companion `AgentPet`) is, in order: its saved character (`CompanionStore` override), its petdex pet's moves - (`PetAvatarStore`), its Hermes face, shape or Bot Studio avatar (`AgentLookStore`, from the profiles' looks), its Bots mode mark + (`PetAvatarStore`), its Hermes face, shape or Bot Studio avatar (`AgentLookStore`, from the profiles' looks), its mark (`SimpleBotMarkStore`), then its picture. The first two live on the device, so saving any other kind of avatar must clear them (`AgentEditorModel.applySavedLook`), or chats keep the old one. There is no app-wide pet: each agent's pet is its own face. @@ -1228,7 +1336,7 @@ New code uses Bighelp names. Don't "finish" the rename on this list. (`HostSignInMatrixUITests`). - `Scripts/NativeWorkspaceAcceptanceProbe.py` covers the workspace and chat acceptance flows. - `Scripts/RoomLinkProbe.py` starts two isolated hosts and checks a group chat with an agent from each - (Hermes RoomLink); `--simulator-id` runs the app's own UI test against them. The scratch Hermes needs + (Hermes RoomLink) through the protocol calls. The scratch Hermes needs Python 3.14 and its `messaging` extra (the API server serves RoomLink). - `Scripts/AppStoreScreenshots.sh` takes the App Store screenshots from the real app on an isolated host whose agents really run their tools on made-up files. No demo chats in store screenshots. diff --git a/Bighelp.xcodeproj/project.pbxproj b/Bighelp.xcodeproj/project.pbxproj index 301a46eb..7e7fb379 100644 --- a/Bighelp.xcodeproj/project.pbxproj +++ b/Bighelp.xcodeproj/project.pbxproj @@ -23,20 +23,22 @@ 0165CE49CFB9B4CF398ACB9D /* HermesLogsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F60D9BF8F9A20662AE22786 /* HermesLogsView.swift */; }; 01771AEBEF12FF0B94C7BAB9 /* BighelpPushRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 528CFD4BD3A37CA415724F2F /* BighelpPushRegistrar.swift */; }; 01A31276F48AAB6DE4F520A5 /* CardBackgroundView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9088DE1567D631DC797171DB /* CardBackgroundView.swift */; }; - 01B73B8BCFD2D5C83E04112E /* AgentProfileSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDCFBB5C4E5985D8EC6C78FD /* AgentProfileSheet.swift */; }; 01C35068F36A28908A363564 /* DirectHermesEndpointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E0042C72BAF1336AB1578750 /* DirectHermesEndpointTests.swift */; }; 01D1992B2A990CE49F3DFDF6 /* CarPlayAgentChoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23C9FFB12E9C54333FBCED36 /* CarPlayAgentChoice.swift */; }; 01D2F5AEDA225C7661778B7F /* DemoWorkflowsClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08CA3E8CE8BF9FF6920DE209 /* DemoWorkflowsClient.swift */; }; 023CB07AFFB851D701DE512D /* OnDeviceVoiceSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43DC33ACEF48388887235EEE /* OnDeviceVoiceSettings.swift */; }; 0245FA2481F1D25284A33027 /* LongTextEditorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B9BFECF9345E2D8DC72595E /* LongTextEditorTests.swift */; }; 024C64D3856D3AEB18623729 /* WikiCreationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5AD2ED484B9562E3339F9AB /* WikiCreationTests.swift */; }; + 026EE8E1DAABEA9BFB6B15D3 /* AgentsSectionCaption.swift in Sources */ = {isa = PBXBuildFile; fileRef = 322A3C7A5248CE931D627A74 /* AgentsSectionCaption.swift */; }; 0286FBC6D97E10D963F43C78 /* SessionCatalogLargeWorkspaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F972D8331BE114EEEEE074F0 /* SessionCatalogLargeWorkspaceTests.swift */; }; 0295E1C420530DDEC8B25050 /* DirectHermesSessionControlClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37B2EB49CB9A23116469C17F /* DirectHermesSessionControlClientTests.swift */; }; + 02AF109D3DD981434BF2219B /* TodayPanelLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E2FCD0CE3A5F9E9513CB461 /* TodayPanelLayoutTests.swift */; }; 02DEA88EA31DF263024E58A6 /* BighelpCardTemplateStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3282A97CC25FC44176A0DAE5 /* BighelpCardTemplateStoreTests.swift */; }; 0310CEBE1FD9DC5D45DC517B /* SessionCatalogReconciliation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CED46EE473ABA70B07472CF /* SessionCatalogReconciliation.swift */; }; 032C77F0CB598EB2CC271291 /* templates-list.json in Resources */ = {isa = PBXBuildFile; fileRef = 1BD9E74ADB69CC3250229440 /* templates-list.json */; }; 032F202339A536C605160741 /* BighelpPinnedAgentsWidgetFeed.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5D53C2B79F59FC36E3E2ABE /* BighelpPinnedAgentsWidgetFeed.swift */; }; 036316D8E77743CAC2A79D59 /* PhononTTS in Frameworks */ = {isa = PBXBuildFile; platformFilters = (ios, ); productRef = 2B2E851DCB92390D3232DA88 /* PhononTTS */; }; + 036CFADFEE4116FF69BD1BDF /* TodayBoardsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4111B56D03996279BB006CC /* TodayBoardsStore.swift */; }; 03A50E03E3E6689D77C6CB3C /* DirectHermesWorkspaceClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2744AFEE1431D53C47F401 /* DirectHermesWorkspaceClientTests.swift */; }; 03B61C6BB681E2EC5C74EF77 /* ChatAttachmentSaving.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64AF3D5321DFFC9B9556E9B9 /* ChatAttachmentSaving.swift */; }; 03B7DEB1937FFFE3888F6B09 /* ImageDraftsHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89B2945CB5AC29F0E779012D /* ImageDraftsHostUITests.swift */; }; @@ -45,9 +47,9 @@ 040D8CC44E215299B66F6A06 /* Teamwork.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F1EFA3A141B8A46192AF5C5 /* Teamwork.swift */; }; 043D50CBEB85769829DBBFAC /* WorkspacePageStates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93C40496DA01F9AC2116C506 /* WorkspacePageStates.swift */; }; 046D31CE6FBAE0AAEB73A002 /* BighelpImageGeneratingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E71BAF3ED050711558DACCE /* BighelpImageGeneratingView.swift */; }; + 048787A3730C8D49CB08BB83 /* ChatsInboxRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F1EBF478C30A24456E26A25 /* ChatsInboxRow.swift */; }; 048F7A61F0CA0760D47A2BF2 /* DirectHermesAttachmentClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 81CABC4DD0A03C05A6531348 /* DirectHermesAttachmentClientTests.swift */; }; 0499789C48A13CFC46D6E128 /* DirectHermesGeneratedMediaClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80938D1DC3C8FD823A41A1E1 /* DirectHermesGeneratedMediaClient.swift */; }; - 050AF19EDB08DD39CFB94B47 /* UnifiedModeToggleUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF768AB5BA4E7E7F91249A1D /* UnifiedModeToggleUITests.swift */; }; 051146CA8DA17E3FF2A1F883 /* NativeWorkspaceLockedWakeLiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 117DF67A867B04D7F822E7D8 /* NativeWorkspaceLockedWakeLiveTests.swift */; }; 0537F66F671525DE97D570CE /* VoiceConfigurationStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335213208F41D9012118F4BD /* VoiceConfigurationStore.swift */; }; 053E66E5A37D5E8F24168EBC /* BighelpRealtimeAudioPeer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 918B96E497E5895E812E63C3 /* BighelpRealtimeAudioPeer.swift */; }; @@ -68,6 +70,7 @@ 0729E07D086789DEBFDEDFA9 /* GitHubCredentialAcceptanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42963DDEFB1D5438885970EA /* GitHubCredentialAcceptanceTests.swift */; }; 0736263B512C63A4AEF1D33B /* BighelpNotificationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = E23D2ABE5C87A42EEE580AC8 /* BighelpNotificationContext.swift */; }; 073800F22E724696203CC50F /* BighelpSheetSize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BE74E54DB93F0E290670B40 /* BighelpSheetSize.swift */; }; + 0743E22555A70EBC89AB2A10 /* NewChatRecipients.swift in Sources */ = {isa = PBXBuildFile; fileRef = 341899D306173E3A6BF70917 /* NewChatRecipients.swift */; }; 0799B9446E83D23984F3E275 /* ChatPerformanceProbe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 179723EE50D9141778E15E3C /* ChatPerformanceProbe.swift */; }; 07A1FEF03D3F4ABD30148664 /* ChatView+Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E743538DB81EB0202DEB71F /* ChatView+Timeline.swift */; }; 07AC57088F0A3AB316390448 /* RetiredChatAppearance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C8285C25EF405257D9D5A7D /* RetiredChatAppearance.swift */; }; @@ -81,6 +84,7 @@ 09154066FEA537D20BEBF02B /* ProviderUsageSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E62018803B85F864D126FF9 /* ProviderUsageSettingsView.swift */; }; 094B518B9DF39B9B4AA67B4D /* BighelpWorkActivityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0719AE56C96E86FC621D9B18 /* BighelpWorkActivityTests.swift */; }; 09536479F69F0F340C5B946C /* PendingAgentFilesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D781192BA7676007D6D5FF37 /* PendingAgentFilesView.swift */; }; + 095FEFD74A2FA1D648B59B6A /* SpacesStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8E5581E4759087BDC795DA7 /* SpacesStoreTests.swift */; }; 0963824B1C1CDB181BEBF365 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = EA02A54D78F51C5693D834C4 /* PrivacyInfo.xcprivacy */; }; 09651BA643D9557E64F410ED /* DashboardActivityDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCC640306666832EF7BEC2A0 /* DashboardActivityDetailView.swift */; }; 097C03162CA1EBD2B7D40CA6 /* DirectHermesKanbanAdministrationClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0146AA0B6247AD289E1620B5 /* DirectHermesKanbanAdministrationClient.swift */; }; @@ -97,6 +101,7 @@ 0A271556F235501D8BDB0A1B /* DemoKanbanService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19400F9AFD7AA21E799510C5 /* DemoKanbanService.swift */; }; 0A3554DA51329F075B247793 /* ReferenceNativeEditorAcceptanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 110327E861D3E832B5032BF2 /* ReferenceNativeEditorAcceptanceTests.swift */; }; 0A691D79FC5660769876D0DB /* DirectHermesScheduledTaskCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09B1710AD58F8254E86D3E44 /* DirectHermesScheduledTaskCodec.swift */; }; + 0A6967A48C99D6A2F92ED523 /* BotProfileActionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42C37CAEBF941CE56AEC027B /* BotProfileActionsTests.swift */; }; 0A72754300CD6BE0F0B4346D /* NativeWorkspaceSelectionStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = F99853BC40C48C560475D54A /* NativeWorkspaceSelectionStore.swift */; }; 0A946DC969DB99FEB9C01AE8 /* HermesGroupsHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59CE897F445CA638FA3897BE /* HermesGroupsHostUITests.swift */; }; 0AF64F4A689AA476676FC18D /* WorktreeManagementView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D074072376DAC19ECF4B94A /* WorktreeManagementView.swift */; }; @@ -124,6 +129,7 @@ 0ED4C7D9A60B28A0593F64A5 /* ChatCitationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08C24E636F6551619D202CD1 /* ChatCitationTests.swift */; }; 0EE72D4840B3C9A4AF0B3DBC /* SessionPickerWireModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BE3FBAE98AF4D38AEEC8C2D /* SessionPickerWireModels.swift */; }; 0F2D2EE99597B7B4432DAB03 /* MidSessionSendHoldStateMachineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2374DE9B77B289CA2C4A4E8 /* MidSessionSendHoldStateMachineTests.swift */; }; + 0F4E40B1AEEDEB1E0256DAF3 /* DemoSpacesClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD862801EBAA40B5D76F8123 /* DemoSpacesClient.swift */; }; 0F6AB98EDF03574F11ECA589 /* ChatLiveWorkView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F68F20978C0AB2C937FE171 /* ChatLiveWorkView.swift */; }; 0F7503A6FF6BBDB9B82E5EA6 /* KanbanLane.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED592EAB0C77EF222B56EC54 /* KanbanLane.swift */; }; 0FA7A6AFF29411F90A565A9E /* BighelpSpinner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1626430F2EC2CF189A88B4B0 /* BighelpSpinner.swift */; }; @@ -136,6 +142,7 @@ 10932693804EC479FFA9D9D2 /* bighelp-talking.json in Resources */ = {isa = PBXBuildFile; fileRef = 9A1D78BBAD147F6960A7AF5D /* bighelp-talking.json */; }; 10C4C39FA2758C7127480865 /* ChatMarkdownTableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC9944B9527C263AE1CAA797 /* ChatMarkdownTableView.swift */; }; 10DBE7123EC87508A7FF5EDB /* BoardBlueprintAndGoalCategoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4DA121DC4F3462AA6F8C58F6 /* BoardBlueprintAndGoalCategoryTests.swift */; }; + 10E30BA534D118C2033CE598 /* RootHome.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45C970BDD3E46D550BEF79C2 /* RootHome.swift */; }; 10E3992D7315AFA766435388 /* HTMLAppWebView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2637EE8814A681109559F67 /* HTMLAppWebView.swift */; }; 10EEF81E5F23C12501887BC9 /* AgentBoard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B8B37EC9D882249EE83AE37 /* AgentBoard.swift */; }; 110C1D7EF11DD5793A144D1F /* DashboardModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A798709937DA6520A2B5190 /* DashboardModelTests.swift */; }; @@ -146,11 +153,13 @@ 1178C8CDB388F1FBEC495E76 /* ScheduledTaskIdentityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A00466FEB95921C98B18EDC /* ScheduledTaskIdentityTests.swift */; }; 118B7B722A22624157B2D13D /* DirectHermesSessionCatalogRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDA65FB5CDACAC184E55451B /* DirectHermesSessionCatalogRowTests.swift */; }; 118E64EF7A92C0A500B827B6 /* KanbanFailureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B471C653B70E1EF7F99BDB67 /* KanbanFailureTests.swift */; }; + 11C26F0E7556FB6B4B2AB21B /* HTMLAppNavigationPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 056F1D91C370B7F7DA5585BC /* HTMLAppNavigationPolicyTests.swift */; }; 11CD6C31F4B66485205EE743 /* HTMLAppsFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4570755E70AA053D254D4835 /* HTMLAppsFixture.swift */; }; 11DBFDA36E02794E27831031 /* BotsAppStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7638A9EA643D13DFA9FF59E /* BotsAppStateTests.swift */; }; 1210FA290293C238A6C1F377 /* IslandStage.swift in Sources */ = {isa = PBXBuildFile; fileRef = D927E9C5B53DDE1797A520AD /* IslandStage.swift */; }; 12301F3F2B8E250EF645B699 /* NativeChatTimeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0796549895193A983D17B93 /* NativeChatTimeline.swift */; }; 1230E7F777C8E9CC120BDB9A /* SimpleBotsHomeSections.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE11871CC7E3CE3213E44774 /* SimpleBotsHomeSections.swift */; }; + 126B64563AEC9DE243B51FDA /* NewChatSendRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = B61A7DB547372B52760235D4 /* NewChatSendRelay.swift */; }; 12808DC2BA673141EF5E66E9 /* UsageReaders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F995AC2F5D7E281A7D8C7E1 /* UsageReaders.swift */; }; 12A782C1801E4B4297155BB1 /* WikiHomeAcceptanceFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BE88F44D6F978BC80B7819C /* WikiHomeAcceptanceFixture.swift */; }; 12BE755854921ECA455D8D6E /* HermesFacesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6EDE4E1F1CB7E447EB31ECC /* HermesFacesTests.swift */; }; @@ -159,6 +168,7 @@ 12E179D0DA1E2F4FB6A46191 /* ShareView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B77ADA2B69435659745E1FC8 /* ShareView.swift */; }; 134B9E7EE272FBA6318269D7 /* HomeWorkAcceptanceFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E3A8F019E59F4BEE6DDF45E /* HomeWorkAcceptanceFixture.swift */; }; 138117A0E7DF3A512D7C1B0E /* WorkspaceEdgeSwipeResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17675B00C0F92D64834A179E /* WorkspaceEdgeSwipeResolverTests.swift */; }; + 13BB63D1F8BDEEB7F3571C7A /* ChatsInboxFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5108A9609A6F74C9F35402CB /* ChatsInboxFixture.swift */; }; 13C3B392B0314D45C7D3261D /* LinkPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0579190CC3161DE303C711B3 /* LinkPreview.swift */; }; 13D54309A7C515D5192FA50C /* BighelpSuggestionList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 130DDE93CBDE378679C2DD58 /* BighelpSuggestionList.swift */; }; 1401F2F08D29710E9A81B9B5 /* CodeModeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AB9122D29E69588B293F502 /* CodeModeTests.swift */; }; @@ -168,6 +178,7 @@ 141F094C6DB2C0AD5FBDDDB9 /* DirectHermesManagedFilesClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0425407E6EBA0F54A07B61F1 /* DirectHermesManagedFilesClient.swift */; }; 14234C0A42A1E80B31C37E38 /* BighelpMacSessionSidebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4683C7DFC7A443F70635533 /* BighelpMacSessionSidebar.swift */; }; 142F9375293DC17B5E1CEFCA /* status-v2.json in Resources */ = {isa = PBXBuildFile; fileRef = 30E9A77859EDE36C4651D4E9 /* status-v2.json */; }; + 14607C374EACFE7655F419BA /* TodayFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7220AEB50241663CD55FCCEC /* TodayFixture.swift */; }; 14A6207C227938283D537F3F /* SessionContentRepositoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12DB23F855205AE60F84F5AD /* SessionContentRepositoryTests.swift */; }; 14D42954287FAAB485569BEB /* AvatarKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE75D7CC7FBD2BA5E7311A0D /* AvatarKit.swift */; }; 1510B5AFB84C82A2064A382F /* ChatNativeMarkdownTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A94D671CE12EC8AF785076DC /* ChatNativeMarkdownTextView.swift */; }; @@ -211,6 +222,7 @@ 1BA53E4F4E35D42F490C3529 /* AppearanceStudioView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 853942665777C89A188608DD /* AppearanceStudioView.swift */; }; 1BAA90A2B8193011238E83C8 /* MarketplaceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B5AEC4C016E148764469A07 /* MarketplaceView.swift */; }; 1BB9BE49DC6285985C71019E /* BotModeRoomStore+NativeEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EEED5396B4A5CA08D8C5836 /* BotModeRoomStore+NativeEvents.swift */; }; + 1BBF90B872D21C4E044958FC /* HomeStripTabs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12F13ECE65C76FAE69B91F89 /* HomeStripTabs.swift */; }; 1BC620974ED3EFD8FF672F0B /* ProviderHostSignIn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 247690E7990F653E1F8B6F80 /* ProviderHostSignIn.swift */; }; 1C2996EAD548C006AA2B48F3 /* NotificationErrorCodeUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4501149A8FC90C58403E903D /* NotificationErrorCodeUITests.swift */; }; 1C2BB4E83D031A33B376321C /* BighelpShortcutService+Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19D7160AE9C689BF3CA8ECC8 /* BighelpShortcutService+Actions.swift */; }; @@ -218,6 +230,7 @@ 1C763567CD9CCE8F93EA60F8 /* HostSignInMatrixUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37C85FB08FD771ED53292DB4 /* HostSignInMatrixUITests.swift */; }; 1CAD3F56F34703C56D4795E1 /* DirectHermesProjectClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2F8FB47038C2E9A1EE89696 /* DirectHermesProjectClientTests.swift */; }; 1CBBCA37E4825CA82FAB683F /* SimpleBotProfileExtras.swift in Sources */ = {isa = PBXBuildFile; fileRef = D51BF68C15E152807C58243B /* SimpleBotProfileExtras.swift */; }; + 1CBFD9B876E36D5544E7129A /* ChatsInboxView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA031A13A7DDB2CCF96B99A3 /* ChatsInboxView.swift */; }; 1CC3AE6034187BEBA8FD6610 /* BuzzKit in Frameworks */ = {isa = PBXBuildFile; productRef = 9A8FD2C384E308443336FDA7 /* BuzzKit */; }; 1D0ED381C419538DC3C37394 /* LocalModelsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4171E9FAAD22E3C63A32E6A /* LocalModelsStore.swift */; }; 1D434F8E937522A7FA6C6414 /* UserIdentityStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EFD49EAD36B9F2F7F171108 /* UserIdentityStore.swift */; }; @@ -226,6 +239,7 @@ 1DF8464D84E0AB8EEC5A0BCF /* WorkflowCode.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB4584A9DDB822B7E5E5AD1C /* WorkflowCode.swift */; }; 1E12DD4E69973E8720D96765 /* BuzzKitRuntimeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A152008E3C68EF9B9E67FA /* BuzzKitRuntimeTests.swift */; }; 1E173E934B333915CFD40337 /* soul-hearth.md in Resources */ = {isa = PBXBuildFile; fileRef = CA20A6A9C1345E7637F802AE /* soul-hearth.md */; }; + 1E17E2ED1D11EEF625D9F354 /* TodayPanelLayoutStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8628FAF07244D8889C7BE975 /* TodayPanelLayoutStore.swift */; }; 1E37DE2D68B7FC7B21CB3319 /* ChatReplyViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A669B98F3452E9FAA27FF4B /* ChatReplyViews.swift */; }; 1E620B9602AC780116EACCF8 /* ProviderKeysViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74E8FA438D71C0FD2DB9A0B6 /* ProviderKeysViews.swift */; }; 1E63EC1B22266247584C5C61 /* ManagedNotificationServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74B255BFB0C7ACD56433F907 /* ManagedNotificationServiceTests.swift */; }; @@ -242,6 +256,7 @@ 200F6961061432BAB0112370 /* UsageExportView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4C9D35E6FDBE936F915C342 /* UsageExportView.swift */; }; 203A6CD8067024257B40C50E /* ChatModel+StagedSends.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3352E707EF38E5A471AD47C1 /* ChatModel+StagedSends.swift */; }; 2050AF9EE6E6B3D062967674 /* ClarificationAnswers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06CDF83DBBEFEDDE6FD2A98F /* ClarificationAnswers.swift */; }; + 207937BD6C0C3D5FC8176224 /* TodayBoardsStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D97ED75999EE9AF01D2C143 /* TodayBoardsStoreTests.swift */; }; 207E1BB44E1203F301F1C8F7 /* VoiceSettingsWorkspaceClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA7F4E8ADF86A4544FCB7277 /* VoiceSettingsWorkspaceClientTests.swift */; }; 20988031875FE72D243E259E /* HermesBotModePeerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3268467BC26D1CFEBDE37B07 /* HermesBotModePeerTests.swift */; }; 20CE312554EB23D3DB5B6C67 /* NativeSessionControlsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7EBD6D4D292595F47067DF4 /* NativeSessionControlsModel.swift */; }; @@ -268,6 +283,7 @@ 235FA6D1886986736103B26B /* SimpleBotHostSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B441AAD6BA036D23DE6389 /* SimpleBotHostSettings.swift */; }; 23722D1412B3BDC4552A49A7 /* MidSessionSendHoldStateMachine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F5839F4502130F191439023 /* MidSessionSendHoldStateMachine.swift */; }; 2399339D2945E0E1FD0F70C6 /* DirectHermesReconnectParityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEC8B021A78258C09B430750 /* DirectHermesReconnectParityTests.swift */; }; + 239C2ADF1E607A7351DC61CA /* TodayNeedsYouCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEEA567FC87A8CA69A326CC2 /* TodayNeedsYouCard.swift */; }; 23B0BA64D6D1B22169626DF8 /* NativeWorkspaceRuntime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C91AAE8E1839B2BC3E252AB /* NativeWorkspaceRuntime.swift */; }; 23B60460BED5D72BE1D7C6F4 /* ModelNameCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC59500AEED985EECAA4D71F /* ModelNameCatalog.swift */; }; 23C3F038DE66D135C72B5BCD /* ClipboardImporterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21F642B03F9BC79D235BA847 /* ClipboardImporterTests.swift */; }; @@ -292,12 +308,12 @@ 25AFF76DBCE649A20FBB638A /* ChatToolDetailText.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6241B3C68880AD101042260 /* ChatToolDetailText.swift */; }; 25C23B2CFD93B91257724C71 /* TelemetryControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67B1DBC4A63038C4E21F709E /* TelemetryControllerTests.swift */; }; 25C2CC5D27E05100F552C05C /* SessionRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6B07EC6B775EE897F1611EF /* SessionRow.swift */; }; - 25F2AE0AEF5D0DF35EDA7875 /* AgentsDirectoryComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D379559BEB94B7580AEFD29 /* AgentsDirectoryComponents.swift */; }; 2601DB62BFBEE45B1455D6C9 /* SettingsView+LocalData.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0895D54237F25417076950B /* SettingsView+LocalData.swift */; }; 261666AB6BFC03CAD1B6B330 /* BighelpLiveActivityProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 015D146A996F9F8372C8D7D5 /* BighelpLiveActivityProjection.swift */; }; 2637C5B0BA8D229204254DD1 /* VoiceStagePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA8C731A82EA69FF3DFB01B9 /* VoiceStagePresentationTests.swift */; }; 263BBC0472B13907A52567A1 /* DirectHermesConversationClient+Queued.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A8EFA755488AC962B573043 /* DirectHermesConversationClient+Queued.swift */; }; 2647D30C223569EDF3468753 /* soul-bridge.md in Resources */ = {isa = PBXBuildFile; fileRef = 517D85803C55B72202A77B6C /* soul-bridge.md */; }; + 269AEEF3C2DC916D8095C963 /* RootNewChat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82B229D6F8990CA2258211D5 /* RootNewChat.swift */; }; 26B1B0BA754E90F20A6FFE0B /* KanbanTaskSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73A2757825B6213FFB630591 /* KanbanTaskSheet.swift */; }; 26B7B2AAD3AA95DE5A380187 /* AgentDriveUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E871FD3BCF7788448CADCFA /* AgentDriveUITests.swift */; }; 26C32F6C9A4DAF24B994C675 /* DirectHermesHostOperationsClient+Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = E73A5BB3ECDA83D28D23F206 /* DirectHermesHostOperationsClient+Configuration.swift */; }; @@ -329,6 +345,7 @@ 2A6D3CA091FF00A1814E1B49 /* ChatAgentTalkRunPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D83C10011F42314B0D8D4DD5 /* ChatAgentTalkRunPanel.swift */; }; 2A811F391A35F3D5B99B13AD /* sealed-alert-v2-vector.json in Resources */ = {isa = PBXBuildFile; fileRef = 4D5BB3FF93B2BFBE1309307F /* sealed-alert-v2-vector.json */; }; 2A9B76AAB859A209C1819624 /* PluginMarketplaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2A5D4E05C574182D219973E /* PluginMarketplaceTests.swift */; }; + 2A9E17F7B80D5900B6BAD11E /* WorkItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94966B58C7C316950BD235FB /* WorkItem.swift */; }; 2AD5EC547A554B6CEDDE45B7 /* ManagementSearch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 578DE4F4361908BAD8275D2F /* ManagementSearch.swift */; }; 2B280F14781611D6C34CBDD5 /* ChatTimelineBuiltRowsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5C5208F6702E30ED928E2AC /* ChatTimelineBuiltRowsTests.swift */; }; 2B5A5C20C36FCAF68021702B /* PendingShareInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = D476A29FAFA9F813839D032A /* PendingShareInbox.swift */; }; @@ -351,7 +368,6 @@ 2D5100CED6FB2884FF8A85B2 /* ConfiguredWorkspaceArtifactsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E7BACC1FD139A013D21E80B /* ConfiguredWorkspaceArtifactsView.swift */; }; 2D54087475FFD61C65C2D7B7 /* DeviceMusicToolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5773624C45D469AD5E685C4B /* DeviceMusicToolTests.swift */; }; 2D5C56C4141E0E2AE210CCC1 /* LiveVoiceDebug.swift in Sources */ = {isa = PBXBuildFile; fileRef = 109F04DFB422C0BB43066B7A /* LiveVoiceDebug.swift */; }; - 2D664446DD8E3469E8F74DEF /* AgentActionSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93BE73F918F3EED5F80259F6 /* AgentActionSheet.swift */; }; 2D6695867A9C97F15A8DFB4B /* validate-v2.json in Resources */ = {isa = PBXBuildFile; fileRef = D4BF8062D2F2C49ECB6B2A60 /* validate-v2.json */; }; 2DA8B5FD9C28B0C587D9779A /* BighelpRelayTrust.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0156FCAF6D581B79EABC68 /* BighelpRelayTrust.swift */; }; 2DEDCC45362D886BA7193D84 /* HermesShapeFace.swift in Sources */ = {isa = PBXBuildFile; fileRef = B92A64B932A98ACC81A60866 /* HermesShapeFace.swift */; }; @@ -366,7 +382,9 @@ 2F15C733D9CED26838D4BB9C /* PendingShareWaitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB8DE472A814BDEBF89DB933 /* PendingShareWaitTests.swift */; }; 2F3679E86D328CDE2E65F935 /* BighelpHuggingWidth.swift in Sources */ = {isa = PBXBuildFile; fileRef = F203AC6A3ECC9F563034515E /* BighelpHuggingWidth.swift */; }; 2F3700F6A9F6E5A733978BCF /* AttachmentCapabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DA00D2A3F0B2E3DDC831E2D /* AttachmentCapabilityTests.swift */; }; + 2F42986D75386199E60C88FC /* NewChatSend.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFF8D000FF938312063CD8C2 /* NewChatSend.swift */; }; 2F46E2D89A7FE9EEB8068E01 /* IndependentHostScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93BCA75E13D979E7977DE481 /* IndependentHostScopeTests.swift */; }; + 2F78D2A9E85917902FD86A88 /* SpacePanelStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA90CB3BCDCF4864F3B4EA64 /* SpacePanelStateTests.swift */; }; 304585F19BA88B7F6C44B0FE /* ChatAttachment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64675E385D5EF27EF87F2634 /* ChatAttachment.swift */; }; 3064DCF1230313502D93549E /* DeviceGeofenceToolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4D68C05FA8A9B56A2E63BC6 /* DeviceGeofenceToolTests.swift */; }; 307E2A2936B6EB808B7E7C7B /* KanbanAdministrationModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB8D88561781C5226D0072A2 /* KanbanAdministrationModels.swift */; }; @@ -376,6 +394,7 @@ 30DB57B49580CEF3A254C6CE /* RootShellView+BotScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE0BE7349C657290F14F710F /* RootShellView+BotScreen.swift */; }; 30EA43BDF3387F6084925431 /* BotModeModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5476B018071A5E47915D89A1 /* BotModeModels.swift */; }; 313E0D3151A48CE98320724D /* ChatStreamingAnchorUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32A8093F2FE15DF1627DCB77 /* ChatStreamingAnchorUITests.swift */; }; + 317013F28587EF601E34DBB7 /* SpacesWire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F459BB26EC4023A79F7139E /* SpacesWire.swift */; }; 318377F3BA9400EC2D916FBA /* BighelpCardValueResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B6DC6F01BFD5E1AE50EF6E4 /* BighelpCardValueResolverTests.swift */; }; 318652A995356C5CD2CB24C9 /* AgentFilesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52FF8BDE2009ECF11CD36CD3 /* AgentFilesUITests.swift */; }; 318F35220CAFCAE611B4725E /* ImageDraftNativeEditors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D023C32250FD63B1ADC605C /* ImageDraftNativeEditors.swift */; }; @@ -447,17 +466,18 @@ 39A3AA0D135710343A243272 /* ScheduledTaskFixtures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52EBB91094C47E61D846446D /* ScheduledTaskFixtures.swift */; }; 39B8FD33B7C9DF2EE82096E2 /* HTMLAppsHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F825A925559FC87FEB69271 /* HTMLAppsHostUITests.swift */; }; 39BF59E6C7019FDA3EAC77B4 /* OFL.txt in Resources */ = {isa = PBXBuildFile; fileRef = 8016485004A1036D585246D5 /* OFL.txt */; }; - 39FC5FBDB150414717D93A83 /* BottomMenuUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AEAE8B958F81AA860450230 /* BottomMenuUITests.swift */; }; 3A0019E2847052ACE800E926 /* ChatCompletedTurnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBCFB9A0E5579974EAC62DEE /* ChatCompletedTurnTests.swift */; }; 3A137298CA51606AC6972405 /* card-catalog-index.json in Resources */ = {isa = PBXBuildFile; fileRef = D6CD0DEFA89A000590BF9837 /* card-catalog-index.json */; }; 3A1938056AC1833ACD2140F6 /* WatchWire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DFC0469859FF2F766A0F9A5 /* WatchWire.swift */; }; 3A4C3BD63F9AD9122450E4A5 /* BighelpBoardWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E3F7BC4DE0D166012849DBB /* BighelpBoardWidgets.swift */; }; + 3A557EDD8981195F9BE06451 /* SpaceDraftCardStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 01ACA08D84DDE576D1756E14 /* SpaceDraftCardStateTests.swift */; }; 3A594C9B53EBF9F00712E1BE /* session-path.json in Resources */ = {isa = PBXBuildFile; fileRef = 172B7497F44AA26F893DD141 /* session-path.json */; }; 3AA6E7EAA99FD6C034F8A654 /* BighelpFocusFilterState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 317F3D4090FD79701E7E1B7A /* BighelpFocusFilterState.swift */; }; 3AABEACF3DF7C6022828FB53 /* BighelpLinkPushEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE129246716CE44864F927A5 /* BighelpLinkPushEnvironment.swift */; }; 3AB6DDD20A75CEB013581D39 /* NativeWorkspaceSessionBridge+Prompts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5467FAB05B10A607ED9DBE3C /* NativeWorkspaceSessionBridge+Prompts.swift */; }; 3AC380D2C6ED5E6C41E85C5A /* BighelpV3MessageStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F7281B7E7971EE34A73716B /* BighelpV3MessageStyle.swift */; }; 3AEF9711748131D3F4D17B44 /* BighelpActivityRowsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D0756F28F8D83DCD99820C5 /* BighelpActivityRowsView.swift */; }; + 3B17749964BD5B1D70864B5B /* HomeChromeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BA6C9356310A75F99AE911C /* HomeChromeTests.swift */; }; 3B1B256184670D6206650FE1 /* SimpleBotsReadState.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC2618030B874F836A2CD709 /* SimpleBotsReadState.swift */; }; 3B26D057C95D7D70F4D15F81 /* BighelpCardValidatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2007B746E9AB0E6276E8303F /* BighelpCardValidatorTests.swift */; }; 3B31977C0095185737081B6B /* AvatarCreatorUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 027157CAB5BF115163393990 /* AvatarCreatorUITests.swift */; }; @@ -503,8 +523,10 @@ 3F0425028A8D9FBA99ABAA85 /* VoiceStepLineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18869FCEF37622904146C4D3 /* VoiceStepLineTests.swift */; }; 3F0C4BAF80C369849AF98E48 /* AgentProfileID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82585A099C0B2200151BF919 /* AgentProfileID.swift */; }; 3F1147E8EDFBBDA25542FDBD /* BighelpExternalSessionOpen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4903CB5D015E3FA9F21B0F19 /* BighelpExternalSessionOpen.swift */; }; + 3F5559F32E958448E57530ED /* TodayNotice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19C19DC5D809E5B14A9EC002 /* TodayNotice.swift */; }; 3F5B1F0CFCD0C4AC6B12BD56 /* SearchPlacementUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 067FBC1424A9C5BFAF72DFEC /* SearchPlacementUITests.swift */; }; 3F795BCF05532D5802FE81EA /* SpatialAvatarSettingsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = B147B77930BA89891FE3634C /* SpatialAvatarSettingsSection.swift */; }; + 3F7DCF39A1DE7F0EE751BA26 /* TodayBoardPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD80F8ED097EE748E6EE2B15 /* TodayBoardPage.swift */; }; 3F81DB96172E670921A4490E /* BotModeRoomCacheSchema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 321B9D6AC07FA23E8A77C13D /* BotModeRoomCacheSchema.swift */; }; 3F9B09435FB28A088F244847 /* BighelpJSONValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = B77583FA75E9E50C09A3C6A3 /* BighelpJSONValue.swift */; }; 3F9B938D5C72D0A3F8147DDB /* OptionalReferenceServices.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06823B4FCA08768A2CCB471A /* OptionalReferenceServices.swift */; }; @@ -518,7 +540,6 @@ 40607B210431BEEE90022E01 /* AvatarKitView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4EF40390B49367173F071A4 /* AvatarKitView.swift */; }; 40BA8C7AF650DBFF97704487 /* BighelpCardTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68A31C169E92D2A4F7554C8E /* BighelpCardTemplate.swift */; }; 40E3CA8B926228E363347A3B /* ProjectChangesStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D5E604EC2EF8CB526E026C5 /* ProjectChangesStoreTests.swift */; }; - 410FE1D097AFE35EA630F759 /* FleetListOrganizing.swift in Sources */ = {isa = PBXBuildFile; fileRef = D672F719F83A86A2B56F91E8 /* FleetListOrganizing.swift */; }; 4122539152FD6C26ACEA61D2 /* BighelpActivitySession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A1995B1EB0B79F83BBD5AAB /* BighelpActivitySession.swift */; }; 413FEAA783A4E7FECEB2C9DE /* DeviceMusicTool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67FEA1842E4118FCC66B29FD /* DeviceMusicTool.swift */; }; 4165623A768286F93DE2D72B /* HermesFaceViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0E6677C62D0693F1F22BCE /* HermesFaceViews.swift */; }; @@ -536,6 +557,7 @@ 42A70AD42602C4DFC6192459 /* ChatSendTimingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 537F73A45A85176FFC648F59 /* ChatSendTimingsTests.swift */; }; 42BB9ECD432AD5EB155FD113 /* SettingsComputersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80EF0E810A5F31E5AC017099 /* SettingsComputersTests.swift */; }; 42C6DB2374D7427D000AB094 /* TemplateCatalogStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A44223CB9667024350A9D441 /* TemplateCatalogStore.swift */; }; + 4302B6870E4E985F8334F6E7 /* HomeSettingsMigration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75AB021D2A15E98A55C24DC1 /* HomeSettingsMigration.swift */; }; 4313B7CBC502A7BD1C69BE08 /* PeopleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5ABB843955626E16B7224421 /* PeopleTests.swift */; }; 431A69D90CC86137EB213D47 /* MarkdownAttachmentUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 187B51036858D39AAFA54E5F /* MarkdownAttachmentUITests.swift */; }; 439C7B1833A69D5C7785AC14 /* HermesLogsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D88AAE29CD127FD229FF04B /* HermesLogsTests.swift */; }; @@ -570,6 +592,7 @@ 46BECEA8DDE9B9515861F88E /* ChatShareUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 347F6F5E45B6F3677EFA73B2 /* ChatShareUITests.swift */; }; 46CAE47D3692C279975A92E1 /* HermesBotModeClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDF59A73834035F0B3F45A03 /* HermesBotModeClient.swift */; }; 46D87E20D93117E61811695E /* DemoRepository.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28B6B4CE9471B818624B11BC /* DemoRepository.swift */; }; + 46DA80763559E077B8E42879 /* BighelpAppSpaces.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F6A78A03D128C51B25B5CC3 /* BighelpAppSpaces.swift */; }; 46DEECD025B5D1D2603E3A1B /* soul-spark.md in Resources */ = {isa = PBXBuildFile; fileRef = 05B6F78535E261227E75CEDF /* soul-spark.md */; }; 46E4D906BA675045C8BE5011 /* AvatarCreatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C9B5778F31BB34BA51CD73A /* AvatarCreatorTests.swift */; }; 470381545EB2F7CCE49B55C7 /* ChatTimelinePresentationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC3F5DFA60CB944EBA4AC304 /* ChatTimelinePresentationPolicy.swift */; }; @@ -584,13 +607,12 @@ 484CF91F53F54082DA0320D2 /* CanonicalChatCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 758BC7AD425BF64408758569 /* CanonicalChatCoordinator.swift */; }; 484E290C7AF098BA39B26C7F /* LinkPreviewLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7717E4DECC27FF02102FEFEE /* LinkPreviewLoader.swift */; }; 486C974071404BED690FA982 /* KanbanAdministrationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39ABA20DFBC9888E9D43DEFE /* KanbanAdministrationView.swift */; }; + 488842D2C3364326FEF38717 /* HomeTabBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25550A0A0F3821ADED7FEDBE /* HomeTabBar.swift */; }; 489352B8790D5EFB6EB1B943 /* HostManagementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B79E147B2F0C41D20965E73 /* HostManagementTests.swift */; }; 489E33414695B4DAFEBDBCCE /* GeminiLiveAudioPeer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C416CC342BB5C934FA2EC1BC /* GeminiLiveAudioPeer.swift */; }; 48B33D61FCBA1FF8BC658F00 /* AgentFaceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C75B8692B6E78F7A91E68F0 /* AgentFaceTests.swift */; }; - 48CD0544D668BD0CD0DAA793 /* UnifiedModeToggleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 586E07FD677EADCB35B80837 /* UnifiedModeToggleTests.swift */; }; 48DAF421676C5F8F1A161E4A /* WorkspaceOperationPerforming.swift in Sources */ = {isa = PBXBuildFile; fileRef = E94C4E9BB8427AB94F813F4C /* WorkspaceOperationPerforming.swift */; }; 48F9D157AD6B68A57D5B06B1 /* DuoLayoutUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3542B12EF84E055C3AE7772 /* DuoLayoutUITests.swift */; }; - 493358AF1E2A642F5525956B /* CodeHomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18F68037ACD2B17DE44200C1 /* CodeHomeView.swift */; }; 49355590DEA1E32901A40B69 /* FleetStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09FE7AF3652707DEC52C692C /* FleetStoreTests.swift */; }; 4939999F1A727CBDE8B7146E /* DeviceToolCoordinatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 594B7D3DF0CA444270F48A14 /* DeviceToolCoordinatorTests.swift */; }; 4958590BB173210A5CB69679 /* HermesAgentMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B2B706F0F95D18D12795BAB /* HermesAgentMetadata.swift */; }; @@ -610,6 +632,7 @@ 4A992C3202A4AC4865948631 /* HostSignInMethodTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5ABF63171EFA2FB67EB1ABBA /* HostSignInMethodTests.swift */; }; 4AB6403BD9CD0499AB34FFA1 /* BighelpCardNovelUseCaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09472D14EDEDAF8E2EC2DEDF /* BighelpCardNovelUseCaseTests.swift */; }; 4B27018216A53D6864A7860A /* live-earthquakes.json in Resources */ = {isa = PBXBuildFile; fileRef = 43E999D974BD5735B4179BF6 /* live-earthquakes.json */; }; + 4B2D72DAFDA29AAF1D7BB25A /* NewChatSendTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D073861D277DC7E6AA6DACBB /* NewChatSendTests.swift */; }; 4B821EE1EFD8C51E964F110C /* ChatLayoutSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B6C2E9F7E97E148B6F57E26 /* ChatLayoutSettingsView.swift */; }; 4B82FE376EEA99A844721FF1 /* UsageLimitsComputers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70FA79D8173E1F90C3B949A5 /* UsageLimitsComputers.swift */; }; 4BA6CC4ABD173834FBCB5483 /* WorkspaceClientError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 246E185D994F31F4ACCEC8F2 /* WorkspaceClientError.swift */; }; @@ -618,6 +641,7 @@ 4C7EA7662DEC9EADB06A96ED /* WorkspaceArtifactEnumeration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0170EA9C3CB2F9E421319E21 /* WorkspaceArtifactEnumeration.swift */; }; 4CB1D67C6F49D8AF80A9072A /* WikiScratchpadContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 622111E706C0BE0545468130 /* WikiScratchpadContext.swift */; }; 4CDF6031E80A61E7E1544B06 /* KanbanWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BF9A436F1AD6B230A4D395F /* KanbanWindow.swift */; }; + 4D2D9994C72E0C45D4EB632F /* NewChatRecipientsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 008725B5A36A63BFFDA30E0D /* NewChatRecipientsTests.swift */; }; 4D603ADE0EB4AC5F94AE9AD1 /* ImageDraftReview.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF2A5D0B92E54D02BD806D94 /* ImageDraftReview.swift */; }; 4D6BEF1D032F171B03429665 /* DirectHermesHostOperationsClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 967BDE7966DC4F5F55D38014 /* DirectHermesHostOperationsClient.swift */; }; 4D965F31E40D508E72681A58 /* BighelpCardTemplateStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD3AB6858B9FA111E6A2DC37 /* BighelpCardTemplateStore.swift */; }; @@ -639,7 +663,6 @@ 4EFC07D04483C167474C32D7 /* ModelsMixtureOfAgentsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F0A326E8B62C81E7DFE1B5D /* ModelsMixtureOfAgentsView.swift */; }; 4F2BD0E4B2B920B3DDF06152 /* KanbanCardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2D90A74097F0FF386ACDEF3 /* KanbanCardView.swift */; }; 4F3B17E2E566E942FEDCD536 /* AsyncOperationTestGate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9965BF9A6F80AA4F0C3FEA00 /* AsyncOperationTestGate.swift */; }; - 4F4BFD5D7FE39BBA056987FA /* SimpleBotVoiceBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2D043AD3DE1B95D66A8421C /* SimpleBotVoiceBar.swift */; }; 4FEEBCF403A455B61F2B5F7F /* BighelpBlockColor.swift in Sources */ = {isa = PBXBuildFile; fileRef = E73C8ED3127FC294AA7B6B5B /* BighelpBlockColor.swift */; }; 5020A0991D8055D665E140CF /* BighelpPushToStartObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A734D25BEF7EFFD9AF1132F9 /* BighelpPushToStartObserver.swift */; }; 504D0D4DBC028D5E7DCAEF13 /* SpatialAvatarRig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99A41F789761960F1B5EFD87 /* SpatialAvatarRig.swift */; }; @@ -655,7 +678,6 @@ 51DA4E0343897F10E3048302 /* WorkflowRunView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 696582E23F3BDB6987E19C78 /* WorkflowRunView.swift */; }; 5222C95B449746172625A6B2 /* BotModeActivityFixtureClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = C28FC793B551D3283801E600 /* BotModeActivityFixtureClient.swift */; }; 5229854A551A26D0D7C3217C /* SessionCatalogStore+Read.swift in Sources */ = {isa = PBXBuildFile; fileRef = 646159A08D713527205CB8A2 /* SessionCatalogStore+Read.swift */; }; - 523769209DFC189C9D2CCBC2 /* AgentRuntimeDefaultsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6887CF181F29248E7BEA6CC6 /* AgentRuntimeDefaultsSection.swift */; }; 523AEFC4CF8DFD571E9D0D9B /* SimpleBotsSectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94485713CC1B3A6A5E2237F7 /* SimpleBotsSectionsTests.swift */; }; 524DA40768FDE508AE664C1A /* VoiceConfigurationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80088FB04D05EDBFE994777D /* VoiceConfigurationView.swift */; }; 52B29E4302F12DEA1C369668 /* NeedsYouBlueprintsModesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBA20F460ABD2525AE3BF756 /* NeedsYouBlueprintsModesUITests.swift */; }; @@ -701,6 +723,7 @@ 5782EF05ED7B25A18E98AB3C /* KanbanService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 953B22D814ABE8181BB7A195 /* KanbanService.swift */; }; 578CD9445FCD53E8C8A20AE1 /* SharedItemTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 901AA9723C7F8E0CE8A51C37 /* SharedItemTypes.swift */; }; 57946B42A19C582B5AA73965 /* DirectHermesVoiceMediaTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AB67E399FCAF7E7DD9399B6 /* DirectHermesVoiceMediaTransport.swift */; }; + 57A4AA568CB3AC55BBE26970 /* TodayCreateBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CC73679034D8C6500C601BC /* TodayCreateBox.swift */; }; 582C615E816FECBEB56B6D4C /* BotModeFixtureClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71C18B8C5A5094B92668A5EE /* BotModeFixtureClient.swift */; }; 582C79BC0D61BA6F6A1C16C8 /* DashboardWorkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2505D162745A6571E823C256 /* DashboardWorkTests.swift */; }; 5897BAA14BDE252B3507697A /* AgentEditorModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168D2D0E4ED12247C378E7BE /* AgentEditorModelTests.swift */; }; @@ -712,6 +735,7 @@ 5930C45B7848380B5ABA0A76 /* CompanionSurfacePhysics.swift in Sources */ = {isa = PBXBuildFile; fileRef = D50DC8E2C99731C2D773E1E8 /* CompanionSurfacePhysics.swift */; }; 595A3E827114EF6143EEEC26 /* SpatialAvatarSculpt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CB5F2C485C852B14B781AF /* SpatialAvatarSculpt.swift */; }; 595DFFBFA88D2E6B6FFA9AB6 /* PluginUpdateStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE77E909503B789EBF514EC9 /* PluginUpdateStoreTests.swift */; }; + 59664A8052597D180CC63F01 /* HomeHeaderBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7C5981D12B64F22097298EE /* HomeHeaderBar.swift */; }; 5984D86628B04C7B3534E338 /* FeedPostFilesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4F8D65E674D386650BAB8E8 /* FeedPostFilesUITests.swift */; }; 59BCDACA75A2AC2BD5C7F3C0 /* BighelpScreenPosture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A8EB9D554D130C79962400F /* BighelpScreenPosture.swift */; }; 59CF1CB77306DF14AF5C57B2 /* OtherAppChatsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63BBC3D0A9A41D731EE9D5B0 /* OtherAppChatsTests.swift */; }; @@ -719,6 +743,7 @@ 5A03AFA13C6289B7BB80E8E9 /* HermesToolsList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25B42C0520EEAFCC064E8825 /* HermesToolsList.swift */; }; 5A044C9061C88CA10BBD96F6 /* HermesFacePlayer.swift in Sources */ = {isa = PBXBuildFile; fileRef = B790E89E45A355459ABFB9FB /* HermesFacePlayer.swift */; }; 5A06094B12516F4C88133FE8 /* ChatBoardCardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EBC42DDD3A3EF941FC8F001 /* ChatBoardCardTests.swift */; }; + 5A11900790336EF04767C40F /* HomeTabOrnament.swift in Sources */ = {isa = PBXBuildFile; fileRef = 433095D96A00DF67C1DEF48F /* HomeTabOrnament.swift */; }; 5A394E6D02D5BA8702A671C1 /* BighelpRailCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3839FB429704BEC09A1DF03 /* BighelpRailCard.swift */; }; 5A5C26429791A98EBF3DF089 /* PendingShareLedger.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBEB6BA3161F76CD081422A8 /* PendingShareLedger.swift */; }; 5A5E28837861B4344C9C4451 /* ChatToolCodeCellTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 955EF8DC3E8F0CC2CFB5D6C9 /* ChatToolCodeCellTests.swift */; }; @@ -758,7 +783,6 @@ 5F045D1B4AB70D91DD7696CA /* DirectHermesConversationClient+Submission.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C8DDF0689A3701E95A2D109 /* DirectHermesConversationClient+Submission.swift */; }; 5F0B8C5D04DD1928B9A2878A /* PendingHostCredentialTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D733A935B040D1310BC2E6A6 /* PendingHostCredentialTests.swift */; }; 5F2CA001462B966644725F9C /* DirectHermesKanbanTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2C147A62B7578877E16AE2 /* DirectHermesKanbanTransport.swift */; }; - 5F8AA8BE7A160D7B21D67689 /* AgentRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DAE06C366386CEA7ABCDF84 /* AgentRowView.swift */; }; 5F99F778F875FFA6EDD14205 /* AgentHandle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83807284839F9DB96E27F21F /* AgentHandle.swift */; }; 5F9E9FAF086E514159FD632B /* WorkflowFlowGraph.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F215FC8422B1FFAE3704481 /* WorkflowFlowGraph.swift */; }; 5FD498E823ABD9959D3BC275 /* DirectHermesWikiClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBF01F4ECD3990C4129E19B9 /* DirectHermesWikiClientTests.swift */; }; @@ -777,7 +801,7 @@ 613A69AE78661B735734B0E0 /* BoardSwipeBlueprintsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 226B3E15639DDE404A0865BA /* BoardSwipeBlueprintsUITests.swift */; }; 614B6E422CDD27A019C1E71C /* ClipboardImagePasteControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B45258C70F501D58F768487 /* ClipboardImagePasteControl.swift */; }; 6173B64EA4C584E29EC5039C /* ConnectorOperation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 031905AB88C75597494BC306 /* ConnectorOperation.swift */; }; - 61960032A057ECFAF4D6CAC3 /* AppLayoutSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBB1CCEF5EE02CA14CAFD9A3 /* AppLayoutSettingsView.swift */; }; + 61CF38C56DEC66EC0638171A /* TodaySpacesModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4687B186E93DDF76E573F8B /* TodaySpacesModel.swift */; }; 622936B165C74FD2471219E0 /* DirectHermesCapabilityClientsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C55C9332C73EC2740153DCD /* DirectHermesCapabilityClientsTests.swift */; }; 624D2499A678D18DA954C8CC /* BighelpAgentWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9271648D36B89271BB6F58AF /* BighelpAgentWidget.swift */; }; 62D6F988052FD9D26159D6E1 /* DirectHermesManagementLiveTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A598BF0A59557DF48DD3BD96 /* DirectHermesManagementLiveTests.swift */; }; @@ -787,10 +811,10 @@ 632491EA260234EED186E14D /* DirectHostNotificationClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CEE2FDBEA76CC233FEB5E2A /* DirectHostNotificationClient.swift */; }; 6325C716CACD3259AAEE6958 /* VoiceStepLine.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD863B27A2D12B4D4BA415BF /* VoiceStepLine.swift */; }; 634C081E4FEB3F215307928A /* ChatsUnreadAndDraftsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 506BC65D498BDDDC8E07C040 /* ChatsUnreadAndDraftsUITests.swift */; }; + 638EC98CED5D1D416C535B8D /* AgentStudioCaption.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB640E443FE6AB3A381C1FFD /* AgentStudioCaption.swift */; }; 639B79BE0990E9981CF93953 /* TelemetryClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = B097782C130EE6F6862DCFBF /* TelemetryClient.swift */; }; 63B5CB9168E6E8D655B82074 /* GeneratedMediaView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1A136B4A7CA143CF46EFF26 /* GeneratedMediaView.swift */; }; 641CE0C20A1557AD3161ECAE /* BighelpMacShellView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 790A8491E59011BE09C9461A /* BighelpMacShellView.swift */; }; - 64859B1AD343A54DA7359AB9 /* AgentFastModeRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3AB7B41F130CAF111F94C162 /* AgentFastModeRow.swift */; }; 64864A314FB01F6C478D6862 /* PendingShareCenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 213DAB0A75951DCC27AB1895 /* PendingShareCenter.swift */; }; 64A4DB3742C4A15DFBAA5F06 /* GeneratedCards.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72473030CFED4D30E5FE45EB /* GeneratedCards.swift */; }; 64B142D1345CA8273CB4C67A /* BighelpBuzzKitPreferences.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DC1C3740F6110A7F601680A /* BighelpBuzzKitPreferences.swift */; }; @@ -805,7 +829,6 @@ 65776D4BD37736BAEBABF49F /* WikiDraftPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = BA975C65014CEBC1F57EBA79 /* WikiDraftPersistence.swift */; }; 657B5180F6A6C3BBDCE85A95 /* GitHubJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF236F5F22907E090A58AC18 /* GitHubJSON.swift */; }; 65A65D35CEC72C325069355A /* CompanionComposerPathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AF9B290647073A148F1F303 /* CompanionComposerPathTests.swift */; }; - 65DFF1ECAD26221426359F67 /* AgentsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EE9EB659F86107004A3BEE6 /* AgentsView.swift */; }; 65F791F27614304074AF8A3A /* NativeLiveVoiceSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = F83C6C89073925B7B902D076 /* NativeLiveVoiceSession.swift */; }; 65FEFED9B711B1896CFD3AE7 /* ForegroundAlertTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3B8B411D4DDBEACAECC5BF9 /* ForegroundAlertTests.swift */; }; 660B2787E61B897CC4A75193 /* DirectHermesConversationClient+Attachments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51AA6E7CE4BAF0F1D72A876D /* DirectHermesConversationClient+Attachments.swift */; }; @@ -821,7 +844,6 @@ 66FD046AD28B299B9EBCE271 /* BighelpSessionActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69316E6086691BDD2C164048 /* BighelpSessionActivityAttributes.swift */; }; 67060F2A727824FCBB960E60 /* ArchivedChatsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D80BCA89F758946DC31CD4BA /* ArchivedChatsUITests.swift */; }; 6726D0EAC8BA9D2AA00516C5 /* ComposioCatalog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F5AB4DD1555D26C17AE0E7F /* ComposioCatalog.swift */; }; - 672CD54682C4894751F4DBF4 /* AgentGroupRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D91E97CBBCE0471255EBDF13 /* AgentGroupRowView.swift */; }; 673B84AAA1E36D511917039E /* HostUsageLoaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35B1687221981CFB4772FD42 /* HostUsageLoaderTests.swift */; }; 675ACBDAA073A598C7D5DCF0 /* DirectHermesHostOperationsClient+Inventory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67834B3EF415CFFF4DB8778F /* DirectHermesHostOperationsClient+Inventory.swift */; }; 677F557F35BF7773EC1AD1C2 /* DirectHermesWorkspaceStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CCCB5ED966F2CF4F355D6B1 /* DirectHermesWorkspaceStore.swift */; }; @@ -870,6 +892,7 @@ 6BD88175032DD61874ADEA7B /* ChatActivityRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7849FA017894CE31B416774 /* ChatActivityRow.swift */; }; 6BEB521EBB0F1E16CF88B875 /* WorkflowsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEB2EB68074BFE00C9154498 /* WorkflowsUITests.swift */; }; 6C2A27D540FA52E7C72FFB46 /* DirectHermesVoiceConfigurationClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F69DF4D8979ACD704171100 /* DirectHermesVoiceConfigurationClient.swift */; }; + 6C40C95CB6777ECABA223475 /* TodayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ACCD154FBFC52C597F6885C /* TodayView.swift */; }; 6C8B0235D4A9C3E7D6A4910C /* BighelpCardDataClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77764B35BFE7ED560378376D /* BighelpCardDataClient.swift */; }; 6C8B12029C433A02B29B019B /* SubagentCanvasFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 609B924E62D63E7AAB4F39D3 /* SubagentCanvasFixture.swift */; }; 6C8D593035D45B6BD03BF084 /* SpatialAvatarScenes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48A9580A1B2BFA518A3D1BF7 /* SpatialAvatarScenes.swift */; }; @@ -881,13 +904,16 @@ 6D25CD51D34AB257947B3612 /* SkillHubPageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C1A2CA53D077B5C0D0EC6F7 /* SkillHubPageView.swift */; }; 6D8AD46F7C21EABA72E032B2 /* DirectHermesScheduledTasksClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D64C4FB90FC4173015F0A440 /* DirectHermesScheduledTasksClientTests.swift */; }; 6D8D7512DCB232B5B9265083 /* BotLookTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 929861837C5BBFA9C66BDF35 /* BotLookTests.swift */; }; + 6D8EDC56BE5C016E0AF79B29 /* TodayPanelGrid.swift in Sources */ = {isa = PBXBuildFile; fileRef = F090FA90D6797435F1D83FE7 /* TodayPanelGrid.swift */; }; 6DB2FA5ADB0A93BC0C11D1EB /* ReminderLocationTrigger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82E646023D459F98FB09479A /* ReminderLocationTrigger.swift */; }; + 6DD42B747B23495B31DCDED4 /* TodaySpacesModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23170C47F20C59BE05E144B4 /* TodaySpacesModelTests.swift */; }; 6DF422D8B0F7D141914018B4 /* ChatTurnFailureCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = B81E4D55F5AC3C4CBA3A8728 /* ChatTurnFailureCard.swift */; }; 6E06FD7A158360A66779DB29 /* ToolDisclosureUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D1E11795B7E88BB7F60730C /* ToolDisclosureUITests.swift */; }; 6E0BC3375967BABB3E31A8FB /* PendingShareComposerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0D60AE6AED500202DACAA94 /* PendingShareComposerTests.swift */; }; 6E20D4EE9BEA5FFEBA4E2DC2 /* BighelpNotificationIdentityInstallationScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A190714D79AB52AA0A2AA7DA /* BighelpNotificationIdentityInstallationScopeTests.swift */; }; 6E3E601E38F2D28A3E2D8E72 /* WorkspaceAuthority.swift in Sources */ = {isa = PBXBuildFile; fileRef = 293C4C99CFC91705B2C3B2CF /* WorkspaceAuthority.swift */; }; 6E41A48C69FCDE4B87894FE5 /* SubagentCanvasView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3E4194DE5A3290DDC47268B /* SubagentCanvasView.swift */; }; + 6E4D1EFBBF714AF91350C8AC /* SpacesWireTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D81EBA1C6A48BA0E8104698D /* SpacesWireTests.swift */; }; 6E58E9FB4DCCE110FA2FE5DB /* ChatPDFPagesDraft.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1941C3C4A19C2BFA1B4A9BC3 /* ChatPDFPagesDraft.swift */; }; 6E9AB565D825E6F32B1BD5DD /* HermesFolderPath.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADCC3B055B82A96326367C2B /* HermesFolderPath.swift */; }; 6EC4E7B382C1AB062749AB96 /* bighelp-hello.json in Resources */ = {isa = PBXBuildFile; fileRef = D29BFFB555278BF1B0A7BE96 /* bighelp-hello.json */; }; @@ -908,7 +934,9 @@ 70521F46E1A2AA90EC8031B0 /* ChatTimelineBuiltRows.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B5925D63EDF3AE6245630FA /* ChatTimelineBuiltRows.swift */; }; 705A1F88DB322FF588173B53 /* PermissionCenterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A3548EA837BB0A869121EE7 /* PermissionCenterTests.swift */; }; 706C3E1DB960EA624CC55242 /* AgentAppearanceUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C216615614428B4C59CE9A0C /* AgentAppearanceUITests.swift */; }; + 7074B083148E080A6143AFDF /* static-space-draft.json in Resources */ = {isa = PBXBuildFile; fileRef = 3C40C08AB0B176B19A5E7DBC /* static-space-draft.json */; }; 7077A30295A20B567E092DF9 /* PermissionsViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7445286B80C4CA76D5634B40 /* PermissionsViews.swift */; }; + 7081ACDD746875804F5AFF2D /* HomeShellUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FE55A8596FE2BA8F810C73E /* HomeShellUITests.swift */; }; 70A53193AF353DFF746F6072 /* OnDeviceVoiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67FB49189817CF58FA1D72FD /* OnDeviceVoiceTests.swift */; }; 70B16FF6528732CFF9532445 /* TemplateCatalogStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55908FE63618CE0809275791 /* TemplateCatalogStoreTests.swift */; }; 70B54A214F3DF723BC90BD9C /* BighelpCardRuntimeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5075464D94E5EC591527DFB /* BighelpCardRuntimeTests.swift */; }; @@ -956,7 +984,9 @@ 74D0C05E9DAC9AAE649F24F8 /* DeviceToolPermissionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E4A9CFF654000DFAEC8E208 /* DeviceToolPermissionsTests.swift */; }; 74DE88B9E100CD090302285F /* SettingsDestination.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E2D22067ABBEB0D4D724FBE /* SettingsDestination.swift */; }; 7513F6A9564131935F9DC69B /* ChatTimelineKeptRowsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE10504C7ACA6DAC0F72C9B1 /* ChatTimelineKeptRowsTests.swift */; }; + 754B628888B22A434636D598 /* SpacesTodayBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1EF3F596C4FEACFDC3F7340 /* SpacesTodayBridge.swift */; }; 754BA4BE81D05357AF2D5A9B /* AvatarKit.json in Resources */ = {isa = PBXBuildFile; fileRef = ABB3BECDD5B9E82037109977 /* AvatarKit.json */; }; + 7552538E84CB2EC35D0AD57A /* HomeChromeFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 63F611B65636A8E2749EE9B8 /* HomeChromeFixture.swift */; }; 755B2AF3234CF8B3A31AB7B1 /* CardRepliesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5F79F934C5B97C55FBDEB32 /* CardRepliesUITests.swift */; }; 756DE8BED12A998CA830A3FA /* ManagementSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D4BC302EAA32A5632E24C8D /* ManagementSearchTests.swift */; }; 75C0AE91E97798033204DA52 /* ProjectsLifecycleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B6042C0EC3B8B2FA6F5837C4 /* ProjectsLifecycleView.swift */; }; @@ -967,7 +997,6 @@ 76A46628A6F4FF3679DFD92E /* ChatSessionTitleHeaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C921117448BFD93E2B732354 /* ChatSessionTitleHeaderTests.swift */; }; 76E347715491113098751F4B /* UsageExportHTML.swift in Sources */ = {isa = PBXBuildFile; fileRef = 294CAADD6C666FC513722844 /* UsageExportHTML.swift */; }; 76E6EC211AC38F503F1F03C7 /* BighelpShortcutIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = D138674A02ECB3B509216ED0 /* BighelpShortcutIntents.swift */; }; - 7705B6E59B50B085309600BB /* PluginUpdateSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6C9097DA71E5B36A26C212E /* PluginUpdateSection.swift */; }; 7723DF268E69BB818D9EBD62 /* BighelpAppStartupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1592CE8A16B8511F90D5C3A /* BighelpAppStartupTests.swift */; }; 7761860D622D058AEFC947DE /* AgentDeletion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83595049FDD06EBAEB6E1F32 /* AgentDeletion.swift */; }; 7766ECFD158103AF65F2E20C /* HTMLAppTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DA7B55CB98F303563E3B3EE /* HTMLAppTests.swift */; }; @@ -989,7 +1018,6 @@ 79886F92EDC77B3FF813148B /* BighelpPluginUpdateClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9EFF30AB0E3CE7D1E90D7DFD /* BighelpPluginUpdateClient.swift */; }; 798AB46934955192680B3C22 /* LiveVoiceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DE2AFF1D5FD9181A8FD5C0C /* LiveVoiceView.swift */; }; 79A00EF2BD2E132C8F01287E /* ChatModelSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7667052281E92557BA2DC87B /* ChatModelSettingsTests.swift */; }; - 79B603212451FE324DA59380 /* BighelpTabGlyphTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F92745044C01ED431726BEDF /* BighelpTabGlyphTests.swift */; }; 79D02B84205D99E9D6CF38E2 /* BighelpCarPlayScene.swift in Sources */ = {isa = PBXBuildFile; fileRef = 054D3F1E61308B59672A882A /* BighelpCarPlayScene.swift */; }; 79D6909B9E1B244C15549428 /* QuietHoursUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCB46164ED10DBD654E8A0FA /* QuietHoursUITests.swift */; }; 79DDD17A622B812479F8582C /* SessionSubagentPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6AC7DF2F678C14DF3F82F320 /* SessionSubagentPresentation.swift */; }; @@ -1020,6 +1048,7 @@ 7C6B14CE617A66CE9912D404 /* ModelsSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94977376DF9FE2BF6A3793D7 /* ModelsSettingsView.swift */; }; 7CA4FC410BD37D2BBD499618 /* ScheduledTasksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1977D62C2B1D6F0B5F429E69 /* ScheduledTasksView.swift */; }; 7CC97AB51B2E888D2F9F5B4F /* ChatBlueprintDraft.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70E27D7C36503753B5BF5C26 /* ChatBlueprintDraft.swift */; }; + 7CF7514CFC9C84DF6B20AF28 /* CodeCards.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3A8B2CB8130C73F35DC4FB9 /* CodeCards.swift */; }; 7D263D5EE382D73C95FC8AA9 /* AvatarKitRenderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28041D404A0746C175B50B49 /* AvatarKitRenderingTests.swift */; }; 7D4535E6D8830CFA9F39879A /* BighelpThinkingControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCB14C56580BE75E57FF26D4 /* BighelpThinkingControl.swift */; }; 7D4AAD2B1957CC25252A7408 /* ProjectGitCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C585356AFD2587912A31D12 /* ProjectGitCodec.swift */; }; @@ -1055,6 +1084,7 @@ 819BF2446A7EAD503D22B283 /* AIDataConsentGateUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06D6BB21987E78CAF5995A40 /* AIDataConsentGateUITests.swift */; }; 81A09A62D28B0F020F0A9EE2 /* WorkflowPublishUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D5B09FF189F3E04B594D313 /* WorkflowPublishUITests.swift */; }; 81B006E8BEBEC3F398368DC7 /* TeamCallModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EC842A92E069219C4BFDBC9 /* TeamCallModel.swift */; }; + 81D7047FB611B60B23F56026 /* NewChatView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0469E9BECD9BD8B61F3E04F6 /* NewChatView.swift */; }; 81E8A31E76A3D6764A275CD3 /* AgentSelectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CF7C685B0AB5D146A3A9831 /* AgentSelectionView.swift */; }; 81F4515DE6FD011FA76CD44F /* PersonalityWireModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73A11354869D7210B3F78458 /* PersonalityWireModels.swift */; }; 81F798CFC5B41CDC8991B6B3 /* soul-lumen.md in Resources */ = {isa = PBXBuildFile; fileRef = 5D9C7AC41A4CA4FA52110611 /* soul-lumen.md */; }; @@ -1063,6 +1093,7 @@ 82081D53132456713ECD8A44 /* MentionParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B096F962476F8F58B191844 /* MentionParser.swift */; }; 8213B622C7788B8869CD3832 /* ChatCardTranscriptProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F892D8D79520DF44F46C0C4 /* ChatCardTranscriptProjection.swift */; }; 8244C717428965EF8036302E /* DeviceGeofenceLive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 886136BA6D50DA5D5862647B /* DeviceGeofenceLive.swift */; }; + 8245C2A4E114176D8819CE58 /* HTMLAppNavigationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA853D5841E722A30CB58DC2 /* HTMLAppNavigationPolicy.swift */; }; 825E4DACC70236397DEDD50A /* DirectHermesPrompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC5E84BA54BC689F8372A4C5 /* DirectHermesPrompt.swift */; }; 82CBEB764B27D1CCC17E8F47 /* WorkspaceInventoryDecoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB90671104D35742A479E374 /* WorkspaceInventoryDecoder.swift */; }; 82EA5B4478996B202D41026E /* SessionDraftMarkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD6614CC330F1A63E7373B9F /* SessionDraftMarkTests.swift */; }; @@ -1073,7 +1104,6 @@ 8372672BD6FE98E203AC89DA /* BighelpActivityDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CF32CA404AC85688FA54FCF /* BighelpActivityDetail.swift */; }; 83A60225FD79E9EEC947A379 /* BighelpNotificationIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44A6C6E3CF44927895F2574B /* BighelpNotificationIdentity.swift */; }; 83AB7370EBBA889DB26F1C35 /* AgentTemplateLibraryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F366E8128EB787B5C24A8E30 /* AgentTemplateLibraryTests.swift */; }; - 83D0AE9123454E12BB3E5D49 /* AppLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6772541AD53BC7065CD5D78C /* AppLayoutTests.swift */; }; 83DAE04FC0272938CF23EBE1 /* ChatReplyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F36C1F6D8AA34C0085ED6F38 /* ChatReplyTests.swift */; }; 83DCA7C086C3F1BBE6D2A359 /* ChatTranscriptProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = A423C5225CB5578027A4A41D /* ChatTranscriptProjection.swift */; }; 842B5E01AA01D87DE0AD45A9 /* SimpleBotProfileView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2B0B12CCADA6D8292B64AFA /* SimpleBotProfileView.swift */; }; @@ -1102,7 +1132,6 @@ 8650BF0E9E703D0C8FBFE086 /* AdvancedOptionsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A316AF5D5E76DE3DA72CD1A /* AdvancedOptionsStore.swift */; }; 865BFC4226DB5B31D481C198 /* BotModeCreateRoomView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 242E8827AB2BB2BCDAB8DBDC /* BotModeCreateRoomView.swift */; }; 8664D79F9C79317862920F24 /* SessionOriginUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E51CE6C1FF8C2646AD519F69 /* SessionOriginUITests.swift */; }; - 866A3D87C3251AB40763D685 /* AllHostsHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FAAC3B2B524A603A53FB5 /* AllHostsHostUITests.swift */; }; 866AFD99DE5B38B15F18B704 /* GenerativeUIFormWireModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E4C7708B565263D5891089A /* GenerativeUIFormWireModels.swift */; }; 866E2720BD255D07B22ECF2F /* WorkspaceManagementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB4444FC61A3E484D6C1F188 /* WorkspaceManagementTests.swift */; }; 86828616C0652504329CA63E /* AgentDeletionUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD268648AC84425AD755C76C /* AgentDeletionUITests.swift */; }; @@ -1144,6 +1173,7 @@ 8B5C4E04472BA3E7E6040F83 /* WorkspaceReconnectPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E8EE605E09317091AADFEC31 /* WorkspaceReconnectPolicyTests.swift */; }; 8B9D2DE5DE7AF18F84D1DAE6 /* WorkspaceClientProxies.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D4CC044B37E9AE3D8244446 /* WorkspaceClientProxies.swift */; }; 8BE490A6DB08D5828E763B04 /* DesignSystemTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B164685C8448EC3814C1D248 /* DesignSystemTests.swift */; }; + 8BEC3192D84F108324C9534F /* WorkFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AAB566FE7CD9FCB1622B0C2 /* WorkFixture.swift */; }; 8C49974C630D03C98563D621 /* SessionRuntimeSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20F62CA5A9FEC6B5580D7020 /* SessionRuntimeSelection.swift */; }; 8C522E5D289AC375D2EBA07C /* PendingShareReview.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B1D91FD801F38CF52525766 /* PendingShareReview.swift */; }; 8C6E9258ED83517A22EB52BD /* DirectHermesPluginLifecycleClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A1418805D01E397603B568C /* DirectHermesPluginLifecycleClient.swift */; }; @@ -1160,8 +1190,10 @@ 8D9B0E73D8D88ABC2AC19614 /* UsageNavigationUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997B937232851A556998C545 /* UsageNavigationUITests.swift */; }; 8E0C7D9B8F8F80AD3E8CAB8B /* bighelp-launch.json in Resources */ = {isa = PBXBuildFile; fileRef = 806AB84F8B1C79EA3DA38114 /* bighelp-launch.json */; }; 8E2E6965629031C58D5CB3F1 /* PluginLifecycleManagementView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 018AE94307FCF69BF62A9C22 /* PluginLifecycleManagementView.swift */; }; + 8E2F4DFB7B79F13BB3782BAA /* HomeMenuPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72EFBA3EEB1AC550F4611C79 /* HomeMenuPresentation.swift */; }; 8E3BB65962F3CA30B144A237 /* BighelpRecentAlerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E3339C3838A62B28806B7B8 /* BighelpRecentAlerts.swift */; }; 8E3F4C9B0DAE062488F3BF53 /* WatchBoardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFD551373422D9AA073D2A85 /* WatchBoardView.swift */; }; + 8E61F1D2FC05C1C3EDF74D48 /* WorkDoors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 901B9368C8FF33D186FA7426 /* WorkDoors.swift */; }; 8E8C2F2F3ED0D00516ECB1AC /* BigFileUploadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD158BB3C6929566D234F2FC /* BigFileUploadTests.swift */; }; 8EA851E3E7883CEEC7D39940 /* PetdexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53B43195521A318E92F67D5D /* PetdexTests.swift */; }; 8EB331FA9AB606CC4B9452C2 /* DirectHermesReleaseContract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84EEBCC10DF98DD740571997 /* DirectHermesReleaseContract.swift */; }; @@ -1195,9 +1227,7 @@ 928856931E1C1BF5B257238B /* BighelpUsageWidgetWide.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75EBE9D92DEFB7D780999FC1 /* BighelpUsageWidgetWide.swift */; }; 929ACA88C176BBDA4F31266F /* ProviderLogoURLSessionTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A77F06A4EB3AC264271D1B8 /* ProviderLogoURLSessionTransport.swift */; }; 92B52193244FCF9153E11226 /* SessionRuntimeControlModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AD4D831AE3D6470D046BE65 /* SessionRuntimeControlModel.swift */; }; - 92D1BEC254D80BEF39834541 /* AgentHomeDrawer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A93F1D8C3BDEABBBE407101F /* AgentHomeDrawer.swift */; }; 92D3654D741FB50C6DC05780 /* BighelpPinnedAgentsWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1FF50374D94C106E4CE34A4 /* BighelpPinnedAgentsWidget.swift */; }; - 92F5479967E8A8F847DC626A /* AppLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7585C28F626CAE1CA1403BF6 /* AppLayout.swift */; }; 93142A7F8E6655BEF3B8A522 /* BighelpMacWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = EBCE4D0A5B551F3B6980919E /* BighelpMacWindow.swift */; }; 93165E02393D81034E63436E /* ImageDraftReviewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 342B3F1660D119570134E75B /* ImageDraftReviewTests.swift */; }; 932A00B950E6AAF1307E45F9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2469077E01CAA7FC2AF4BE56 /* Assets.xcassets */; }; @@ -1234,7 +1264,6 @@ 98580BDDB0C059980950F327 /* WorkspaceFileTransferView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C6E3EE1BAF5669F077AAE6D /* WorkspaceFileTransferView.swift */; }; 986C8A1687765DE27416B37A /* TelemetryClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D97E5402CF9055B231A0336 /* TelemetryClientTests.swift */; }; 98B42FDE475799703DE55D80 /* HostSetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 156C7F4C9BC8078DA0D133C3 /* HostSetupView.swift */; }; - 98BCDE99C7F506CDC74308D0 /* FloatingTabBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = A266F3E6A29E081028EF481A /* FloatingTabBar.swift */; }; 98DA7B05D6643B75924F144A /* ChatCompletedTurnPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = C92202D7CED62BC075E6080B /* ChatCompletedTurnPresentation.swift */; }; 990889521E8DE8A7FF81CFFE /* OnDeviceVoiceModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D974E3909FD9B16C10964DAD /* OnDeviceVoiceModel.swift */; }; 992DD07AD07D98260F5A7333 /* VoiceConfigurationRecordingController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 612A286335B424F224A432EF /* VoiceConfigurationRecordingController.swift */; }; @@ -1257,6 +1286,7 @@ 9B9E9EC25058F06FC48FB7D5 /* CompanionReactionSignals.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A88F3ECDD2C240F9283D56 /* CompanionReactionSignals.swift */; }; 9BAB2718B76E8A1A140779B0 /* ChatModel+DraftImports.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18A424D3745CCCBB577472BE /* ChatModel+DraftImports.swift */; }; 9BAF0B9235644C02F9843BBB /* bighelp-done.json in Resources */ = {isa = PBXBuildFile; fileRef = 9181B431309664D49E1DA5C6 /* bighelp-done.json */; }; + 9BFC6BE92F3648689B671CF1 /* SpacesFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77961B6DA3CE5396EDCB297D /* SpacesFixture.swift */; }; 9C275F3044E17BFF11E7CF52 /* ChatCameraPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 346E60E2A592A84C62801324 /* ChatCameraPicker.swift */; }; 9C5524E08F58B108162490CC /* ChatToolReadableDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = A574AF8E9AC1BDB9730BEF0B /* ChatToolReadableDetail.swift */; }; 9C5E3A299587D3E5187168EB /* DirectHermesConversationClient+Processes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 531493235C7F015D20CF3C29 /* DirectHermesConversationClient+Processes.swift */; }; @@ -1274,11 +1304,9 @@ 9D4CBAB6B3911D5906AE4FD5 /* RichDraftEditingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB9FF7B35EAC57B17AB008F9 /* RichDraftEditingTransaction.swift */; }; 9D61C4051D17431E293831EA /* BighelpWidgetStyle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C0C46DD88DD92320846BD65 /* BighelpWidgetStyle.swift */; }; 9D746590A066AA6E8FBAFD33 /* GroupSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD27E2099CE872F95B460A4 /* GroupSettingsView.swift */; }; - 9D79073CB83AC124FB548509 /* AllHostsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59DC6DF119E780C3D98AA087 /* AllHostsUITests.swift */; }; 9DA1CDDA2585742D0A165CB7 /* CanonicalChatCoordinatorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19B428FA3E537FAD07A0CEC9 /* CanonicalChatCoordinatorTests.swift */; }; 9DB11887312B77A7203B0180 /* NativeWorkspaceSessionBridge+Maintenance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F17ED3AA403533F22755654 /* NativeWorkspaceSessionBridge+Maintenance.swift */; }; 9DB3108A1C8618661A5F1616 /* ModelProviderPlan.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4AAD53ECD449ACF5AE72CBF /* ModelProviderPlan.swift */; }; - 9DC7D6EC6D986D76159D5E54 /* AgentEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93C3C53CDF672AC9FDB30C6D /* AgentEditorView.swift */; }; 9DD7E46277A7E2916004A41C /* RootChatSwitcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE74C5805E7DA6DCD0E8A91E /* RootChatSwitcher.swift */; }; 9DDDFAFE94260719AF919ABF /* BighelpCardNetworkPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFBEE9CFB9B0B589E8587043 /* BighelpCardNetworkPolicyTests.swift */; }; 9DE3A82EA141CB7CAFAD98DF /* ChatAgentTalkTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 895A6107616893ACE15724A2 /* ChatAgentTalkTests.swift */; }; @@ -1341,7 +1369,6 @@ A3E6DC016D945C3A1B3EB1EB /* WeatherCardsFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFDE5644508F81ED80494EA9 /* WeatherCardsFixture.swift */; }; A40708964471E141FEAEAA3F /* NotoSans-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 5444CB93842B51985754EB7A /* NotoSans-Regular.ttf */; }; A4146827B760FF893C53D2FA /* AgentShortcutsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80B9D3C7D1ACB2DDE58773C8 /* AgentShortcutsView.swift */; }; - A41C3049FC9CB255DB429539 /* BighelpModePill.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5A2475E246493163A55B6B3 /* BighelpModePill.swift */; }; A44ED7A8245A6FFA0D9EE82B /* WikiClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EE26876A1BD8945E87A878B /* WikiClient.swift */; }; A45347C1F5A7CA5B6C893A13 /* ChatOpenOnceUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6136A88FCCE7AAC2A5508D54 /* ChatOpenOnceUITests.swift */; }; A48D1F0B1336BE92EDD7ED7B /* BighelpLiveActivityPresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0EC71D7FF4691AFBEBB2F27 /* BighelpLiveActivityPresentationTests.swift */; }; @@ -1361,6 +1388,7 @@ A64A719778D24A3FF5BF5C38 /* HermesGroupsHostPathTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BBEF3DFBAB691CE1CD31DD9 /* HermesGroupsHostPathTests.swift */; }; A675EA761668E0D2B3D5321E /* HTMLAppScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 613EA998D71264182F07CAE0 /* HTMLAppScreen.swift */; }; A67BD6DE12B2587A514228AA /* NativeMessageReactionMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C781788DB7B1B5C134F323A /* NativeMessageReactionMapping.swift */; }; + A6865F6049D51FE50B97B6C3 /* CodePickers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38B1CDE2956C9FF1683BE521 /* CodePickers.swift */; }; A6B1FE4A12E128F9220C193D /* WorkflowEditorModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B34624743AF44BDE0DCCF68C /* WorkflowEditorModel.swift */; }; A6C905A7A7426DA8BCD412AE /* DirectHermesHistoryProjectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B514B0875F7F274E6189C77B /* DirectHermesHistoryProjectionTests.swift */; }; A6CD561A6CFD9A4347EF8096 /* HermesGroupRoomSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E331F48E29B807A93CCF34AA /* HermesGroupRoomSettingsTests.swift */; }; @@ -1371,6 +1399,7 @@ A6F7EABAE9414F940C0E567F /* SessionCatalogReconciliation+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B44FC009700CCB1A5BEFF77 /* SessionCatalogReconciliation+Index.swift */; }; A6FD15D81C48614EEA26F238 /* WikiNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDE853A92392551EBA916C0E /* WikiNavigation.swift */; }; A72D48948B447E5C97EE084F /* ChatCardImageCopy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FD7F747650F9C1AEB8642FF /* ChatCardImageCopy.swift */; }; + A744B22B79EAF3F73C85C874 /* TodayBoardsPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A670996B08FE4B02F6189B0 /* TodayBoardsPanel.swift */; }; A76BA98465EBCEA7CBC187BB /* WorkspaceManagementStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03575CB24B16E0FD4C3E36CC /* WorkspaceManagementStore.swift */; }; A7C2379A027DC80D5E6F898A /* ConnectorCardStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45CB822E9F832933D18360C2 /* ConnectorCardStore.swift */; }; A7C7EB7E92B99BFCB9EAC992 /* HermesBotModeActivityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F88EB8201529B07C80DE0C9B /* HermesBotModeActivityTests.swift */; }; @@ -1386,6 +1415,7 @@ A9862F72D31D162D35B57E4E /* ProviderLogos-NOTICES.txt in Resources */ = {isa = PBXBuildFile; fileRef = 580AB2B819C0E24ADA7B2FB0 /* ProviderLogos-NOTICES.txt */; }; A98A5C56F8CF6122C6E38E0E /* BighelpNotificationHostTrustTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A622F7E5AB2E944C8EFEBE70 /* BighelpNotificationHostTrustTests.swift */; }; A9954AF1B09A956175AF1FBF /* DirectHermesManagedFileTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA529FFE00C2CE7F678A21A /* DirectHermesManagedFileTransport.swift */; }; + A9FE6500A69CDE5F318CA51D /* WorkProjectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C32D94835AB8421789B59C0 /* WorkProjectionTests.swift */; }; AA4BE7095FA7772DE048864D /* HermesUserMessageDisplayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C1110763B724D51E070E0B1 /* HermesUserMessageDisplayTests.swift */; }; AA4FCE53357C77F08832FF15 /* VisionFirstRunConsentUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 70F41C7DEF199504BEC6D9A4 /* VisionFirstRunConsentUITests.swift */; }; AA8F9A424A2265F947BF0869 /* ChatCompactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7459CDC081DDB6A14E0C9F21 /* ChatCompactionTests.swift */; }; @@ -1394,13 +1424,13 @@ AAABBBF74D7023621067377F /* DirectHermesPayloadDecoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3876EEE966594BB31EE4EB /* DirectHermesPayloadDecoding.swift */; }; AAB250E89BAABBAE3FED3E71 /* BighelpWidgetSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83868AA62A2AB35D2349D238 /* BighelpWidgetSnapshotTests.swift */; }; AAEB8982D7E6FF8DFF842F7F /* WorkflowsEditingUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA7CE183DB9ED1863F32864 /* WorkflowsEditingUITests.swift */; }; - AAFC950C49292EDF9A0EA8B6 /* PrimaryNavigationSelectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6F7B0C6B71878310AF32D1 /* PrimaryNavigationSelectionTests.swift */; }; AAFF23F7539A77CB444B9BBE /* CoreFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = C6A5452A79F7ADB8D480C39D /* CoreFiles.swift */; }; AB37CC3BE76F45E6D345BD2F /* ImageDraftsFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 397D1DE7BAC6F361370C55F7 /* ImageDraftsFixture.swift */; }; AB395D163107CBC699ECDF63 /* soul-muse.md in Resources */ = {isa = PBXBuildFile; fileRef = 5ED7AA71154BB0B11EE43FE7 /* soul-muse.md */; }; AB43C53CA037210ACD421590 /* runs-get.json in Resources */ = {isa = PBXBuildFile; fileRef = A831E64537E81D7881423D3B /* runs-get.json */; }; AB50229B9D95E539FB6025BE /* BighelpUsageWidgetRenderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCAF3D623834C0CE6C667AAD /* BighelpUsageWidgetRenderTests.swift */; }; AB7ABE12E87D282221510753 /* BighelpLiveAlertTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07F23D0718DD2CF18502AF95 /* BighelpLiveAlertTests.swift */; }; + AB7E89B1F59136390C7114F9 /* SpaceModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 258E9AEE85E8EC569A65A5A7 /* SpaceModels.swift */; }; ABD009A027CB30C4ECD5FA0A /* template-research-draft-review.json in Resources */ = {isa = PBXBuildFile; fileRef = 8124A0F693BE98F5EBD01B37 /* template-research-draft-review.json */; }; ABDDB82650A10B2CF7CA1249 /* WorkspaceArtifactsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 140A77E5360261714297C992 /* WorkspaceArtifactsTests.swift */; }; ABE4C62D05B96C6B05D54F89 /* BighelpFocusFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50B550FE531ED1016583F805 /* BighelpFocusFilter.swift */; }; @@ -1451,7 +1481,6 @@ B1B7AB57F763D0CC6BD4B86E /* BighelpLinkWorkspaceClients.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D17025515EFDA60E54C39F6 /* BighelpLinkWorkspaceClients.swift */; }; B1B97CAEF0C2F99FFCA9EA9F /* BighelpLinkBase64URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 858E2FAA652515FEC2CE5130 /* BighelpLinkBase64URL.swift */; }; B1BC43703C086C62796D6EF2 /* FeedPostFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14791450B5A4D6CE103EC937 /* FeedPostFiles.swift */; }; - B1E018B4E66E93621FD75071 /* AgentStartPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = A196966B973298711CDD11ED /* AgentStartPicker.swift */; }; B2854B2E64A30214C217C46D /* SessionCatalogStore+Load.swift in Sources */ = {isa = PBXBuildFile; fileRef = A42541EDF5728C23F3CB3493 /* SessionCatalogStore+Load.swift */; }; B29566B74DF4A8B08E2649B6 /* SimpleBotFilesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10808A9987A2E9F3F2358F19 /* SimpleBotFilesTests.swift */; }; B29EB569692D44B6BB1E2555 /* DeviceToolPermissionsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46D19587978755B4DC4B7D9E /* DeviceToolPermissionsUITests.swift */; }; @@ -1472,6 +1501,7 @@ B3EC5789602FB904AEA7AF78 /* SubagentControlTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72B7397F7D4D61EB688CC8B4 /* SubagentControlTests.swift */; }; B3F1B21B8C3D26A5E0FDEEE5 /* DirectHermesSessionCatalogClient+ListRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8FE80355509F8B363965132 /* DirectHermesSessionCatalogClient+ListRequest.swift */; }; B3F9F117624746C5AF0CEC6B /* ChatToolPhrase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 91D4F8D182EE30C5C7CDB870 /* ChatToolPhrase.swift */; }; + B4224CC495345ECF6E6CA745 /* CodeSessionStatusReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B075D7D83BBC4A23C03B5C1 /* CodeSessionStatusReaderTests.swift */; }; B44B30DBBAFA2B7EDB45621A /* SimpleBotsUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F0FDE4E094EF1BBFD3E82DD /* SimpleBotsUITests.swift */; }; B46FB0AC1F4E70E1C70B859E /* RichDraftMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A37E1D59199BAE6514567D0 /* RichDraftMarkdown.swift */; }; B472C7AE7FE52D0A877D7887 /* valid-form.json in Resources */ = {isa = PBXBuildFile; fileRef = C092C3BB9D2A2FEE279DC7CF /* valid-form.json */; }; @@ -1495,12 +1525,14 @@ B60BC5275069EA540FB0545E /* SettingsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67F0B31843F2BBB8FE261D76 /* SettingsStore.swift */; }; B60FFFEA8730E8B8988D4846 /* WikiHomeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 819D2463F44346804B7C6AE1 /* WikiHomeTests.swift */; }; B64D060B1FD84DA788BE7BB2 /* inbox-card-workspace.json in Resources */ = {isa = PBXBuildFile; fileRef = 55564C451754194E0EF381FF /* inbox-card-workspace.json */; }; + B662B3C3DF2696D49F1C1F74 /* WorkView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5F345BA3A10B8E6D2A5274F /* WorkView.swift */; }; B665E162FA1BACCA4168073B /* BighelpHomeWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16B85BE01827FCFD38480171 /* BighelpHomeWidgets.swift */; }; B6B47AA87393A6D80A45ED06 /* WatchRelayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8CF98249E40E406230777FCC /* WatchRelayTests.swift */; }; B6BF0CD6223E722A0CE8B2F1 /* WorkflowEditingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5639CCA1C95FC8441701764 /* WorkflowEditingTests.swift */; }; B6C40DC2D80992F3CD7B405A /* ChatBackgroundResultCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = C554359955749145E7E3FFEB /* ChatBackgroundResultCard.swift */; }; B718A6888BF9DDD990E95123 /* MentionParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 814C4956CCEA87E8B067861A /* MentionParserTests.swift */; }; B76454D950DAE576FEF2E878 /* DirectHermesSessionCatalogClient+Bindings.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB67E4443F09B0F1E4F744B2 /* DirectHermesSessionCatalogClient+Bindings.swift */; }; + B7996C9815EBC0898932D12D /* BotProfileMoreMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4F74FD537BF156A33F07D80 /* BotProfileMoreMenu.swift */; }; B7A703DA0117B43C3E402299 /* RootUsage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A61B0F03132E152859EE95 /* RootUsage.swift */; }; B840CB87DCBCB6ACBC80CAE6 /* DeviceToolCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE0D46B41203E5ABB073CFB3 /* DeviceToolCoordinator.swift */; }; B85A12A0BC8811D8CAE73C52 /* GitHubTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03D093F97DED2D3FB6E80258 /* GitHubTransport.swift */; }; @@ -1525,7 +1557,6 @@ B9E261D23BEFF6CC32A26AF4 /* ChatCardInteractionEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 04487A51D190019815D00D9D /* ChatCardInteractionEnvironment.swift */; }; B9EF1822609A94721C7E7C4C /* ProviderUsage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EFF67D22D71AE32378176C4 /* ProviderUsage.swift */; }; BA0BFCB553A0791FB2B78024 /* ResponseHapticsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DADB6E6EE1B88862A84AB9C /* ResponseHapticsTests.swift */; }; - BA0C5D590E64C54CEB0CF317 /* AgentPinnedGrid.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FDF4E08DF2A7F5CBC393F11 /* AgentPinnedGrid.swift */; }; BA26C9D3B5706D34DBB02016 /* DirectHermesProviderClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B29000261D6C2587FCDE99E /* DirectHermesProviderClient.swift */; }; BA2DB9582FD11D9DB0CFB2AC /* DeviceFocusToolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73FA2398602D858EDB43E766 /* DeviceFocusToolTests.swift */; }; BA5D3D6B994FAFB24B41C1DB /* BighelpActionRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4BA91D42B8CD65D9DDB4908 /* BighelpActionRow.swift */; }; @@ -1537,6 +1568,7 @@ BB0E8A5C17D13AFDEE9EFEA4 /* ProjectsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FB92C87FA3C2AEFE88CC27F /* ProjectsStore.swift */; }; BB0FEC14E7280C63BE65F1B7 /* DirectHermesHostImportTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F153F100B7A625AFD7145C9 /* DirectHermesHostImportTransport.swift */; }; BB4C274C0588810261C7F7DE /* ShellFeatureStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9775DDC3330098E37AD98104 /* ShellFeatureStore.swift */; }; + BB9CE1A084021E1CD9FFD1F5 /* WorkCards.swift in Sources */ = {isa = PBXBuildFile; fileRef = 407581F24811888F32AEF469 /* WorkCards.swift */; }; BBA132CACFBE9000296578AB /* CompanionReactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21796C5BE7BB0044774A8C36 /* CompanionReactionTests.swift */; }; BBB4B5382B941F7779CF9548 /* BotModeApprovalCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0DE05E6C5C380E5B3B7D1C9 /* BotModeApprovalCard.swift */; }; BC05BAA79DF938CEA66B34DF /* ChatEdgeBlurUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5877EBCE70707C4A168CE6E9 /* ChatEdgeBlurUITests.swift */; }; @@ -1547,6 +1579,7 @@ BD831F910C487B700185FFAB /* BighelpActivityPose.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD81C509ADE4E67B19BA9F6E /* BighelpActivityPose.swift */; }; BD93F85CEA873C499CE14AEE /* LiveVoiceUnavailableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE3F5EF033F2E51AC96DFFA /* LiveVoiceUnavailableTests.swift */; }; BDB4B26933A6AC0A5F9A508E /* ImageActionsSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 311F65DA16FD3A19442C1D03 /* ImageActionsSettingsTests.swift */; }; + BDC2F172ED9AAE6107393977 /* NewChatPickTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A0023FA904FEED13C2B7682 /* NewChatPickTests.swift */; }; BDD57A279FACE88F4DDD285C /* ChatReactionBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = B657E4B774D2DA98DB27151E /* ChatReactionBar.swift */; }; BDDA3B0BCA5E489B72CE8FF9 /* BighelpThinkingLook.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E7481EB926BB814A9312940 /* BighelpThinkingLook.swift */; }; BE08F9E19719B67EEE98EA1C /* BighelpShortcutAskProbe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CC23C241BE39F27A688DFE9 /* BighelpShortcutAskProbe.swift */; }; @@ -1583,6 +1616,7 @@ C15B2EBFADBCB4E666135C48 /* AvatarCatalogKit.json in Resources */ = {isa = PBXBuildFile; fileRef = F67531847A62207D0A37AEBB /* AvatarCatalogKit.json */; }; C16EC1A6C6FB7E80F5573E04 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEFD73B5E60844ECD7FD44A2 /* AppState.swift */; }; C178567129F50942DB48F7FA /* HostOperationsPayloadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A647DF649F6F486557B0D97 /* HostOperationsPayloadTests.swift */; }; + C18324A6DF111FC0C40893A0 /* SpacesHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3336318691E9CBE17531916 /* SpacesHost.swift */; }; C1973F8CC1722D86D562D98F /* DirectHermesSessionActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 159745E2CA27BFC3F0A91671 /* DirectHermesSessionActions.swift */; }; C1B8811FE39B6EA95B8A0E78 /* invalid-private-url.json in Resources */ = {isa = PBXBuildFile; fileRef = 7CA0FA38B3D5E215D45A26F9 /* invalid-private-url.json */; }; C1FB39C6F4D951394EC6A67A /* ComposerInteractionUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D12AC6E66E242B6AA18EECAF /* ComposerInteractionUITests.swift */; }; @@ -1593,6 +1627,7 @@ C2499B7A9C27898D36572D0F /* SimpleBotMark.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E1BC6478B50BC01F0A39494 /* SimpleBotMark.swift */; }; C263D09076A2146A67329700 /* GeneratedMediaLifecycleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0BEC630295845F372BFA4B4 /* GeneratedMediaLifecycleTests.swift */; }; C267F57B8B192B726A30CC4A /* BighelpWidgetBackgroundRefresh.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6382873E9B8EF8068E7994D /* BighelpWidgetBackgroundRefresh.swift */; }; + C2A8BAEFCDAFB2DCF1A370F5 /* SpacePanelView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B87ED03DBD1643D84F6BFB7C /* SpacePanelView.swift */; }; C2AFE20C3C4AA8CDDA8FE812 /* BighelpWidgetSnapshotPublisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61FAF80155262EA27672A941 /* BighelpWidgetSnapshotPublisher.swift */; }; C2CF86BA634A77911247CE1D /* BighelpLiveAlerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FCE52C885EEC2EA2DD9502E /* BighelpLiveAlerts.swift */; }; C2DEFF3F15F2F2E7AADD2221 /* MoveChatToProjectSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83DCA4046E43C265BD099931 /* MoveChatToProjectSheet.swift */; }; @@ -1604,6 +1639,7 @@ C3597A1DC48D47B78EBB6CCA /* DeviceAccessCardFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9454C94BDB7FEC2FDA142604 /* DeviceAccessCardFixture.swift */; }; C36B372C93023630CC8CCED0 /* ConnectorCardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78BCAB823CFB8356902421FF /* ConnectorCardTests.swift */; }; C3D5F1A378CEEEFFF973F779 /* AgentHelperModelsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F92374C41F49709D66355D8A /* AgentHelperModelsTests.swift */; }; + C42681DAA0C267F0E6BB6D18 /* NewChatFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF5A878B9936E443526A5F33 /* NewChatFixture.swift */; }; C497810FDB7B8B2890714C6F /* HermesBotModeApproval.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC147D5463924B17D6DD72DC /* HermesBotModeApproval.swift */; }; C4A4B7F2D827ED33013A5F65 /* HermesBotModeWireCodec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 971A8322A4FE7AC616941DCB /* HermesBotModeWireCodec.swift */; }; C4B01B25DE637F6EF23428CC /* BighelpNotificationProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 698126767AACDCDC068BD00F /* BighelpNotificationProcessor.swift */; }; @@ -1611,13 +1647,12 @@ C51E78FF26158BE3194F3180 /* BighelpMenuRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3343ABABDB79BADCF447EEF /* BighelpMenuRow.swift */; }; C5204B11B341760378224923 /* ChatGlassArchitectureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A676AE9F5121BDE19DA97F9E /* ChatGlassArchitectureTests.swift */; }; C5276AA51FAE02FB251A077F /* BighelpLinkProjectGitClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45769F0DA6DB3DBA1A9175F0 /* BighelpLinkProjectGitClient.swift */; }; + C52FF73155AC111979486D13 /* MacTileMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EA7457F8492B531A665AC9E /* MacTileMenu.swift */; }; C54E0AD84B5E305A1ABFB0F7 /* BighelpActivityRowsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D0756F28F8D83DCD99820C5 /* BighelpActivityRowsView.swift */; }; C58B7EF60D58D116ABA172E7 /* DirectHermesChatView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 71D04B41D7481AD9B8197BF0 /* DirectHermesChatView.swift */; }; - C5A66B6EA0CF91080459BDA8 /* CodeComposer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02889C4BAB355C04380A9EEC /* CodeComposer.swift */; }; C5C059D1F8B1D811EF818F42 /* bighelp-trick-question.json in Resources */ = {isa = PBXBuildFile; fileRef = FC50D6DD3056D236C62E8B60 /* bighelp-trick-question.json */; }; C5C4D2B8DCD48DF9AB58C907 /* WorkflowsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3E24D8DB9EC2245F591AB76 /* WorkflowsTests.swift */; }; C5C7D6DF90F63E17E68BD8F9 /* LiveVoiceReadinessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F50CA5FA31F95111A047BE14 /* LiveVoiceReadinessTests.swift */; }; - C5CF86430FFC993BEB04AB83 /* AppLayoutUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E827A96DEF163977F50C25C4 /* AppLayoutUITests.swift */; }; C5EE201A610DBB663723D189 /* bighelp-pull.json in Resources */ = {isa = PBXBuildFile; fileRef = FEC0FE9520454EA548CB8387 /* bighelp-pull.json */; }; C5F654FEFBC97A50B0FC6170 /* WatchWire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DFC0469859FF2F766A0F9A5 /* WatchWire.swift */; }; C61E53841C4FC5469757E02E /* DriveShellHooks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D7DDA8E65B97F20E8EC76A3 /* DriveShellHooks.swift */; }; @@ -1625,6 +1660,7 @@ C649497D9C13036255400241 /* BighelpWidgetRenderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 707DEB68CC2E0A81E7A559C9 /* BighelpWidgetRenderTests.swift */; }; C65CCE3D3F17ECCDD9991D9D /* BotsAppStateHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6720AFA97990E8EC292BAD70 /* BotsAppStateHostUITests.swift */; }; C66D44A9FDD34941E3F5EB73 /* AppStateClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5324260A0E2339E8BBAD5E8F /* AppStateClient.swift */; }; + C66EFBDB5C7201226959CDF2 /* ChatsInboxProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BE3DF440F6B8CF977E52DF2 /* ChatsInboxProjection.swift */; }; C69497E9FC3B6170E57B8D01 /* BuzzKit in Frameworks */ = {isa = PBXBuildFile; productRef = 64CBDFFEB41F346EC79DB61A /* BuzzKit */; }; C6B16DCA7D55170136DC96B9 /* ChatInfoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4F690B803E234AB5651282B /* ChatInfoUITests.swift */; }; C6C394C42B5BC6721E2E0DCC /* DeviceToolEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E45B7FBC8B435DDF94BAF6E /* DeviceToolEnvironment.swift */; }; @@ -1633,6 +1669,7 @@ C76B51FDA36B91222D516904 /* BighelpLoaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8761CEA92E4434CA88E28E1D /* BighelpLoaderTests.swift */; }; C7AE3EF40F91370CE326A01B /* HermesBlobEditsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32E521E0B53082AC36D71775 /* HermesBlobEditsTests.swift */; }; C7B2E0C04AE700B442ECD2F1 /* LocalModelsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14A9B9DC867AB47CD9C85F44 /* LocalModelsView.swift */; }; + C7D36ABB07D7045DDE11FA68 /* NewChatHandoff.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FD879BB6C04AF91AB35FBEA /* NewChatHandoff.swift */; }; C7F3CE7070ED715E4EDB8621 /* RootFreshSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8EA377D3701B3F86FEF078F3 /* RootFreshSession.swift */; }; C82641368BB7448560AC192B /* UsageSummaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 840E0F9C1ECF3B744DFD7B88 /* UsageSummaryTests.swift */; }; C836BC84BA9A520A2DB166CB /* UsageStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2A14692501D4ABFB17F76BB /* UsageStoreTests.swift */; }; @@ -1653,6 +1690,7 @@ C9AB02210A36530B2026C103 /* BighelpWidgetSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = F81474FE0CBEB18DD469D2DC /* BighelpWidgetSnapshot.swift */; }; C9C93176E1132AEEED2508AF /* BighelpNoodleMotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 043963184D90C22B260C552A /* BighelpNoodleMotion.swift */; }; C9E0B72F9792853E6C3D5DEC /* PetdexFixtures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 554C29D85773C730ECA6358B /* PetdexFixtures.swift */; }; + CA2ACB0BF7012FEDFFADF007 /* SpaceDraftCardView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83E05FBFBD01ACEC622AD77E /* SpaceDraftCardView.swift */; }; CA4FB90E5AC22CD9F560E338 /* ChatMessageGroupingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB935DC7106AD70D15BFF877 /* ChatMessageGroupingTests.swift */; }; CA7C9B89C261EB43B25BC078 /* DirectHermesFileAttachments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B40CF01292786E98BB37CE5 /* DirectHermesFileAttachments.swift */; }; CABED41D685A8EC3843D7B40 /* ChatTranscriptCanvasCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = D08151AC5B7909855D3D5CF9 /* ChatTranscriptCanvasCache.swift */; }; @@ -1685,6 +1723,7 @@ CE1DF299593F46FBD4865C23 /* DemoAgentFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CEFCE60D2F34D34C50B0D00 /* DemoAgentFiles.swift */; }; CE39880EAFE7E85C1E7602F8 /* RFBMessages.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61084824CFBC1D659322B136 /* RFBMessages.swift */; }; CE3BC3F28C5C326791974361 /* DirectHermesNativeContextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48173B463824CCC83DBBEF0A /* DirectHermesNativeContextTests.swift */; }; + CE91C33B4F90531C2DD0BDE1 /* BighelpNavigationGlass.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA4DC8827D5C22B43B42CB9E /* BighelpNavigationGlass.swift */; }; CEA434957AFAAB0E40673CDC /* CodeProjectSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 075FAECB019B3FF463A04703 /* CodeProjectSource.swift */; }; CEA5D7A18CF42D4A70EAC195 /* TemplateVariablesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8B4B7166870C2C9A3CC6E33 /* TemplateVariablesTests.swift */; }; CEE3DA726A75443996BBD170 /* ConnectorAppsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2156B02FA574BCCBF86C34D /* ConnectorAppsModel.swift */; }; @@ -1756,12 +1795,13 @@ D61515622140213AD7E0FB1E /* soul-counterpoint.md in Resources */ = {isa = PBXBuildFile; fileRef = 60C035E1E9D9E86ADE7FF305 /* soul-counterpoint.md */; }; D658DABD316296699BA57736 /* soul-quill.md in Resources */ = {isa = PBXBuildFile; fileRef = EBA3D8873FF00E975871E446 /* soul-quill.md */; }; D66D2449778F4D1AAEA2CC50 /* BighelpLogo.swift in Sources */ = {isa = PBXBuildFile; fileRef = D29D3004AA6E39970301E5B4 /* BighelpLogo.swift */; }; + D67CBBAF649B67AFA6D4ECE5 /* NewChatChoicesRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D91EA7C155C5C7DDF393261 /* NewChatChoicesRow.swift */; }; D6953205AD992A7915070EF8 /* ComposerGlassUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 530632539B8C069371C9BC57 /* ComposerGlassUITests.swift */; }; D6A802CC2404B335CF4136F8 /* DirectHermesNativeAttachmentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06604943C1C5D780822F64D6 /* DirectHermesNativeAttachmentTests.swift */; }; D6CA11453C9E2BA2A65F09AC /* StockGitReviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2F653D00F8A7467F524639E /* StockGitReviewView.swift */; }; D70A0CBF9875274DF55F8F06 /* ChatMentionTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B6E8F02A6376ED091905B6E /* ChatMentionTextView.swift */; }; D70DEC902B2C6CFD066B5B31 /* SettingsLayoutUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F77F33887EFC9676338781 /* SettingsLayoutUITests.swift */; }; - D73A500F5026BA4450D00CF6 /* BighelpHostSwitcherLockup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42596C8500B087541B4547CB /* BighelpHostSwitcherLockup.swift */; }; + D71255F5A8BC5AEB87C2CF27 /* HomeContracts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 938394CBC82D25F1D3D74000 /* HomeContracts.swift */; }; D749464340CA12D9569A2149 /* ChatComposerActionButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADBA5038A7DACA3C8A70AE75 /* ChatComposerActionButton.swift */; }; D78F656A4787495D0BEE6AD8 /* CodeBatchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9B2BE24717336EE27018F9A /* CodeBatchTests.swift */; }; D7A5840DC86BB9BFB3D45F6D /* ScheduleRequestBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF1723D5FD7AC0CB0201BF60 /* ScheduleRequestBuilderTests.swift */; }; @@ -1788,6 +1828,7 @@ D9CB6B11A5ECE669BE0CB5BA /* ImageDraft.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2A64F7CE8F3CA117AE15906 /* ImageDraft.swift */; }; D9F66517D2932E092EB55578 /* TelemetryTestSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69565D1233A936662EACA061 /* TelemetryTestSupport.swift */; }; DA1FFAB77004F6B2F259E162 /* templates-use.json in Resources */ = {isa = PBXBuildFile; fileRef = 3C86D9728A87BCA80883BBB0 /* templates-use.json */; }; + DA3310874BC25AFC22063B8E /* HomeSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E2BB3763EC1668CE0F9BBF0 /* HomeSelection.swift */; }; DA5DC0252795F51285FA1300 /* NativeLifecycleWiringTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E807EED6B0FB41B0B40AD51B /* NativeLifecycleWiringTests.swift */; }; DA77A59C85A9D7FB8F7D24DE /* MarketplaceUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5E2FFB60768D022AEC0FED9 /* MarketplaceUITests.swift */; }; DA8C20B69EE62BF047DE012B /* RegistryRoomPeerHosts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57008152A33D1E123EA4099E /* RegistryRoomPeerHosts.swift */; }; @@ -1811,7 +1852,6 @@ DD3C714309567DDD3A92CC46 /* TelemetryTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59A48681DBB3045BCA4DA5EA /* TelemetryTransport.swift */; }; DD5E51846C0D4324833F5691 /* RootSimpleBots.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA81A7BA5D2897087FB2DF79 /* RootSimpleBots.swift */; }; DD61C441D36A3F8F10E2A3CE /* DirectHermesSecurePrompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AE67157D14F1E865DCF1318 /* DirectHermesSecurePrompt.swift */; }; - DD9B0458037184ABC60AC77B /* NativeAgentCreationVisualTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 380D86D09ADE0D64E0E00DE9 /* NativeAgentCreationVisualTests.swift */; }; DDB387AAC636F4FBBE381774 /* BighelpPinnedAgentsWidgetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F16FAEC87996B0A15F362D5 /* BighelpPinnedAgentsWidgetTests.swift */; }; DDC77F06F189A8EF8B2A4183 /* ChatStreamingTextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECE93E481399A4306DBACFC /* ChatStreamingTextTests.swift */; }; DDDB0BDA2DE5793ED873DCFC /* ChatModel+Transcript.swift in Sources */ = {isa = PBXBuildFile; fileRef = 421B2DDC261C166C740FAD8A /* ChatModel+Transcript.swift */; }; @@ -1839,7 +1879,6 @@ DFAF9A57222753DA6A7027D3 /* ReferenceComposerTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D07FA523BB682E8AC4A5E3DB /* ReferenceComposerTextView.swift */; }; DFC3A5FD6960C3A1BB765898 /* ReferenceStrictJSONParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60DBDE69BA245F9F8B1633A4 /* ReferenceStrictJSONParser.swift */; }; DFFEDACD945D5232FC4F56B9 /* AgentSoulTemplates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49CE092FE72E674CAE173EDE /* AgentSoulTemplates.swift */; }; - E0ABA2CFFE7CF938EFC8046A /* BighelpMenuUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8FFBC9B200835B3E101AA83 /* BighelpMenuUITests.swift */; }; E0E26CC2702BC633B82814BB /* GroupSettingsDemoClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBA62136367463A2714FF00B /* GroupSettingsDemoClient.swift */; }; E0FC4D0756B791358EA0DA7F /* NativeSubagentProductionUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ADF27E2CDA198F28038830E /* NativeSubagentProductionUITests.swift */; }; E12BD9CFFED30397E22AA43D /* BighelpManagedNativeActivityRuntime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52BC5220E7150E224E5841D7 /* BighelpManagedNativeActivityRuntime.swift */; }; @@ -1863,8 +1902,10 @@ E2B650F2E6C666A347C1916F /* GeminiLiveAudioReport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8FCB52A58D38CE645CCA340 /* GeminiLiveAudioReport.swift */; }; E2B771B30C555C4A476D2426 /* KanbanBoardModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1DB559BCA138130360AAB97 /* KanbanBoardModelTests.swift */; }; E2E71B0A0841C04595031A0D /* DeviceLocationFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03F2BE61948FF19AE45EEE5B /* DeviceLocationFixture.swift */; }; + E2E78FA3923A12B1849ADE08 /* ChatsInboxProjectionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C332FB058A8999F4E5B17A3 /* ChatsInboxProjectionTests.swift */; }; E321D19D467864BCE80DFAE2 /* NativeBotModeHandles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E3EE6A61F6893406ADE37AA /* NativeBotModeHandles.swift */; }; E329D7AA7DA29740FF0E5D01 /* ReferenceHubTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 171E2DAFB37938E59B631D44 /* ReferenceHubTests.swift */; }; + E355DBD684668B6D178D7E2C /* BotProfileDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ECCC126A47FD48754D1E82F /* BotProfileDetails.swift */; }; E3575C0DA2C8ACE98170B4BF /* ChannelAlertsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78B82566718A67B20E114E89 /* ChannelAlertsTests.swift */; }; E38C49A8BC478675844E72D2 /* BigFileChatUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E4529C210BF8B03ADCC3AEB /* BigFileChatUITests.swift */; }; E3CBB3FECCB837D3C8D91BA7 /* NotificationEventWireModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0640E3E2195E13C7537FDEF /* NotificationEventWireModels.swift */; }; @@ -1887,13 +1928,16 @@ E5AE72FCAF0D598E265BF605 /* ProfileLifecycleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B3EF4DE0B3F0D3F8FF8DA5 /* ProfileLifecycleView.swift */; }; E5ED0E414BA70426E622F483 /* HostAccessEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FFE0A4000866389A931340CB /* HostAccessEditorView.swift */; }; E631FB670F611061813B80C9 /* ModelNameCatalogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06E0752CDEB93F69DFC3661C /* ModelNameCatalogTests.swift */; }; + E64170A092AE47599073DA7A /* ChatNewChatSlot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49C6C5B621D594D25819458C /* ChatNewChatSlot.swift */; }; E64E2686D7C3C64D3E3E529A /* VoiceOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558FB53391D183473F14A43A /* VoiceOptions.swift */; }; E67563B3E12A73308A799A38 /* AgentTemplateBrowser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B51E351013BB3D09F5BF96A /* AgentTemplateBrowser.swift */; }; E6B5DA183CBCD546DCAABD9B /* ChatLayoutPreferencesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F26A9153E01384FF3334E701 /* ChatLayoutPreferencesTests.swift */; }; E6BE2C3667CEEEBA7A13FB3A /* RichDraftRecoveryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9341CEE698D541FD92FE8E4B /* RichDraftRecoveryStore.swift */; }; E70E158E605E4850E1309EB4 /* BigFileHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BE2715903BE8E99DEEE051F /* BigFileHostUITests.swift */; }; + E72E72D9E57D895D330CE366 /* SpacesClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57C4016E6EAD1B7E05838FDF /* SpacesClient.swift */; }; E73E1D95E28EA296430297DF /* ComposioSignInHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C7F3009E78870A5880C0A883 /* ComposioSignInHostUITests.swift */; }; E76DFCD3004B26CC4F2D656E /* SessionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D5EB7AE597E41A68DBA8FAD /* SessionsView.swift */; }; + E798B4DB35FB66A4A63C5E3B /* WorkProjection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07DFD6584189183A9CB646A8 /* WorkProjection.swift */; }; E7B8E6BF713D7D2C3003938E /* MessageBubble.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5386E5A4E8404332E26434A3 /* MessageBubble.swift */; }; E7D3BB990E465B9395495929 /* DirectHermesConversationClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 940DF8F0DAA4D2DBF3F553E3 /* DirectHermesConversationClient.swift */; }; E7EC2D7EE358D9BBF2A3BDD6 /* CompanionPhysics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E867F3A3D47196EFD108490 /* CompanionPhysics.swift */; }; @@ -1908,7 +1952,6 @@ E93AE9C0CD311464DD107F29 /* WorkflowsClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 662F6DEE9C28B0A2688B53CE /* WorkflowsClient.swift */; }; E95CD5159D7486D80A4BFBC5 /* SkillsAndToolsCatalogView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 033B2BFE02C6DE80789B8372 /* SkillsAndToolsCatalogView.swift */; }; E99EDEED8708E14A3AB2F5FE /* RFBSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 557745AD7F5CDFBA8D16E59C /* RFBSession.swift */; }; - E9DC964BFA209B91F0642406 /* AgentOpenRealHostUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2DA1AB00CBFD4C4778E695C2 /* AgentOpenRealHostUITests.swift */; }; E9F0842DBF61686F095825E6 /* MacSheetPresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07588E35220CDB0BE85082C3 /* MacSheetPresentationTests.swift */; }; E9F815DFBBC60E7835B198B4 /* ChatComposerRedrawTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE166C7ADCDC0F7DC5446830 /* ChatComposerRedrawTests.swift */; }; EA2012CDDFF088E90E12C654 /* TelemetryEncodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E09E40FC51388583D55E26 /* TelemetryEncodingTests.swift */; }; @@ -1948,6 +1991,7 @@ EE0B108AF417B7FCC4F81F2E /* BighelpFoundationModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B7F846E6B472F0B4D981E2E /* BighelpFoundationModels.swift */; }; EE171626C3F67C4719FC0903 /* VoiceOptionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D1FF33949CE0592C501CFD6 /* VoiceOptionsTests.swift */; }; EE209C921040BCEA143BFE2B /* ChatActivityPresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09E9B3E12B25F9A6A9CE7C2B /* ChatActivityPresentationTests.swift */; }; + EE2A914B0CA1DFF0BDE626A0 /* SpacesStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A226807A61AF3E06372E3409 /* SpacesStore.swift */; }; EE3C73C255647DBB8B73D65D /* DeviceAppearanceFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2271D36949B061D1891E546B /* DeviceAppearanceFixture.swift */; }; EE47A87EE0032BAEEBD18CF7 /* DirectHermesCapabilityManifest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EA3E1856CF21502D87D4216 /* DirectHermesCapabilityManifest.swift */; }; EE47C6D021C5C6B11DDDF885 /* BighelpCardEnvelope.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDD30D26F79A0E05511ADF5A /* BighelpCardEnvelope.swift */; }; @@ -1958,7 +2002,6 @@ EF0B45A9A7EACA84E234890C /* FleetSections.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDF1096DDAAF5B03091930ED /* FleetSections.swift */; }; EF0D429BEB6DDB3EDC933020 /* AppleDeviceToolServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97E85DBCBB8DDC592F728728 /* AppleDeviceToolServiceTests.swift */; }; EF1C7E1EBF6EFD90D17295BB /* VoiceTurnCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69AECFDA53E95EDAC1A7705B /* VoiceTurnCaptureTests.swift */; }; - EF39C6AB48360D884BFB5C51 /* SettingsView+Experience.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9720EBAF47E4E42E8C8B48C8 /* SettingsView+Experience.swift */; }; EF871C0FAEF2AF8F517F6612 /* DeviceNavigationTool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 236C86A455F34F6363A78431 /* DeviceNavigationTool.swift */; }; EF8F7A752B5FA1A879D3DEC9 /* LiveVoiceCallContextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5A4FB21D0093CE621CCB578 /* LiveVoiceCallContextTests.swift */; }; EFB26400EDFB9B522A9EBF4E /* BotsAppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E358FD837D6AAE26CD5A413 /* BotsAppState.swift */; }; @@ -1972,6 +2015,7 @@ F0B426BFDA0C86220AC8E6A8 /* ChatMessageExport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CCE4C6173E94FB589174BD4 /* ChatMessageExport.swift */; }; F0FAF8A1CC9DADBDDCC8275A /* BighelpBuzzKitRuntime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FB7E0EB692CC87455A9E67B /* BighelpBuzzKitRuntime.swift */; }; F11176EB450930F8E8E983DC /* BighelpNotificationGrouping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 284257AC13E13E5859B88C21 /* BighelpNotificationGrouping.swift */; }; + F151DD92C6E8AEE3215B5591 /* HomeSidebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1EE295BE87CDDA311DDC298 /* HomeSidebar.swift */; }; F1562FA78D50387FF05BA312 /* DirectHermesVoiceClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 156C32372A4D91EB1456BAB2 /* DirectHermesVoiceClientTests.swift */; }; F15D75965B4B8129D5C47157 /* BighelpShortcutConnectionWait.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C7D87A9D884D8A27F3E83EC /* BighelpShortcutConnectionWait.swift */; }; F169CBC388CACBBE3FE7EF56 /* ScratchpadFormattingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CA565F0CEECC8289EB2F045 /* ScratchpadFormattingTests.swift */; }; @@ -1990,7 +2034,6 @@ F341755AC880D86DFD86B52F /* TextSizeDefaultUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C9C1ED2BC60CA3C8BF159D0 /* TextSizeDefaultUITests.swift */; }; F348F065E83BAF11B87F61C7 /* generation-preview.mp4 in Resources */ = {isa = PBXBuildFile; fileRef = E7173F836ECF6E4D13740E1B /* generation-preview.mp4 */; }; F36387C9C9008A1AF53E9229 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74A210458E70F5ECD3043677 /* ShareViewController.swift */; }; - F3DDC06464DA83E58A7B8D52 /* AgentActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5068277073666FC21BE690A9 /* AgentActions.swift */; }; F402A7FA85AEDCDB788F3D55 /* ProfileDeletionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4BA8B35DA3A81885AD5F235 /* ProfileDeletionTests.swift */; }; F4161E4B346B270C76670473 /* NativeSessionControlsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F6059C9938AE497F3666A96 /* NativeSessionControlsView.swift */; }; F457459FC8D55A6830E08429 /* ProviderUsageUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58625F7B2E999825B55E3351 /* ProviderUsageUITests.swift */; }; @@ -2055,6 +2098,7 @@ FB1549A5148B7362638DDFAA /* BighelpMacUpdater.bundle in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 36E49823646B5715F924EFF9 /* BighelpMacUpdater.bundle */; platformFilters = (maccatalyst, ); settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; FB4253AB23A775E002E4026E /* MoveChatToProjectUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95AE454D7AE6FB94CC9C5B1E /* MoveChatToProjectUITests.swift */; }; FB5A5528B181EFACBC3CBECC /* ScheduleCadencePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77DE30B07B1CB21D93054AF7 /* ScheduleCadencePicker.swift */; }; + FB88850F7A44A4D6D7C96E1B /* HomeSettingsMigrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6515EF2C7EF2A6FC8041124C /* HomeSettingsMigrationTests.swift */; }; FB90A8EFB9AEF8C517700101 /* WorkspaceManagementClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A648B71B7D1F154050281B2 /* WorkspaceManagementClient.swift */; }; FB9E3C59A382CC59D5D167CD /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = C67E02B2BD7833C9DE7C3B7B /* NotificationService.swift */; }; FBB75ECBDCB2B3E4DC1A5019 /* HostBackupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12962B16DD7F5CFD17BD5DAA /* HostBackupView.swift */; }; @@ -2085,6 +2129,7 @@ FE8EC8B99F02CF84A306216D /* HostOperationsStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4038907121A33524DF3B42C /* HostOperationsStore.swift */; }; FEC0892D0D87CD21F45EA175 /* get-v2.json in Resources */ = {isa = PBXBuildFile; fileRef = 8A7FC461E78CD9D4FCEF6EBF /* get-v2.json */; }; FED8E5F305979FC3AA8E7DB5 /* ChatScreenMount.swift in Sources */ = {isa = PBXBuildFile; fileRef = E360711FDD2AAA48FD1377BD /* ChatScreenMount.swift */; }; + FF125C53A6B1E528373562A0 /* NewChatSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B998C39CEDFC9B00D736014 /* NewChatSession.swift */; }; FF237C3721857F6489DE324D /* ChatMarkdownDocument.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E9FCA4F43E5BEE8D4C5207C /* ChatMarkdownDocument.swift */; }; FF4E13DE34C81A4B1B3167AA /* ReferenceHubDrawer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27A896F0E41C5733EC9959CD /* ReferenceHubDrawer.swift */; }; FFACAB5BF8E2C75E21289B88 /* bighelp-reveal.json in Resources */ = {isa = PBXBuildFile; fileRef = 123219BA513DFDB4145C074A /* bighelp-reveal.json */; }; @@ -2205,6 +2250,7 @@ /* Begin PBXFileReference section */ 001912186DD9AA0BC05F9990 /* RFBZRLE.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RFBZRLE.swift; sourceTree = ""; }; + 008725B5A36A63BFFDA30E0D /* NewChatRecipientsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatRecipientsTests.swift; sourceTree = ""; }; 00C44545710D979AEBB72D7A /* ScreenPostureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenPostureTests.swift; sourceTree = ""; }; 00D0EE1D5615E09D7B3D144F /* DemoCodeGit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoCodeGit.swift; sourceTree = ""; }; 00D2CFE5B08FFF1AD09D7CB7 /* HTMLAppWire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLAppWire.swift; sourceTree = ""; }; @@ -2222,12 +2268,12 @@ 01A12040C312898C4C789116 /* ImageDraftLiveDestinations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftLiveDestinations.swift; sourceTree = ""; }; 01A7DA853F11B75A534629DC /* TelemetryGlobalTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TelemetryGlobalTests.swift; sourceTree = ""; }; 01A918D06D010CA604387580 /* DemoSessionCatalogClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoSessionCatalogClient.swift; sourceTree = ""; }; + 01ACA08D84DDE576D1756E14 /* SpaceDraftCardStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpaceDraftCardStateTests.swift; sourceTree = ""; }; 01AE2544591B053DE53955A8 /* DeviceAppearanceTool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAppearanceTool.swift; sourceTree = ""; }; 01C45EBB07EC2FA326A3D7D2 /* WatchAppUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchAppUITests.swift; sourceTree = ""; }; 02163AD49A36843D1EBFAD91 /* BighelpCardObjectsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardObjectsTests.swift; sourceTree = ""; }; 027157CAB5BF115163393990 /* AvatarCreatorUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarCreatorUITests.swift; sourceTree = ""; }; 0284978EC9F5AD21700F6E31 /* AvatarKitRenderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarKitRenderTests.swift; sourceTree = ""; }; - 02889C4BAB355C04380A9EEC /* CodeComposer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeComposer.swift; sourceTree = ""; }; 02BB3BFA464829CA09B84FFD /* BoardBlocks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoardBlocks.swift; sourceTree = ""; }; 02DC14B5DC48148BBC38D0A9 /* templates-list-code.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "templates-list-code.json"; sourceTree = ""; }; 02F2DEE243A51982965DE06D /* BighelpLinkProjectGitClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLinkProjectGitClientTests.swift; sourceTree = ""; }; @@ -2250,6 +2296,7 @@ 04487A51D190019815D00D9D /* ChatCardInteractionEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatCardInteractionEnvironment.swift; sourceTree = ""; }; 044F71569210C6A2E1914814 /* UsageSections.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageSections.swift; sourceTree = ""; }; 0469453A64AEEFFBA08505AB /* SessionGoalSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionGoalSheet.swift; sourceTree = ""; }; + 0469E9BECD9BD8B61F3E04F6 /* NewChatView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatView.swift; sourceTree = ""; }; 04732CAE4445ECD7CD386D09 /* RegistryFleetReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegistryFleetReader.swift; sourceTree = ""; }; 04C04136C11827E672449E5B /* RootShellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootShellView.swift; sourceTree = ""; }; 04C0A77E2E8EA521E679BE14 /* ChatModel+Reactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChatModel+Reactions.swift"; sourceTree = ""; }; @@ -2258,6 +2305,7 @@ 05423F0CCD093BC481067692 /* TeamCallBargeIn.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TeamCallBargeIn.swift; sourceTree = ""; }; 054D3F1E61308B59672A882A /* BighelpCarPlayScene.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCarPlayScene.swift; sourceTree = ""; }; 054DEC6CD8AC8C52DA632264 /* GenerativeUICardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GenerativeUICardView.swift; sourceTree = ""; }; + 056F1D91C370B7F7DA5585BC /* HTMLAppNavigationPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLAppNavigationPolicyTests.swift; sourceTree = ""; }; 0579190CC3161DE303C711B3 /* LinkPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LinkPreview.swift; sourceTree = ""; }; 05971E8F375C4B8871760975 /* DirectHermesReactionHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesReactionHistory.swift; sourceTree = ""; }; 05B6F78535E261227E75CEDF /* soul-spark.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-spark.md"; sourceTree = ""; }; @@ -2280,6 +2328,7 @@ 075FAECB019B3FF463A04703 /* CodeProjectSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeProjectSource.swift; sourceTree = ""; }; 07658E64F41039CE24E408FE /* AttachmentWireModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AttachmentWireModels.swift; sourceTree = ""; }; 07D6D42F8892E938661C3EFE /* soul-anchor.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-anchor.md"; sourceTree = ""; }; + 07DFD6584189183A9CB646A8 /* WorkProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkProjection.swift; sourceTree = ""; }; 07F23D0718DD2CF18502AF95 /* BighelpLiveAlertTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLiveAlertTests.swift; sourceTree = ""; }; 07F358B0F3EFF0113D2718C2 /* AgentTodayDetailTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTodayDetailTests.swift; sourceTree = ""; }; 07F4CF3C8735C83544AAD84F /* SettingsStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsStoreTests.swift; sourceTree = ""; }; @@ -2373,6 +2422,7 @@ 12962B16DD7F5CFD17BD5DAA /* HostBackupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostBackupView.swift; sourceTree = ""; }; 12D93519128F8E3A35F264D0 /* CapabilitiesManagementView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CapabilitiesManagementView.swift; sourceTree = ""; }; 12DB23F855205AE60F84F5AD /* SessionContentRepositoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionContentRepositoryTests.swift; sourceTree = ""; }; + 12F13ECE65C76FAE69B91F89 /* HomeStripTabs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeStripTabs.swift; sourceTree = ""; }; 12FA36BAEFD2FF0501AF0356 /* ChatModel+BotMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChatModel+BotMode.swift"; sourceTree = ""; }; 130DDE93CBDE378679C2DD58 /* BighelpSuggestionList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSuggestionList.swift; sourceTree = ""; }; 130FF53809B8390E95869DC2 /* LandingScreenUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LandingScreenUITests.swift; sourceTree = ""; }; @@ -2426,13 +2476,11 @@ 180030F6E8C769153C77C4D8 /* RootAgentHome.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootAgentHome.swift; sourceTree = ""; }; 1811DC72DF4BCDCC91ED78C0 /* ProviderAccountsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderAccountsView.swift; sourceTree = ""; }; 18306E9412C2D2A2A5013368 /* DirectHermesPDFAttachments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesPDFAttachments.swift; sourceTree = ""; }; - 183FAAC3B2B524A603A53FB5 /* AllHostsHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AllHostsHostUITests.swift; sourceTree = ""; }; 1864BEF8CC2D8D761503798E /* live-bitcoin.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "live-bitcoin.json"; sourceTree = ""; }; 187B51036858D39AAFA54E5F /* MarkdownAttachmentUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownAttachmentUITests.swift; sourceTree = ""; }; 18869FCEF37622904146C4D3 /* VoiceStepLineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceStepLineTests.swift; sourceTree = ""; }; 18A424D3745CCCBB577472BE /* ChatModel+DraftImports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChatModel+DraftImports.swift"; sourceTree = ""; }; 18E94A655AC6FD5808D8F386 /* OnDeviceVoiceLiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnDeviceVoiceLiveTests.swift; sourceTree = ""; }; - 18F68037ACD2B17DE44200C1 /* CodeHomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeHomeView.swift; sourceTree = ""; }; 19126808A649AB7ECCB3E6B4 /* ImageDraftCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftCardView.swift; sourceTree = ""; }; 1913F54465167193622E446E /* UsageLimitsSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageLimitsSection.swift; sourceTree = ""; }; 193FB3F79D5331CD5035BE1A /* BighelpCardValidator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardValidator.swift; sourceTree = ""; }; @@ -2440,6 +2488,7 @@ 1941C3C4A19C2BFA1B4A9BC3 /* ChatPDFPagesDraft.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatPDFPagesDraft.swift; sourceTree = ""; }; 1977D62C2B1D6F0B5F429E69 /* ScheduledTasksView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduledTasksView.swift; sourceTree = ""; }; 19B428FA3E537FAD07A0CEC9 /* CanonicalChatCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CanonicalChatCoordinatorTests.swift; sourceTree = ""; }; + 19C19DC5D809E5B14A9EC002 /* TodayNotice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayNotice.swift; sourceTree = ""; }; 19CBE3874A5EB0DBC56584FC /* ResponseHaptics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResponseHaptics.swift; sourceTree = ""; }; 19D7160AE9C689BF3CA8ECC8 /* BighelpShortcutService+Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BighelpShortcutService+Actions.swift"; sourceTree = ""; }; 1A017EDD12024EEDFCDF7BD5 /* DashboardFixtures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardFixtures.swift; sourceTree = ""; }; @@ -2507,6 +2556,7 @@ 22E1D992FC101ADD5A43E45C /* HostToolBackendsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostToolBackendsStore.swift; sourceTree = ""; }; 22F447815E049E9EF24628CF /* ToolsetManagementView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolsetManagementView.swift; sourceTree = ""; }; 2311CDD0D0FDF41C4E377226 /* SettingsView+Identity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SettingsView+Identity.swift"; sourceTree = ""; }; + 23170C47F20C59BE05E144B4 /* TodaySpacesModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodaySpacesModelTests.swift; sourceTree = ""; }; 23310258C55313037433648F /* FirstRunOnboardingSteps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirstRunOnboardingSteps.swift; sourceTree = ""; }; 2341C59BB3C9BB272CF501E5 /* MessagingOnboardingStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessagingOnboardingStore.swift; sourceTree = ""; }; 236C86A455F34F6363A78431 /* DeviceNavigationTool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceNavigationTool.swift; sourceTree = ""; }; @@ -2521,8 +2571,10 @@ 24C6AF9DA3509FD62CD3DED3 /* MCPLargeServerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MCPLargeServerTests.swift; sourceTree = ""; }; 2505D162745A6571E823C256 /* DashboardWorkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardWorkTests.swift; sourceTree = ""; }; 25406CC474CAEC5B3FD368D0 /* ProviderUsageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderUsageTests.swift; sourceTree = ""; }; + 25550A0A0F3821ADED7FEDBE /* HomeTabBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeTabBar.swift; sourceTree = ""; }; 255997EE9AA60BD554229F3F /* ChatEdgeBlurTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatEdgeBlurTests.swift; sourceTree = ""; }; 25672AE617255B86F0620D46 /* VoiceSettingsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceSettingsUITests.swift; sourceTree = ""; }; + 258E9AEE85E8EC569A65A5A7 /* SpaceModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpaceModels.swift; sourceTree = ""; }; 2593E8067B2628E38DFB9576 /* ChatDissolveTransition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatDissolveTransition.swift; sourceTree = ""; }; 25B42C0520EEAFCC064E8825 /* HermesToolsList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesToolsList.swift; sourceTree = ""; }; 25F0B1E9D31F4CF2DAC474EC /* BighelpThinkingOrb.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpThinkingOrb.swift; sourceTree = ""; }; @@ -2555,6 +2607,7 @@ 2A6627D24E25B0628052F268 /* runs-get-text-runner.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-get-text-runner.json"; sourceTree = ""; }; 2A77F06A4EB3AC264271D1B8 /* ProviderLogoURLSessionTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderLogoURLSessionTransport.swift; sourceTree = ""; }; 2AA1D6A11E2C529C863AA083 /* ChatActivityDisclosureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatActivityDisclosureTests.swift; sourceTree = ""; }; + 2AAB566FE7CD9FCB1622B0C2 /* WorkFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkFixture.swift; sourceTree = ""; }; 2AB67E399FCAF7E7DD9399B6 /* DirectHermesVoiceMediaTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesVoiceMediaTransport.swift; sourceTree = ""; }; 2AC06A224EDED86627B32ECD /* AvatarImageProcessorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarImageProcessorTests.swift; sourceTree = ""; }; 2AC0C5C21B939C2BC28A21F4 /* HostPluginUpdate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostPluginUpdate.swift; sourceTree = ""; }; @@ -2583,7 +2636,6 @@ 2D4BF0E77894904D0E9F8014 /* BighelpChatSwitcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpChatSwitcher.swift; sourceTree = ""; }; 2D4F0775A087437288D32E0B /* PetdexAnimation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PetdexAnimation.swift; sourceTree = ""; }; 2D7F47D20D53B5FF15C7CD63 /* AgentActivityIsland.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActivityIsland.swift; sourceTree = ""; }; - 2DA1AB00CBFD4C4778E695C2 /* AgentOpenRealHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentOpenRealHostUITests.swift; sourceTree = ""; }; 2DA9A35B9B3C917C29643F1E /* BighelpNotificationService.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = BighelpNotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 2E1B6FEA123ABC335C807E5C /* ChatAttachmentMenuUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatAttachmentMenuUITests.swift; sourceTree = ""; }; 2E3EE6A61F6893406ADE37AA /* NativeBotModeHandles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeBotModeHandles.swift; sourceTree = ""; }; @@ -2596,12 +2648,14 @@ 2EE8FEACC28113129634CF42 /* MarkdownFileView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownFileView.swift; sourceTree = ""; }; 2EE9CF48D63A477B018A403D /* LiquidOrbPresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiquidOrbPresentationTests.swift; sourceTree = ""; }; 2F1C22259789A14CAA48A65A /* HermesHostOperationModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesHostOperationModels.swift; sourceTree = ""; }; + 2F1EBF478C30A24456E26A25 /* ChatsInboxRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsInboxRow.swift; sourceTree = ""; }; 2F5839F4502130F191439023 /* MidSessionSendHoldStateMachine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MidSessionSendHoldStateMachine.swift; sourceTree = ""; }; 2F5AB4DD1555D26C17AE0E7F /* ComposioCatalog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposioCatalog.swift; sourceTree = ""; }; 2F68507D37E222AAAD79CE5B /* TemplatePickerParts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplatePickerParts.swift; sourceTree = ""; }; 2F69DF4D8979ACD704171100 /* DirectHermesVoiceConfigurationClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesVoiceConfigurationClient.swift; sourceTree = ""; }; 2F84A337096DA59B68CAF506 /* ImageActionsSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageActionsSettings.swift; sourceTree = ""; }; 2FA73AFA26F8900D33EE46AF /* telemetry-v1.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "telemetry-v1.json"; sourceTree = ""; }; + 2FE55A8596FE2BA8F810C73E /* HomeShellUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeShellUITests.swift; sourceTree = ""; }; 30032BB7A11575E32DECD170 /* BotChatActivityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotChatActivityTests.swift; sourceTree = ""; }; 301F7F2D182A2BEC6F9B21B1 /* BighelpLoaderGallery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLoaderGallery.swift; sourceTree = ""; }; 302F46ED6E8E91351466F5B3 /* TelemetryLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TelemetryLifecycle.swift; sourceTree = ""; }; @@ -2621,6 +2675,7 @@ 31FE492B5B8378E9BE51DE32 /* KanbanStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanStore.swift; sourceTree = ""; }; 321B9D6AC07FA23E8A77C13D /* BotModeRoomCacheSchema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotModeRoomCacheSchema.swift; sourceTree = ""; }; 3224A99734E1A96A44D3595E /* SessionRuntimeControlSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionRuntimeControlSupport.swift; sourceTree = ""; }; + 322A3C7A5248CE931D627A74 /* AgentsSectionCaption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentsSectionCaption.swift; sourceTree = ""; }; 325CC2CD4BF28934B5BF0B07 /* ChatEdgeBlur.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatEdgeBlur.swift; sourceTree = ""; }; 3268467BC26D1CFEBDE37B07 /* HermesBotModePeerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesBotModePeerTests.swift; sourceTree = ""; }; 3282A97CC25FC44176A0DAE5 /* BighelpCardTemplateStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardTemplateStoreTests.swift; sourceTree = ""; }; @@ -2636,6 +2691,7 @@ 33E4EB272EA68374E3B3E748 /* BotModeStopTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotModeStopTests.swift; sourceTree = ""; }; 33E9FF3390300F44BE3F8C60 /* BighelpSealedAlertPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSealedAlertPresentation.swift; sourceTree = ""; }; 33F9EE654CBD35C5C2B5D853 /* AppleDeviceToolService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleDeviceToolService.swift; sourceTree = ""; }; + 341899D306173E3A6BF70917 /* NewChatRecipients.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatRecipients.swift; sourceTree = ""; }; 342B3F1660D119570134E75B /* ImageDraftReviewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftReviewTests.swift; sourceTree = ""; }; 344FB8E575EFBAACC708770D /* BighelpManagedNotificationNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpManagedNotificationNavigation.swift; sourceTree = ""; }; 346E60E2A592A84C62801324 /* ChatCameraPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatCameraPicker.swift; sourceTree = ""; }; @@ -2664,11 +2720,11 @@ 37D2DE1F0AF4478D40FD0E25 /* DashboardTodaySection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardTodaySection.swift; sourceTree = ""; }; 37E34B22010E152743301103 /* ProjectChangesStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectChangesStore.swift; sourceTree = ""; }; 3804996F38C55F49E94E091B /* BotModeObservedToolView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotModeObservedToolView.swift; sourceTree = ""; }; - 380D86D09ADE0D64E0E00DE9 /* NativeAgentCreationVisualTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeAgentCreationVisualTests.swift; sourceTree = ""; }; 3834D3A41B46698E21994E00 /* runs-start.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-start.json"; sourceTree = ""; }; 38447DDE28940F5B8C5B280F /* CodeModeHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeModeHostUITests.swift; sourceTree = ""; }; 387D6E33823CED3FE9B61893 /* BighelpMac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = BighelpMac.app; sourceTree = BUILT_PRODUCTS_DIR; }; 38A2FD97DEB1DADA5CCF853F /* NativeWorkspaceSessionBridge+Reentry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NativeWorkspaceSessionBridge+Reentry.swift"; sourceTree = ""; }; + 38B1CDE2956C9FF1683BE521 /* CodePickers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodePickers.swift; sourceTree = ""; }; 38DE5B8365EC7098DE0942B7 /* ChatActionMenuTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatActionMenuTests.swift; sourceTree = ""; }; 392D42FE59349A7C53F56B62 /* DirectHermesDashboardDataSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesDashboardDataSourceTests.swift; sourceTree = ""; }; 393615CD28B3A6AD2B32DD80 /* BighelpLocalCacheRefreshCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLocalCacheRefreshCoordinator.swift; sourceTree = ""; }; @@ -2679,11 +2735,11 @@ 39ABA20DFBC9888E9D43DEFE /* KanbanAdministrationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanAdministrationView.swift; sourceTree = ""; }; 39D10EEEB485E300792A9402 /* ChatMentionRendering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatMentionRendering.swift; sourceTree = ""; }; 39E2D77A3FB09D926BCE99A5 /* AvatarCreatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarCreatorView.swift; sourceTree = ""; }; + 3A0023FA904FEED13C2B7682 /* NewChatPickTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatPickTests.swift; sourceTree = ""; }; 3A36B8CBD8CCEE2731609BB9 /* soul-compass.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-compass.md"; sourceTree = ""; }; 3A647DF649F6F486557B0D97 /* HostOperationsPayloadTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostOperationsPayloadTests.swift; sourceTree = ""; }; 3A648B71B7D1F154050281B2 /* WorkspaceManagementClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceManagementClient.swift; sourceTree = ""; }; 3AA47B556B27FBDE7C18D2EE /* AppStateSync.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppStateSync.swift; sourceTree = ""; }; - 3AB7B41F130CAF111F94C162 /* AgentFastModeRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentFastModeRow.swift; sourceTree = ""; }; 3AC84C8E8881720E69DDDB59 /* ProjectLifecycleStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectLifecycleStore.swift; sourceTree = ""; }; 3AC85256784649A35E10ADC0 /* SettingsView+Preferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SettingsView+Preferences.swift"; sourceTree = ""; }; 3AFA6E2F7D42A8AB897FBA47 /* DirectHermesProjectGitClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesProjectGitClient.swift; sourceTree = ""; }; @@ -2697,11 +2753,13 @@ 3B84B943BBAB63CBF3543D7A /* CodeBranchName.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeBranchName.swift; sourceTree = ""; }; 3BEF307512389C0729BDF539 /* BotScreenStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotScreenStateTests.swift; sourceTree = ""; }; 3C3BC46F417B6D78CAB68273 /* templates-use-yours.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "templates-use-yours.json"; sourceTree = ""; }; + 3C40C08AB0B176B19A5E7DBC /* static-space-draft.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "static-space-draft.json"; sourceTree = ""; }; 3C61156DD553A34F476CB104 /* ChatFolderBrowserTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatFolderBrowserTests.swift; sourceTree = ""; }; 3C6F519E7C6F3B6B9D409724 /* BotModeDiscardCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotModeDiscardCard.swift; sourceTree = ""; }; 3C86D9728A87BCA80883BBB0 /* templates-use.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "templates-use.json"; sourceTree = ""; }; 3CA4FC4CA714026F061C78B5 /* ChatFolderBrowserView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatFolderBrowserView.swift; sourceTree = ""; }; 3CAC3D993B2C6404E9FD7484 /* LocalizationUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalizationUITests.swift; sourceTree = ""; }; + 3CC73679034D8C6500C601BC /* TodayCreateBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayCreateBox.swift; sourceTree = ""; }; 3CDABE72B40973455A986015 /* CredentialVaultUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CredentialVaultUITests.swift; sourceTree = ""; }; 3CE4498ABE2981E7AB6B2091 /* bighelp-listening.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "bighelp-listening.json"; sourceTree = ""; }; 3CEE2FDBEA76CC233FEB5E2A /* DirectHostNotificationClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHostNotificationClient.swift; sourceTree = ""; }; @@ -2719,8 +2777,8 @@ 3E3EDB37FA6D8157237A2037 /* AppStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppStateTests.swift; sourceTree = ""; }; 3E62018803B85F864D126FF9 /* ProviderUsageSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderUsageSettingsView.swift; sourceTree = ""; }; 3E63FA2CC59A6F8A771FF92A /* BighelpCardRelayIsolationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardRelayIsolationTests.swift; sourceTree = ""; }; + 3EA7457F8492B531A665AC9E /* MacTileMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacTileMenu.swift; sourceTree = ""; }; 3EBB614F75D0EEDA0B6D89CA /* HostHooksView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostHooksView.swift; sourceTree = ""; }; - 3EE9EB659F86107004A3BEE6 /* AgentsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentsView.swift; sourceTree = ""; }; 3EFD49EAD36B9F2F7F171108 /* UserIdentityStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserIdentityStore.swift; sourceTree = ""; }; 3F0738A049DA123D59EF0166 /* CardBackgroundTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardBackgroundTests.swift; sourceTree = ""; }; 3F074CC92AFF2AA534532D2F /* bighelp-resting.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "bighelp-resting.json"; sourceTree = ""; }; @@ -2734,6 +2792,7 @@ 401D0D342478A78D54E3644D /* SessionMaintenanceStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionMaintenanceStore.swift; sourceTree = ""; }; 401EF3EF0F27952E31CE9822 /* DirectHermesBotScreenStream.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesBotScreenStream.swift; sourceTree = ""; }; 40313A6F429A2BA26D05AB2A /* FirstRunModeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirstRunModeTests.swift; sourceTree = ""; }; + 407581F24811888F32AEF469 /* WorkCards.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkCards.swift; sourceTree = ""; }; 40CF165A2874CBEC1ACA5FB6 /* AgentBoardFileTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentBoardFileTests.swift; sourceTree = ""; }; 4108190EED2122E9485E02C6 /* ThinkingLookUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingLookUITests.swift; sourceTree = ""; }; 411907A0DEC2F2BEE6A7FA44 /* soul-waypoint.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-waypoint.md"; sourceTree = ""; }; @@ -2748,11 +2807,12 @@ 421D7CE7F431134882907DE5 /* BighelpButtonLoading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpButtonLoading.swift; sourceTree = ""; }; 422D437FFA91390550EBC51B /* ChatDestinationAttachments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatDestinationAttachments.swift; sourceTree = ""; }; 4257C42FC04B0F807EEA538B /* VoiceHoldLoop.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = VoiceHoldLoop.wav; sourceTree = ""; }; - 42596C8500B087541B4547CB /* BighelpHostSwitcherLockup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpHostSwitcherLockup.swift; sourceTree = ""; }; 426C42D8F875320110D6639E /* LiveVoiceDebugTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveVoiceDebugTests.swift; sourceTree = ""; }; 42963DDEFB1D5438885970EA /* GitHubCredentialAcceptanceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubCredentialAcceptanceTests.swift; sourceTree = ""; }; + 42C37CAEBF941CE56AEC027B /* BotProfileActionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotProfileActionsTests.swift; sourceTree = ""; }; 42F14F3ADF32EDBDB727499F /* VisionReadabilityUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VisionReadabilityUITests.swift; sourceTree = ""; }; 4325F750432EFB2A83F5FC52 /* BotScreenRFBTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotScreenRFBTests.swift; sourceTree = ""; }; + 433095D96A00DF67C1DEF48F /* HomeTabOrnament.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeTabOrnament.swift; sourceTree = ""; }; 4350B3112132634E6AE0A0F4 /* AgentCompanionAvatarRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentCompanionAvatarRenderer.swift; sourceTree = ""; }; 43C94BD61162D35FD4205BA8 /* BighelpGlyph.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpGlyph.swift; sourceTree = ""; }; 43DC33ACEF48388887235EEE /* OnDeviceVoiceSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnDeviceVoiceSettings.swift; sourceTree = ""; }; @@ -2773,6 +2833,7 @@ 4570755E70AA053D254D4835 /* HTMLAppsFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLAppsFixture.swift; sourceTree = ""; }; 45769F0DA6DB3DBA1A9175F0 /* BighelpLinkProjectGitClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLinkProjectGitClient.swift; sourceTree = ""; }; 458AECEE1D05EA55E6476DDE /* GeneratedMediaProjectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedMediaProjectionTests.swift; sourceTree = ""; }; + 45C970BDD3E46D550BEF79C2 /* RootHome.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootHome.swift; sourceTree = ""; }; 45CB822E9F832933D18360C2 /* ConnectorCardStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectorCardStore.swift; sourceTree = ""; }; 4608F7B111BF38A1875E82D7 /* BighelpWatchUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = BighelpWatchUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 4633A8076FD7DC2B28F17301 /* HostListSizeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostListSizeTests.swift; sourceTree = ""; }; @@ -2793,6 +2854,7 @@ 4903CB5D015E3FA9F21B0F19 /* BighelpExternalSessionOpen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpExternalSessionOpen.swift; sourceTree = ""; }; 49232E1CBDD8758F2AF9C099 /* BighelpComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpComponents.swift; sourceTree = ""; }; 49B85C57A989814E3BF315C3 /* ConnectionIsland.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionIsland.swift; sourceTree = ""; }; + 49C6C5B621D594D25819458C /* ChatNewChatSlot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatNewChatSlot.swift; sourceTree = ""; }; 49CE092FE72E674CAE173EDE /* AgentSoulTemplates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentSoulTemplates.swift; sourceTree = ""; }; 49D8CAECDBF4C2CA0FE40EB7 /* AgentTalkDeliveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTalkDeliveryTests.swift; sourceTree = ""; }; 49D9D355DEF45A1D088CE1AA /* MemoryGraphStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemoryGraphStore.swift; sourceTree = ""; }; @@ -2805,7 +2867,7 @@ 4A3BBD4EAE2A44378C37BEE0 /* SimpleBotsAppearanceUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotsAppearanceUITests.swift; sourceTree = ""; }; 4A5EDC5345FB3A9ED8908CC6 /* ToolDisclosureHydrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolDisclosureHydrationTests.swift; sourceTree = ""; }; 4AD4B5D1DA594EE46275CCA9 /* BighelpBotsWidgetFeed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpBotsWidgetFeed.swift; sourceTree = ""; }; - 4AEAE8B958F81AA860450230 /* BottomMenuUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BottomMenuUITests.swift; sourceTree = ""; }; + 4B075D7D83BBC4A23C03B5C1 /* CodeSessionStatusReaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeSessionStatusReaderTests.swift; sourceTree = ""; }; 4B096F962476F8F58B191844 /* MentionParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MentionParser.swift; sourceTree = ""; }; 4B45258C70F501D58F768487 /* ClipboardImagePasteControl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClipboardImagePasteControl.swift; sourceTree = ""; }; 4B6054AC92551D8B212BD782 /* AgentFace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentFace.swift; sourceTree = ""; }; @@ -2818,6 +2880,7 @@ 4C0C46DD88DD92320846BD65 /* BighelpWidgetStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpWidgetStyle.swift; sourceTree = ""; }; 4C1A2CA53D077B5C0D0EC6F7 /* SkillHubPageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillHubPageView.swift; sourceTree = ""; }; 4C2530CDD9E8256830CACEC6 /* NativeHermesSessionForkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeHermesSessionForkTests.swift; sourceTree = ""; }; + 4C32D94835AB8421789B59C0 /* WorkProjectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkProjectionTests.swift; sourceTree = ""; }; 4C6DBCCBBC55CBBA9186BEF1 /* soul-lens.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-lens.md"; sourceTree = ""; }; 4C72CD027D36BE76A5D574C2 /* DrivePlace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DrivePlace.swift; sourceTree = ""; }; 4C81BE8C178FF496859CE63B /* NotificationProcessorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationProcessorTests.swift; sourceTree = ""; }; @@ -2850,7 +2913,6 @@ 4FB152CCFD82E237A8543E00 /* ChatBackgroundResult.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBackgroundResult.swift; sourceTree = ""; }; 4FD5FD6075748203E10CC6B7 /* AchievementsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AchievementsStore.swift; sourceTree = ""; }; 502B365298F8DCD98E706CD9 /* BighelpCardRendererTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardRendererTests.swift; sourceTree = ""; }; - 5068277073666FC21BE690A9 /* AgentActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActions.swift; sourceTree = ""; }; 506BC65D498BDDDC8E07C040 /* ChatsUnreadAndDraftsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsUnreadAndDraftsUITests.swift; sourceTree = ""; }; 5075EA67E589FD9D2CB5FC85 /* NotoSans-SemiBold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "NotoSans-SemiBold.ttf"; sourceTree = ""; }; 508B5494DD3674010E5DD91E /* RichDraftFormatting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RichDraftFormatting.swift; sourceTree = ""; }; @@ -2859,6 +2921,7 @@ 50D5B36F5B0E2A80F566878C /* DemoAgentTodayDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoAgentTodayDetail.swift; sourceTree = ""; }; 50DF24CB6BEF6BD9383CCEBA /* BotScreenUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotScreenUITests.swift; sourceTree = ""; }; 50FC259931387E252734EE08 /* FileExplorerOptionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileExplorerOptionsTests.swift; sourceTree = ""; }; + 5108A9609A6F74C9F35402CB /* ChatsInboxFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsInboxFixture.swift; sourceTree = ""; }; 515005CE54D7F43A5B863003 /* WorkflowComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowComponents.swift; sourceTree = ""; }; 515B729EC6C73BB17D8A272A /* ChatCardMessageProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatCardMessageProjection.swift; sourceTree = ""; }; 517D85803C55B72202A77B6C /* soul-bridge.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-bridge.md"; sourceTree = ""; }; @@ -2922,12 +2985,12 @@ 5773624C45D469AD5E685C4B /* DeviceMusicToolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceMusicToolTests.swift; sourceTree = ""; }; 578DE4F4361908BAD8275D2F /* ManagementSearch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ManagementSearch.swift; sourceTree = ""; }; 579F050808B1CE8C5147D10F /* BighelpThinkingOrbTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpThinkingOrbTests.swift; sourceTree = ""; }; + 57C4016E6EAD1B7E05838FDF /* SpacesClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesClient.swift; sourceTree = ""; }; 580978D40E72CAB3863619A6 /* ComposerAttachmentDrop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposerAttachmentDrop.swift; sourceTree = ""; }; 580AB2B819C0E24ADA7B2FB0 /* ProviderLogos-NOTICES.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = "ProviderLogos-NOTICES.txt"; sourceTree = ""; }; 5839EBC64D344E43871E5958 /* ChatAttributionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatAttributionTests.swift; sourceTree = ""; }; 583BA6F94639B8B2ECA04CA9 /* RootMarketplace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootMarketplace.swift; sourceTree = ""; }; 58625F7B2E999825B55E3351 /* ProviderUsageUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderUsageUITests.swift; sourceTree = ""; }; - 586E07FD677EADCB35B80837 /* UnifiedModeToggleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnifiedModeToggleTests.swift; sourceTree = ""; }; 5877EBCE70707C4A168CE6E9 /* ChatEdgeBlurUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatEdgeBlurUITests.swift; sourceTree = ""; }; 58AB3FB19EEBEC30769CFB84 /* SessionCatalogCacheAuthorityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionCatalogCacheAuthorityTests.swift; sourceTree = ""; }; 58CC03D60404D1A5A53E65FE /* DirectHermesKanbanTransportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesKanbanTransportTests.swift; sourceTree = ""; }; @@ -2938,7 +3001,6 @@ 59A48681DBB3045BCA4DA5EA /* TelemetryTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TelemetryTransport.swift; sourceTree = ""; }; 59C1D022528FB63E037C7B28 /* PetdexGallery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PetdexGallery.swift; sourceTree = ""; }; 59CE897F445CA638FA3897BE /* HermesGroupsHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesGroupsHostUITests.swift; sourceTree = ""; }; - 59DC6DF119E780C3D98AA087 /* AllHostsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AllHostsUITests.swift; sourceTree = ""; }; 59E02588694976F1229F33CB /* SkillsAndToolsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillsAndToolsStore.swift; sourceTree = ""; }; 59E46C55A3F95C6B1D58E9C7 /* BighelpReasoningPickerSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpReasoningPickerSheet.swift; sourceTree = ""; }; 5A0D9E32BA614BB2E014A2C7 /* ChatDestinationAgentResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatDestinationAgentResolverTests.swift; sourceTree = ""; }; @@ -2971,7 +3033,6 @@ 5D49BDC3EAAE5B94D33EF04B /* AgentDefaultModelsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDefaultModelsView.swift; sourceTree = ""; }; 5D6B4B1E5F9374B89D737B30 /* TelemetrySettingsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TelemetrySettingsUITests.swift; sourceTree = ""; }; 5D9C7AC41A4CA4FA52110611 /* soul-lumen.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = "soul-lumen.md"; sourceTree = ""; }; - 5DAE06C366386CEA7ABCDF84 /* AgentRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRowView.swift; sourceTree = ""; }; 5DD3B3FFCC600318BEB64D85 /* WatchDesign.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchDesign.swift; sourceTree = ""; }; 5DFC0469859FF2F766A0F9A5 /* WatchWire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchWire.swift; sourceTree = ""; }; 5E0EE8E006424BDE9D97E690 /* DirectHermesManagedFilesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesManagedFilesTests.swift; sourceTree = ""; }; @@ -2990,6 +3051,7 @@ 5FC16504871822C0D070D37B /* RecordedActivityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordedActivityTests.swift; sourceTree = ""; }; 5FCE52C885EEC2EA2DD9502E /* BighelpLiveAlerts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLiveAlerts.swift; sourceTree = ""; }; 5FD27E2099CE872F95B460A4 /* GroupSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupSettingsView.swift; sourceTree = ""; }; + 5FD879BB6C04AF91AB35FBEA /* NewChatHandoff.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatHandoff.swift; sourceTree = ""; }; 5FF31C4FC4CEC312CBA88252 /* SessionModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionModels.swift; sourceTree = ""; }; 5FF7ABCA7FA5BE6EEC86947A /* DirectHermesLogsClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesLogsClient.swift; sourceTree = ""; }; 602A75CCF7D0A3FE19C0B002 /* PluginCatalogPageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PluginCatalogPageView.swift; sourceTree = ""; }; @@ -3033,11 +3095,13 @@ 63BBC3D0A9A41D731EE9D5B0 /* OtherAppChatsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OtherAppChatsTests.swift; sourceTree = ""; }; 63BD3CBB6E48D1AB957D471B /* BighelpLoaderMotion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLoaderMotion.swift; sourceTree = ""; }; 63D740A0872FA380E38FB50F /* TelemetryMetricMapping.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TelemetryMetricMapping.swift; sourceTree = ""; }; + 63F611B65636A8E2749EE9B8 /* HomeChromeFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeChromeFixture.swift; sourceTree = ""; }; 6409443250C4A662A08AB72E /* unarchive.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = unarchive.json; sourceTree = ""; }; 6454E72718581BF4DD7C86F9 /* UsageSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageSummary.swift; sourceTree = ""; }; 646159A08D713527205CB8A2 /* SessionCatalogStore+Read.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SessionCatalogStore+Read.swift"; sourceTree = ""; }; 64675E385D5EF27EF87F2634 /* ChatAttachment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatAttachment.swift; sourceTree = ""; }; 64AF3D5321DFFC9B9556E9B9 /* ChatAttachmentSaving.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatAttachmentSaving.swift; sourceTree = ""; }; + 6515EF2C7EF2A6FC8041124C /* HomeSettingsMigrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSettingsMigrationTests.swift; sourceTree = ""; }; 658B59C231EAF42CD31649DE /* CompactChatComposerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompactChatComposerTests.swift; sourceTree = ""; }; 65BD4C0208441BB886FDB670 /* AgentHeroHeaderLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentHeroHeaderLayoutTests.swift; sourceTree = ""; }; 65C604AF091476475A7EF15D /* DevicePhotosLibrary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevicePhotosLibrary.swift; sourceTree = ""; }; @@ -3056,7 +3120,6 @@ 6730194E90E4486A384E89E9 /* SimpleBotsSectionViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotsSectionViews.swift; sourceTree = ""; }; 67523907B748CF380DF5E276 /* ScheduleRequestBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleRequestBuilder.swift; sourceTree = ""; }; 6764D4FE1C1FC7B8695075EA /* GeminiLiveAudioReportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeminiLiveAudioReportTests.swift; sourceTree = ""; }; - 6772541AD53BC7065CD5D78C /* AppLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLayoutTests.swift; sourceTree = ""; }; 67834B3EF415CFFF4DB8778F /* DirectHermesHostOperationsClient+Inventory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DirectHermesHostOperationsClient+Inventory.swift"; sourceTree = ""; }; 6787F09E4FAAC9A79C987333 /* RootCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootCode.swift; sourceTree = ""; }; 67AED906093CF52D3271BDF3 /* BighelpBackgroundUploads.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpBackgroundUploads.swift; sourceTree = ""; }; @@ -3071,7 +3134,6 @@ 68331DD86FAA8DB390250583 /* NativeMessageReactionViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeMessageReactionViews.swift; sourceTree = ""; }; 6845AF0639C9B3171B2E3DEB /* FleetViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FleetViews.swift; sourceTree = ""; }; 687949CFACF582DCB8685E39 /* ZipArchiveExtractor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZipArchiveExtractor.swift; sourceTree = ""; }; - 6887CF181F29248E7BEA6CC6 /* AgentRuntimeDefaultsSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRuntimeDefaultsSection.swift; sourceTree = ""; }; 6889347DEEE3C4D54499D7E5 /* NativeDeviceToolSessionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeDeviceToolSessionTests.swift; sourceTree = ""; }; 68A31C169E92D2A4F7554C8E /* BighelpCardTemplate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardTemplate.swift; sourceTree = ""; }; 68AF9DEA76190434247169F3 /* CodeSessionStatusReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeSessionStatusReader.swift; sourceTree = ""; }; @@ -3091,6 +3153,7 @@ 69F4FF8F2C5673B2E05F45CE /* BighelpActivityRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpActivityRow.swift; sourceTree = ""; }; 6A1995B1EB0B79F83BBD5AAB /* BighelpActivitySession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpActivitySession.swift; sourceTree = ""; }; 6A432A029A730DCC2850AFF7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; }; + 6A670996B08FE4B02F6189B0 /* TodayBoardsPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayBoardsPanel.swift; sourceTree = ""; }; 6A8EFA755488AC962B573043 /* DirectHermesConversationClient+Queued.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DirectHermesConversationClient+Queued.swift"; sourceTree = ""; }; 6AB17B0D938A21E7F457F737 /* BighelpCardObjectViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardObjectViews.swift; sourceTree = ""; }; 6AB9122D29E69588B293F502 /* CodeModeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeModeTests.swift; sourceTree = ""; }; @@ -3103,6 +3166,7 @@ 6BE74E54DB93F0E290670B40 /* BighelpSheetSize.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSheetSize.swift; sourceTree = ""; }; 6BF389D0E37C21E2F445B802 /* CompanionSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompanionSettingsView.swift; sourceTree = ""; }; 6BFBFE60217D0F9676F7FD23 /* LiveVoiceModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveVoiceModel.swift; sourceTree = ""; }; + 6C332FB058A8999F4E5B17A3 /* ChatsInboxProjectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsInboxProjectionTests.swift; sourceTree = ""; }; 6C44773F84C3D6A3BE8C0459 /* SessionAppFilter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionAppFilter.swift; sourceTree = ""; }; 6C531087A40056E4A891401A /* RichDraftSourceFormatting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RichDraftSourceFormatting.swift; sourceTree = ""; }; 6C743815F5232ED6FDD5A64D /* NativeSessionControlsReadOnlyViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeSessionControlsReadOnlyViews.swift; sourceTree = ""; }; @@ -3110,11 +3174,13 @@ 6D0A47577211899F827BFC71 /* ChatPendingCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatPendingCardView.swift; sourceTree = ""; }; 6D1FF33949CE0592C501CFD6 /* VoiceOptionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceOptionsTests.swift; sourceTree = ""; }; 6D903B6D24C041C30F119F48 /* HermesUserMessageDisplay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesUserMessageDisplay.swift; sourceTree = ""; }; + 6D97ED75999EE9AF01D2C143 /* TodayBoardsStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayBoardsStoreTests.swift; sourceTree = ""; }; 6D9F303B84EF8DDEB9A14638 /* BighelpLinkHTTPTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLinkHTTPTransport.swift; sourceTree = ""; }; 6DA7B55CB98F303563E3B3EE /* HTMLAppTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLAppTests.swift; sourceTree = ""; }; 6DC1C3740F6110A7F601680A /* BighelpBuzzKitPreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpBuzzKitPreferences.swift; sourceTree = ""; }; 6DC9F6449F300EE8936752D8 /* BighelpCardSurfaceIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardSurfaceIntegrationTests.swift; sourceTree = ""; }; 6DCA1EB24295D1F121696B3E /* NativeHistoryCoverageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeHistoryCoverageTests.swift; sourceTree = ""; }; + 6E2FCD0CE3A5F9E9513CB461 /* TodayPanelLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayPanelLayoutTests.swift; sourceTree = ""; }; 6E4B01D37486A8514B64F2E3 /* AppFixtureAgentTemplates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppFixtureAgentTemplates.swift; sourceTree = ""; }; 6E4C7708B565263D5891089A /* GenerativeUIFormWireModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GenerativeUIFormWireModels.swift; sourceTree = ""; }; 6EE5E11EF15659E52E927941 /* ChatCitationFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatCitationFixture.swift; sourceTree = ""; }; @@ -3142,11 +3208,13 @@ 71D0B88F66012F6BCA6356E3 /* ProviderAssetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderAssetTests.swift; sourceTree = ""; }; 71E6EFD69A945F46C389CD47 /* AvatarFacePresets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarFacePresets.swift; sourceTree = ""; }; 71EF93E0F7C1CC09BF838197 /* ConnectionContractTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionContractTests.swift; sourceTree = ""; }; + 7220AEB50241663CD55FCCEC /* TodayFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayFixture.swift; sourceTree = ""; }; 72473030CFED4D30E5FE45EB /* GeneratedCards.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedCards.swift; sourceTree = ""; }; 724E3B60353CBF97DFFF0449 /* BighelpSideMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSideMenu.swift; sourceTree = ""; }; 72935CFF0B27C2CF0A214D99 /* DirectHermesCapabilityClients.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesCapabilityClients.swift; sourceTree = ""; }; 72B7397F7D4D61EB688CC8B4 /* SubagentControlTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubagentControlTests.swift; sourceTree = ""; }; 72CCE22F78850C9F1D2F8222 /* ImageDraftReviewParts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftReviewParts.swift; sourceTree = ""; }; + 72EFBA3EEB1AC550F4611C79 /* HomeMenuPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeMenuPresentation.swift; sourceTree = ""; }; 732B24883CC1D3F35E2F66BF /* AgentRuntimeDefaults.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRuntimeDefaults.swift; sourceTree = ""; }; 736835BE6DF7AAF0BD52E6CA /* BighelpLiveActivity.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = BighelpLiveActivity.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 736A73126C4818B6222FE787 /* BighelpNotificationService.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = BighelpNotificationService.entitlements; sourceTree = ""; }; @@ -3171,10 +3239,10 @@ 7567BB2655C50021201B538D /* ChatActivityDisclosureStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatActivityDisclosureStore.swift; sourceTree = ""; }; 75694E31C9C1B65B25A24FE4 /* BighelpNoodleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpNoodleTests.swift; sourceTree = ""; }; 75825C0D9C432116324712E3 /* VoiceLaunchCover.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceLaunchCover.swift; sourceTree = ""; }; - 7585C28F626CAE1CA1403BF6 /* AppLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLayout.swift; sourceTree = ""; }; 758BC7AD425BF64408758569 /* CanonicalChatCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CanonicalChatCoordinator.swift; sourceTree = ""; }; 7595C27FD5A0E590DBF1FF6C /* DirectHermesProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesProjection.swift; sourceTree = ""; }; 75A9A6B0C9E8C9BEC16C2B8E /* DirectHermesGoalControlTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesGoalControlTests.swift; sourceTree = ""; }; + 75AB021D2A15E98A55C24DC1 /* HomeSettingsMigration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSettingsMigration.swift; sourceTree = ""; }; 75BC105CA160422A2BAFE38B /* WorkspaceGrantedFilesClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGrantedFilesClientTests.swift; sourceTree = ""; }; 75D6AAA8BD0DFA2307BF1CD7 /* BighelpAppComposition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpAppComposition.swift; sourceTree = ""; }; 75EBE9D92DEFB7D780999FC1 /* BighelpUsageWidgetWide.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpUsageWidgetWide.swift; sourceTree = ""; }; @@ -3196,6 +3264,7 @@ 775FC5D9A3E4A403ED64FF6C /* BighelpLinkAccountRetirement.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLinkAccountRetirement.swift; sourceTree = ""; }; 7773C53167EE878A8E8CF470 /* BotModeRoomStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotModeRoomStoreTests.swift; sourceTree = ""; }; 77764B35BFE7ED560378376D /* BighelpCardDataClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardDataClient.swift; sourceTree = ""; }; + 77961B6DA3CE5396EDCB297D /* SpacesFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesFixture.swift; sourceTree = ""; }; 77DE30B07B1CB21D93054AF7 /* ScheduleCadencePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleCadencePicker.swift; sourceTree = ""; }; 7854C8ABE2067EF6C0779F70 /* AgentTodayDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTodayDetail.swift; sourceTree = ""; }; 78569AED58B1C7BD8A6C15F7 /* GitHubDeviceCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubDeviceCode.swift; sourceTree = ""; }; @@ -3225,6 +3294,7 @@ 7B6DC6F01BFD5E1AE50EF6E4 /* BighelpCardValueResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardValueResolverTests.swift; sourceTree = ""; }; 7B73DAC3DFA07E9D022CB02F /* BighelpDeliveryReceipts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpDeliveryReceipts.swift; sourceTree = ""; }; 7B7F846E6B472F0B4D981E2E /* BighelpFoundationModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpFoundationModels.swift; sourceTree = ""; }; + 7BA6C9356310A75F99AE911C /* HomeChromeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeChromeTests.swift; sourceTree = ""; }; 7BB0FBEAA2E5A432FC273022 /* SessionTasksSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionTasksSheet.swift; sourceTree = ""; }; 7BC29ED35D8D397DB63CC944 /* BighelpMenuCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpMenuCommands.swift; sourceTree = ""; }; 7BC5790C6EA24CF21A6B814A /* AgentRuntimeDefaultsEditorModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentRuntimeDefaultsEditorModel.swift; sourceTree = ""; }; @@ -3244,15 +3314,17 @@ 7D5EB7AE597E41A68DBA8FAD /* SessionsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionsView.swift; sourceTree = ""; }; 7D600DFF65A66FBB7C51E89F /* AvatarKitRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarKitRenderer.swift; sourceTree = ""; }; 7D69B5B75C0E90971A08C169 /* ChatTextSelectionSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatTextSelectionSheet.swift; sourceTree = ""; }; - 7D6F7B0C6B71878310AF32D1 /* PrimaryNavigationSelectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryNavigationSelectionTests.swift; sourceTree = ""; }; 7D7745D5E94F1FD8C5764702 /* BighelpManagedLiveActivityRegistrar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpManagedLiveActivityRegistrar.swift; sourceTree = ""; }; + 7D91EA7C155C5C7DDF393261 /* NewChatChoicesRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatChoicesRow.swift; sourceTree = ""; }; 7DB1B9E73CD85A90EC183093 /* CapabilitiesManagementModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CapabilitiesManagementModels.swift; sourceTree = ""; }; 7E0D78136612EFA054AF2191 /* BotChatActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotChatActivity.swift; sourceTree = ""; }; + 7E2BB3763EC1668CE0F9BBF0 /* HomeSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSelection.swift; sourceTree = ""; }; 7E2D22067ABBEB0D4D724FBE /* SettingsDestination.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsDestination.swift; sourceTree = ""; }; 7E3F7BC4DE0D166012849DBB /* BighelpBoardWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpBoardWidgets.swift; sourceTree = ""; }; 7E6C5F041D5AA49174026344 /* VoiceOrb.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceOrb.swift; sourceTree = ""; }; 7E72EC67FC663AE543259A11 /* UsageLimitsComputersTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageLimitsComputersTests.swift; sourceTree = ""; }; 7E96E0B1F96BAC7D40775D94 /* ThemePresetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThemePresetTests.swift; sourceTree = ""; }; + 7ECCC126A47FD48754D1E82F /* BotProfileDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotProfileDetails.swift; sourceTree = ""; }; 7EEB8BFBFA2836E26C774C0C /* DeviceAppearanceToolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAppearanceToolTests.swift; sourceTree = ""; }; 7F17ED3AA403533F22755654 /* NativeWorkspaceSessionBridge+Maintenance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NativeWorkspaceSessionBridge+Maintenance.swift"; sourceTree = ""; }; 7F188F6E953D952F74316C39 /* Bighelp.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Bighelp.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -3262,7 +3334,6 @@ 7F90DFFB9822D36299A5AB83 /* WorkflowTriggerSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowTriggerSheet.swift; sourceTree = ""; }; 7FAA637668A8FF2E4BBD6B38 /* SessionsModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionsModel.swift; sourceTree = ""; }; 7FDA79340BB299976FAA7A22 /* RootSplit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootSplit.swift; sourceTree = ""; }; - 7FDF4E08DF2A7F5CBC393F11 /* AgentPinnedGrid.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentPinnedGrid.swift; sourceTree = ""; }; 80088FB04D05EDBFE994777D /* VoiceConfigurationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceConfigurationView.swift; sourceTree = ""; }; 8016485004A1036D585246D5 /* OFL.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = OFL.txt; sourceTree = ""; }; 80167A7CC98815F188AEFB79 /* AgentStartTemplateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentStartTemplateTests.swift; sourceTree = ""; }; @@ -3295,6 +3366,7 @@ 82585A099C0B2200151BF919 /* AgentProfileID.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentProfileID.swift; sourceTree = ""; }; 827FB1BAC0E8E4C2F4FFE359 /* ChatBackgroundResultTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBackgroundResultTests.swift; sourceTree = ""; }; 829BFE850F0857E0FD3E57AF /* ThinkingLookSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingLookSettingsView.swift; sourceTree = ""; }; + 82B229D6F8990CA2258211D5 /* RootNewChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootNewChat.swift; sourceTree = ""; }; 82C23D9C034B645E742BBC2D /* WorkspaceGrantedFilesDecoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGrantedFilesDecoder.swift; sourceTree = ""; }; 82D28A1DFB92ED088711A3E5 /* VoiceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceView.swift; sourceTree = ""; }; 82E646023D459F98FB09479A /* ReminderLocationTrigger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReminderLocationTrigger.swift; sourceTree = ""; }; @@ -3308,6 +3380,7 @@ 83868AA62A2AB35D2349D238 /* BighelpWidgetSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpWidgetSnapshotTests.swift; sourceTree = ""; }; 83DB0B11E9248D7C1336AF5E /* ManagedNotificationLedgerMigrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ManagedNotificationLedgerMigrationTests.swift; sourceTree = ""; }; 83DCA4046E43C265BD099931 /* MoveChatToProjectSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MoveChatToProjectSheet.swift; sourceTree = ""; }; + 83E05FBFBD01ACEC622AD77E /* SpaceDraftCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpaceDraftCardView.swift; sourceTree = ""; }; 83EA38568DBD3BB92AC7E37A /* DirectHermesAgentProfileService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesAgentProfileService.swift; sourceTree = ""; }; 840E0F9C1ECF3B744DFD7B88 /* UsageSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageSummaryTests.swift; sourceTree = ""; }; 8429056A03559E8F8070FF3B /* WatchDemoPhone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchDemoPhone.swift; sourceTree = ""; }; @@ -3328,6 +3401,7 @@ 858E6E65F8A00595E50683E0 /* VoiceHoldMusicTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceHoldMusicTests.swift; sourceTree = ""; }; 85C4A871CD36D30FAC91B4F1 /* CodeMentionTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeMentionTextView.swift; sourceTree = ""; }; 85DC1E5B5FD060F4323CBD59 /* AgentsPresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentsPresentationTests.swift; sourceTree = ""; }; + 8628FAF07244D8889C7BE975 /* TodayPanelLayoutStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayPanelLayoutStore.swift; sourceTree = ""; }; 86558B0A0648697B13F8EF90 /* UsageExportCSV.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageExportCSV.swift; sourceTree = ""; }; 86794A73A72414A5A0AB866D /* BighelpManagedNotificationLedger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpManagedNotificationLedger.swift; sourceTree = ""; }; 867B5FA4CFB7A2BC768EF04E /* HermesBotModeCatalog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesBotModeCatalog.swift; sourceTree = ""; }; @@ -3362,7 +3436,9 @@ 8A7FC461E78CD9D4FCEF6EBF /* get-v2.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "get-v2.json"; sourceTree = ""; }; 8A8F24F167A10AE4D49D436A /* ScheduledAlertLinkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduledAlertLinkTests.swift; sourceTree = ""; }; 8AA23755717D72394BC99A0F /* ChatToolBlock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatToolBlock.swift; sourceTree = ""; }; + 8ACCD154FBFC52C597F6885C /* TodayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayView.swift; sourceTree = ""; }; 8AE3F5EF033F2E51AC96DFFA /* LiveVoiceUnavailableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveVoiceUnavailableTests.swift; sourceTree = ""; }; + 8B998C39CEDFC9B00D736014 /* NewChatSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatSession.swift; sourceTree = ""; }; 8B9BFECF9345E2D8DC72595E /* LongTextEditorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LongTextEditorTests.swift; sourceTree = ""; }; 8BB7964381C21043CA68DB0D /* CompanionPhysicsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompanionPhysicsTests.swift; sourceTree = ""; }; 8BE3FBAE98AF4D38AEEC8C2D /* SessionPickerWireModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionPickerWireModels.swift; sourceTree = ""; }; @@ -3374,7 +3450,6 @@ 8CF98249E40E406230777FCC /* WatchRelayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchRelayTests.swift; sourceTree = ""; }; 8CFBDDE8E3CF0A12E9805C4D /* ChatTaskDrawer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatTaskDrawer.swift; sourceTree = ""; }; 8D0F163EDAE473786869F8B9 /* BighelpThemeReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpThemeReader.swift; sourceTree = ""; }; - 8D379559BEB94B7580AEFD29 /* AgentsDirectoryComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentsDirectoryComponents.swift; sourceTree = ""; }; 8D3876EEE966594BB31EE4EB /* DirectHermesPayloadDecoding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesPayloadDecoding.swift; sourceTree = ""; }; 8D5A4B2F15407D6F507943DC /* BighelpSideStrip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSideStrip.swift; sourceTree = ""; }; 8DADB6E6EE1B88862A84AB9C /* ResponseHapticsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ResponseHapticsTests.swift; sourceTree = ""; }; @@ -3403,6 +3478,7 @@ 8F8D3EAA68D390EB783F6B71 /* BighelpUsageWidgetViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpUsageWidgetViews.swift; sourceTree = ""; }; 8FC3A1BCA9FC5B6364FD9CF9 /* NativeFileProductionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeFileProductionTests.swift; sourceTree = ""; }; 901AA9723C7F8E0CE8A51C37 /* SharedItemTypes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedItemTypes.swift; sourceTree = ""; }; + 901B9368C8FF33D186FA7426 /* WorkDoors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkDoors.swift; sourceTree = ""; }; 901D2828E64091858D603134 /* BighelpScheduledAlertLinks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpScheduledAlertLinks.swift; sourceTree = ""; }; 902E06ADA277EE9D8806B818 /* BighelpUsageWidgetLockScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpUsageWidgetLockScreen.swift; sourceTree = ""; }; 9088DE1567D631DC797171DB /* CardBackgroundView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardBackgroundView.swift; sourceTree = ""; }; @@ -3433,11 +3509,10 @@ 935843A247F6DB9DB6899AC0 /* BighelpShortcutServiceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpShortcutServiceTests.swift; sourceTree = ""; }; 936605189C269CB66A3AAAF9 /* HermesFolderPathTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesFolderPathTests.swift; sourceTree = ""; }; 936797598DC8A6D276F7EE10 /* WatchRelay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchRelay.swift; sourceTree = ""; }; + 938394CBC82D25F1D3D74000 /* HomeContracts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeContracts.swift; sourceTree = ""; }; 939B3D6EB46251894796B1AB /* KanbanWidgetPublisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanWidgetPublisher.swift; sourceTree = ""; }; 93AF619FC64FBCBE86BFF436 /* BighelpCardCatalogClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpCardCatalogClient.swift; sourceTree = ""; }; 93BCA75E13D979E7977DE481 /* IndependentHostScopeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndependentHostScopeTests.swift; sourceTree = ""; }; - 93BE73F918F3EED5F80259F6 /* AgentActionSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActionSheet.swift; sourceTree = ""; }; - 93C3C53CDF672AC9FDB30C6D /* AgentEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentEditorView.swift; sourceTree = ""; }; 93C40496DA01F9AC2116C506 /* WorkspacePageStates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspacePageStates.swift; sourceTree = ""; }; 93C66204164E5D37679588AB /* ImageDraftDecisions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftDecisions.swift; sourceTree = ""; }; 93F3442377D79656AFEB127A /* BighelpUsageWorkflowsWidgetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpUsageWorkflowsWidgetTests.swift; sourceTree = ""; }; @@ -3446,6 +3521,7 @@ 94485713CC1B3A6A5E2237F7 /* SimpleBotsSectionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotsSectionsTests.swift; sourceTree = ""; }; 9454C94BDB7FEC2FDA142604 /* DeviceAccessCardFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceAccessCardFixture.swift; sourceTree = ""; }; 945AB629B2EB65B45BD2666C /* BighelpFontCatalog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpFontCatalog.swift; sourceTree = ""; }; + 94966B58C7C316950BD235FB /* WorkItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkItem.swift; sourceTree = ""; }; 94977376DF9FE2BF6A3793D7 /* ModelsSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelsSettingsView.swift; sourceTree = ""; }; 953B22D814ABE8181BB7A195 /* KanbanService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanService.swift; sourceTree = ""; }; 955EF8DC3E8F0CC2CFB5D6C9 /* ChatToolCodeCellTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatToolCodeCellTests.swift; sourceTree = ""; }; @@ -3460,7 +3536,6 @@ 96BF743CCE71B017C130203B /* BighelpVisionUITests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = BighelpVisionUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 96C74BDF98AAE3E3E3A18027 /* DirectHermesFileAttachmentTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesFileAttachmentTests.swift; sourceTree = ""; }; 971A8322A4FE7AC616941DCB /* HermesBotModeWireCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesBotModeWireCodec.swift; sourceTree = ""; }; - 9720EBAF47E4E42E8C8B48C8 /* SettingsView+Experience.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SettingsView+Experience.swift"; sourceTree = ""; }; 9757B6D56D92DEDE5D9464A8 /* DirectHermesBrowserAuthenticationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesBrowserAuthenticationTests.swift; sourceTree = ""; }; 975A91EBDB1C161C5F813C12 /* HostOperationsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostOperationsView.swift; sourceTree = ""; }; 976873BD4A04753268CBA227 /* WorkflowFlowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowFlowView.swift; sourceTree = ""; }; @@ -3494,6 +3569,7 @@ 9B52C691C286DCA8EDC22DD8 /* BighelpConnectionStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpConnectionStatus.swift; sourceTree = ""; }; 9B6C2E9F7E97E148B6F57E26 /* ChatLayoutSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatLayoutSettingsView.swift; sourceTree = ""; }; 9BC7BAE4C833AE3986E8EE80 /* HostTextFiles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostTextFiles.swift; sourceTree = ""; }; + 9BE3DF440F6B8CF977E52DF2 /* ChatsInboxProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsInboxProjection.swift; sourceTree = ""; }; 9BF9A436F1AD6B230A4D395F /* KanbanWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanWindow.swift; sourceTree = ""; }; 9C27DC4B649073D955340D34 /* DevFactoryRunGroupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevFactoryRunGroupView.swift; sourceTree = ""; }; 9C55C9332C73EC2740153DCD /* DirectHermesCapabilityClientsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesCapabilityClientsTests.swift; sourceTree = ""; }; @@ -3524,6 +3600,8 @@ 9EFE4B7F7CB11895654EA588 /* ScheduledTaskDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduledTaskDetailView.swift; sourceTree = ""; }; 9EFF30AB0E3CE7D1E90D7DFD /* BighelpPluginUpdateClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpPluginUpdateClient.swift; sourceTree = ""; }; 9F37A3435A5BA30BBD8998B0 /* ComposioAppsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposioAppsTests.swift; sourceTree = ""; }; + 9F459BB26EC4023A79F7139E /* SpacesWire.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesWire.swift; sourceTree = ""; }; + 9F6A78A03D128C51B25B5CC3 /* BighelpAppSpaces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpAppSpaces.swift; sourceTree = ""; }; 9F825A925559FC87FEB69271 /* HTMLAppsHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLAppsHostUITests.swift; sourceTree = ""; }; 9FBA20053C60D44A1CEB6548 /* DirectHermesContextBreakdownTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesContextBreakdownTests.swift; sourceTree = ""; }; A0003AA20865E5C603817C0C /* ScheduledTasksStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduledTasksStoreTests.swift; sourceTree = ""; }; @@ -3536,13 +3614,13 @@ A165878C3209946E72E421B1 /* DirectHermesAchievementsClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesAchievementsClient.swift; sourceTree = ""; }; A1743EC57BBB9882E10B308F /* CodeBatchChatView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeBatchChatView.swift; sourceTree = ""; }; A190714D79AB52AA0A2AA7DA /* BighelpNotificationIdentityInstallationScopeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpNotificationIdentityInstallationScopeTests.swift; sourceTree = ""; }; - A196966B973298711CDD11ED /* AgentStartPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentStartPicker.swift; sourceTree = ""; }; A196AB02B4F486670EB8CBFB /* ChatComposer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatComposer.swift; sourceTree = ""; }; A1A136B4A7CA143CF46EFF26 /* GeneratedMediaView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedMediaView.swift; sourceTree = ""; }; A1DE79294A568DC5DD50BBD6 /* AppsHubView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppsHubView.swift; sourceTree = ""; }; A1E19430B8201A8AC2B59ADC /* AdvancedOptionsPages.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AdvancedOptionsPages.swift; sourceTree = ""; }; + A1EF3F596C4FEACFDC3F7340 /* SpacesTodayBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesTodayBridge.swift; sourceTree = ""; }; + A226807A61AF3E06372E3409 /* SpacesStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesStore.swift; sourceTree = ""; }; A24F8EDFED2D47FDF964F65C /* LocalizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalizationTests.swift; sourceTree = ""; }; - A266F3E6A29E081028EF481A /* FloatingTabBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FloatingTabBar.swift; sourceTree = ""; }; A2A64F7CE8F3CA117AE15906 /* ImageDraft.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraft.swift; sourceTree = ""; }; A2BE14FEDA589D81E489A8E5 /* BighelpWidgetGatewayPublisher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpWidgetGatewayPublisher.swift; sourceTree = ""; }; A2C2858573E9D2AA99968EC5 /* ChatToolCodeCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatToolCodeCellView.swift; sourceTree = ""; }; @@ -3554,6 +3632,7 @@ A3CF5F4CE86ACD833DFC0479 /* runs-signoff.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-signoff.json"; sourceTree = ""; }; A3D33D033FCD517C658D0299 /* GeneratedMediaModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedMediaModels.swift; sourceTree = ""; }; A3E97CB7C5A90AB58A055674 /* AgentDriveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDriveTests.swift; sourceTree = ""; }; + A4111B56D03996279BB006CC /* TodayBoardsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayBoardsStore.swift; sourceTree = ""; }; A423C5225CB5578027A4A41D /* ChatTranscriptProjection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatTranscriptProjection.swift; sourceTree = ""; }; A42541EDF5728C23F3CB3493 /* SessionCatalogStore+Load.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SessionCatalogStore+Load.swift"; sourceTree = ""; }; A44223CB9667024350A9D441 /* TemplateCatalogStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateCatalogStore.swift; sourceTree = ""; }; @@ -3565,7 +3644,6 @@ A55DAB5072E51C8D1AC15B64 /* OnDeviceVoiceInstaller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnDeviceVoiceInstaller.swift; sourceTree = ""; }; A574AF8E9AC1BDB9730BEF0B /* ChatToolReadableDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatToolReadableDetail.swift; sourceTree = ""; }; A598BF0A59557DF48DD3BD96 /* DirectHermesManagementLiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesManagementLiveTests.swift; sourceTree = ""; }; - A5A2475E246493163A55B6B3 /* BighelpModePill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpModePill.swift; sourceTree = ""; }; A5ACE26EC046A497C12D4047 /* UsageFixtures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageFixtures.swift; sourceTree = ""; }; A5AD2ED484B9562E3339F9AB /* WikiCreationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiCreationTests.swift; sourceTree = ""; }; A5D0A1510907BA587785DD40 /* ImageDraftDecisionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftDecisionsTests.swift; sourceTree = ""; }; @@ -3597,12 +3675,12 @@ A8A443E13F77F703CC88751D /* ReferenceWikiAdapterSections.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceWikiAdapterSections.swift; sourceTree = ""; }; A8B4B7166870C2C9A3CC6E33 /* TemplateVariablesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateVariablesTests.swift; sourceTree = ""; }; A8FF2070E38323168CEBF1E5 /* CodeModeUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeModeUITests.swift; sourceTree = ""; }; - A93F1D8C3BDEABBBE407101F /* AgentHomeDrawer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentHomeDrawer.swift; sourceTree = ""; }; A94D671CE12EC8AF785076DC /* ChatNativeMarkdownTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatNativeMarkdownTextView.swift; sourceTree = ""; }; A95DAFEF682C9D5378746749 /* FleetMaintenance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FleetMaintenance.swift; sourceTree = ""; }; A99087CC1EE92AC63D73DF39 /* ReferenceProviderAdapters.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceProviderAdapters.swift; sourceTree = ""; }; A9BF6BB7A009B0E756CC1048 /* runs-get-running.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-get-running.json"; sourceTree = ""; }; A9DDA46C8D5D94F4628360B5 /* AgentDuplicateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDuplicateView.swift; sourceTree = ""; }; + AA031A13A7DDB2CCF96B99A3 /* ChatsInboxView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatsInboxView.swift; sourceTree = ""; }; AA08F6E9FB1F09B8FD8F92D6 /* ConversationMessageWireModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationMessageWireModels.swift; sourceTree = ""; }; AA289C3474766DAA42835F53 /* DirectHermesNetworking.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesNetworking.swift; sourceTree = ""; }; AA6507F08B04CFD29333707E /* ChatSkillEditorSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatSkillEditorSheet.swift; sourceTree = ""; }; @@ -3626,6 +3704,7 @@ AD1C877CBBFBA2516F7DC78C /* ChatModel+Attachments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ChatModel+Attachments.swift"; sourceTree = ""; }; AD6614CC330F1A63E7373B9F /* SessionDraftMarkTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionDraftMarkTests.swift; sourceTree = ""; }; AD6FD6401E7772A4E6F302CD /* NotificationChatRoutingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationChatRoutingTests.swift; sourceTree = ""; }; + AD80F8ED097EE748E6EE2B15 /* TodayBoardPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayBoardPage.swift; sourceTree = ""; }; AD863B27A2D12B4D4BA415BF /* VoiceStepLine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceStepLine.swift; sourceTree = ""; }; ADBA5038A7DACA3C8A70AE75 /* ChatComposerActionButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatComposerActionButton.swift; sourceTree = ""; }; ADCC3B055B82A96326367C2B /* HermesFolderPath.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesFolderPath.swift; sourceTree = ""; }; @@ -3693,6 +3772,7 @@ B5EFC473F407C8EF9C1CE5BE /* templates-delete.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "templates-delete.json"; sourceTree = ""; }; B6042C0EC3B8B2FA6F5837C4 /* ProjectsLifecycleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectsLifecycleView.swift; sourceTree = ""; }; B6092D0840FB8FA27D82D26A /* HostRuntimeStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostRuntimeStore.swift; sourceTree = ""; }; + B61A7DB547372B52760235D4 /* NewChatSendRelay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatSendRelay.swift; sourceTree = ""; }; B6214AC1E602D0A74AA6F4BD /* WorkspaceEdgeSwipeResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceEdgeSwipeResolver.swift; sourceTree = ""; }; B626CC553921E60F230F7A70 /* ReferenceSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceSnapshot.swift; sourceTree = ""; }; B63050DDDB07FF271C12047D /* BighelpShare.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = BighelpShare.entitlements; sourceTree = ""; }; @@ -3711,12 +3791,14 @@ B7B48917975EC68FF7172C1E /* DemoImageDraftDestinations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoImageDraftDestinations.swift; sourceTree = ""; }; B7B99CFF0AD27EEAE58ECFBB /* AppCompositionSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppCompositionSupport.swift; sourceTree = ""; }; B7C415101BB0D4042CFBE194 /* PushDisplayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushDisplayTests.swift; sourceTree = ""; }; + B7C5981D12B64F22097298EE /* HomeHeaderBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeHeaderBar.swift; sourceTree = ""; }; B81B8950A6D2FC8F59414ED3 /* DirectHermesHostOperationsClient+BackupImport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DirectHermesHostOperationsClient+BackupImport.swift"; sourceTree = ""; }; B81E4D55F5AC3C4CBA3A8728 /* ChatTurnFailureCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatTurnFailureCard.swift; sourceTree = ""; }; B82073CABF9477908D2AF2A7 /* BighelpActivityHeroView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpActivityHeroView.swift; sourceTree = ""; }; B8439FC19E8957B01F36C2F3 /* HostToolBackendsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostToolBackendsView.swift; sourceTree = ""; }; B85E99EAB6136CE00D0E00B2 /* VerifiedHostConnection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VerifiedHostConnection.swift; sourceTree = ""; }; B8672869710139E39853CCCD /* DriveTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DriveTarget.swift; sourceTree = ""; }; + B87ED03DBD1643D84F6BFB7C /* SpacePanelView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacePanelView.swift; sourceTree = ""; }; B897D6B1FF7D4359BA874D89 /* ImageDraftLocalFile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftLocalFile.swift; sourceTree = ""; }; B8DA0185E6E99ACE4FACF1F5 /* ImageDraftsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDraftsUITests.swift; sourceTree = ""; }; B8FE80355509F8B363965132 /* DirectHermesSessionCatalogClient+ListRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DirectHermesSessionCatalogClient+ListRequest.swift"; sourceTree = ""; }; @@ -3733,6 +3815,7 @@ BA308CBE6AA81CCA15CBFACC /* AvatarCatalogStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvatarCatalogStore.swift; sourceTree = ""; }; BA52D1F7172AB517F1FDE6D1 /* BighelpMacFoundationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpMacFoundationTests.swift; sourceTree = ""; }; BA60D75DFF42E5BD94CFFEEE /* BighelpAlarmLiveActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpAlarmLiveActivity.swift; sourceTree = ""; }; + BA90CB3BCDCF4864F3B4EA64 /* SpacePanelStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacePanelStateTests.swift; sourceTree = ""; }; BA975C65014CEBC1F57EBA79 /* WikiDraftPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiDraftPersistence.swift; sourceTree = ""; }; BAA26E20211920FE4A58BCBD /* BighelpModelPickerSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpModelPickerSheet.swift; sourceTree = ""; }; BAA77B0CC309B9880FEEC281 /* CatalogStorefrontTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CatalogStorefrontTests.swift; sourceTree = ""; }; @@ -3755,6 +3838,7 @@ BD236D3F2FCE5C233ACAFBFD /* SkillDocumentMutationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillDocumentMutationTests.swift; sourceTree = ""; }; BD70C77DE16F0C5CDD82DD3E /* KanbanAvailabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanAvailabilityTests.swift; sourceTree = ""; }; BD7114FB1F13B6E3E9536820 /* runs-start-code.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-start-code.json"; sourceTree = ""; }; + BD862801EBAA40B5D76F8123 /* DemoSpacesClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoSpacesClient.swift; sourceTree = ""; }; BDCAFBE9F10F16C12A6D4203 /* WikiEditingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiEditingTests.swift; sourceTree = ""; }; BDDA296E17AEE83F9BF9EB5A /* NativeSessionRollbackReviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeSessionRollbackReviewView.swift; sourceTree = ""; }; BDF369BA5FA33CC75D4DC115 /* AgentAttachmentCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentAttachmentCache.swift; sourceTree = ""; }; @@ -3806,6 +3890,7 @@ C340AD81178E4864E29F460B /* WebRTC-LICENSE.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = "WebRTC-LICENSE.txt"; sourceTree = ""; }; C380E34BD7BE880470DB9EEB /* HostNotificationSetup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostNotificationSetup.swift; sourceTree = ""; }; C391D786C632E57338EFE988 /* SpatialAvatarPreview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpatialAvatarPreview.swift; sourceTree = ""; }; + C3A8B2CB8130C73F35DC4FB9 /* CodeCards.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeCards.swift; sourceTree = ""; }; C3EE16EA439C111EDA369B91 /* CarPlayVoiceUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CarPlayVoiceUITests.swift; sourceTree = ""; }; C4038907121A33524DF3B42C /* HostOperationsStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostOperationsStore.swift; sourceTree = ""; }; C41261A50D6785CC2FA66CF1 /* sealed-card-v1-vector.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "sealed-card-v1-vector.json"; sourceTree = ""; }; @@ -3880,7 +3965,6 @@ CD81C509ADE4E67B19BA9F6E /* BighelpActivityPose.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpActivityPose.swift; sourceTree = ""; }; CD8CEE35C3DA794958BBBB9B /* DirectHermesOwnedRPC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesOwnedRPC.swift; sourceTree = ""; }; CDA65FB5CDACAC184E55451B /* DirectHermesSessionCatalogRowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesSessionCatalogRowTests.swift; sourceTree = ""; }; - CDCFBB5C4E5985D8EC6C78FD /* AgentProfileSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentProfileSheet.swift; sourceTree = ""; }; CDDE2652D6BECAC1152A81D3 /* ChatBoardCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatBoardCard.swift; sourceTree = ""; }; CDE853A92392551EBA916C0E /* WikiNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiNavigation.swift; sourceTree = ""; }; CE0D46B41203E5ABB073CFB3 /* DeviceToolCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceToolCoordinator.swift; sourceTree = ""; }; @@ -3909,6 +3993,7 @@ D03BFF7A271F3D7D178354CF /* ChatDissolveTransitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatDissolveTransitionTests.swift; sourceTree = ""; }; D04DCAF7F90EF8190BB0B2A2 /* UsageStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageStore.swift; sourceTree = ""; }; D06C24D87C372A65A26A919F /* YouTubeVideo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YouTubeVideo.swift; sourceTree = ""; }; + D073861D277DC7E6AA6DACBB /* NewChatSendTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatSendTests.swift; sourceTree = ""; }; D07FA523BB682E8AC4A5E3DB /* ReferenceComposerTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceComposerTextView.swift; sourceTree = ""; }; D08151AC5B7909855D3D5CF9 /* ChatTranscriptCanvasCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatTranscriptCanvasCache.swift; sourceTree = ""; }; D0B441AAD6BA036D23DE6389 /* SimpleBotHostSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotHostSettings.swift; sourceTree = ""; }; @@ -3938,6 +4023,7 @@ D4BF8062D2F2C49ECB6B2A60 /* validate-v2.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "validate-v2.json"; sourceTree = ""; }; D4EE1DC2822C5FC210D90AE0 /* BighelpWindowAppearance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpWindowAppearance.swift; sourceTree = ""; }; D4F646E405205B3A5C8D7BED /* WorkspaceManagementLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceManagementLayoutTests.swift; sourceTree = ""; }; + D4F74FD537BF156A33F07D80 /* BotProfileMoreMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotProfileMoreMenu.swift; sourceTree = ""; }; D50DC8E2C99731C2D773E1E8 /* CompanionSurfacePhysics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompanionSurfacePhysics.swift; sourceTree = ""; }; D50FD3CA953DAFD527E101B6 /* DirectHermesAdmissionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesAdmissionTests.swift; sourceTree = ""; }; D5149D050C5E815198C4977A /* runs-agent.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-agent.json"; sourceTree = ""; }; @@ -3953,7 +4039,6 @@ D61D4A1568A237A5756BD16D /* SessionTodoSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionTodoSnapshotTests.swift; sourceTree = ""; }; D649D04AB7BA3BB227458334 /* BotModeRoomNotices.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotModeRoomNotices.swift; sourceTree = ""; }; D64C4FB90FC4173015F0A440 /* DirectHermesScheduledTasksClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesScheduledTasksClientTests.swift; sourceTree = ""; }; - D672F719F83A86A2B56F91E8 /* FleetListOrganizing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FleetListOrganizing.swift; sourceTree = ""; }; D67D3BE72C34629BEE766E8A /* CompanionAvatar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompanionAvatar.swift; sourceTree = ""; }; D69199DCA99C97BCF9890042 /* WorkspaceCredentialViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceCredentialViews.swift; sourceTree = ""; }; D6B24A7BAABCEB7CB0F47D9F /* DirectHermesInterfaces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesInterfaces.swift; sourceTree = ""; }; @@ -3972,13 +4057,13 @@ D7CCFDC793D0FC6199EB7D55 /* model-names.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "model-names.json"; sourceTree = ""; }; D803C10CAEDA47274EF5AD50 /* BighelpPointer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpPointer.swift; sourceTree = ""; }; D80BCA89F758946DC31CD4BA /* ArchivedChatsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArchivedChatsUITests.swift; sourceTree = ""; }; + D81EBA1C6A48BA0E8104698D /* SpacesWireTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesWireTests.swift; sourceTree = ""; }; D82428C63A55F2DA71FD7F87 /* BighelpDeliveryReceiptsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpDeliveryReceiptsTests.swift; sourceTree = ""; }; D83C10011F42314B0D8D4DD5 /* ChatAgentTalkRunPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatAgentTalkRunPanel.swift; sourceTree = ""; }; D885EEDB742B2589822E2135 /* WorkflowRunMonitorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowRunMonitorView.swift; sourceTree = ""; }; D8B9F6C28C72C0F51DAED539 /* AdvancedOptionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AdvancedOptionsTests.swift; sourceTree = ""; }; D8F3071F371FE6494DFEBF94 /* ReferenceWikiAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceWikiAdapter.swift; sourceTree = ""; }; D9077B726E569326920D99CB /* HostImportView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostImportView.swift; sourceTree = ""; }; - D91E97CBBCE0471255EBDF13 /* AgentGroupRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentGroupRowView.swift; sourceTree = ""; }; D927E9C5B53DDE1797A520AD /* IslandStage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandStage.swift; sourceTree = ""; }; D974E3909FD9B16C10964DAD /* OnDeviceVoiceModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnDeviceVoiceModel.swift; sourceTree = ""; }; D9853597BF6721C1FFA38C43 /* SubagentCanvasTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubagentCanvasTests.swift; sourceTree = ""; }; @@ -3988,13 +4073,16 @@ D9BDE066016389C9FFF8D00F /* BighelpPhysicalActivityTokenRegistrar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpPhysicalActivityTokenRegistrar.swift; sourceTree = ""; }; D9C5DE0DF1A13A4A2543DC9C /* WorkspaceGrantedFilesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceGrantedFilesTests.swift; sourceTree = ""; }; DA29847ABB2B6CF61029A960 /* SettingsPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsPresentation.swift; sourceTree = ""; }; + DA4DC8827D5C22B43B42CB9E /* BighelpNavigationGlass.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpNavigationGlass.swift; sourceTree = ""; }; DA72880EFC6357C4E04ABA5F /* BoardBlueprints.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoardBlueprints.swift; sourceTree = ""; }; DA795075264416409F0B1726 /* ProjectChangesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectChangesView.swift; sourceTree = ""; }; + DA853D5841E722A30CB58DC2 /* HTMLAppNavigationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTMLAppNavigationPolicy.swift; sourceTree = ""; }; DAABE5DC7098941E2DD8ECAD /* ObjectCardsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectCardsUITests.swift; sourceTree = ""; }; DAED33EFE39C435EEECF5599 /* BighelpPersonID.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpPersonID.swift; sourceTree = ""; }; DB0C6B1B426629EDA96C7ACC /* BighelpLiveActivityLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpLiveActivityLog.swift; sourceTree = ""; }; DB11B9CD72BA82F3CF4FC06E /* BotLook.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotLook.swift; sourceTree = ""; }; DB2FF592B8A04DEEFD7B17AF /* AgentMediaTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentMediaTests.swift; sourceTree = ""; }; + DB640E443FE6AB3A381C1FFD /* AgentStudioCaption.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentStudioCaption.swift; sourceTree = ""; }; DB83B642C9FCC3341B0169D4 /* BighelpSkeleton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpSkeleton.swift; sourceTree = ""; }; DBA59170E7E0197326FCAE8D /* AgentDirectoryStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentDirectoryStore.swift; sourceTree = ""; }; DBCD5BED0DF914830CCEA8A1 /* FleetSwitchFallbackTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FleetSwitchFallbackTests.swift; sourceTree = ""; }; @@ -4049,11 +4137,11 @@ E2A14692501D4ABFB17F76BB /* UsageStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsageStoreTests.swift; sourceTree = ""; }; E2B0B12CCADA6D8292B64AFA /* SimpleBotProfileView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotProfileView.swift; sourceTree = ""; }; E2C274F8CDDC43A089AC6DB9 /* BighelpAppearanceChoices.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpAppearanceChoices.swift; sourceTree = ""; }; - E2D043AD3DE1B95D66A8421C /* SimpleBotVoiceBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotVoiceBar.swift; sourceTree = ""; }; E2D90A74097F0FF386ACDEF3 /* KanbanCardView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanCardView.swift; sourceTree = ""; }; E2DC853C3341972B406D5AF9 /* DeferredVoiceSessionClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeferredVoiceSessionClientTests.swift; sourceTree = ""; }; E2F8FB47038C2E9A1EE89696 /* DirectHermesProjectClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesProjectClientTests.swift; sourceTree = ""; }; E331F48E29B807A93CCF34AA /* HermesGroupRoomSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesGroupRoomSettingsTests.swift; sourceTree = ""; }; + E3336318691E9CBE17531916 /* SpacesHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesHost.swift; sourceTree = ""; }; E360711FDD2AAA48FD1377BD /* ChatScreenMount.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatScreenMount.swift; sourceTree = ""; }; E396859ECB98B3DF97A81ED8 /* ChatAllModelsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatAllModelsView.swift; sourceTree = ""; }; E3B0CA3070A4651E7382A056 /* static-html-app.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "static-html-app.json"; sourceTree = ""; }; @@ -4063,6 +4151,7 @@ E3E24D8DB9EC2245F591AB76 /* WorkflowsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowsTests.swift; sourceTree = ""; }; E40A1FF4996A158205CECD0A /* NotificationChannelsUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationChannelsUITests.swift; sourceTree = ""; }; E45CBA02DF12767AE018CD15 /* SimpleBotDefaultVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotDefaultVoice.swift; sourceTree = ""; }; + E4687B186E93DDF76E573F8B /* TodaySpacesModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodaySpacesModel.swift; sourceTree = ""; }; E49CD214EF82602A9DBD0E24 /* NoodleUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoodleUITests.swift; sourceTree = ""; }; E4AAD53ECD449ACF5AE72CBF /* ModelProviderPlan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelProviderPlan.swift; sourceTree = ""; }; E4B3EF4DE0B3F0D3F8FF8DA5 /* ProfileLifecycleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileLifecycleView.swift; sourceTree = ""; }; @@ -4090,12 +4179,12 @@ E7D61D803AFF04ABB33D6171 /* PluginUpdateStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PluginUpdateStore.swift; sourceTree = ""; }; E7F77F33887EFC9676338781 /* SettingsLayoutUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsLayoutUITests.swift; sourceTree = ""; }; E807EED6B0FB41B0B40AD51B /* NativeLifecycleWiringTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeLifecycleWiringTests.swift; sourceTree = ""; }; - E827A96DEF163977F50C25C4 /* AppLayoutUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLayoutUITests.swift; sourceTree = ""; }; E8281B9CB87395A29B8C307B /* runs-get-code-command.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "runs-get-code-command.json"; sourceTree = ""; }; E870F072CBA0B66AC95493FB /* SimpleBotsSearchView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotsSearchView.swift; sourceTree = ""; }; E884434B41BFED4DC5BB92D4 /* DemoHosts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoHosts.swift; sourceTree = ""; }; E894A75421815361196871C4 /* HostOnboardingUITestSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostOnboardingUITestSupport.swift; sourceTree = ""; }; E8D7C03DCF4ECBC3DCED486C /* WikiNativeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiNativeTests.swift; sourceTree = ""; }; + E8E5581E4759087BDC795DA7 /* SpacesStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpacesStoreTests.swift; sourceTree = ""; }; E8EE605E09317091AADFEC31 /* WorkspaceReconnectPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceReconnectPolicyTests.swift; sourceTree = ""; }; E8F660F333A668B6DBEB99A8 /* SessionOpenLatencyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionOpenLatencyTests.swift; sourceTree = ""; }; E94C4E9BB8427AB94F813F4C /* WorkspaceOperationPerforming.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceOperationPerforming.swift; sourceTree = ""; }; @@ -4133,17 +4222,20 @@ EE5AC55A069EE69D5F01EA8C /* DeviceLocationToolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceLocationToolTests.swift; sourceTree = ""; }; EE77E909503B789EBF514EC9 /* PluginUpdateStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PluginUpdateStoreTests.swift; sourceTree = ""; }; EEAAC293921CC8A177EB54B7 /* NativeMessageSelectionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeMessageSelectionTests.swift; sourceTree = ""; }; + EEEA567FC87A8CA69A326CC2 /* TodayNeedsYouCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayNeedsYouCard.swift; sourceTree = ""; }; EF0FC423CD328CD1CD1ADF2B /* ClipboardDraftTextEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClipboardDraftTextEditor.swift; sourceTree = ""; }; EF1723D5FD7AC0CB0201BF60 /* ScheduleRequestBuilderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleRequestBuilderTests.swift; sourceTree = ""; }; EF236F5F22907E090A58AC18 /* GitHubJSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubJSON.swift; sourceTree = ""; }; - EF768AB5BA4E7E7F91249A1D /* UnifiedModeToggleUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnifiedModeToggleUITests.swift; sourceTree = ""; }; + EF5A878B9936E443526A5F33 /* NewChatFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatFixture.swift; sourceTree = ""; }; EFA7E4FAA3985E6559B42726 /* DirectHermesAccessCredentialsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesAccessCredentialsTests.swift; sourceTree = ""; }; EFAB21B494DC7BB11FC84213 /* ReleaseScreensWalkthroughUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReleaseScreensWalkthroughUITests.swift; sourceTree = ""; }; EFBEF44DAA16CCE53311F44F /* SimpleBotFiles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotFiles.swift; sourceTree = ""; }; EFCF330DC54C68A0B1976995 /* ModelAdministrationFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelAdministrationFixture.swift; sourceTree = ""; }; + EFF8D000FF938312063CD8C2 /* NewChatSend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewChatSend.swift; sourceTree = ""; }; F00740F6A66C9CFF3D856113 /* DirectHermesBotChatActivityClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DirectHermesBotChatActivityClient.swift; sourceTree = ""; }; F01086DE6C5EB56F04C92807 /* ChatImageStack.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatImageStack.swift; sourceTree = ""; }; F07E7992D0F6174A8A459896 /* LongChatPerformanceFixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LongChatPerformanceFixture.swift; sourceTree = ""; }; + F090FA90D6797435F1D83FE7 /* TodayPanelGrid.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayPanelGrid.swift; sourceTree = ""; }; F09B103CE58F5458BB1F76A6 /* YouTubeEmbedTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YouTubeEmbedTests.swift; sourceTree = ""; }; F0BEC630295845F372BFA4B4 /* GeneratedMediaLifecycleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneratedMediaLifecycleTests.swift; sourceTree = ""; }; F0D60AE6AED500202DACAA94 /* PendingShareComposerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PendingShareComposerTests.swift; sourceTree = ""; }; @@ -4158,6 +4250,7 @@ F19950FC182073DB19EF1F9D /* TeamCallSpeechPipeline.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TeamCallSpeechPipeline.swift; sourceTree = ""; }; F1CCD48AB707E4FB6E740F7B /* SimpleBotsChatOpening.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleBotsChatOpening.swift; sourceTree = ""; }; F1DB559BCA138130360AAB97 /* KanbanBoardModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KanbanBoardModelTests.swift; sourceTree = ""; }; + F1EE295BE87CDDA311DDC298 /* HomeSidebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSidebar.swift; sourceTree = ""; }; F1FF50374D94C106E4CE34A4 /* BighelpPinnedAgentsWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpPinnedAgentsWidget.swift; sourceTree = ""; }; F2038A52DC5309296BB3CB20 /* NotificationPresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationPresentationTests.swift; sourceTree = ""; }; F203AC6A3ECC9F563034515E /* BighelpHuggingWidth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpHuggingWidth.swift; sourceTree = ""; }; @@ -4188,13 +4281,13 @@ F5639CCA1C95FC8441701764 /* WorkflowEditingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowEditingTests.swift; sourceTree = ""; }; F58C1F4CA05FD6B2C5C2631E /* ChatFolderBrowser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatFolderBrowser.swift; sourceTree = ""; }; F5AC35A79ACACE81F456243E /* list.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = list.json; sourceTree = ""; }; + F5F345BA3A10B8E6D2A5274F /* WorkView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkView.swift; sourceTree = ""; }; F605047400252670A1610388 /* WikiDraftStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WikiDraftStore.swift; sourceTree = ""; }; F612CF2AD1CD6C6CF51B1A50 /* WorkflowPublishBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowPublishBar.swift; sourceTree = ""; }; F62835AF1B54DF0076781B3E /* ReferenceCodec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceCodec.swift; sourceTree = ""; }; F6370FE65444B974BB2D3DA1 /* SkillsAndToolsCatalogContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillsAndToolsCatalogContent.swift; sourceTree = ""; }; F67531847A62207D0A37AEBB /* AvatarCatalogKit.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = AvatarCatalogKit.json; sourceTree = ""; }; F69C0374B3943429B3465FDF /* ProviderUsageHostUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderUsageHostUITests.swift; sourceTree = ""; }; - F6C9097DA71E5B36A26C212E /* PluginUpdateSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PluginUpdateSection.swift; sourceTree = ""; }; F6CBA45744D6CCCFEE5F627D /* RootWorkspaceActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootWorkspaceActions.swift; sourceTree = ""; }; F70C369BED1601B4EBA57E41 /* GitHubResourceProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GitHubResourceProvider.swift; sourceTree = ""; }; F743DA1E968F0FFED28C304F /* ThinkingLooksScenes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingLooksScenes.swift; sourceTree = ""; }; @@ -4208,11 +4301,9 @@ F8864550F66BDF61AD736AA9 /* SkillsHubManagementView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillsHubManagementView.swift; sourceTree = ""; }; F88EB8201529B07C80DE0C9B /* HermesBotModeActivityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HermesBotModeActivityTests.swift; sourceTree = ""; }; F8FCB52A58D38CE645CCA340 /* GeminiLiveAudioReport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeminiLiveAudioReport.swift; sourceTree = ""; }; - F8FFBC9B200835B3E101AA83 /* BighelpMenuUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpMenuUITests.swift; sourceTree = ""; }; F912878C67A0C542FCEA2078 /* NativeWorkspaceSavedOpenLiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeWorkspaceSavedOpenLiveTests.swift; sourceTree = ""; }; F91AB3213E2C4E85CBED57B4 /* ConversationClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationClient.swift; sourceTree = ""; }; F92374C41F49709D66355D8A /* AgentHelperModelsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentHelperModelsTests.swift; sourceTree = ""; }; - F92745044C01ED431726BEDF /* BighelpTabGlyphTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BighelpTabGlyphTests.swift; sourceTree = ""; }; F94895E4E66A6F087A9145D6 /* CodeLauncher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodeLauncher.swift; sourceTree = ""; }; F9503615B7D15F3AE2096661 /* ProviderDisplayNameTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProviderDisplayNameTests.swift; sourceTree = ""; }; F972D8331BE114EEEEE074F0 /* SessionCatalogLargeWorkspaceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionCatalogLargeWorkspaceTests.swift; sourceTree = ""; }; @@ -4226,7 +4317,6 @@ FB4584A9DDB822B7E5E5AD1C /* WorkflowCode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkflowCode.swift; sourceTree = ""; }; FB4F78E4AFF7D918C452079F /* ReferenceGitHubAdapterSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReferenceGitHubAdapterSnapshot.swift; sourceTree = ""; }; FBA20F460ABD2525AE3BF756 /* NeedsYouBlueprintsModesUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NeedsYouBlueprintsModesUITests.swift; sourceTree = ""; }; - FBB1CCEF5EE02CA14CAFD9A3 /* AppLayoutSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLayoutSettingsView.swift; sourceTree = ""; }; FBCFB9A0E5579974EAC62DEE /* ChatCompletedTurnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatCompletedTurnTests.swift; sourceTree = ""; }; FBE7E5A269ED395BA4834BB7 /* AgentHandleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentHandleTests.swift; sourceTree = ""; }; FBEE99F7C37EFBAE04EC7160 /* BotsWidgetUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotsWidgetUITests.swift; sourceTree = ""; }; @@ -4458,6 +4548,37 @@ path = Workflows; sourceTree = ""; }; + 19C256D99F2716948DE3EE80 /* Work */ = { + isa = PBXGroup; + children = ( + 407581F24811888F32AEF469 /* WorkCards.swift */, + 901B9368C8FF33D186FA7426 /* WorkDoors.swift */, + 2AAB566FE7CD9FCB1622B0C2 /* WorkFixture.swift */, + 94966B58C7C316950BD235FB /* WorkItem.swift */, + 07DFD6584189183A9CB646A8 /* WorkProjection.swift */, + F5F345BA3A10B8E6D2A5274F /* WorkView.swift */, + ); + path = Work; + sourceTree = ""; + }; + 1A9662732150AC962E2C2FF2 /* Home */ = { + isa = PBXGroup; + children = ( + 63F611B65636A8E2749EE9B8 /* HomeChromeFixture.swift */, + 938394CBC82D25F1D3D74000 /* HomeContracts.swift */, + B7C5981D12B64F22097298EE /* HomeHeaderBar.swift */, + 72EFBA3EEB1AC550F4611C79 /* HomeMenuPresentation.swift */, + 7E2BB3763EC1668CE0F9BBF0 /* HomeSelection.swift */, + F1EE295BE87CDDA311DDC298 /* HomeSidebar.swift */, + 12F13ECE65C76FAE69B91F89 /* HomeStripTabs.swift */, + 25550A0A0F3821ADED7FEDBE /* HomeTabBar.swift */, + 433095D96A00DF67C1DEF48F /* HomeTabOrnament.swift */, + 7CA67713A8A847B06EA02E57 /* Chats */, + 3BAEAFF7CE5EFFFFDA594143 /* NewChat */, + ); + path = Home; + sourceTree = ""; + }; 1AA7B1E28C535C6F0BD237BB /* Notifications */ = { isa = PBXGroup; children = ( @@ -4638,10 +4759,8 @@ 419249A452E114FBDD04C000 /* AgentBoardViews.swift */, 916BA766E72BFBA579E1C614 /* AgentGoalsView.swift */, 9A51D920C9BAB00A0B245CFD /* AgentHomeChrome.swift */, - A93F1D8C3BDEABBBE407101F /* AgentHomeDrawer.swift */, 89765C6E0EFED004E535524D /* AgentLiveAvatar.swift */, D7039EBD45CE3DBB7D8555F6 /* AgentMedia.swift */, - CDCFBB5C4E5985D8EC6C78FD /* AgentProfileSheet.swift */, C6EB2B60EAB7C5174D9D7542 /* AgentToday.swift */, 7854C8ABE2067EF6C0779F70 /* AgentTodayDetail.swift */, 7437B65BFB4AFEE0CCB68086 /* BighelpActivityAvatarWriter.swift */, @@ -4660,6 +4779,21 @@ path = Board; sourceTree = ""; }; + 3BAEAFF7CE5EFFFFDA594143 /* NewChat */ = { + isa = PBXGroup; + children = ( + 7D91EA7C155C5C7DDF393261 /* NewChatChoicesRow.swift */, + EF5A878B9936E443526A5F33 /* NewChatFixture.swift */, + 5FD879BB6C04AF91AB35FBEA /* NewChatHandoff.swift */, + 341899D306173E3A6BF70917 /* NewChatRecipients.swift */, + EFF8D000FF938312063CD8C2 /* NewChatSend.swift */, + B61A7DB547372B52760235D4 /* NewChatSendRelay.swift */, + 8B998C39CEDFC9B00D736014 /* NewChatSession.swift */, + 0469E9BECD9BD8B61F3E04F6 /* NewChatView.swift */, + ); + path = NewChat; + sourceTree = ""; + }; 436BB2A1A9C3E8D071F3CC5F /* CompanionSurfaces */ = { isa = PBXGroup; children = ( @@ -4833,6 +4967,8 @@ isa = PBXGroup; children = ( A5E446967E12033D002DF036 /* BotActiveProjectView.swift */, + 7ECCC126A47FD48754D1E82F /* BotProfileDetails.swift */, + D4F74FD537BF156A33F07D80 /* BotProfileMoreMenu.swift */, 2648FA24305F0FA49895B39C /* BotProfileOpening.swift */, C6A5452A79F7ADB8D480C39D /* CoreFiles.swift */, 0E07205449A8A98669AD732C /* SimpleBotCreateView.swift */, @@ -4856,7 +4992,6 @@ C6D5ABF5E4CE7FD36AF3820A /* SimpleBotsSwitcher.swift */, 2D3CFECA336C5F41FF704F2B /* SimpleBotTemplates.swift */, FEB67FBB2D69C2D2ADC26F4A /* SimpleBotTimeZonePicker.swift */, - E2D043AD3DE1B95D66A8421C /* SimpleBotVoiceBar.swift */, ); path = SimpleBots; sourceTree = ""; @@ -5008,6 +5143,22 @@ path = BighelpMacTests; sourceTree = ""; }; + 78CBADBFD487014AB14F7C14 /* Today */ = { + isa = PBXGroup; + children = ( + AD80F8ED097EE748E6EE2B15 /* TodayBoardPage.swift */, + 6A670996B08FE4B02F6189B0 /* TodayBoardsPanel.swift */, + A4111B56D03996279BB006CC /* TodayBoardsStore.swift */, + 7220AEB50241663CD55FCCEC /* TodayFixture.swift */, + EEEA567FC87A8CA69A326CC2 /* TodayNeedsYouCard.swift */, + 19C19DC5D809E5B14A9EC002 /* TodayNotice.swift */, + F090FA90D6797435F1D83FE7 /* TodayPanelGrid.swift */, + 8628FAF07244D8889C7BE975 /* TodayPanelLayoutStore.swift */, + 8ACCD154FBFC52C597F6885C /* TodayView.swift */, + ); + path = Today; + sourceTree = ""; + }; 7B54EC2A3CFF7D291A809232 /* Resources */ = { isa = PBXGroup; children = ( @@ -5032,6 +5183,17 @@ path = Resources; sourceTree = ""; }; + 7CA67713A8A847B06EA02E57 /* Chats */ = { + isa = PBXGroup; + children = ( + 5108A9609A6F74C9F35402CB /* ChatsInboxFixture.swift */, + 9BE3DF440F6B8CF977E52DF2 /* ChatsInboxProjection.swift */, + 2F1EBF478C30A24456E26A25 /* ChatsInboxRow.swift */, + AA031A13A7DDB2CCF96B99A3 /* ChatsInboxView.swift */, + ); + path = Chats; + sourceTree = ""; + }; 7D1B4FE7033C33D1D6F2D429 /* SoulTemplates */ = { isa = PBXGroup; children = ( @@ -5141,7 +5303,6 @@ 82F76A4A76555AA8C6776687 /* BighelpBackgroundGrace.swift */, 4AD4B5D1DA594EE46275CCA9 /* BighelpBotsWidgetFeed.swift */, 4903CB5D015E3FA9F21B0F19 /* BighelpExternalSessionOpen.swift */, - 42596C8500B087541B4547CB /* BighelpHostSwitcherLockup.swift */, 80BB3AA765DC6032DB384CB3 /* BighelpIncomingURLRoute.swift */, 96606583761B6B677044DEBB /* BighelpKeyboard.swift */, 89AE53B34B50D30485E7053F /* BighelpLanding.swift */, @@ -5151,7 +5312,6 @@ 764549B50FCE1851F2CE76A7 /* BighelpMenu.swift */, 7BC29ED35D8D397DB63CC944 /* BighelpMenuCommands.swift */, C3343ABABDB79BADCF447EEF /* BighelpMenuRow.swift */, - A5A2475E246493163A55B6B3 /* BighelpModePill.swift */, B5D53C2B79F59FC36E3E2ABE /* BighelpPinnedAgentsWidgetFeed.swift */, 171EC4C4FCD5B6442AB8A2E0 /* BighelpRuntimeConfiguration.swift */, 21D5F1F7073125CA2EC42B19 /* BighelpSessionContentReader.swift */, @@ -5183,10 +5343,12 @@ 41F9EB6894454B1B3580988F /* RootDestinations.swift */, 55FCA29550754E1842C5209C /* RootFleet.swift */, 8EA377D3701B3F86FEF078F3 /* RootFreshSession.swift */, + 45C970BDD3E46D550BEF79C2 /* RootHome.swift */, 064E0E78CD6C7255C6EC0E57 /* RootKanban.swift */, 583BA6F94639B8B2ECA04CA9 /* RootMarketplace.swift */, 8DB6D75DD31D1C5BE64C62A3 /* RootNavigationViews.swift */, 5C17768C63B72EE9A3E30406 /* RootNeedsYou.swift */, + 82B229D6F8990CA2258211D5 /* RootNewChat.swift */, CC967019FBCCB0BF5A9C860D /* RootPendingShares.swift */, 86A4501FBA77CB8F1BCE049E /* RootPresentationContracts.swift */, 0CFDE9A3FCBD442C3CCA73BF /* RootScheduledAlerts.swift */, @@ -5289,8 +5451,6 @@ 8DFEF1915617586F476069EA /* Agents */ = { isa = PBXGroup; children = ( - 5068277073666FC21BE690A9 /* AgentActions.swift */, - 93BE73F918F3EED5F80259F6 /* AgentActionSheet.swift */, 4350B3112132634E6AE0A0F4 /* AgentCompanionAvatarRenderer.swift */, 4F87A3EBF6FBA713BE641EC3 /* AgentCreationCloneSelection.swift */, 5D49BDC3EAAE5B94D33EF04B /* AgentDefaultModelsView.swift */, @@ -5299,25 +5459,18 @@ EBCCCAC2ABC048282724A2A4 /* AgentDuplicateModel.swift */, A9DDA46C8D5D94F4628360B5 /* AgentDuplicateView.swift */, E5C08B6704459B497589E2B3 /* AgentEditorModel.swift */, - 93C3C53CDF672AC9FDB30C6D /* AgentEditorView.swift */, - 3AB7B41F130CAF111F94C162 /* AgentFastModeRow.swift */, - D91E97CBBCE0471255EBDF13 /* AgentGroupRowView.swift */, 83807284839F9DB96E27F21F /* AgentHandle.swift */, 16749C054F394CF679ABD67D /* AgentHelperModels.swift */, BE1A610BA96C081B382CCF04 /* AgentModels.swift */, - 7FDF4E08DF2A7F5CBC393F11 /* AgentPinnedGrid.swift */, C1E367076F7639DD9CC52BCA /* AgentProfileCloneClient.swift */, 82585A099C0B2200151BF919 /* AgentProfileID.swift */, - 5DAE06C366386CEA7ABCDF84 /* AgentRowView.swift */, 732B24883CC1D3F35E2F66BF /* AgentRuntimeDefaults.swift */, 7BC5790C6EA24CF21A6B814A /* AgentRuntimeDefaultsEditorModel.swift */, - 6887CF181F29248E7BEA6CC6 /* AgentRuntimeDefaultsSection.swift */, - 8D379559BEB94B7580AEFD29 /* AgentsDirectoryComponents.swift */, 80B9D3C7D1ACB2DDE58773C8 /* AgentShortcutsView.swift */, 49CE092FE72E674CAE173EDE /* AgentSoulTemplates.swift */, 9E07486D08776DE6DC09087A /* AgentsPresentation.swift */, - A196966B973298711CDD11ED /* AgentStartPicker.swift */, - 3EE9EB659F86107004A3BEE6 /* AgentsView.swift */, + 322A3C7A5248CE931D627A74 /* AgentsSectionCaption.swift */, + DB640E443FE6AB3A381C1FFD /* AgentStudioCaption.swift */, 6B51E351013BB3D09F5BF96A /* AgentTemplateBrowser.swift */, 0F108CDF2AF7D1B53DC2FE7B /* AgentTemplateFillView.swift */, 363125E35F32B409045A5DD4 /* AgentTemplateLibrary.swift */, @@ -5387,18 +5540,16 @@ children = ( 78705B25A7D9D785DC421550 /* AppearanceSizeControls.swift */, 853942665777C89A188608DD /* AppearanceStudioView.swift */, - 7585C28F626CAE1CA1403BF6 /* AppLayout.swift */, - FBB1CCEF5EE02CA14CAFD9A3 /* AppLayoutSettingsView.swift */, E23D2ABE5C87A42EEE580AC8 /* BighelpNotificationContext.swift */, F3017A55790BCADA03551370 /* BighelpNotificationSettingsView.swift */, 9EFF30AB0E3CE7D1E90D7DFD /* BighelpPluginUpdateClient.swift */, C4826215D89788776EBFE0F3 /* BighelpVoiceSettingsClient.swift */, 9B6C2E9F7E97E148B6F57E26 /* ChatLayoutSettingsView.swift */, + 75AB021D2A15E98A55C24DC1 /* HomeSettingsMigration.swift */, 90F37C5331CA364A0C713127 /* HostRuntimeSection.swift */, B6092D0840FB8FA27D82D26A /* HostRuntimeStore.swift */, 94977376DF9FE2BF6A3793D7 /* ModelsSettingsView.swift */, 43DC33ACEF48388887235EEE /* OnDeviceVoiceSettings.swift */, - F6C9097DA71E5B36A26C212E /* PluginUpdateSection.swift */, E7D61D803AFF04ABB33D6171 /* PluginUpdateStore.swift */, 1C8285C25EF405257D9D5A7D /* RetiredChatAppearance.swift */, 7E2D22067ABBEB0D4D724FBE /* SettingsDestination.swift */, @@ -5407,7 +5558,6 @@ 67F0B31843F2BBB8FE261D76 /* SettingsStore.swift */, 743A8422BB20CF6C30B55B4B /* SettingsView.swift */, 159656CBEFF9E3A8CCFF7715 /* SettingsView+Computers.swift */, - 9720EBAF47E4E42E8C8B48C8 /* SettingsView+Experience.swift */, 2311CDD0D0FDF41C4E377226 /* SettingsView+Identity.swift */, C0895D54237F25417076950B /* SettingsView+LocalData.swift */, 11CFFEC0DBBAF848BB1380A6 /* SettingsView+Menu.swift */, @@ -5496,7 +5646,6 @@ A15863BCEAD74614DD39B039 /* AgentVoiceChoicesTests.swift */, B5B9F82EEB2541BEE9642460 /* AIDataConsentTests.swift */, 568BD9C6A4BF6FE13070369B /* AppearanceChoicesTests.swift */, - 6772541AD53BC7065CD5D78C /* AppLayoutTests.swift */, 97E85DBCBB8DDC592F728728 /* AppleDeviceToolServiceTests.swift */, 523FAEE099C696A0EB986626 /* ApprovalModelTests.swift */, A6B2A7B45E20343405BED0A9 /* AppStateSyncTests.swift */, @@ -5560,7 +5709,6 @@ 935843A247F6DB9DB6899AC0 /* BighelpShortcutServiceTests.swift */, A4C635A2879E0F34F2D33F7D /* BighelpSideMenuTests.swift */, 8C3001BE0BE59F9103945CC0 /* BighelpSurfaceTests.swift */, - F92745044C01ED431726BEDF /* BighelpTabGlyphTests.swift */, 579F050808B1CE8C5147D10F /* BighelpThinkingOrbTests.swift */, 7D4904A446410A6BC1300EE6 /* BighelpToolActivityCatalogTests.swift */, DCAF3D623834C0CE6C667AAD /* BighelpUsageWidgetRenderTests.swift */, @@ -5576,6 +5724,7 @@ 7773C53167EE878A8E8CF470 /* BotModeRoomStoreTests.swift */, 2C2051CDE611EC630D846F17 /* BotModeRunTests.swift */, 33E4EB272EA68374E3B3E748 /* BotModeStopTests.swift */, + 42C37CAEBF941CE56AEC027B /* BotProfileActionsTests.swift */, 68CA13151991BF1069B9CFC9 /* BotProfileOpeningTests.swift */, E7638A9EA643D13DFA9FF59E /* BotsAppStateTests.swift */, 4325F750432EFB2A83F5FC52 /* BotScreenRFBTests.swift */, @@ -5634,6 +5783,7 @@ 13D4CCAF0FE56A9CDE0E8C2C /* ChatSendWhileConnectingTests.swift */, C921117448BFD93E2B732354 /* ChatSessionTitleHeaderTests.swift */, 0F12CCB3615A7FC9AC3615C1 /* ChatSilentReplyTests.swift */, + 6C332FB058A8999F4E5B17A3 /* ChatsInboxProjectionTests.swift */, 0ECE93E481399A4306DBACFC /* ChatStreamingTextTests.swift */, C5C5208F6702E30ED928E2AC /* ChatTimelineBuiltRowsTests.swift */, BE10504C7ACA6DAC0F72C9B1 /* ChatTimelineKeptRowsTests.swift */, @@ -5651,6 +5801,7 @@ 21F642B03F9BC79D235BA847 /* ClipboardImporterTests.swift */, B9B2BE24717336EE27018F9A /* CodeBatchTests.swift */, 6AB9122D29E69588B293F502 /* CodeModeTests.swift */, + 4B075D7D83BBC4A23C03B5C1 /* CodeSessionStatusReaderTests.swift */, 658B59C231EAF42CD31649DE /* CompactChatComposerTests.swift */, 0AF9B290647073A148F1F303 /* CompanionComposerPathTests.swift */, 8BB7964381C21043CA68DB0D /* CompanionPhysicsTests.swift */, @@ -5758,6 +5909,8 @@ 5BBEF3DFBAB691CE1CD31DD9 /* HermesGroupsHostPathTests.swift */, 4D88AAE29CD127FD229FF04B /* HermesLogsTests.swift */, 1C1110763B724D51E070E0B1 /* HermesUserMessageDisplayTests.swift */, + 7BA6C9356310A75F99AE911C /* HomeChromeTests.swift */, + 6515EF2C7EF2A6FC8041124C /* HomeSettingsMigrationTests.swift */, CFF0176BACFC11059D4F8A6F /* HostActivityRenderTests.swift */, 71AB75411B7397CFAC2B5AE0 /* HostConnectionStatusTests.swift */, 4633A8076FD7DC2B28F17301 /* HostListSizeTests.swift */, @@ -5768,6 +5921,7 @@ 5ABF63171EFA2FB67EB1ABBA /* HostSignInMethodTests.swift */, 29F06E37F0A613811E19F212 /* HostStatusDiscoveryTests.swift */, 35B1687221981CFB4772FD42 /* HostUsageLoaderTests.swift */, + 056F1D91C370B7F7DA5585BC /* HTMLAppNavigationPolicyTests.swift */, 6DA7B55CB98F303563E3B3EE /* HTMLAppTests.swift */, 311F65DA16FD3A19442C1D03 /* ImageActionsSettingsTests.swift */, BB3D4F4312A3269B02562FB0 /* ImageDraftCardTests.swift */, @@ -5804,7 +5958,6 @@ 06E0752CDEB93F69DFC3661C /* ModelNameCatalogTests.swift */, EC5FC19EDFA0F25D3A66F291 /* ModelProviderPlanTests.swift */, 11073DDD6A9E23FFD6048851 /* MyTemplatesTests.swift */, - 380D86D09ADE0D64E0E00DE9 /* NativeAgentCreationVisualTests.swift */, C57D8A18708453461E88F17A /* NativeContinuousStreamLiveTests.swift */, 6889347DEEE3C4D54499D7E5 /* NativeDeviceToolSessionTests.swift */, 8FC3A1BCA9FC5B6364FD9CF9 /* NativeFileProductionTests.swift */, @@ -5823,6 +5976,9 @@ CFD2EB9171DAF6783C60499D /* NativeWorkspaceSessionBridgeTests.swift */, 0CC87D2B2C1511FADA193002 /* NeedsYouBlueprintsModesTests.swift */, 796D456E65153197E2D8FF67 /* NewChatCoordinatorTests.swift */, + 3A0023FA904FEED13C2B7682 /* NewChatPickTests.swift */, + 008725B5A36A63BFFDA30E0D /* NewChatRecipientsTests.swift */, + D073861D277DC7E6AA6DACBB /* NewChatSendTests.swift */, D7300A82F304603F649DDD43 /* NotificationBundleConfigurationTests.swift */, AD6FD6401E7772A4E6F302CD /* NotificationChatRoutingTests.swift */, 0B84DEB699D5F14D678A55A5 /* NotificationErrorCodeTests.swift */, @@ -5847,7 +6003,6 @@ C2A5D4E05C574182D219973E /* PluginMarketplaceTests.swift */, EE77E909503B789EBF514EC9 /* PluginUpdateStoreTests.swift */, BE5198D653522270B0E3E3BD /* PluginUpdateWorkspaceClientTests.swift */, - 7D6F7B0C6B71878310AF32D1 /* PrimaryNavigationSelectionTests.swift */, C57D31192F1D92F6F8B4E2B5 /* ProductionVoiceSessionTests.swift */, F4BA8B35DA3A81885AD5F235 /* ProfileDeletionTests.swift */, BE4CFE251DBC65B055ECEB92 /* ProfileLifecycleStoreTests.swift */, @@ -5904,6 +6059,10 @@ BD236D3F2FCE5C233ACAFBFD /* SkillDocumentMutationTests.swift */, 34EF80804B4ED118D93BBBD0 /* SkillMutationLifecycleTests.swift */, 034E5A8037D7BE0AEA14BFC0 /* SkillsAndPluginsHostShapeTests.swift */, + 01ACA08D84DDE576D1756E14 /* SpaceDraftCardStateTests.swift */, + BA90CB3BCDCF4864F3B4EA64 /* SpacePanelStateTests.swift */, + E8E5581E4759087BDC795DA7 /* SpacesStoreTests.swift */, + D81EBA1C6A48BA0E8104698D /* SpacesWireTests.swift */, D9853597BF6721C1FFA38C43 /* SubagentCanvasTests.swift */, 72B7397F7D4D61EB688CC8B4 /* SubagentControlTests.swift */, CE55F4616453540B7AC56768 /* TeamCallTests.swift */, @@ -5919,8 +6078,10 @@ A8B4B7166870C2C9A3CC6E33 /* TemplateVariablesTests.swift */, 7E96E0B1F96BAC7D40775D94 /* ThemePresetTests.swift */, 617258D76E52A913FC6044EF /* ThinkingLadderTests.swift */, + 6D97ED75999EE9AF01D2C143 /* TodayBoardsStoreTests.swift */, + 6E2FCD0CE3A5F9E9513CB461 /* TodayPanelLayoutTests.swift */, + 23170C47F20C59BE05E144B4 /* TodaySpacesModelTests.swift */, 4A5EDC5345FB3A9ED8908CC6 /* ToolDisclosureHydrationTests.swift */, - 586E07FD677EADCB35B80837 /* UnifiedModeToggleTests.swift */, 1F192A98CA05B3B3D3C45AC8 /* UsageExportTests.swift */, 7E72EC67FC663AE543259A11 /* UsageLimitsComputersTests.swift */, E2A14692501D4ABFB17F76BB /* UsageStoreTests.swift */, @@ -5942,6 +6103,7 @@ E8D7C03DCF4ECBC3DCED486C /* WikiNativeTests.swift */, F5639CCA1C95FC8441701764 /* WorkflowEditingTests.swift */, E3E24D8DB9EC2245F591AB76 /* WorkflowsTests.swift */, + 4C32D94835AB8421789B59C0 /* WorkProjectionTests.swift */, 140A77E5360261714297C992 /* WorkspaceArtifactsTests.swift */, 17675B00C0F92D64834A179E /* WorkspaceEdgeSwipeResolverTests.swift */, 040B3A483026B7A85B75ED56 /* WorkspaceFolderChooserTests.swift */, @@ -5963,13 +6125,13 @@ C5749CB7646CC1449F2BA5EA /* CodeBatch.swift */, A1743EC57BBB9882E10B308F /* CodeBatchChatView.swift */, 3B84B943BBAB63CBF3543D7A /* CodeBranchName.swift */, + C3A8B2CB8130C73F35DC4FB9 /* CodeCards.swift */, 136185D2EA49575D03B47529 /* CodeChangesView.swift */, - 02889C4BAB355C04380A9EEC /* CodeComposer.swift */, CB4DF9151CCC62975FB4482F /* CodeHomeStore.swift */, - 18F68037ACD2B17DE44200C1 /* CodeHomeView.swift */, F94895E4E66A6F087A9145D6 /* CodeLauncher.swift */, 85C4A871CD36D30FAC91B4F1 /* CodeMentionTextView.swift */, 5A8A577E89C43DE9591CEE92 /* CodeModels.swift */, + 38B1CDE2956C9FF1683BE521 /* CodePickers.swift */, 075FAECB019B3FF463A04703 /* CodeProjectSource.swift */, 0BC199890AABD0D1F1BC71AD /* CodePullRequestsSheet.swift */, 68AF9DEA76190434247169F3 /* CodeSessionStatusReader.swift */, @@ -6069,12 +6231,8 @@ DD268648AC84425AD755C76C /* AgentDeletionUITests.swift */, 2E871FD3BCF7788448CADCFA /* AgentDriveUITests.swift */, 52FF8BDE2009ECF11CD36CD3 /* AgentFilesUITests.swift */, - 2DA1AB00CBFD4C4778E695C2 /* AgentOpenRealHostUITests.swift */, 76E7A796DFE3645505F61E05 /* AgentsUITests.swift */, 06D6BB21987E78CAF5995A40 /* AIDataConsentGateUITests.swift */, - 183FAAC3B2B524A603A53FB5 /* AllHostsHostUITests.swift */, - 59DC6DF119E780C3D98AA087 /* AllHostsUITests.swift */, - E827A96DEF163977F50C25C4 /* AppLayoutUITests.swift */, 49ED2DDD4856123984A84520 /* AppReviewHostUITests.swift */, E063E0682AC8293005BF72D6 /* AppStoreScreenshotUITests.swift */, D80BCA89F758946DC31CD4BA /* ArchivedChatsUITests.swift */, @@ -6082,7 +6240,6 @@ F23D5A6A8AF1BB90F50ED4BD /* BackgroundWorkHostUITests.swift */, 4E4529C210BF8B03ADCC3AEB /* BigFileChatUITests.swift */, 5BE2715903BE8E99DEEE051F /* BigFileHostUITests.swift */, - F8FFBC9B200835B3E101AA83 /* BighelpMenuUITests.swift */, 226B3E15639DDE404A0865BA /* BoardSwipeBlueprintsUITests.swift */, 896288A3A1DA7F3B71991B81 /* BotActivityHostUITests.swift */, E3CCA76D09B4A42D0FD343AB /* BotChatUITests.swift */, @@ -6091,7 +6248,6 @@ CE155427C34C90502C9B8AE8 /* BotScreenHostUITests.swift */, 50DF24CB6BEF6BD9383CCEBA /* BotScreenUITests.swift */, FBEE99F7C37EFBAE04EC7160 /* BotsWidgetUITests.swift */, - 4AEAE8B958F81AA860450230 /* BottomMenuUITests.swift */, E5F79F934C5B97C55FBDEB32 /* CardRepliesUITests.swift */, C3EE16EA439C111EDA369B91 /* CarPlayVoiceUITests.swift */, C130A87556531870129AFB11 /* CatalogStorefrontUITests.swift */, @@ -6138,6 +6294,7 @@ 2BD21A8FBBCA9AF95D546F15 /* FleetSettingsUITests.swift */, 74CF31E4691DBAABD234E2EE /* GroupSettingsUITests.swift */, 59CE897F445CA638FA3897BE /* HermesGroupsHostUITests.swift */, + 2FE55A8596FE2BA8F810C73E /* HomeShellUITests.swift */, E894A75421815361196871C4 /* HostOnboardingUITestSupport.swift */, 37C85FB08FD771ED53292DB4 /* HostSignInMatrixUITests.swift */, 9F825A925559FC87FEB69271 /* HTMLAppsHostUITests.swift */, @@ -6193,7 +6350,6 @@ 4108190EED2122E9485E02C6 /* ThinkingLookUITests.swift */, D9A549A54D7F65F13E87498A /* ToolCodeCellUITests.swift */, 2D1E11795B7E88BB7F60730C /* ToolDisclosureUITests.swift */, - EF768AB5BA4E7E7F91249A1D /* UnifiedModeToggleUITests.swift */, 997B937232851A556998C545 /* UsageNavigationUITests.swift */, 25672AE617255B86F0620D46 /* VoiceSettingsUITests.swift */, 60E050D2B298F1D866F2DFF1 /* VoiceShortcutUITests.swift */, @@ -6214,7 +6370,6 @@ children = ( 53F0572AA51437755324849A /* DemoRoomPeerHosts.swift */, CA803DD41158F462CBC22D43 /* FleetFixtureReader.swift */, - D672F719F83A86A2B56F91E8 /* FleetListOrganizing.swift */, A95DAFEF682C9D5378746749 /* FleetMaintenance.swift */, 30A97642BFC438C4DD69B21D /* FleetModels.swift */, FDF1096DDAAF5B03091930ED /* FleetSections.swift */, @@ -6234,6 +6389,7 @@ children = ( 576C17092288E8B64C86E78B /* DemoHTMLAppsClient.swift */, A6654DED276DCB0CC634A319 /* HTMLAppCardView.swift */, + DA853D5841E722A30CB58DC2 /* HTMLAppNavigationPolicy.swift */, DE7190310A1A07AE4E51577D /* HTMLAppsClient.swift */, 613EA998D71264182F07CAE0 /* HTMLAppScreen.swift */, 995C09E711CCBC8C7E46D975 /* HTMLAppScreenModel.swift */, @@ -6390,6 +6546,7 @@ E3B0CA3070A4651E7382A056 /* static-html-app.json */, 17867E65EFD1AF8D432F01FE /* static-image-drafts.json */, 46E55627383BAC697F21560D /* static-metrics.json */, + 3C40C08AB0B176B19A5E7DBC /* static-space-draft.json */, ); path = CardExamples; sourceTree = ""; @@ -6642,6 +6799,7 @@ B08CADB683DEC6627DBEF1E7 /* GitHub */, 85298FC426860F30C75C0143 /* Hermes */, F882A9C52CA5140EB1DD18F3 /* HermesPlugins */, + 1A9662732150AC962E2C2FF2 /* Home */, 90B0DAF2CF3AD177F76ACA6F /* Hosts */, B05120D4D90F2CB026399573 /* HTMLApps */, EC1DED5AD02635949F5D73A6 /* ImageDrafts */, @@ -6666,15 +6824,18 @@ 6A5390C41FC1214619896CE9 /* ShareShared */, DA26CE5DC0E8D308228DDFF0 /* Shortcuts */, 614BBCD37EA38E685C336160 /* SimpleBots */, + FD2495B1D34A031F948B9E34 /* Spaces */, E87317C0A68052515FF0062E /* Spatial */, F7BDA1F0B69019E1B083177B /* TeamCall */, 652FA55C6DBC560AFC328F33 /* Telemetry */, + 78CBADBFD487014AB14F7C14 /* Today */, 0BAF7D2800FACC10798E9071 /* Uploads */, F3F5C51CEEF50494AB4939B5 /* Usage */, 247984879E373A882C64A399 /* Vault */, C79D797A6ACE1F9CBC0CD6B8 /* Voice */, B95B2E2F2A230778B012776C /* Watch */, 9F9A13656CA293A51F559EAA /* Wiki */, + 19C256D99F2716948DE3EE80 /* Work */, FB4B3C19F043A2F61A4BA9F4 /* Workflows */, 133E6B04CB0D3D5CEEE9C77C /* Workspace */, 91023722101BC819A5316FA6 /* WorkspaceManagement */, @@ -6705,6 +6866,7 @@ A71E63C37770914A367700E4 /* BighelpModelChoiceRow.swift */, 8A05B4198AE1992F982E4DEF /* BighelpModelConfirmationModifier.swift */, BAA26E20211920FE4A58BCBD /* BighelpModelPickerSheet.swift */, + DA4DC8827D5C22B43B42CB9E /* BighelpNavigationGlass.swift */, 069FD09F2F97855A9292B399 /* BighelpPlatform.swift */, D803C10CAEDA47274EF5AD50 /* BighelpPointer.swift */, D3839FB429704BEC09A1DF03 /* BighelpRailCard.swift */, @@ -6721,9 +6883,9 @@ 60766A9532090D8E8A79ACE8 /* BighelpTokens.swift */, 84AA36F0115E0AB3D89F4D05 /* BighelpV2Style.swift */, D4EE1DC2822C5FC210D90AE0 /* BighelpWindowAppearance.swift */, - A266F3E6A29E081028EF481A /* FloatingTabBar.swift */, 0A044AC6EE1343EDBF6F530F /* FocusedTextEditor.swift */, 99DA80A4B1C3CBBFAC9DFA1B /* LongTextEditor.swift */, + 3EA7457F8492B531A665AC9E /* MacTileMenu.swift */, BC59500AEED985EECAA4D71F /* ModelNameCatalog.swift */, AF43FE7C65CE6F08A4870AA1 /* ModelNameCatalogStore.swift */, 42035E7783F34ECD1C61887F /* ProviderLogoRepository.swift */, @@ -7136,6 +7298,7 @@ 36E3B5F0213C68AE641282A2 /* ChatModelSummary.swift */, 1CF64A930FF6C4F681D96FB3 /* ChatNativeMarkdownRendering.swift */, A94D671CE12EC8AF785076DC /* ChatNativeMarkdownTextView.swift */, + 49C6C5B621D594D25819458C /* ChatNewChatSlot.swift */, 1941C3C4A19C2BFA1B4A9BC3 /* ChatPDFPagesDraft.swift */, 6D0A47577211899F827BFC71 /* ChatPendingCardView.swift */, 179723EE50D9141778E15E3C /* ChatPerformanceProbe.swift */, @@ -7299,6 +7462,26 @@ path = Workflows; sourceTree = ""; }; + FD2495B1D34A031F948B9E34 /* Spaces */ = { + isa = PBXGroup; + children = ( + 9F6A78A03D128C51B25B5CC3 /* BighelpAppSpaces.swift */, + BD862801EBAA40B5D76F8123 /* DemoSpacesClient.swift */, + 83E05FBFBD01ACEC622AD77E /* SpaceDraftCardView.swift */, + 258E9AEE85E8EC569A65A5A7 /* SpaceModels.swift */, + B87ED03DBD1643D84F6BFB7C /* SpacePanelView.swift */, + 57C4016E6EAD1B7E05838FDF /* SpacesClient.swift */, + 77961B6DA3CE5396EDCB297D /* SpacesFixture.swift */, + E3336318691E9CBE17531916 /* SpacesHost.swift */, + A226807A61AF3E06372E3409 /* SpacesStore.swift */, + A1EF3F596C4FEACFDC3F7340 /* SpacesTodayBridge.swift */, + 9F459BB26EC4023A79F7139E /* SpacesWire.swift */, + 3CC73679034D8C6500C601BC /* TodayCreateBox.swift */, + E4687B186E93DDF76E573F8B /* TodaySpacesModel.swift */, + ); + path = Spaces; + sourceTree = ""; + }; FEB73B139567EA4146800F9E /* GenerativeUIV2 */ = { isa = PBXGroup; children = ( @@ -7708,6 +7891,7 @@ 1F10FCEF2AA164E0700BFB76 /* static-html-app.json in Resources */, FD4B2BB6A6E341CFEA308648 /* static-image-drafts.json in Resources */, 9E007F87658B975FD9828BEE /* static-metrics.json in Resources */, + 7074B083148E080A6143AFDF /* static-space-draft.json in Resources */, 5FFD77BE4D90A9010292FDA4 /* status-offline.json in Resources */, 142F9375293DC17B5E1CEFCA /* status-v2.json in Resources */, B2D7B0A255CCAF48495AD44A /* status.json in Resources */, @@ -7813,8 +7997,6 @@ DCE2AEF72BAD507D236E11A5 /* AdvancedOptionsPages.swift in Sources */, 8650BF0E9E703D0C8FBFE086 /* AdvancedOptionsStore.swift in Sources */, 38179F67B905DED56E9CEA0B /* AdvancedOptionsView.swift in Sources */, - 2D664446DD8E3469E8F74DEF /* AgentActionSheet.swift in Sources */, - F3DDC06464DA83E58A7B8D52 /* AgentActions.swift in Sources */, D356E3E287F01733D8F8C359 /* AgentActivityIsland.swift in Sources */, 66413579683ED0EAD9A4A93F /* AgentAttachmentCache.swift in Sources */, 10EEF81E5F23C12501887BC9 /* AgentBoard.swift in Sources */, @@ -7827,34 +8009,26 @@ 2517EC3B67275424C379852D /* AgentDuplicateModel.swift in Sources */, 4ED1B739ABF6C910BDC51C7F /* AgentDuplicateView.swift in Sources */, 84DDA2D5B4684516979D85D0 /* AgentEditorModel.swift in Sources */, - 9DC7D6EC6D986D76159D5E54 /* AgentEditorView.swift in Sources */, FADCDCFB703E86F82C604AA9 /* AgentFace.swift in Sources */, - 64859B1AD343A54DA7359AB9 /* AgentFastModeRow.swift in Sources */, 72680F9DB07E070984A67579 /* AgentFileFailure.swift in Sources */, 452532BC40CF3B51562A5DCA /* AgentGoalsView.swift in Sources */, - 672CD54682C4894751F4DBF4 /* AgentGroupRowView.swift in Sources */, 5F99F778F875FFA6EDD14205 /* AgentHandle.swift in Sources */, 64C799E7DECB179412AB2C24 /* AgentHelperModels.swift in Sources */, 47739E5FC7053A96B9E412AE /* AgentHomeChrome.swift in Sources */, - 92D1BEC254D80BEF39834541 /* AgentHomeDrawer.swift in Sources */, 30A221F1D223BC33BA5AA675 /* AgentLiveAvatar.swift in Sources */, 0C4FC9C274F0B40976D6F218 /* AgentMedia.swift in Sources */, 0CAB703692F0E09C4A846973 /* AgentModels.swift in Sources */, D8B8905185B768448BB7F378 /* AgentPersonaAvatar.swift in Sources */, DC0D5B51A04CBD7C03E96B11 /* AgentPet.swift in Sources */, - BA0C5D590E64C54CEB0CF317 /* AgentPinnedGrid.swift in Sources */, B8EA36491E4894B4824F96D2 /* AgentProfileCloneClient.swift in Sources */, 3F0C4BAF80C369849AF98E48 /* AgentProfileID.swift in Sources */, - 01B73B8BCFD2D5C83E04112E /* AgentProfileSheet.swift in Sources */, - 5F8AA8BE7A160D7B21D67689 /* AgentRowView.swift in Sources */, 9F908C3330098ED5E0F42F33 /* AgentRuntimeDefaults.swift in Sources */, DF2B308F3D20B22CD44F0B45 /* AgentRuntimeDefaultsEditorModel.swift in Sources */, - 523769209DFC189C9D2CCBC2 /* AgentRuntimeDefaultsSection.swift in Sources */, 69F3D7A9B02C0CE3650CD759 /* AgentScreenTab.swift in Sources */, 81E8A31E76A3D6764A275CD3 /* AgentSelectionView.swift in Sources */, A4146827B760FF893C53D2FA /* AgentShortcutsView.swift in Sources */, DFFEDACD945D5232FC4F56B9 /* AgentSoulTemplates.swift in Sources */, - B1E018B4E66E93621FD75071 /* AgentStartPicker.swift in Sources */, + 638EC98CED5D1D416C535B8D /* AgentStudioCaption.swift in Sources */, 44CDCD083C353139A4872074 /* AgentTalkFixtures.swift in Sources */, E67563B3E12A73308A799A38 /* AgentTemplateBrowser.swift in Sources */, 2CDCB582BEE1831EA325B9F3 /* AgentTemplateFillView.swift in Sources */, @@ -7863,15 +8037,12 @@ D31E9FE7924F1E0019E0E2B0 /* AgentTodayDetail.swift in Sources */, DEDBD361653C38F603CD673D /* AgentVoiceChoices.swift in Sources */, F8D10C4C83902547DB0CA33C /* AgentsAcceptanceFixture.swift in Sources */, - 25F2AE0AEF5D0DF35EDA7875 /* AgentsDirectoryComponents.swift in Sources */, 347E8B05869E3F69E7060542 /* AgentsPresentation.swift in Sources */, - 65DFF1ECAD26221426359F67 /* AgentsView.swift in Sources */, + 026EE8E1DAABEA9BFB6B15D3 /* AgentsSectionCaption.swift in Sources */, 22011C15AB10F1B115440705 /* AppCompositionSupport.swift in Sources */, 6857CC07BA0E110605E217DA /* AppFixtureAgentTemplates.swift in Sources */, 8D97B83C4FD588D4CCD14D65 /* AppFixtureClients.swift in Sources */, 11673206C1DA4BD4694FBC26 /* AppFixtureSetup.swift in Sources */, - 92F5479967E8A8F847DC626A /* AppLayout.swift in Sources */, - 61960032A057ECFAF4D6CAC3 /* AppLayoutSettingsView.swift in Sources */, CC67B3F2DD369DC0682B682B /* AppRoute.swift in Sources */, C16EC1A6C6FB7E80F5573E04 /* AppState.swift in Sources */, C66D44A9FDD34941E3F5EB73 /* AppStateClient.swift in Sources */, @@ -7919,6 +8090,7 @@ E8415FDA5F5475B0D6AEE296 /* BighelpAppBotsState.swift in Sources */, 740571327FB47B4F812C1992 /* BighelpAppComposition.swift in Sources */, B8A729CEE679D296CF63FC59 /* BighelpAppIntents.swift in Sources */, + 46DA80763559E077B8E42879 /* BighelpAppSpaces.swift in Sources */, D298D910DEC65761AE8B3AF0 /* BighelpAppearanceChoices.swift in Sources */, 49C55CB4934DDF4C731D9900 /* BighelpBackgroundGrace.swift in Sources */, 9FE5A34B7A032F3979213756 /* BighelpBackgroundUploads.swift in Sources */, @@ -7965,7 +8137,6 @@ 95D8BB88A08570179A634486 /* BighelpGlyph.swift in Sources */, 6F5D59B13C7D425800CEE120 /* BighelpHomeWidgets.swift in Sources */, EA5BA6383F5EA2038E045B40 /* BighelpHostRegistry.swift in Sources */, - D73A500F5026BA4450D00CF6 /* BighelpHostSwitcherLockup.swift in Sources */, 2F3679E86D328CDE2E65F935 /* BighelpHuggingWidth.swift in Sources */, 046D31CE6FBAE0AAEB73A002 /* BighelpImageGeneratingView.swift in Sources */, 62E58EC17E3B0D20B42DFCE7 /* BighelpIncomingURLRoute.swift in Sources */, @@ -8006,10 +8177,10 @@ 99563F5BD1782B4D8522EF6E /* BighelpMenu.swift in Sources */, 4BD670B6443A906D374625DF /* BighelpMenuCommands.swift in Sources */, C51E78FF26158BE3194F3180 /* BighelpMenuRow.swift in Sources */, - A41C3049FC9CB255DB429539 /* BighelpModePill.swift in Sources */, 6783EE29885D2E6E26863C22 /* BighelpModelChoiceRow.swift in Sources */, 2CF4BECFF04D7DC702A5B071 /* BighelpModelConfirmationModifier.swift in Sources */, B4DF99A4471719B41DE3B4AA /* BighelpModelPickerSheet.swift in Sources */, + CE91C33B4F90531C2DD0BDE1 /* BighelpNavigationGlass.swift in Sources */, C9C93176E1132AEEED2508AF /* BighelpNoodleMotion.swift in Sources */, A4C0FDE80B731F00B3E623FA /* BighelpNoodleView.swift in Sources */, 0736263B512C63A4AEF1D33B /* BighelpNotificationContext.swift in Sources */, @@ -8123,6 +8294,8 @@ 37E5AD1F0826F177E8E90B7B /* BotModeRoomStore+NativeSubmission.swift in Sources */, F9E6334DCA64BC6F8EB3D973 /* BotModeRoomStore+Submission.swift in Sources */, E7EDE5C8D03D118AE8C802DF /* BotModeRoomStore.swift in Sources */, + E355DBD684668B6D178D7E2C /* BotProfileDetails.swift in Sources */, + B7996C9815EBC0898932D12D /* BotProfileMoreMenu.swift in Sources */, A10A38C75366CC41D71FDD82 /* BotProfileOpening.swift in Sources */, CBA3085280A25D558E08D076 /* BotScreenCanvas.swift in Sources */, 8080F1A5B7E741E5C92843C2 /* BotScreenControl.swift in Sources */, @@ -8234,6 +8407,7 @@ 0EC536EDBC4A5D9FA4850471 /* ChatModels.swift in Sources */, DE5B4700D25B828CB4E201C2 /* ChatNativeMarkdownRendering.swift in Sources */, 1510B5AFB84C82A2064A382F /* ChatNativeMarkdownTextView.swift in Sources */, + E64170A092AE47599073DA7A /* ChatNewChatSlot.swift in Sources */, 6E58E9FB4DCCE110FA2FE5DB /* ChatPDFPagesDraft.swift in Sources */, 88D7FEFF96EAFC31CC02B57C /* ChatPendingCardView.swift in Sources */, 0799B9446E83D23984F3E275 /* ChatPerformanceProbe.swift in Sources */, @@ -8272,6 +8446,10 @@ 07A1FEF03D3F4ABD30148664 /* ChatView+Timeline.swift in Sources */, 2E923F9E6D44DE5364D4509A /* ChatView.swift in Sources */, 1A332378C82EBA37BF825E11 /* ChatWorkTrailCard.swift in Sources */, + 13BB63D1F8BDEEB7F3571C7A /* ChatsInboxFixture.swift in Sources */, + C66EFBDB5C7201226959CDF2 /* ChatsInboxProjection.swift in Sources */, + 048787A3730C8D49CB08BB83 /* ChatsInboxRow.swift in Sources */, + 1CBFD9B876E36D5544E7129A /* ChatsInboxView.swift in Sources */, 2050AF9EE6E6B3D062967674 /* ClarificationAnswers.swift in Sources */, 7F8F4C1CD762CDFD7FD9E7DA /* ClarificationFallbackFixture.swift in Sources */, B10CAEBBCED229688E8DCDB2 /* ClipboardDraftTextEditor.swift in Sources */, @@ -8280,13 +8458,13 @@ AFBB61C6851FC85F944CA620 /* CodeBatch.swift in Sources */, A2914B7AE4184E15BAAAC304 /* CodeBatchChatView.swift in Sources */, 1A6926C74C93FC29E1B268B5 /* CodeBranchName.swift in Sources */, + 7CF7514CFC9C84DF6B20AF28 /* CodeCards.swift in Sources */, 7F50552BAD035C5C3CB4B278 /* CodeChangesView.swift in Sources */, - C5A66B6EA0CF91080459BDA8 /* CodeComposer.swift in Sources */, 6A51D89F2325F1FA72F9B2D0 /* CodeHomeStore.swift in Sources */, - 493358AF1E2A642F5525956B /* CodeHomeView.swift in Sources */, 69E7CD405A0F3F5E44E9332F /* CodeLauncher.swift in Sources */, D1C6E1AC3EABC6E981C8A13B /* CodeMentionTextView.swift in Sources */, D962566220603289110AC817 /* CodeModels.swift in Sources */, + A6865F6049D51FE50B97B6C3 /* CodePickers.swift in Sources */, CEA434957AFAAB0E40673CDC /* CodeProjectSource.swift in Sources */, AE52CFC862B6214181D24C4A /* CodePullRequestsSheet.swift in Sources */, DF1F77EECB0014A93C4F2067 /* CodeSessionStatusReader.swift in Sources */, @@ -8353,6 +8531,7 @@ 46D87E20D93117E61811695E /* DemoRepository.swift in Sources */, F1CA5FA973B5BEB0D7A8AF12 /* DemoRoomPeerHosts.swift in Sources */, D8B47079AAD04A89B7437156 /* DemoSessionCatalogClient.swift in Sources */, + 0F4E40B1AEEDEB1E0256DAF3 /* DemoSpacesClient.swift in Sources */, 01D2F5AEDA225C7661778B7F /* DemoWorkflowsClient.swift in Sources */, 2810BD1768BCB89341823D18 /* DevFactoryRunGroupView.swift in Sources */, 1C583C9DF419F0654D7CDC02 /* DevFactoryStore.swift in Sources */, @@ -8499,7 +8678,6 @@ 23CB63D387E8CF825F27484D /* FirstRunOnboardingView.swift in Sources */, DF3F13718D85BEDBF3044464 /* FixtureWorkspaceManagementClient.swift in Sources */, 7C3A2C2512B1C45AA4DD00CD /* FleetFixtureReader.swift in Sources */, - 410FE1D097AFE35EA630F759 /* FleetListOrganizing.swift in Sources */, AA9836BFE6CD4AE0446E1AEE /* FleetMaintenance.swift in Sources */, 8EC0C02825325E07EA9EEBF0 /* FleetMaintenanceFixture.swift in Sources */, E8DF089A91EB2ABB11E218BD /* FleetModels.swift in Sources */, @@ -8508,7 +8686,6 @@ 4489CDCCDA96CEB5E466693F /* FleetStore.swift in Sources */, B06EA34EF55DA7B28440B74A /* FleetSwitchFallback.swift in Sources */, 3C348F622E813505DE17112D /* FleetViews.swift in Sources */, - 98BCDE99C7F506CDC74308D0 /* FloatingTabBar.swift in Sources */, BF4CB44F60316B4A88AA1D9A /* FocusedTextEditor.swift in Sources */, 489E33414695B4DAFEBDBCCE /* GeminiLiveAudioPeer.swift in Sources */, E2B650F2E6C666A347C1916F /* GeminiLiveAudioReport.swift in Sources */, @@ -8533,6 +8710,7 @@ E0E26CC2702BC633B82814BB /* GroupSettingsDemoClient.swift in Sources */, 9D746590A066AA6E8FBAFD33 /* GroupSettingsView.swift in Sources */, 8D1EC9D53AE48FDCEC962091 /* HTMLAppCardView.swift in Sources */, + 8245C2A4E114176D8819CE58 /* HTMLAppNavigationPolicy.swift in Sources */, A675EA761668E0D2B3D5321E /* HTMLAppScreen.swift in Sources */, D1702179B3553E96B4387819 /* HTMLAppScreenModel.swift in Sources */, 10E3992D7315AFA766435388 /* HTMLAppWebView.swift in Sources */, @@ -8564,6 +8742,16 @@ D85D11C72CD2EDBB8B7AC5CB /* HermesUserMessageDisplay.swift in Sources */, 013CD7CC970434CDC15943AC /* HermesWorkspaceStore.swift in Sources */, DBFE063EF4F0B08D8B940F3C /* HermesWorkspaceViews.swift in Sources */, + 7552538E84CB2EC35D0AD57A /* HomeChromeFixture.swift in Sources */, + D71255F5A8BC5AEB87C2CF27 /* HomeContracts.swift in Sources */, + 59664A8052597D180CC63F01 /* HomeHeaderBar.swift in Sources */, + 8E2F4DFB7B79F13BB3782BAA /* HomeMenuPresentation.swift in Sources */, + DA3310874BC25AFC22063B8E /* HomeSelection.swift in Sources */, + 4302B6870E4E985F8334F6E7 /* HomeSettingsMigration.swift in Sources */, + F151DD92C6E8AEE3215B5591 /* HomeSidebar.swift in Sources */, + 1BBF90B872D21C4E044958FC /* HomeStripTabs.swift in Sources */, + 488842D2C3364326FEF38717 /* HomeTabBar.swift in Sources */, + 5A11900790336EF04767C40F /* HomeTabOrnament.swift in Sources */, 134B9E7EE272FBA6318269D7 /* HomeWorkAcceptanceFixture.swift in Sources */, E5ED0E414BA70426E622F483 /* HostAccessEditorView.swift in Sources */, 1B2C5F81B5157A90ED3B9D9E /* HostAuthenticationDiscovery.swift in Sources */, @@ -8634,6 +8822,7 @@ A016DB6FAED92BC0D74818F6 /* LongChatPerformanceFixture.swift in Sources */, 00D5476E0F65978857126727 /* LongTextEditor.swift in Sources */, 6C8EB87B1B263055E4806FA9 /* MCPManagementView.swift in Sources */, + C52FF73155AC111979486D13 /* MacTileMenu.swift in Sources */, 2AD5EC547A554B6CEDDE45B7 /* ManagementSearch.swift in Sources */, 3955467DE40CB457604DADCA /* MarkdownAttachmentFixture.swift in Sources */, A2EEC340776C053BEA4C0E93 /* MarkdownFileView.swift in Sources */, @@ -8686,7 +8875,15 @@ E8D2D62701BB5E391765D5D6 /* NativeWorkspaceSessionBridge.swift in Sources */, 180A967E219A8869347A3823 /* NativeWorkspaceUnavailableClient.swift in Sources */, D909E9A3BC9540DA150CDDE6 /* NeedsYouDeckView.swift in Sources */, + D67CBBAF649B67AFA6D4ECE5 /* NewChatChoicesRow.swift in Sources */, AE85745E270D801B6B92F8C0 /* NewChatCoordinator.swift in Sources */, + C42681DAA0C267F0E6BB6D18 /* NewChatFixture.swift in Sources */, + C7D36ABB07D7045DDE11FA68 /* NewChatHandoff.swift in Sources */, + 0743E22555A70EBC89AB2A10 /* NewChatRecipients.swift in Sources */, + 2F42986D75386199E60C88FC /* NewChatSend.swift in Sources */, + 126B64563AEC9DE243B51FDA /* NewChatSendRelay.swift in Sources */, + FF125C53A6B1E528373562A0 /* NewChatSession.swift in Sources */, + 81D7047FB611B60B23F56026 /* NewChatView.swift in Sources */, E3CBB3FECCB837D3C8D91BA7 /* NotificationEventWireModels.swift in Sources */, 380BEBE7B899E835C2B6D9F2 /* ObjectCardsFixture.swift in Sources */, 43C24FF940F829FF2DDB9B89 /* OnDeviceSpeechEngine.swift in Sources */, @@ -8719,7 +8916,6 @@ 3FD2F6C1ED4F532BEAA155BB /* PluginCatalogPageView.swift in Sources */, 1825F20AA7BD8EAE546A3693 /* PluginLatestRelease.swift in Sources */, 8E2E6965629031C58D5CB3F1 /* PluginLifecycleManagementView.swift in Sources */, - 7705B6E59B50B085309600BB /* PluginUpdateSection.swift in Sources */, 46959AFCC70618D5C2F01158 /* PluginUpdateStore.swift in Sources */, CACD83D4E9CE48A53447437D /* ProfileLifecycleStore.swift in Sources */, E5AE72FCAF0D598E265BF605 /* ProfileLifecycleView.swift in Sources */, @@ -8785,10 +8981,12 @@ 797DEBAA188DE7C5206C28E8 /* RootDestinations.swift in Sources */, 3D5188F4645A9BF72BF94339 /* RootFleet.swift in Sources */, C7F3CE7070ED715E4EDB8621 /* RootFreshSession.swift in Sources */, + 10E30BA534D118C2033CE598 /* RootHome.swift in Sources */, 94E45666E9C29B8C723D8F44 /* RootKanban.swift in Sources */, 2B94917A65166711CB2DD854 /* RootMarketplace.swift in Sources */, 8C88CCE26B4A8CAEC0948771 /* RootNavigationViews.swift in Sources */, 5B72AA4F73E91E67D6D23BEF /* RootNeedsYou.swift in Sources */, + 269AEEF3C2DC916D8095C963 /* RootNewChat.swift in Sources */, 80D6A4B73438D7A47CE3D1B1 /* RootPendingShares.swift in Sources */, 67D4744BB85A11BD72A1C110 /* RootPresentationContracts.swift in Sources */, E40540E41EF8AE064FD5E908 /* RootScheduledAlerts.swift in Sources */, @@ -8852,7 +9050,6 @@ B3D4DF884C078EB77DB8E725 /* SettingsPresentation.swift in Sources */, B60BC5275069EA540FB0545E /* SettingsStore.swift in Sources */, 803276D6A5DCF1B3A52CB02A /* SettingsView+Computers.swift in Sources */, - EF39C6AB48360D884BFB5C51 /* SettingsView+Experience.swift in Sources */, C849F9C933C1AECF8591D626 /* SettingsView+Identity.swift in Sources */, 2601DB62BFBEE45B1455D6C9 /* SettingsView+LocalData.swift in Sources */, 7FAE396F71DA60264B402B7E /* SettingsView+Menu.swift in Sources */, @@ -8872,7 +9069,6 @@ 842B5E01AA01D87DE0AD45A9 /* SimpleBotProfileView.swift in Sources */, 10006BC271D7C92540B570B2 /* SimpleBotTemplates.swift in Sources */, 41F83314C2CE35C83B984C1A /* SimpleBotTimeZonePicker.swift in Sources */, - 4F4BFD5D7FE39BBA056987FA /* SimpleBotVoiceBar.swift in Sources */, 5AABDC9FB87A5F78228292E0 /* SimpleBotsChatOpening.swift in Sources */, 1230E7F777C8E9CC120BDB9A /* SimpleBotsHomeSections.swift in Sources */, 9439485E2A2FA9EC2B7ED47F /* SimpleBotsHomeView.swift in Sources */, @@ -8891,6 +9087,15 @@ 0CD023A3E8304ACF8C094447 /* SkillsHubManagementView.swift in Sources */, BEEADC4963E5C4C57046FA8D /* SkippedPartsNote.swift in Sources */, 84D064537E79C825FB5EBA5E /* SlashCommands.swift in Sources */, + CA2ACB0BF7012FEDFFADF007 /* SpaceDraftCardView.swift in Sources */, + AB7E89B1F59136390C7114F9 /* SpaceModels.swift in Sources */, + C2A8BAEFCDAFB2DCF1A370F5 /* SpacePanelView.swift in Sources */, + E72E72D9E57D895D330CE366 /* SpacesClient.swift in Sources */, + 9BFC6BE92F3648689B671CF1 /* SpacesFixture.swift in Sources */, + C18324A6DF111FC0C40893A0 /* SpacesHost.swift in Sources */, + EE2A914B0CA1DFF0BDE626A0 /* SpacesStore.swift in Sources */, + 754B628888B22A434636D598 /* SpacesTodayBridge.swift in Sources */, + 317013F28587EF601E34DBB7 /* SpacesWire.swift in Sources */, 0855EC09D3422B6178283DB8 /* SpatialAvatarHeadwear.swift in Sources */, 7299EC77E859961D03CA3C86 /* SpatialAvatarModel.swift in Sources */, B49607CCA26B13A8F4BC854C /* SpatialAvatarPreview.swift in Sources */, @@ -8939,6 +9144,17 @@ 2B8EBA772AE58A240B6C5AF0 /* ThinkingLooksScenes.swift in Sources */, B50D48CBABF05CFADAEF2A91 /* ThinkingSliderEngine.swift in Sources */, E3D10F586399F1391433AC71 /* ThinkingSliderTrack.swift in Sources */, + 3F7DCF39A1DE7F0EE751BA26 /* TodayBoardPage.swift in Sources */, + A744B22B79EAF3F73C85C874 /* TodayBoardsPanel.swift in Sources */, + 036CFADFEE4116FF69BD1BDF /* TodayBoardsStore.swift in Sources */, + 57A4AA568CB3AC55BBE26970 /* TodayCreateBox.swift in Sources */, + 14607C374EACFE7655F419BA /* TodayFixture.swift in Sources */, + 239C2ADF1E607A7351DC61CA /* TodayNeedsYouCard.swift in Sources */, + 3F5559F32E958448E57530ED /* TodayNotice.swift in Sources */, + 6D8EDC56BE5C016E0AF79B29 /* TodayPanelGrid.swift in Sources */, + 1E17E2ED1D11EEF625D9F354 /* TodayPanelLayoutStore.swift in Sources */, + 61CF38C56DEC66EC0638171A /* TodaySpacesModel.swift in Sources */, + 6C40C95CB6777ECABA223475 /* TodayView.swift in Sources */, F6BBE258159B0F21F790EF53 /* ToolsetManagementView.swift in Sources */, 572777425A63A9F9561CBB85 /* UnavailableAppClients.swift in Sources */, E18C53E93E3D38EF910A848A /* UsageExport.swift in Sources */, @@ -8995,6 +9211,12 @@ F0854C20EBD5AEFDD27B8BF3 /* WikiRecoveryWork.swift in Sources */, 4CB1D67C6F49D8AF80A9072A /* WikiScratchpadContext.swift in Sources */, DF89F5234015466C9B72583D /* WikiStore.swift in Sources */, + BB9CE1A084021E1CD9FFD1F5 /* WorkCards.swift in Sources */, + 8E61F1D2FC05C1C3EDF74D48 /* WorkDoors.swift in Sources */, + 8BEC3192D84F108324C9534F /* WorkFixture.swift in Sources */, + 2A9E17F7B80D5900B6BAD11E /* WorkItem.swift in Sources */, + E798B4DB35FB66A4A63C5E3B /* WorkProjection.swift in Sources */, + B662B3C3DF2696D49F1C1F74 /* WorkView.swift in Sources */, 34228115E26AC623DE813802 /* WorkflowCanvasBoard.swift in Sources */, 9C7045994CCF3301A5BE1D6B /* WorkflowCanvasLayout.swift in Sources */, E1807302F0120872B5648935 /* WorkflowCanvasView.swift in Sources */, @@ -9217,7 +9439,6 @@ 94143673BB126A24786419D0 /* AgentTodayDetailTests.swift in Sources */, C10B5B01C96C2D77B0842124 /* AgentVoiceChoicesTests.swift in Sources */, 334C431DA1A5A6AA749BF53A /* AgentsPresentationTests.swift in Sources */, - 83D0AE9123454E12BB3E5D49 /* AppLayoutTests.swift in Sources */, A929D78738AA73BFD2F5AF0B /* AppStateSyncTests.swift in Sources */, 5FD9F0F18BD763BC16E0B9D1 /* AppStateTests.swift in Sources */, 6840E53D10369DC672943D96 /* AppearanceChoicesTests.swift in Sources */, @@ -9282,7 +9503,6 @@ 3EAEC4BC755B2CF562145823 /* BighelpShortcutServiceTests.swift in Sources */, DBBDCEA6636324C0FF3A294D /* BighelpSideMenuTests.swift in Sources */, 606B063BE2AB450E976BC394 /* BighelpSurfaceTests.swift in Sources */, - 79B603212451FE324DA59380 /* BighelpTabGlyphTests.swift in Sources */, CAD5A93103A9B633034C702A /* BighelpThinkingOrbTests.swift in Sources */, B2E742F3DE9015D38D8864D0 /* BighelpToolActivityCatalogTests.swift in Sources */, AB50229B9D95E539FB6025BE /* BighelpUsageWidgetRenderTests.swift in Sources */, @@ -9298,6 +9518,7 @@ 7842F1110DEB2F0851754D9E /* BotModeRoomStoreTests.swift in Sources */, 5A8766E7C2251965026C4EAE /* BotModeRunTests.swift in Sources */, 602ACF7A3D6AF109680A45D4 /* BotModeStopTests.swift in Sources */, + 0A6967A48C99D6A2F92ED523 /* BotProfileActionsTests.swift in Sources */, 1F608E34D20AD5747F9E8993 /* BotProfileOpeningTests.swift in Sources */, DDEFE05D3CD6FCA70C9D3256 /* BotScreenRFBTests.swift in Sources */, 3523846944DD383A6D161D7D /* BotScreenStateTests.swift in Sources */, @@ -9367,12 +9588,14 @@ 86355DA58586159E38C31B97 /* ChatToolReadableDetailTests.swift in Sources */, A171339C555F24465F41331F /* ChatTurnFailureTests.swift in Sources */, BE105A8DE3A05F744C77D655 /* ChatWorkStyleTests.swift in Sources */, + E2E78FA3923A12B1849ADE08 /* ChatsInboxProjectionTests.swift in Sources */, 3CA6F45D717F0C4B2233F8CC /* ClarificationAnswersTests.swift in Sources */, 88D054CE4CAA009DEC856C25 /* ClarificationFallbackTests.swift in Sources */, FD8210E151243CEA00E119CC /* ClipboardAttachmentTests.swift in Sources */, 23C3F038DE66D135C72B5BCD /* ClipboardImporterTests.swift in Sources */, D78F656A4787495D0BEE6AD8 /* CodeBatchTests.swift in Sources */, 1401F2F08D29710E9A81B9B5 /* CodeModeTests.swift in Sources */, + B4224CC495345ECF6E6CA745 /* CodeSessionStatusReaderTests.swift in Sources */, F31F4A76FA960358DEA1BE1B /* CompactChatComposerTests.swift in Sources */, 65A65D35CEC72C325069355A /* CompanionComposerPathTests.swift in Sources */, A17C108052065A1B039C549C /* CompanionPhysicsTests.swift in Sources */, @@ -9469,6 +9692,7 @@ DE205DF7F6F0287FD70D5DA5 /* GeneratedMediaProjectionTests.swift in Sources */, 0729E07D086789DEBFDEDFA9 /* GitHubCredentialAcceptanceTests.swift in Sources */, 89BD4536E75187344E6D9221 /* GitHubIntegrationTests.swift in Sources */, + 11C26F0E7556FB6B4B2AB21B /* HTMLAppNavigationPolicyTests.swift in Sources */, 7766ECFD158103AF65F2E20C /* HTMLAppTests.swift in Sources */, C7AE3EF40F91370CE326A01B /* HermesBlobEditsTests.swift in Sources */, A7C7EB7E92B99BFCB9EAC992 /* HermesBotModeActivityTests.swift in Sources */, @@ -9481,6 +9705,8 @@ A64A719778D24A3FF5BF5C38 /* HermesGroupsHostPathTests.swift in Sources */, 439C7B1833A69D5C7785AC14 /* HermesLogsTests.swift in Sources */, AA4BE7095FA7772DE048864D /* HermesUserMessageDisplayTests.swift in Sources */, + 3B17749964BD5B1D70864B5B /* HomeChromeTests.swift in Sources */, + FB88850F7A44A4D6D7C96E1B /* HomeSettingsMigrationTests.swift in Sources */, 3E57E5E4628907AED11947A9 /* HostActivityRenderTests.swift in Sources */, 9845E8B8092D3DB7AF828839 /* HostConnectionStatusTests.swift in Sources */, CD77D3FC449640CE3AD267A9 /* HostListSizeTests.swift in Sources */, @@ -9526,7 +9752,6 @@ E631FB670F611061813B80C9 /* ModelNameCatalogTests.swift in Sources */, FAD78D4E195692FC547BA54B /* ModelProviderPlanTests.swift in Sources */, 67B8F6757651C668CC1B65E3 /* MyTemplatesTests.swift in Sources */, - DD9B0458037184ABC60AC77B /* NativeAgentCreationVisualTests.swift in Sources */, C98E642B79FB5D970AF17C6D /* NativeContinuousStreamLiveTests.swift in Sources */, AE5A79DA64189A49AD9F5719 /* NativeDeviceToolSessionTests.swift in Sources */, 33C4CD88CCCB22E040F5D39F /* NativeFileProductionTests.swift in Sources */, @@ -9545,6 +9770,9 @@ E7F94962F9DE60E9D5ED47D0 /* NativeWorkspaceSessionBridgeTests.swift in Sources */, 873627A0788894E370CA1D86 /* NeedsYouBlueprintsModesTests.swift in Sources */, F748D31409E3D5790C8B3F97 /* NewChatCoordinatorTests.swift in Sources */, + BDC2F172ED9AAE6107393977 /* NewChatPickTests.swift in Sources */, + 4D2D9994C72E0C45D4EB632F /* NewChatRecipientsTests.swift in Sources */, + 4B2D72DAFDA29AAF1D7BB25A /* NewChatSendTests.swift in Sources */, 88ED87F9AC0696EC231467DF /* NotificationBundleConfigurationTests.swift in Sources */, F0AD0020E69F586FEB91B60A /* NotificationChatRoutingTests.swift in Sources */, A5ABFA183304F3F2C7B33174 /* NotificationErrorCodeTests.swift in Sources */, @@ -9569,7 +9797,6 @@ 2A9B76AAB859A209C1819624 /* PluginMarketplaceTests.swift in Sources */, 595DFFBFA88D2E6B6FFA9AB6 /* PluginUpdateStoreTests.swift in Sources */, 5AC0BB82A250434BD7BC12E5 /* PluginUpdateWorkspaceClientTests.swift in Sources */, - AAFC950C49292EDF9A0EA8B6 /* PrimaryNavigationSelectionTests.swift in Sources */, 8CFAAB08A340C1F1230668CF /* ProductionVoiceSessionTests.swift in Sources */, F402A7FA85AEDCDB788F3D55 /* ProfileDeletionTests.swift in Sources */, 7301F8B3A47464D8DD600ED5 /* ProfileLifecycleStoreTests.swift in Sources */, @@ -9626,6 +9853,10 @@ 1AB516FA3EAED04152EDE089 /* SkillDocumentMutationTests.swift in Sources */, 9A762D8156FF1063F2B5BD58 /* SkillMutationLifecycleTests.swift in Sources */, BE76EAE4EF61CF095476A7E2 /* SkillsAndPluginsHostShapeTests.swift in Sources */, + 3A557EDD8981195F9BE06451 /* SpaceDraftCardStateTests.swift in Sources */, + 2F78D2A9E85917902FD86A88 /* SpacePanelStateTests.swift in Sources */, + 095FEFD74A2FA1D648B59B6A /* SpacesStoreTests.swift in Sources */, + 6E4D1EFBBF714AF91350C8AC /* SpacesWireTests.swift in Sources */, 879F26B5861D37C7F19A5099 /* SubagentCanvasTests.swift in Sources */, B3EC5789602FB904AEA7AF78 /* SubagentControlTests.swift in Sources */, 26DACF622E681A594FD09C8B /* TeamCallTests.swift in Sources */, @@ -9641,8 +9872,10 @@ CEA5D7A18CF42D4A70EAC195 /* TemplateVariablesTests.swift in Sources */, 140C29760EC97CD5A42B96F6 /* ThemePresetTests.swift in Sources */, F88B25D1899CB2B2E234711D /* ThinkingLadderTests.swift in Sources */, + 207937BD6C0C3D5FC8176224 /* TodayBoardsStoreTests.swift in Sources */, + 02AF109D3DD981434BF2219B /* TodayPanelLayoutTests.swift in Sources */, + 6DD42B747B23495B31DCDED4 /* TodaySpacesModelTests.swift in Sources */, AAAAA95C75044DF38179A1B0 /* ToolDisclosureHydrationTests.swift in Sources */, - 48CD0544D668BD0CD0DAA793 /* UnifiedModeToggleTests.swift in Sources */, 3C7E68E3BBDF6D20A1EB9667 /* UsageExportTests.swift in Sources */, 5AEE02352685D4432493CBEB /* UsageLimitsComputersTests.swift in Sources */, C836BC84BA9A520A2DB166CB /* UsageStoreTests.swift in Sources */, @@ -9662,6 +9895,7 @@ 95E75CA5B1416FDFB26A4C32 /* WikiEditingTests.swift in Sources */, B60FFFEA8730E8B8988D4846 /* WikiHomeTests.swift in Sources */, F18D95A67829F2D53B2483E1 /* WikiNativeTests.swift in Sources */, + A9FE6500A69CDE5F318CA51D /* WorkProjectionTests.swift in Sources */, B6BF0CD6223E722A0CE8B2F1 /* WorkflowEditingTests.swift in Sources */, C5C4D2B8DCD48DF9AB58C907 /* WorkflowsTests.swift in Sources */, ABDDB82650A10B2CF7CA1249 /* WorkspaceArtifactsTests.swift in Sources */, @@ -9694,11 +9928,7 @@ 86828616C0652504329CA63E /* AgentDeletionUITests.swift in Sources */, 26B7B2AAD3AA95DE5A380187 /* AgentDriveUITests.swift in Sources */, 318652A995356C5CD2CB24C9 /* AgentFilesUITests.swift in Sources */, - E9DC964BFA209B91F0642406 /* AgentOpenRealHostUITests.swift in Sources */, 2C491A44FF77C3ECBBFE8BD4 /* AgentsUITests.swift in Sources */, - 866A3D87C3251AB40763D685 /* AllHostsHostUITests.swift in Sources */, - 9D79073CB83AC124FB548509 /* AllHostsUITests.swift in Sources */, - C5CF86430FFC993BEB04AB83 /* AppLayoutUITests.swift in Sources */, A6ECE7BCF9196AC0DBB06F18 /* AppReviewHostUITests.swift in Sources */, DCA875E23AC81AC45FC8B087 /* AppStoreScreenshotUITests.swift in Sources */, 67060F2A727824FCBB960E60 /* ArchivedChatsUITests.swift in Sources */, @@ -9706,7 +9936,6 @@ DB0BC67325877D2E0AFFFE02 /* BackgroundWorkHostUITests.swift in Sources */, E38C49A8BC478675844E72D2 /* BigFileChatUITests.swift in Sources */, E70E158E605E4850E1309EB4 /* BigFileHostUITests.swift in Sources */, - E0ABA2CFFE7CF938EFC8046A /* BighelpMenuUITests.swift in Sources */, 613A69AE78661B735734B0E0 /* BoardSwipeBlueprintsUITests.swift in Sources */, 3E82DF1A103FC296EB72C081 /* BotActivityHostUITests.swift in Sources */, 8A79D0A026B2159D4089C56F /* BotChatUITests.swift in Sources */, @@ -9715,7 +9944,6 @@ 0043FABFA2A0003D42A29A56 /* BotScreenUITests.swift in Sources */, C65CCE3D3F17ECCDD9991D9D /* BotsAppStateHostUITests.swift in Sources */, 5BE1D14FA4C9D464206D3E1D /* BotsWidgetUITests.swift in Sources */, - 39FC5FBDB150414717D93A83 /* BottomMenuUITests.swift in Sources */, 5C97A46B026D0C507BE0A5A8 /* CarPlayVoiceUITests.swift in Sources */, 755B2AF3234CF8B3A31AB7B1 /* CardRepliesUITests.swift in Sources */, 49F7BB5BF9F5270DEEFEC7EB /* CatalogStorefrontUITests.swift in Sources */, @@ -9764,6 +9992,7 @@ 39B8FD33B7C9DF2EE82096E2 /* HTMLAppsHostUITests.swift in Sources */, 66874BD78C08B214C1E5603B /* HTMLAppsUITests.swift in Sources */, 0A946DC969DB99FEB9C01AE8 /* HermesGroupsHostUITests.swift in Sources */, + 7081ACDD746875804F5AFF2D /* HomeShellUITests.swift in Sources */, 7D9C86F6D2677088CE860A69 /* HostOnboardingUITestSupport.swift in Sources */, 1C763567CD9CCE8F93EA60F8 /* HostSignInMatrixUITests.swift in Sources */, 03B7DEB1937FFFE3888F6B09 /* ImageDraftsHostUITests.swift in Sources */, @@ -9817,7 +10046,6 @@ E4E534E8540E3693454A9DC4 /* ThinkingLookUITests.swift in Sources */, 9331FF96C2F5CCAA6A03068A /* ToolCodeCellUITests.swift in Sources */, 6E06FD7A158360A66779DB29 /* ToolDisclosureUITests.swift in Sources */, - 050AF19EDB08DD39CFB94B47 /* UnifiedModeToggleUITests.swift in Sources */, 8D9B0E73D8D88ABC2AC19614 /* UsageNavigationUITests.swift in Sources */, 908EBB970E2463D62B603F59 /* VoiceSettingsUITests.swift in Sources */, 27B50136A7D03C9538027EBB /* VoiceShortcutUITests.swift in Sources */, diff --git a/Bighelp/AdvancedOptions/AdvancedOptionsView.swift b/Bighelp/AdvancedOptions/AdvancedOptionsView.swift index f6c927bb..14da500a 100644 --- a/Bighelp/AdvancedOptions/AdvancedOptionsView.swift +++ b/Bighelp/AdvancedOptions/AdvancedOptionsView.swift @@ -34,7 +34,7 @@ struct AdvancedOptionsSheet: View { /// One bot's advanced settings, grouped and in a few words each, then every Nerd Mode page for /// it, with the expert ones last. A small (i) beside a setting says what each choice does. -/// Pushed from Bots mode's Settings too, so it brings its own page destinations. +/// Pushed inside Settings, so it brings its own page destinations. @MainActor struct AdvancedOptionsPage: View { let context: AdvancedOptionsContext diff --git a/Bighelp/Agents/AgentActionSheet.swift b/Bighelp/Agents/AgentActionSheet.swift deleted file mode 100644 index bd77aa7f..00000000 --- a/Bighelp/Agents/AgentActionSheet.swift +++ /dev/null @@ -1,206 +0,0 @@ -import SwiftUI - -struct AgentActionSheet: View { - let agent: AgentProfile - var imageURL: URL? = nil - let actions: [AgentActionItem] - let onAction: (AgentRowMenuAction) -> Void - - @Environment(\.dismiss) private var dismiss - - var body: some View { - NavigationStack { - List { - Section { - header - } - .listRowBackground(Color.clear) - .listRowInsets(EdgeInsets(top: 0, leading: BighelpTokens.space16, - bottom: BighelpTokens.space8, trailing: BighelpTokens.space16)) - - // Like a contact card: the two everyday actions sit under the - // agent, then history, then setup, with rarely used actions last. - if !primaryActions.isEmpty { - Section { primaryButtons } - .listRowBackground(Color.clear) - .listRowInsets(EdgeInsets(top: 0, leading: BighelpTokens.space16, - bottom: 0, trailing: BighelpTokens.space16)) - } - actionSection("Activity", conversationActions) - actionSection("Setup", preferenceActions) - actionSection("More", technicalActions) - if let delete = actions.first(where: { $0.action == .delete }) { - Section { - Button(role: .destructive) { onAction(.delete) } label: { - Label(delete.title, systemImage: delete.systemImage) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) - .contentShape(.rect) - } - .disabled(!delete.isEnabled) - .accessibilityIdentifier("agent.\(agent.id).delete") - } - .listRowBackground(theme.surface) - } - } - .listStyle(.insetGrouped) - .accessibilityIdentifier("agent.actions.list") - .scrollContentBackground(.hidden) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle("Agent Details") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("Done") { dismiss() } - .fontWeight(.semibold) - .foregroundStyle(theme.action) - .frame(minHeight: BighelpTokens.toolbarHitTarget) - #if targetEnvironment(macCatalyst) - .keyboardShortcut(.cancelAction) - #endif - } - } - } - .accessibilityIdentifier("agent.actions") - } - - private var header: some View { - VStack(spacing: BighelpTokens.space8) { - AvatarView(stableID: agent.id, displayName: agent.name, - imageURL: imageURL, size: 72) - .accessibilityHidden(true) - Text(agent.name) - .font(.bighelp(.title3).weight(.bold)) - .foregroundStyle(theme.primaryText) - .multilineTextAlignment(.center) - if !agent.role.isEmpty { - Text(agent.role) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - } - if !agent.summary.isEmpty { - Text(agent.summary) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - .lineLimit(2) - } - } - .frame(maxWidth: .infinity) - .padding(.top, BighelpTokens.space8) - .accessibilityElement(children: .combine) - .accessibilityLabel( - [agent.name, agent.role, agent.summary] - .filter { !$0.isEmpty } - .joined(separator: ". ") - ) - } - - private var primaryActions: [AgentActionItem] { - actions.filter { [.openChat, .edit].contains($0.action) } - } - - private var conversationActions: [AgentActionItem] { - actions.filter { [.viewSessions, .scheduledTasks, .groups].contains($0.action) } - } - - private var preferenceActions: [AgentActionItem] { - actions.filter { [.setPrimary, .togglePin].contains($0.action) } - } - - private var technicalActions: [AgentActionItem] { - actions.filter { [.shortcuts, .duplicate, .saveTemplate].contains($0.action) } - } - - /// Message and Edit as two large tiles, filled accent for the primary one. - private var primaryButtons: some View { - HStack(spacing: BighelpTokens.space12) { - ForEach(primaryActions) { item in - let isMessage = item.action == .openChat - Button { onAction(item.action) } label: { - VStack(spacing: BighelpTokens.space4) { - Image(systemName: isMessage ? "message.fill" : item.systemImage) - .font(.system(size: 18, weight: .semibold)) - Text(item.title) - .font(.bighelp(.subheadline).weight(.semibold)) - } - .foregroundStyle(isMessage ? theme.actionForeground : theme.action) - .frame(maxWidth: .infinity, minHeight: 60) - .background(isMessage ? theme.action : theme.surface, - in: .rect(cornerRadius: BighelpTokens.radius16, style: .continuous)) - .opacity(item.isEnabled ? 1 : 0.45) - .contentShape(.rect) - } - .buttonStyle(.bighelpTilePress) - .disabled(!item.isEnabled) - .accessibilityLabel(item.title) - .accessibilityValue(item.detail ?? "") - .accessibilityIdentifier("agent.\(agent.id).\(item.action.rawValue)") - } - } - .padding(.vertical, BighelpTokens.space4) - } - - @ViewBuilder - private func actionSection(_ title: String, _ items: [AgentActionItem]) -> some View { - if !items.isEmpty { - Section { - actionRows(items) - } header: { - AgentStudioCaption(title) - } - .listRowBackground(theme.surface) - } - } - - @ViewBuilder - private func actionRows(_ items: [AgentActionItem]) -> some View { - ForEach(items) { item in - Button { onAction(item.action) } label: { - HStack(spacing: BighelpTokens.space12) { - Image(systemName: item.systemImage) - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(item.isSelected ? theme.actionForeground - : item.isEnabled ? theme.action : theme.tertiaryText) - .frame(width: 32, height: 32) - .background( - RoundedRectangle(cornerRadius: BighelpTokens.radius8, style: .continuous) - .fill(item.isSelected ? theme.action : theme.incomingMessageBackground) - ) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - Text(item.title) - .font(.bighelp(.body)) - .foregroundStyle(item.isEnabled ? theme.primaryText : theme.secondaryText) - if let detail = item.detail { - Text(detail) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - } - Spacer(minLength: 0) - } - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) - .contentShape(.rect) - } - .buttonStyle(.plain) - .disabled(!item.isEnabled) - .accessibilityLabel(item.title) - .accessibilityValue(item.detail ?? "") - .accessibilityIdentifier("agent.\(agent.id).\(item.action.rawValue)") - } - } - - @BighelpThemeReader private var theme -} - -enum AgentActionPresentation { - static let pinnedAgentLimit = 5 - static let setPrimaryHint = "New chats start with this agent." - static let alreadyPrimaryHint = "New chats already start with this agent." - static let pinHint = "Keeps this agent at the top of Agents." - static let unpinHint = "Removes this agent from the top of Agents." - static let pinLimitHint = - "You can pin \(pinnedAgentLimit) agents. Unpin one to make room." -} diff --git a/Bighelp/Agents/AgentActions.swift b/Bighelp/Agents/AgentActions.swift deleted file mode 100644 index 3ea8cdb6..00000000 --- a/Bighelp/Agents/AgentActions.swift +++ /dev/null @@ -1,225 +0,0 @@ -import SwiftUI - -/// What an agent's actions need from the screen showing them. -struct AgentActionsConfig { - let store: AgentDirectoryStore - let runtimeDefaultsClient: any AgentRuntimeDefaultsClient - let owner: WorkspaceOwner? - let capabilities: WorkspaceCapabilities - let cloneClient: (any AgentProfileCloneClient)? - let shortcutsAvailable: Bool - let onAction: (@MainActor (AgentWorkspaceActionRequest) -> Void)? - let agentDeletion: AgentDeletionAction? - - func supports(_ capability: WorkspaceCapability, profileID: String? = nil) -> Bool { - guard let owner else { return false } - return capabilities.supports(capability, owner: owner, profileID: profileID) - } - - func capabilityReason(_ capability: WorkspaceCapability, profileID: String?) -> String { - guard let owner else { return WorkspaceUnavailableReason.notConnected.message } - return AgentActionsPresentation.unavailableMessage( - capabilities.availability(for: capability, owner: owner, profileID: profileID) - ) ?? WorkspaceUnavailableReason.unsupportedOperation.message - } -} - -/// An agent's hold-menu actions and the sheets they open, shared by the Agents -/// list and the Chats "Your agents" rail so both offer the same options. -@MainActor @Observable -final class AgentActions { - var editor: AgentEditorModel? - var shortcutsAgent: AgentProfile? - var duplicateModel: AgentDuplicateModel? - var pendingDeletion: AgentProfile? - private(set) var deletingAgent: AgentProfile? - var templateNotice: String? - var actionError: String? - /// The connection the actions run on. - private(set) var activeOwner: WorkspaceOwner? - /// The computer and sign-in the sheets belong to; they close when it changes. - private var signIn: WorkspaceSignIn? - - func items(_ agent: AgentProfile, _ config: AgentActionsConfig) -> [AgentActionItem] { - AgentActionsPresentation.items( - profileID: agent.id, owner: config.owner, capabilities: config.capabilities, - isPrimary: config.store.isPrimary(agent.id), isPinned: config.store.isPinned(agent.id), - canPin: config.store.canPin(agent.id), canClone: config.cloneClient != nil, - shortcutsAvailable: config.shortcutsAvailable, hasNavigation: config.onAction != nil, - canDelete: config.agentDeletion != nil && deletingAgent == nil && AgentDeletionPresentation.canDelete(agent), - canSaveTemplate: true - ) - } - - /// Runs one action. `.groups` belongs to the Agents list, which handles it itself. - func perform(_ action: AgentRowMenuAction, agent: AgentProfile, config: AgentActionsConfig) { - guard let owner = config.owner, owner == activeOwner, - items(agent, config).first(where: { $0.action == action })?.isEnabled == true else { - actionError = "This action is no longer available. Reopen the agent's actions to see its current status." - return - } - switch action { - case .openChat: dispatch(.openAgentChat(profileID: agent.id), config) - case .viewSessions: dispatch(.openAgentSessions(profileID: agent.id), config) - case .scheduledTasks: dispatch(.openAgentScheduledTasks(profileID: agent.id), config) - case .setPrimary: config.store.setPrimaryAgent(agent.id) - case .togglePin: - if config.store.isPinned(agent.id) { config.store.unpinAgent(agent.id) } - else { config.store.pinAgent(agent.id) } - case .groups: break - case .edit: - editor = .editing(agent, store: config.store, processor: AvatarImageProcessor(), - isCurrent: { [weak self] in self?.activeOwner?.signIn == owner.signIn }) - case .duplicate: - guard let cloneClient = config.cloneClient else { return } - duplicateModel = AgentDuplicateModel(source: agent, owner: owner, client: cloneClient, - isCurrent: { [weak self] in self?.activeOwner == owner }) - case .shortcuts: shortcutsAgent = agent - case .saveTemplate: - let template = AgentTemplateLibrary.shared.save(from: agent) - templateNotice = "“\(template.title)” is saved on this device. To use it, create an agent and choose My templates." - case .delete: pendingDeletion = agent - } - } - - /// Runs after the confirmation. The list refreshes once Hermes confirms the agent is gone. - func delete(_ agent: AgentProfile, config: AgentActionsConfig) { - guard let deletion = config.agentDeletion, let owner = config.owner, owner == activeOwner else { - actionError = "Deleting agents isn't available on this connection." - return - } - deletingAgent = agent - Task { @MainActor in - defer { deletingAgent = nil } - do { - try await deletion.run(agent.id) - } catch { - guard activeOwner == owner else { return } - actionError = AgentDeletionPresentation.errorMessage(error) - } - } - } - - func adopt(owner: WorkspaceOwner?) { - guard owner != activeOwner else { return } - activeOwner = owner - // A copy in progress can't carry over to another connection. - duplicateModel?.cancel() - duplicateModel = nil - // Disconnected, or back on the same computer and sign-in (bighelp - // reconnects after you've been away): open sheets and dialogs stay. - guard let owner, owner.signIn != signIn else { return } - let previousScope = signIn?.authority.cacheScopeID - signIn = owner.signIn - shortcutsAgent = nil - pendingDeletion = nil - if previousScope != owner.cacheScopeID { editor = nil } - } - - private func dispatch(_ action: AgentWorkspaceAction, _ config: AgentActionsConfig) { - guard let owner = config.owner, owner == activeOwner, let onAction = config.onAction else { - actionError = "The host connection changed. Try opening this action again." - return - } - onAction(AgentWorkspaceActionRequest(owner: owner, action: action)) - } -} - -/// The hold menu's buttons for one agent. -struct AgentActionMenuItems: View { - let actions: AgentActions - let agent: AgentProfile - let config: AgentActionsConfig - var hidden: Set = [] - var perform: ((AgentRowMenuAction) -> Void)? = nil - - var body: some View { - ForEach(actions.items(agent, config).filter { !$0.isUnsupported && !hidden.contains($0.action) }) { item in - if item.action.isDestructive { Divider() } - Button(item.title, systemImage: item.systemImage, role: item.action.isDestructive ? .destructive : nil) { - if let perform { perform(item.action) } else { actions.perform(item.action, agent: agent, config: config) } - } - .disabled(!item.isEnabled) - } - } -} - -extension View { - /// Presents what the agent actions open: edit, duplicate, Siri, delete confirmation and notices. - func agentActionsPresentation(_ actions: AgentActions, config: AgentActionsConfig) -> some View { - modifier(AgentActionsSheets(actions: actions, config: config)) - } - - @ViewBuilder - func agentActionsPresentation(_ actions: AgentActions, config: AgentActionsConfig?) -> some View { - if let config { modifier(AgentActionsSheets(actions: actions, config: config)) } else { self } - } -} - -private struct AgentActionsSheets: ViewModifier { - @Bindable var actions: AgentActions - let config: AgentActionsConfig - - func body(content: Content) -> some View { - content - .onAppear { actions.adopt(owner: config.owner) } - .onChange(of: config.owner) { _, owner in actions.adopt(owner: owner) } - .bighelpSheet(item: $actions.editor) { model in - let canReadDefaults = config.supports(.modelsRead, profileID: model.editingAgentID) - let canEditDefaults = config.supports(.agentDefaultsEdit, profileID: model.editingAgentID) - AgentEditorView( - model: model, - runtimeDefaultsClient: canReadDefaults ? config.runtimeDefaultsClient : nil, - runtimeDefaultsReadOnlyReason: model.isEditing && (!canReadDefaults || !canEditDefaults) - ? config.capabilityReason(canReadDefaults ? .agentDefaultsEdit : .modelsRead, - profileID: model.editingAgentID) - : nil - ) { _ in actions.editor = nil } - } - .bighelpSheet(item: $actions.shortcutsAgent) { agent in - AgentShortcutsView(agent: agent) - .bighelpSheetSize(.standard) - } - .bighelpSheet(item: $actions.duplicateModel) { model in - AgentDuplicateView(model: model) { - actions.duplicateModel = nil - Task { await config.store.loadReportingErrors() } - } - .bighelpSheetSize(.standard) - } - .confirmationDialog(actions.pendingDeletion.map(AgentDeletionPresentation.title) ?? "Delete agent?", - isPresented: Binding(get: { actions.pendingDeletion != nil }, - set: { if !$0 { actions.pendingDeletion = nil } }), - titleVisibility: .visible, presenting: actions.pendingDeletion) { agent in - Button("Delete Agent", role: .destructive) { actions.delete(agent, config: config) } - .accessibilityIdentifier("agents.delete.confirm") - } message: { agent in - Text(AgentDeletionPresentation.message(agent)) - } - .overlay(alignment: .bottom) { - if let deleting = actions.deletingAgent { - Label { - Text(AgentDeletionPresentation.progress(deleting)) - } icon: { - ProgressView() - } - .padding(.horizontal, BighelpTokens.space16) - .padding(.vertical, BighelpTokens.space12) - .background(.regularMaterial, in: Capsule()) - .padding(.bottom, BighelpTokens.space24) - .accessibilityIdentifier("agents.deleting") - } - } - .alert("Template saved", isPresented: Binding(get: { actions.templateNotice != nil }, - set: { if !$0 { actions.templateNotice = nil } })) { - } message: { - Text(actions.templateNotice ?? "") - } - .alert("Agent action unavailable", isPresented: Binding( - get: { actions.actionError != nil }, - set: { if !$0 { actions.actionError = nil } } - )) {} message: { - Text(actions.actionError ?? "") - } - } -} diff --git a/Bighelp/Agents/AgentDirectoryStore.swift b/Bighelp/Agents/AgentDirectoryStore.swift index a57d7730..4ca4f82c 100644 --- a/Bighelp/Agents/AgentDirectoryStore.swift +++ b/Bighelp/Agents/AgentDirectoryStore.swift @@ -30,7 +30,7 @@ final class AgentDirectoryStore { /// decision rather than a layout accident, so it lives with the store that /// owns the pin set, and its copy counterpart in `AgentActionPresentation` /// is checked against it by test. - static let pinnedAgentLimit = AgentActionPresentation.pinnedAgentLimit + static let pinnedAgentLimit = 5 private(set) var profiles: [AgentProfile] = [] private(set) var selectedAgentID: String? @@ -346,7 +346,7 @@ final class AgentDirectoryStore { pinAgent(id, limit: Self.pinnedAgentLimit, counting: pinnedAgentIDs.count) } - /// Pins `id` while `counting` is under `limit`. Bots mode counts only the + /// Pins `id` while `counting` is under `limit`. The Bots view counts only the /// pinned bots its home shows (`SimpleBotsHomeProjection.canPin`). @discardableResult func pinAgent(_ id: String, limit: Int, counting: Int) -> Bool { @@ -366,7 +366,7 @@ final class AgentDirectoryStore { return true } - /// Puts the pinned agents in this order (dragging them on the Agents screen). + /// Puts the pinned agents in this order (dragging them on the Bots view). /// Pins not named keep their place after the named ones; unknown ids are ignored. @discardableResult func reorderPinnedAgents(_ ids: [String]) -> Bool { @@ -584,7 +584,7 @@ private struct RemoteAgentAvatarCache { extension AgentDirectoryStore { /// A sign-in's pinned agents (in order), the ones unpinned on purpose and its primary agent: - /// what Bots mode's top shows, kept on the computer too (`BotsAppState`). + /// what the Bots view's top shows, kept on the computer too (`BotsAppState`). struct SavedPins: Equatable, Sendable { var pinned: [String] = [] var unpinned: [String] = [] @@ -613,7 +613,7 @@ extension AgentDirectoryStore { primary: (defaults.dictionary(forKey: Keys.primaryAgentIDByHost) as? [String: String])?[hostBucket]) } - /// Saves a sign-in's pins where its Agents screen reads them, for one that isn't in use. + /// Saves a sign-in's pins where its Bots view reads them, for one that isn't in use. static func savePins(_ pins: SavedPins, in defaults: UserDefaults, hostBucket: String) { var pinned = defaults.dictionary(forKey: Keys.pinnedAgentIDsByHost) as? [String: [String]] ?? [:] var unpinned = defaults.dictionary(forKey: Keys.unpinnedAgentIDsByHost) as? [String: [String]] ?? [:] @@ -638,7 +638,7 @@ extension AgentDirectoryStore { } /// Pins or unpins an agent of a host that isn't selected (from the all-hosts - /// view), saved just as the Agents screen saves it while that host is selected. + /// view), saved just as the Bots view saves it while that host is selected. /// An unpinned agent is remembered as unpinned, so a default agent stays off. @discardableResult static func savePin(_ pinned: Bool, agentID: String, in defaults: UserDefaults, hostBucket: String) -> Bool { diff --git a/Bighelp/Agents/AgentEditorView.swift b/Bighelp/Agents/AgentEditorView.swift deleted file mode 100644 index c857c82e..00000000 --- a/Bighelp/Agents/AgentEditorView.swift +++ /dev/null @@ -1,1043 +0,0 @@ -import PhotosUI -import SwiftUI -import UIKit - -@MainActor -struct AgentEditorView: View { - private enum Destination: Hashable { - case advanced - case photoActions - } - - @State private var model: AgentEditorModel - @State private var navigationPath: [Destination] - @State private var runtimeDefaultsModel: AgentRuntimeDefaultsEditorModel? - @State private var modelPickerScope: AgentRuntimeScope? - @State private var photoSelection: PhotosPickerItem? - @State private var avatarPreparationTask: Task? - @State private var avatarPreparationID: UUID? - @State private var expandsInstructions = false - /// While the instructions box is edited, a drag that scrolls the form keeps the keyboard. - @State private var editsInstructions = false - @State private var avatarPreparationLabel: String? - @State private var isDiscardConfirmationPresented = false - @State private var isModelConfirmationPresented = false - @State private var pendingCompletedProfile: AgentProfile? - @State private var isAvatarCreatorPresented = false - /// Where the creator opens, worked out each time it's opened. - @State private var creatorStart: AvatarCreatorStart? - /// A new agent's first look in the creator, picked once per editor. Also the - /// character page for an agent that wears something else. - @State private var surpriseLook = AvatarCreatorModel.surprise() - /// Templates › Browse all, presented from the form's root so its search gets the keyboard. - @State private var isBrowsingTemplates = false - /// Picked in Browse all; applied once that sheet has closed, since a template's form opens as - /// a sheet of its own. - @State private var browsedTemplate: AgentSoulTemplate? - @FocusState private var focusedField: AgentEditorModel.Field? - @Environment(\.dismiss) private var dismiss - - let onCompleted: (AgentProfile) -> Void - let runtimeDefaultsReadOnlyReason: String? - - init( - model: AgentEditorModel, - runtimeDefaultsClient: (any AgentRuntimeDefaultsClient)? = nil, - runtimeDefaultsReadOnlyReason: String? = nil, - initiallyShowsAdvanced: Bool = false, - onCompleted: @escaping (AgentProfile) -> Void - ) { - _model = State(initialValue: model) - _navigationPath = State(initialValue: initiallyShowsAdvanced ? [.advanced] : []) - if let agentID = model.editingAgentID, let runtimeDefaultsClient { - _runtimeDefaultsModel = State(initialValue: AgentRuntimeDefaultsEditorModel( - agentID: agentID, - client: runtimeDefaultsClient - )) - } else { - _runtimeDefaultsModel = State(initialValue: nil) - } - self.onCompleted = onCompleted - self.runtimeDefaultsReadOnlyReason = runtimeDefaultsReadOnlyReason - } - - @Environment(\.nerdModeEnabled) private var nerdModeEnabled - private var templateLibrary: AgentTemplateLibrary { .shared } - @Environment(\.agentDeletion) private var agentDeletion - @State private var isDeleteConfirmationPresented = false - @State private var isDeleting = false - @State private var deleteError: String? - @State private var templateNotice: String? - - /// Asked for after the confirmation; the editor closes once Hermes confirms. - private func delete(_ agent: AgentProfile) { - guard let agentDeletion else { return } - isDeleting = true - Task { @MainActor in - defer { isDeleting = false } - do { - try await agentDeletion.run(agent.id) - dismiss() - } catch { - deleteError = AgentDeletionPresentation.errorMessage(error) - } - } - } - - var body: some View { - @Bindable var model = model - NavigationStack(path: $navigationPath) { - Form { - identitySection( - model: model, - name: $model.draft.name, - role: $model.draft.role, - summary: $model.draft.summary - ) - instructionsSection(model: model, instructions: $model.draft.instructions) - .onChange(of: model.draft.name) { _, _ in model.nameDidChange() } - if model.editingAgentID != nil { - photoActionsSection - } - if let defaults = runtimeDefaultsModel { - AgentRuntimeDefaultsSection( - model: defaults, - allowsEdits: runtimeDefaultsReadOnlyReason == nil, - scopes: [.mainChats], - modelPickerScope: $modelPickerScope - ) - } - if let reason = runtimeDefaultsReadOnlyReason { - Section { - Label(reason, systemImage: "lock") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } header: { - if runtimeDefaultsModel == nil { AgentStudioCaption("Model") } - } - .listRowBackground(theme.surface) - } - // Handles, subagent models, clone sources and bundled skills are - // host details: the Advanced route appears only with Nerd Mode on. - if nerdModeEnabled || model.fieldErrors[.cloning] != nil { - Section { - if nerdModeEnabled { - NavigationLink(value: Destination.advanced) { - Label { - VStack(alignment: .leading, spacing: 2) { - Text("Advanced") - .foregroundStyle(theme.primaryText) - Text(!model.isEditing - ? "Setup to copy, bundled skills, mention handle" - : runtimeDefaultsModel == nil - ? "Mention handle" - : "Subagent and task models, mention handle") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } - } icon: { - Image(systemName: "slider.horizontal.3") - .foregroundStyle(theme.secondaryText) - } - .frame(minHeight: BighelpTokens.hitTarget) - } - .accessibilityIdentifier("agent.editor.advanced") - } - if let error = model.fieldErrors[.cloning] { recoveryMessage(error) } - } - .listRowBackground(theme.surface) - } - if let saveError = model.saveError { - Section { recoveryMessage(saveError) } - .listRowBackground(theme.surface) - } - if let agent = model.editedProfile { - Section { - Button { - let template = templateLibrary.save(from: AgentProfile( - id: agent.id, name: model.draft.name, role: model.draft.role, - summary: model.draft.summary, instructions: model.draft.instructions, - avatarFileName: model.draft.avatarFileName, avatar: model.draft.avatar, - isDefault: agent.isDefault)) - templateNotice = "“\(template.title)” is saved on this device. To use it, create an agent and choose My templates." - } label: { - Label("Save as Template", systemImage: "square.and.arrow.down.on.square") - .frame(minHeight: BighelpTokens.hitTarget) - } - .accessibilityIdentifier("agent.editor.save-template") - if agentDeletion != nil, AgentDeletionPresentation.canDelete(agent) { - Button(role: .destructive) { - isDeleteConfirmationPresented = true - } label: { - HStack { - Label("Delete Agent", systemImage: "trash") - Spacer() - if isDeleting { ProgressView() } - } - .frame(minHeight: BighelpTokens.hitTarget) - } - .disabled(isDeleting) - .accessibilityIdentifier("agent.editor.delete") - } - } - .listRowBackground(theme.surface) - .confirmationDialog(AgentDeletionPresentation.title(agent), isPresented: $isDeleteConfirmationPresented, - titleVisibility: .visible) { - Button("Delete Agent", role: .destructive) { delete(agent) } - .accessibilityIdentifier("agent.editor.delete.confirm") - } message: { - Text(AgentDeletionPresentation.message(agent)) - } - } - } - .disabled(isSaving || isDeleting) - .alert("Template saved", isPresented: Binding(get: { templateNotice != nil }, set: { if !$0 { templateNotice = nil } })) { - } message: { - Text(templateNotice ?? "") - } - .alert("Couldn't delete this agent", isPresented: Binding(get: { deleteError != nil }, set: { if !$0 { deleteError = nil } })) { - } message: { - Text(deleteError ?? "") - } - .scrollContentBackground(.hidden) - .dismissesKeyboardOnScroll(!editsInstructions) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle(model.isEditing ? "Edit Agent" : "Agent Studio") - .navigationBarTitleDisplayMode(.inline) - .navigationDestination(for: Destination.self) { destination in - switch destination { - case .advanced: - advancedForm(model: model) - case .photoActions: - if let agentID = model.editingAgentID { - PhotoActionsSettingsView(agentID: agentID, agentName: heroTitle) - } - } - } - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Cancel", action: requestDismissal) - .frame(minHeight: BighelpTokens.toolbarHitTarget) - .disabled(isSaving) - #if targetEnvironment(macCatalyst) - .keyboardShortcut(.cancelAction) - #endif - .accessibilityIdentifier("agent.editor.cancel") - .bighelpToolbarText() - } - ToolbarItem(placement: .confirmationAction) { - Button(model.isEditing ? "Save" : "Create", action: saveAgent) - .fontWeight(.semibold) - .bighelpProminentButtonStyle() - .buttonBorderShape(.capsule) - .tint(theme.action) - .foregroundStyle(theme.actionForeground) - .frame(minHeight: BighelpTokens.hitTarget) - .disabled(isSaving || model.hasUnconfirmedSave || avatarPreparationID != nil) - .accessibilityLabel(model.isEditing ? "Save agent" : "Create agent") - .accessibilityIdentifier("agent.editor.save") - } - #if !os(visionOS) // Vision Pro's keyboard has its own dismiss key. - ToolbarItemGroup(placement: .keyboard) { - Spacer() - Button("Done") { focusedField = nil } - .accessibilityLabel("Dismiss keyboard") - } - #endif - } - } - // Always a sheet (Agents, chat, home), so every opening gets the studio's size on the Mac. - .bighelpSheetSize(.large) - // Starts once for the whole editor, including Advanced. See loadIfNeeded(). - .task { await runtimeDefaultsModel?.loadIfNeeded() } - .interactiveDismissDisabled(hasUnsavedChanges || isSaving) - .focusedTextEditor( - isPresented: $expandsInstructions, - title: "Instructions", - text: $model.draft.instructions, - placeholder: instructionsPlaceholder, - identifier: "agent.editor.instructions.expand", - onSave: canSaveAgent ? { saveAgent() } : nil - ) - .onChange(of: photoSelection) { _, selection in - guard let selection else { return } - preparePhotoAvatar(selection) - } - .bighelpSheet(isPresented: $isAvatarCreatorPresented) { - AvatarChooserView( - start: creatorStart ?? currentCreatorStart, characters: surpriseLook, agentName: heroTitle, - faceName: model.faceName, - petSource: PetdexSource(store: model.store, cacheScope: "\(ObjectIdentifier(model.store))") - ) { result in - switch result { - case .companion(let look): prepareCompanionAvatar(look) - case .look(let look): prepareLookAvatar(look) - case .pet(let pet, let avatar): preparePetAvatar(pet, data: avatar) - case .photo(let item): photoSelection = item - case .mark(let mark): prepareMarkAvatar(mark) - } - } - .presentationDragIndicator(.visible) - #if os(visionOS) - // Wide enough for the 3D character beside the choices. - .presentationSizing(.page) - #endif - // The Mac: wide enough for the character beside the choices. - .bighelpSheetSize(.large) - } - .bighelpSheet(isPresented: $isBrowsingTemplates, onDismiss: { - guard let template = browsedTemplate else { return } - browsedTemplate = nil - AgentStartPicker.pick(template, into: model) - }) { - AgentTemplateBrowser { browsedTemplate = $0 } - .bighelpSheetSize(.large) - } - .agentTemplateForm(model) - // Modal ownership must outlive the lazy sections while a picker is presented. - .bighelpSheet(item: $modelPickerScope) { scope in - if let defaults = runtimeDefaultsModel { - agentModelPicker(defaults: defaults, scope: scope) - } - } - .alert( - "Discard agent changes?", - isPresented: $isDiscardConfirmationPresented - ) { - Button("Discard changes", role: .destructive) { dismiss() } - Button("Keep editing", role: .cancel) {} - } message: { - Text("Your unsaved changes will be lost.") - } - .onDisappear { - cancelAvatarPreparation() - runtimeDefaultsModel?.dismissConfirmation() - } - .onChange(of: runtimeDefaultsModel?.pendingConfirmation) { _, confirmation in - isModelConfirmationPresented = confirmation != nil - } - .bighelpSheet(isPresented: $isModelConfirmationPresented) { - BighelpModelWarningSheet( - title: "Confirm model defaults", - message: runtimeDefaultsModel?.pendingConfirmation?.message ?? "" - ) { - isModelConfirmationPresented = false - Task { - do { - try await runtimeDefaultsModel?.confirmPendingSave() - if model.isCurrentContext, !model.hasUnsavedChanges, - runtimeDefaultsModel?.isDirty != true, let profile = pendingCompletedProfile { - onCompleted(profile) - pendingCompletedProfile = nil - dismiss() - } - } catch { - // The defaults model retains the choices and reports the failed confirmation. - } - } - } onCancel: { - isModelConfirmationPresented = false - runtimeDefaultsModel?.dismissConfirmation() - } - } - .accessibilityIdentifier(model.isEditing ? "agent.editor.edit" : "agent.editor.create") - } - - /// The chat's model picker: choose a model and reasoning level, then apply them - /// to this agent's draft. Save still commits them with the rest of the agent. - private func agentModelPicker(defaults: AgentRuntimeDefaultsEditorModel, scope: AgentRuntimeScope) -> some View { - let selection = defaults.draft[scope] - let reasoningUnavailable = defaults.support.reasoningUnavailableReasons[scope] - return BighelpModelPickerSheet( - title: "Choose model", - scopeLabel: scope.title, - providers: defaults.providers, - currentProviderID: selection.modelID.isEmpty ? nil : selection.providerID, - currentModelID: selection.modelID.isEmpty ? nil : selection.modelID, - isLoading: false, - isApplying: false, - errorMessage: defaults.errorMessage, - onClearError: defaults.clearError, - onRetry: { - Task { await defaults.refreshProviders() } - }, - onSelect: { _, _ in }, - reasoningOptions: reasoningUnavailable == nil - ? AgentReasoningOption.all.map { - RuntimeReasoningOption(value: $0.value, label: $0.title, detail: $0.detail, - isCurrent: $0.value == selection.reasoningEffort) - } - : [], - currentReasoningValue: selection.reasoningEffort, - modelUnavailableReason: defaults.support.modelUnavailableReasons[scope], - reasoningUnavailableReason: reasoningUnavailable, - applyTitle: "Use for this agent", - defaultModelTitle: "Default model", - onApply: { draft in - if let providerID = draft.providerID, let modelID = draft.modelID, - providerID != selection.providerID || modelID != selection.modelID { - defaults.selectModel(providerID: providerID, modelID: modelID, for: scope) - } - if let reasoning = draft.reasoningValue, reasoning != selection.reasoningEffort { - defaults.selectReasoning(reasoning, for: scope) - } - if defaults.errorMessage == nil { modelPickerScope = nil } - } - ) - .presentationDetents([.large]) - .presentationDragIndicator(.visible) - .bighelpSheetSize(.standard) - } - - private var isSaving: Bool { - model.isSaving || runtimeDefaultsModel?.isSaving == true - } - - private var hasUnsavedChanges: Bool { - model.hasUnsavedChanges || runtimeDefaultsModel?.isDirty == true - } - - private func advancedForm(model: AgentEditorModel) -> some View { - Form { - if let defaults = runtimeDefaultsModel { - AgentRuntimeDefaultsSection( - model: defaults, - allowsEdits: runtimeDefaultsReadOnlyReason == nil, - scopes: [.subagents, .scheduledTasks], - modelPickerScope: $modelPickerScope - ) - } - if !model.isEditing { cloningSection(model: model) } - handleSection(model: model) - } - .scrollContentBackground(.hidden) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle("Advanced") - .navigationBarTitleDisplayMode(.inline) - } - - private func requestDismissal() { - if hasUnsavedChanges { - isDiscardConfirmationPresented = true - } else { - dismiss() - } - } - - private func cancelAvatarPreparation() { - avatarPreparationTask?.cancel() - avatarPreparationTask = nil - avatarPreparationID = nil - avatarPreparationLabel = nil - } - - private func beginAvatarPreparation(label: String) -> UUID { - cancelAvatarPreparation() - let requestID = UUID() - avatarPreparationID = requestID - avatarPreparationLabel = label - return requestID - } - - private func finishAvatarPreparation(_ requestID: UUID) { - guard avatarPreparationID == requestID else { return } - avatarPreparationTask = nil - avatarPreparationID = nil - avatarPreparationLabel = nil - photoSelection = nil - } - - private func ownsAvatarPreparation(_ requestID: UUID) -> Bool { - avatarPreparationID == requestID && model.isCurrentContext && !Task.isCancelled - } - - @ViewBuilder - private func heroAvatar(model: AgentEditorModel) -> some View { - #if os(visionOS) - if let look = heroLook, let spatial = SpatialAvatarLook(appearance: look, themeHex: theme.actionHex) { - // The same 3D character as in the room, playing its moves. - SpatialAvatarPreview(look: spatial, mood: look.vibe?.moodID, height: 170, isInteractive: false) - } else { - avatarPreview(model: model, size: 120) - } - #else - avatarPreview(model: model, size: 120) - #endif - } - - #if os(visionOS) - /// A designed look to show in 3D: this session's pick, or the agent's saved one. - private var heroLook: CompanionAppearance? { - if model.pendingAvatar != nil { return model.selectedCompanionAppearance } - guard !model.draft.removesAvatar, let agentID = model.editingAgentID, let store = companionStore, - !companionAgentScope.isEmpty else { return nil } - return store.override(for: CompanionStore.agentKey(agentScope: companionAgentScope, agentID: agentID)) - } - #endif - - private var heroState: AgentLiveState { - // A preview, not live status: a new agent perks up once it has a name. - !model.isEditing && !model.draft.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? .happy : .idle - } - - private var heroTitle: String { - let name = model.draft.name.trimmingCharacters(in: .whitespacesAndNewlines) - if !name.isEmpty { return name } - return model.isEditing ? "Agent" : "New agent" - } - - private var hasAvatar: Bool { - model.pendingAvatar != nil || model.draft.avatarFileName != nil || model.draft.avatar != nil - } - - private func hero(model: AgentEditorModel) -> some View { - VStack(spacing: BighelpTokens.space8) { - heroAvatar(model: model) - .contentShape(.circle) - .onTapGesture { openAvatarCreator() } - .accessibilityElement(children: .ignore) - .accessibilityLabel(model.selectedCompanionCharacter.map { - "\($0.displayName) agent avatar preview" - } ?? "Agent avatar preview") - .accessibilityHint("Opens the avatar creator.") - .accessibilityAddTraits(.isButton) - .accessibilityIdentifier("agent.editor.avatar-preview") - .overlay(alignment: .bottomTrailing) { - PhotosPicker(selection: $photoSelection, matching: .images) { - Image(systemName: "camera.fill") - .font(.system(size: 15, weight: .semibold)) - .foregroundStyle(theme.actionForeground) - .frame(width: 34, height: 34) - .background(theme.action, in: .circle) - .overlay(Circle().strokeBorder(theme.canvas, lineWidth: 3)) - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - .contentShape(.circle) - } - #if os(visionOS) - // Otherwise it becomes the whole row's button, a glass slab over the - // avatar that takes every pinch meant for Design avatar. - .buttonStyle(.plain) - .hoverEffect(.highlight) - #endif - .offset(x: 6, y: 6) - .accessibilityLabel("Choose custom agent avatar photo") - .accessibilityIdentifier("agent.editor.avatar-picker") - } - .padding(.bottom, BighelpTokens.space4) - Text(heroTitle) - .font(.bighelp(.title2).weight(.bold)) - .foregroundStyle(theme.primaryText) - .multilineTextAlignment(.center) - .lineLimit(2) - .accessibilityIdentifier("agent.editor.hero-title") - let role = model.draft.role.trimmingCharacters(in: .whitespacesAndNewlines) - if !role.isEmpty { - Text(role) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - .lineLimit(2) - } - HStack(spacing: BighelpTokens.space8) { - Button { - openAvatarCreator() - } label: { - Label(hasAvatar ? "Edit avatar" : "Design avatar", systemImage: "wand.and.stars") - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.action) - .padding(.horizontal, BighelpTokens.space16) - .frame(minHeight: 36) - .background(Capsule().fill(theme.incomingMessageBackground)) - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.capsule) - } - .buttonStyle(.plain) - .accessibilityHint("Pick a character, color, eyes, extras and moves.") - .accessibilityIdentifier("agent.editor.design-avatar") - if hasAvatar { - Button { - cancelAvatarPreparation() - model.removeAvatar() - photoSelection = nil - } label: { - Text("Remove") - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.secondaryText) - .padding(.horizontal, BighelpTokens.space12) - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityLabel("Remove avatar") - .accessibilityIdentifier("agent.editor.avatar-remove") - } - } - // In a Vision Pro form this row was laid out zero points tall, so - // Design avatar hung over the name and missed every pinch. - .frame(minHeight: BighelpTokens.hitTarget) - .fixedSize(horizontal: false, vertical: true) - if let avatarPreparationLabel { - ProgressView(avatarPreparationLabel) - .font(.bighelp(.footnote)) - .accessibilityIdentifier("agent.editor.avatar.loading") - } - if let avatarError = model.avatarError { - recoveryMessage(avatarError) - .multilineTextAlignment(.center) - } - } - .frame(maxWidth: .infinity) - .padding(.top, BighelpTokens.space8) - } - - private func preparePhotoAvatar(_ selection: PhotosPickerItem) { - let requestID = beginAvatarPreparation(label: "Preparing photo avatar") - avatarPreparationTask = Task { @MainActor in - defer { finishAvatarPreparation(requestID) } - do { - let data = try await selection.loadTransferable(type: Data.self) - try Task.checkCancellation() - guard ownsAvatarPreparation(requestID) else { return } - guard let data else { - model.reportAvatarLoadFailure() - return - } - try await model.importAvatar(data: data) - } catch is CancellationError { - return - } catch is AvatarImageProcessor.Error { - // The model already exposed a format or size-specific recovery message. - } catch { - guard ownsAvatarPreparation(requestID) else { return } - model.reportAvatarLoadFailure() - } - } - } - - private func openAvatarCreator() { - creatorStart = currentCreatorStart - isAvatarCreatorPresented = true - } - - /// The avatar the agent has now, or a surprise for a new agent. - private var currentCreatorStart: AvatarCreatorStart { - let key = savedLookKey - return model.avatarCreatorStart( - savedCharacter: key.flatMap { companionStore?.override(for: $0) }, - savedPetSlug: key.flatMap { PetAvatarStore.shared.slug(for: $0) }, - surprise: surpriseLook - ) - } - - /// Where this device keeps the agent's character and pet. - private var savedLookKey: String? { - guard let agentID = model.editingAgentID, !companionAgentScope.isEmpty else { return nil } - return CompanionStore.agentKey(agentScope: companionAgentScope, agentID: agentID) - } - - private func prepareLookAvatar(_ look: AgentAvatarLook) { - photoSelection = nil - let requestID = beginAvatarPreparation(label: "Preparing avatar") - avatarPreparationTask = Task { @MainActor in - defer { finishAvatarPreparation(requestID) } - do { - guard let data = HermesLookRenderer.png(look: look, name: model.faceName) else { - throw AgentCompanionAvatarRenderer.RenderError.emptyImage - } - try Task.checkCancellation() - guard ownsAvatarPreparation(requestID) else { return } - try await model.importLookAvatar(data: data, look: look) - } catch is CancellationError { - return - } catch is AvatarImageProcessor.Error { - // The model already exposed a format or size-specific recovery message. - } catch { - guard ownsAvatarPreparation(requestID) else { return } - model.reportCompanionAvatarRenderFailure() - } - } - } - - /// A Simple Bot mark, as the picture everyone sees. - private func prepareMarkAvatar(_ mark: SimpleBotMark) { - photoSelection = nil - let requestID = beginAvatarPreparation(label: "Preparing avatar") - avatarPreparationTask = Task { @MainActor in - defer { finishAvatarPreparation(requestID) } - do { - guard let data = SimpleBotMarkView.png(mark) else { - throw AgentCompanionAvatarRenderer.RenderError.emptyImage - } - guard ownsAvatarPreparation(requestID) else { return } - try await model.importAvatar(data: data) - } catch is CancellationError { - return - } catch is AvatarImageProcessor.Error { - // The model already exposed a format or size-specific recovery message. - } catch { - guard ownsAvatarPreparation(requestID) else { return } - model.reportCompanionAvatarRenderFailure() - } - } - } - - private func preparePetAvatar(_ pet: PetdexPet, data: Data) { - photoSelection = nil - let requestID = beginAvatarPreparation(label: "Preparing \(pet.displayName) avatar") - avatarPreparationTask = Task { @MainActor in - defer { finishAvatarPreparation(requestID) } - do { - guard ownsAvatarPreparation(requestID) else { return } - try await model.importPetAvatar(data: data, pet: pet) - } catch is CancellationError { - return - } catch is AvatarImageProcessor.Error { - // The model already exposed a format or size-specific recovery message. - } catch { - guard ownsAvatarPreparation(requestID) else { return } - model.reportCompanionAvatarRenderFailure() - } - } - } - - /// The creator's look also becomes this agent's animated chat companion. - private func applyCompanionLook(to profile: AgentProfile) { - guard let store = companionStore, !companionAgentScope.isEmpty else { return } - model.applySavedLook(companions: store, pets: .shared, - key: CompanionStore.agentKey(agentScope: companionAgentScope, agentID: profile.id)) - } - - private func prepareCompanionAvatar(_ look: CompanionAppearance) { - photoSelection = nil - let appearance = appAppearance - let scheme = colorScheme - let contrast = colorSchemeContrast - let requestID = beginAvatarPreparation(label: "Preparing \(look.character.displayName) avatar") - avatarPreparationTask = Task { @MainActor in - defer { finishAvatarPreparation(requestID) } - do { - let data = try await AgentCompanionAvatarRenderer.renderPNG( - companion: look, - appearance: appearance, - colorScheme: scheme, - colorSchemeContrast: contrast - ) - try Task.checkCancellation() - guard ownsAvatarPreparation(requestID) else { return } - try await model.importCompanionAvatar(data: data, appearance: look) - } catch is CancellationError { - return - } catch is AvatarImageProcessor.Error { - // The model already exposed a format or size-specific recovery message. - } catch { - guard ownsAvatarPreparation(requestID) else { return } - model.reportCompanionAvatarRenderFailure() - } - } - } - - @ViewBuilder - private func avatarPreview(model: AgentEditorModel, size: CGFloat = 72) -> some View { - if model.pendingAvatar != nil, let look = model.selectedCompanionAppearance { - // A creator look plays its chosen moves right here, with nothing behind it. - CompanionAvatar(appearance: look, reaction: .idle, isAnimating: true) - .frame(width: size * 0.8, height: size * 0.8) - .frame(width: size, height: size) - } else if model.pendingAvatar != nil, let look = model.pendingLook, look.drawsLive { - // A Hermes face stays sharp at any size, as Hermes Desktop draws it. - HermesLookView(look: look, name: model.faceName) - .frame(width: size, height: size) - } else if let pending = model.pendingAvatar, let image = UIImage(data: pending.data) { - Image(uiImage: image) - .resizable() - .scaledToFill() - .frame(width: size, height: size) - .clipShape(.circle) - } else { - AvatarView( - stableID: model.editingAgentID ?? "agent-editor-new", - displayName: model.draft.name.isEmpty ? "New agent" : model.draft.name, - imageURL: model.draft.removesAvatar ? nil : model.avatarURL, - size: size, - state: heroState - ) - } - } - - @ViewBuilder - private func identitySection( - model: AgentEditorModel, - name: Binding, - role: Binding, - summary: Binding - ) -> some View { - #if os(visionOS) - // Section headers don't grow to fit on Vision Pro: the avatar, name and - // Design avatar piled up and the button ended up zero points tall. A row - // sizes itself. - Section { - heroAndStarters(model: model) - .padding(.vertical, BighelpTokens.space8) - } - .listRowBackground(Color.clear) - #endif - Section { - field("Name", prompt: "Give your agent a name", text: name, focus: .name, - error: model.fieldErrors[.name], identifier: "agent.editor.name") - field("Role", prompt: "e.g. Travel planner", text: role, focus: .role, - error: model.fieldErrors[.role], identifier: "agent.editor.role") - VStack(alignment: .leading, spacing: BighelpTokens.space4) { - fieldCaption("Vibe") - TextField("Vibe", text: summary, prompt: Text("One line about what it does").bighelpFieldHint(theme), - axis: .vertical) - .lineLimit(1...3) - .focused($focusedField, equals: .summary) - .accessibilityLabel("Vibe") - .accessibilityIdentifier("agent.editor.summary") - if let error = model.fieldErrors[.summary] { recoveryMessage(error) } - } - .padding(.vertical, BighelpTokens.space4) - } header: { - VStack(spacing: BighelpTokens.space20) { - #if !os(visionOS) - heroAndStarters(model: model) - #endif - AgentStudioCaption("Identity") - .frame(maxWidth: .infinity, alignment: .leading) - .accessibilityIdentifier("agent.editor.identity-header") - } - .textCase(nil) - .padding(.bottom, BighelpTokens.space4) - } - .listRowBackground(theme.surface) - } - - private func heroAndStarters(model: AgentEditorModel) -> some View { - VStack(spacing: BighelpTokens.space20) { - hero(model: model) - if !model.isEditing { - AgentStartPicker(model: model, library: templateLibrary) { isBrowsingTemplates = true } - } - } - } - - private func cloningSection(model: AgentEditorModel) -> some View { - Section { - if let reason = model.profileCloneSupport.unavailableReason { - Label(reason, systemImage: "info.circle") - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } else { - Picker("Clone from existing profile", selection: cloneSourceBinding(model)) { - Text("None, create fresh").tag(String?.none) - ForEach(model.cloneSources) { profile in - Text(profile.name).tag(String?.some(profile.id)) - } - } - .accessibilityIdentifier("agent.editor.clone.source") - - Toggle("Skip bundled skills", isOn: Binding( - get: { model.draft.skipBundledSkills }, - set: { model.setSkipBundledSkills($0) } - )) - .frame(minHeight: BighelpTokens.hitTarget) - .accessibilityIdentifier("agent.editor.clone.skip-bundled-skills") - .disabled(model.draft.cloneSourceProfileID != nil) - - if model.draft.cloneSourceProfileID != nil { - Label( - "The source’s skills are included. Chat history, scheduled tasks, and local pins are not copied.", - systemImage: "doc.on.doc" - ) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - } - - Label( - "Use a new name and avatar, then review SOUL so this agent keeps a distinct purpose.", - systemImage: "person.crop.circle.badge.exclamationmark" - ) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("agent.editor.clone.soul-reminder") - - if let error = model.fieldErrors[.cloning] { recoveryMessage(error) } - } header: { - AgentStudioCaption("Copy setup from an agent") - } footer: { - Text(model.draft.cloneSourceProfileID == nil - ? "Start fresh can omit Hermes’ bundled skills." - : "Hermes copies configuration, saved credentials, skills, built-in memories, and SOUL on this host. bighelp never displays credential contents.") - } - .listRowBackground(theme.surface) - } - - private func cloneSourceBinding(_ model: AgentEditorModel) -> Binding { - Binding( - get: { model.draft.cloneSourceProfileID }, - set: { model.selectCloneSource($0) } - ) - } - - private func saveAgent() { - Task { - do { - let profile = try await model.save() - applyCompanionLook(to: profile) - pendingCompletedProfile = profile - try await runtimeDefaultsModel?.saveIfNeeded() - guard model.isCurrentContext else { return } - onCompleted(profile) - pendingCompletedProfile = nil - dismiss() - } catch { - // Each model owns precise, recoverable inline error copy. - } - } - } - - private var instructionsPlaceholder: String { - let name = model.draft.name.trimmingCharacters(in: .whitespacesAndNewlines) - return "What should \(name.isEmpty ? "your agent" : name) help you with? How should it talk?" - } - - private var canSaveAgent: Bool { - !isSaving && !model.hasUnconfirmedSave && avatarPreparationID == nil - } - - private func instructionsSection(model: AgentEditorModel, instructions: Binding) -> some View { - Section { - textEditor( - "Instructions", - placeholder: instructionsPlaceholder, - text: instructions, - error: model.fieldErrors[.instructions], - identifier: "agent.editor.instructions" - ) - } header: { - HStack { - AgentStudioCaption("Instructions") - .accessibilityIdentifier("agent.editor.behavior-header") - Spacer() - FocusedTextEditorButton(title: "Instructions", identifier: "agent.editor.instructions.expand") { - expandsInstructions = true - } - } - } footer: { - VStack(alignment: .leading, spacing: BighelpTokens.space4) { - if !model.isEditing && runtimeDefaultsModel == nil && runtimeDefaultsReadOnlyReason == nil { - Label("Uses your default model. You can pick another after creating.", systemImage: "cpu") - .accessibilityIdentifier("agent.editor.model-default-note") - } - if !model.isEditing, let source = model.cloneSourceName { - Label(nerdModeEnabled - ? "Starts with \(source)’s skills, memories and settings. Change this in Advanced." - : "Starts with \(source)’s skills, memories and settings.", - systemImage: "doc.on.doc") - .accessibilityIdentifier("agent.editor.clone-note") - } - } - } - .listRowBackground(theme.surface) - } - - /// Business cards and event posters, beside the instructions they work with. Only a saved agent - /// has settings on its computer. - private var photoActionsSection: some View { - Section { - NavigationLink(value: Destination.photoActions) { - Label { - VStack(alignment: .leading, spacing: 2) { - Text("Photo actions") - .foregroundStyle(theme.primaryText) - Text("Business cards, event posters") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } - } icon: { - Image(systemName: "photo.badge.checkmark") - .foregroundStyle(theme.secondaryText) - } - .frame(minHeight: BighelpTokens.hitTarget) - } - .accessibilityIdentifier("agent.editor.photo-actions") - } - .listRowBackground(theme.surface) - } - - private func handleSection(model: AgentEditorModel) -> some View { - Section { - LabeledContent("Mention handle") { - Text("@\(model.handlePreview)") - .font(.bighelp(.body).monospaced()) - .foregroundStyle(theme.action) - } - } header: { - AgentStudioCaption("Mention handle") - } footer: { - Text("Suggested for new groups. Existing handles stay unchanged.") - } - .listRowBackground(theme.surface) - .accessibilityElement(children: .combine) - .accessibilityLabel("Suggested mention handle @\(model.handlePreview)") - } - - private func fieldCaption(_ title: String) -> some View { - Text(title) - .font(.bighelp(.caption).weight(.semibold)) - .foregroundStyle(theme.secondaryText) - .accessibilityHidden(true) - } - - private func field( - _ title: String, - prompt: String, - text: Binding, - focus: AgentEditorModel.Field, - error: String?, - identifier: String - ) -> some View { - VStack(alignment: .leading, spacing: BighelpTokens.space4) { - fieldCaption(title) - TextField(title, text: text, prompt: Text(prompt).bighelpFieldHint(theme)) - .focused($focusedField, equals: focus) - .accessibilityLabel(title) - .accessibilityIdentifier(identifier) - if let error { recoveryMessage(error) } - } - .padding(.vertical, BighelpTokens.space4) - } - - private func textEditor( - _ title: String, - placeholder: String, - text: Binding, - error: String?, - identifier: String - ) -> some View { - VStack(alignment: .leading, spacing: BighelpTokens.space4) { - // A long SOUL scrolls inside its own box instead of stretching the form, - // so the sections below it (the agent's model) stay within easy reach. - LongTextEditor(text: text, placeholder: placeholder, accessibilityLabel: title, - identifier: identifier, layout: .formBox, onEditingChanged: { editsInstructions = $0 }) - if let error { recoveryMessage(error) } - } - } - - private func recoveryMessage(_ text: String) -> some View { - Label(text, systemImage: "exclamationmark.triangle.fill") - .bighelpFont(.metadata) - .foregroundStyle(theme.danger) - .fixedSize(horizontal: false, vertical: true) - .accessibilityLabel(text) - } - - @BighelpThemeReader private var theme - - @Environment(\.colorScheme) private var colorScheme - @Environment(\.colorSchemeContrast) private var colorSchemeContrast - @Environment(\.appAppearance) private var appAppearance - @Environment(\.companionStore) private var companionStore - @Environment(\.companionAgentScope) private var companionAgentScope -} diff --git a/Bighelp/Agents/AgentFastModeRow.swift b/Bighelp/Agents/AgentFastModeRow.swift deleted file mode 100644 index e819f70c..00000000 --- a/Bighelp/Agents/AgentFastModeRow.swift +++ /dev/null @@ -1,55 +0,0 @@ -import SwiftUI - -struct AgentFastModeRow: View { - let model: AgentRuntimeDefaultsEditorModel - var allowsEdits = true - var saveImmediately = false - - var body: some View { - Menu { - Button { - select(.off) - } label: { - if model.draft.mainChats.fastMode == .off { Label("Off", systemImage: "checkmark") } - else { Text("Off") } - } - Button { - select(.on) - } label: { - Text("On") - Text("May cost more") - if model.draft.mainChats.fastMode == .on { Image(systemName: "checkmark") } - } - .disabled(model.fastModeUnavailableReason != nil) - } label: { - LabeledContent("Fast Mode", value: value) - } - .disabled(!allowsEdits || !model.hasLoaded || model.isSaving || model.isLoading - || (model.fastModeUnavailableReason != nil && model.draft.mainChats.fastMode == .off)) - .accessibilityHint("Default for new chats with this agent. Fast Mode may cost more.") - .accessibilityIdentifier("agent.runtime.mainChats.fast-mode") - if let reason = model.fastModeUnavailableReason { - Text(reason) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - } - - private var value: String { - if model.isSaving { return "Saving…" } - if saveImmediately, model.errorMessage != nil { return "Not confirmed" } - if !model.hasLoaded { return "Loading…" } - return model.fastModeUnavailableReason == nil ? model.draft.mainChats.fastMode.title : "Unavailable" - } - - private func select(_ mode: FastMode) { - if saveImmediately { - Task { await model.saveFastMode(mode) } - } else { - model.selectFastMode(mode) - } - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Agents/AgentGroupRowView.swift b/Bighelp/Agents/AgentGroupRowView.swift deleted file mode 100644 index 137d4ecf..00000000 --- a/Bighelp/Agents/AgentGroupRowView.swift +++ /dev/null @@ -1,121 +0,0 @@ -import SwiftUI - -/// iMessage-style group chat row: an overlapping avatar cluster in the same -/// 52pt slot as agent rows, the group name with its last activity, and the -/// member names underneath. -struct AgentGroupRowView: View { - let group: HermesBotModeRoomSummary - let profiles: [AgentProfile] - let avatarDirectory: URL? - /// Agents on other computers: their own names and pictures. - var peers: (any HermesBotModePeerHosts)? = nil - var isPinned = false - var liveState: AgentLiveState? = nil - let onSelect: () -> Void - - @Environment(\.dynamicTypeSize) private var dynamicTypeSize - @ScaledMetric(relativeTo: .callout) private var nameSize: CGFloat = 16 - @ScaledMetric(relativeTo: .subheadline) private var detailSize: CGFloat = 14 - @ScaledMetric(relativeTo: .footnote) private var timeSize: CGFloat = 13 - - var body: some View { - Button(action: onSelect) { - HStack(alignment: .center, spacing: BighelpTokens.space12) { - AgentGroupAvatarCluster(avatars: clusterAvatars, outlineColor: theme.canvas) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space8) { - Text(group.name) - .font(.system(size: nameSize, weight: .semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 1) - if isPinned { - Image(systemName: "pin.fill") - .font(.system(size: timeSize * 0.85, weight: .semibold)) - .foregroundStyle(theme.tertiaryText) - .accessibilityHidden(true) - } - Spacer(minLength: BighelpTokens.space4) - Text(group.updatedAt, format: .relative(presentation: .named)) - .font(.system(size: timeSize)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - } - Text(memberNames) - .font(.system(size: detailSize)) - .foregroundStyle(theme.secondaryText) - .lineLimit(dynamicTypeSize.isAccessibilitySize ? nil : 1) - if let liveState { - AgentLiveStateLabel(state: liveState, font: .system(size: timeSize)) - } - } - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, alignment: .leading) - .alignmentGuide(.listRowSeparatorLeading) { $0[.leading] } - } - .padding(.vertical, 10) - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityLabel("\(group.name), \(group.memberCount) agents") - .accessibilityValue(accessibilityValue) - .accessibilityHint("Opens the group chat. Long press for options.") - .accessibilityIdentifier("agents.group.\(group.roomID)") - } - - private var participants: [HermesBotModeParticipant] { group.participants(profiles: profiles, peers: peers) } - - private var clusterAvatars: [AvatarStack.Avatar] { - participants.prefix(2).map { - AvatarStack.Avatar( - stableID: $0.memberID, displayName: $0.displayName, - imageURL: $0.peerImageURL ?? AvatarFileURL.resolve(fileName: $0.profile?.avatarFileName, in: avatarDirectory) - ) - } - } - - private var memberNames: String { - let names = participants.map(\.displayName) - guard !names.isEmpty else { return "\(group.memberCount) agents" } - return names.formatted(.list(type: .and)) - } - - private var accessibilityValue: String { - [isPinned ? "Pinned" : nil, liveState?.label, memberNames] - .compactMap { $0 }.joined(separator: ", ") - } - - @BighelpThemeReader private var theme -} - -/// Two overlapping avatars inside a single 52pt slot, like an iMessage group. -private struct AgentGroupAvatarCluster: View { - let avatars: [AvatarStack.Avatar] - let outlineColor: Color - - private let slot = AgentRowView.avatarSize - private let member: CGFloat = 36 - - var body: some View { - ZStack { - if avatars.count >= 2 { - avatar(avatars[1]) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing) - avatar(avatars[0]) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - } else if let only = avatars.first { - AvatarView(stableID: only.stableID, displayName: only.displayName, imageURL: only.imageURL, size: slot) - } else { - Image(systemName: "person.2.fill") - .foregroundStyle(.secondary) - } - } - .frame(width: slot, height: slot) - } - - private func avatar(_ avatar: AvatarStack.Avatar) -> some View { - AvatarView(stableID: avatar.stableID, displayName: avatar.displayName, imageURL: avatar.imageURL, size: member) - .background(Circle().fill(outlineColor).padding(-2)) - } -} diff --git a/Bighelp/Agents/AgentPinnedGrid.swift b/Bighelp/Agents/AgentPinnedGrid.swift deleted file mode 100644 index c9ecb6bf..00000000 --- a/Bighelp/Agents/AgentPinnedGrid.swift +++ /dev/null @@ -1,490 +0,0 @@ -import SwiftUI - -/// The Pinned grid on Agents. Tap opens an agent's chat. Touch and hold lifts -/// the agent: drag it to a new place and the others make room (pinned agents -/// only), or let go without moving to see that agent's actions. -struct AgentPinnedGrid: View { - let agents: [AgentProfile] - let canReorder: Bool - let imageURL: (AgentProfile) -> URL? - let liveState: (AgentProfile) -> AgentLiveState - let isPrimary: (AgentProfile) -> Bool - let open: (AgentProfile) -> Void - let manage: (AgentProfile) -> Void - let reorder: ([String]) -> Void - let create: (() -> Void)? - @Binding var isArranging: Bool - - var body: some View { - PinnedArrangeGrid( - items: agents, - columns: PinnedAgentsLayout.columns, - canReorder: canReorder, space: "agents.pinned", open: open, manage: manage, reorder: reorder, - isArranging: $isArranging, identifier: { "agents.featured.\($0.id)" }, - tile: { agent, lifted in - AgentFeaturedTile(agent: agent, imageURL: imageURL(agent), liveState: liveState(agent), - isPrimary: isPrimary(agent), isLifted: lifted) - }, - trailing: { - if let create { - AgentNewTile(action: create) - .accessibilityIdentifier("agents.featured.create") - } - } - ) - } -} - -/// A grid of pinned things. Tap opens one. Touch and hold lifts it: drag it to -/// a new place and the others make room, or let go without moving to see its -/// actions (when it has any). -/// -/// SwiftUI long-press menus can't be used here: the grid is one List row, and -/// a List row shows the first menu in it whichever tile was pressed. So with -/// `menu`, letting go opens the tile's own UIKit menu (`TileMenuAnchor`), the -/// same system menu a row's `.contextMenu` shows. On the Mac each tile also -/// has its own right-click menu (`MacTileMenu`). -struct PinnedArrangeGrid: View where Item.ID == String { - let items: [Item] - let columns: [GridItem] - let canReorder: Bool - /// The grid's coordinate space; unique per screen. - let space: String - let open: (Item) -> Void - let manage: ((Item) -> Void)? - /// The tile's menu, shown when it's let go without moving. Where a menu - /// can't be opened (visionOS, iOS before 17.4), `manage` runs instead. - var menu: ((Item) -> [TileMenuItem])? = nil - let reorder: ([String]) -> Void - @Binding var isArranging: Bool - let identifier: (Item) -> String - @ViewBuilder let tile: (Item, _ isLifted: Bool) -> Tile - @ViewBuilder let trailing: () -> Trailing - - private struct Lift: Equatable { - let id: String - /// Where each place in the grid was when the tile was lifted. - let slots: [CGRect] - /// The finger's spot within the lifted tile. - let grab: CGSize - /// Where the finger was when the tile lifted. - let start: CGPoint - var location: CGPoint - var moved = false - } - - @State private var frames: [String: CGRect] = [:] - @State private var arrangement: [Item]? - @State private var lift: Lift? - #if os(iOS) - @State private var anchors = TileMenuAnchors() - #endif - @GestureState private var isTouching = false - @Environment(\.accessibilityReduceMotion) private var reduceMotion - - private var shown: [Item] { arrangement ?? items } - - var body: some View { - LazyVGrid(columns: columns, spacing: BighelpTokens.space12) { - ForEach(shown) { item in cell(item) } - trailing() - } - #if os(iOS) - // Beside the tiles, not in them, so each tile stays one element. - .background(alignment: .topLeading) { - if menu != nil { - ForEach(items) { item in - if let frame = frames[item.id] { - TileMenuAnchor(id: item.id, anchors: anchors) - .frame(width: frame.width, height: frame.height) - .offset(x: frame.minX, y: frame.minY) - } - } - .accessibilityHidden(true) - } - } - #endif - .coordinateSpace(.named(space)) - .onChange(of: isTouching) { _, touching in - // Ends a lift however the touch ended, including a cancelled one. - if !touching { finish() } - } - } - - private func cell(_ item: Item) -> some View { - let lifted = lift?.id == item.id - return tile(item, lifted) - #if targetEnvironment(macCatalyst) - .overlay { MacTileMenu(items: { macMenu(for: item) }).accessibilityHidden(true) } - #endif - - .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(space)) } action: { frames[item.id] = $0 } - .offset(lifted ? offset(for: item) : .zero) - .zIndex(lifted ? 1 : 0) - .onTapGesture { open(item) } - .modifier(HoldToArrange( - space: space, legacy: press(item), - began: { begin(item, at: $0) }, moved: { follow(to: $0) }, ended: { finish() })) - .accessibilityAddTraits(.isButton) - .accessibilityHint(hint) - .accessibilityAction { open(item) } - .accessibilityActions { - if let menu { - ForEach(Array(menu(item).filter { $0.children == nil && $0.isEnabled }.enumerated()), id: \.offset) { - Button($0.element.title, action: $0.element.perform) - } - } else if let manage { - Button("Manage agent") { manage(item) } - } - if canReorder { - Button("Move earlier") { move(item, by: -1) } - Button("Move later") { move(item, by: 1) } - } - } - .accessibilityIdentifier(identifier(item)) - } - - private var hint: String { - #if targetEnvironment(macCatalyst) - switch (canReorder, manage != nil || menu != nil) { - case (true, true): "Opens this agent's chat. Click and hold to move it; right-click for more actions." - case (true, false): "Opens this agent's chat. Click and hold to move it." - case (false, _): "Opens this agent's chat. Right-click for more actions." - } - #else - switch (canReorder, manage != nil || menu != nil) { - case (true, true): "Opens this agent's chat. Touch and hold to move it or for more actions." - case (true, false): "Opens this agent's chat. Touch and hold to move it." - case (false, _): "Opens this agent's chat. Touch and hold for more actions." - } - #endif - } - - #if targetEnvironment(macCatalyst) - /// The same choices as holding a tile on iPhone, plus moving it without a drag. - private func macMenu(for item: Item) -> [MacTileMenu.Item] { - var entries = [MacTileMenu.Item(title: "Open chat", systemImage: "bubble.left") { open(item) }] - if let menu { - entries += menu(item).enumerated().map { index, entry in - var entry = entry - if index == 0 { entry.startsGroup = true } - return entry - } - } else if let manage { - entries.append(MacTileMenu.Item(title: "Manage agent", systemImage: "slider.horizontal.3") { manage(item) }) - } - if canReorder, let index = items.firstIndex(where: { $0.id == item.id }) { - entries.append(MacTileMenu.Item(title: "Move earlier", systemImage: "arrow.left", - isEnabled: index > 0, startsGroup: true) { move(item, by: -1) }) - entries.append(MacTileMenu.Item(title: "Move later", systemImage: "arrow.right", - isEnabled: index < items.count - 1) { move(item, by: 1) }) - } - return entries - } - #endif - - /// iOS 17's hold-then-drag. SwiftUI's drag holds back the list's scroll - /// even beside it, so iOS 18 and later use UIKit's long press instead. - private func press(_ item: Item) -> some Gesture { - LongPressGesture(minimumDuration: 0.35, maximumDistance: 10) - .sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .named(space))) - .updating($isTouching) { value, touching, _ in - if case .second(true, _) = value { touching = true } - } - .onChanged { value in - guard case .second(true, let drag) = value else { return } - if lift == nil { begin(item, at: drag?.startLocation) } - if let drag { follow(to: drag.location) } - } - } - - private func begin(_ item: Item, at start: CGPoint?) { - let slots = items.map { frames[$0.id] ?? .zero } - guard let index = items.firstIndex(where: { $0.id == item.id }) else { return } - let slot = slots[index] - let point = start ?? CGPoint(x: slot.midX, y: slot.midY) - BighelpHaptics.tap(rigid: true) - isArranging = true - arrangement = items - withAnimation(.snappy(duration: 0.2)) { - lift = Lift(id: item.id, slots: slots, - grab: CGSize(width: point.x - slot.minX, height: point.y - slot.minY), - start: point, location: point) - } - } - - private func follow(to location: CGPoint) { - guard var current = lift else { return } - current.location = location - if hypot(location.x - current.start.x, location.y - current.start.y) > 8 { current.moved = true } - lift = current - guard canReorder, current.moved, var order = arrangement, - let from = order.firstIndex(where: { $0.id == current.id }), - let to = nearestSlot(to: location, in: current.slots), to != from else { return } - let item = order.remove(at: from) - order.insert(item, at: to) - withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { arrangement = order } - } - - private func finish() { - guard let finished = lift else { return } - let order = arrangement?.map(\.id) - withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { - lift = nil - arrangement = nil - } - isArranging = false - if !finished.moved, let item = items.first(where: { $0.id == finished.id }) { - #if os(iOS) - if let menu, anchors.present(item.id, items: menu(item)) { return } - #endif - manage?(item) - } else if canReorder, let order, order != items.map(\.id) { - reorder(order) - } - } - - /// Keeps the lifted tile under the finger while the grid reflows around it. - private func offset(for item: Item) -> CGSize { - guard let lift, let index = shown.firstIndex(where: { $0.id == item.id }), - lift.slots.indices.contains(index) else { return .zero } - let slot = lift.slots[index] - return CGSize(width: lift.location.x - lift.grab.width - slot.minX, - height: lift.location.y - lift.grab.height - slot.minY) - } - - private func nearestSlot(to point: CGPoint, in slots: [CGRect]) -> Int? { - if let inside = slots.firstIndex(where: { $0.contains(point) }) { return inside } - return slots.indices.min { lhs, rhs in - hypot(slots[lhs].midX - point.x, slots[lhs].midY - point.y) - < hypot(slots[rhs].midX - point.x, slots[rhs].midY - point.y) - } - } - - private func move(_ item: Item, by step: Int) { - guard canReorder, let index = items.firstIndex(where: { $0.id == item.id }), - items.indices.contains(index + step) else { return } - var order = items.map(\.id) - order.swapAt(index, index + step) - reorder(order) - } -} - -/// Touch and hold lifts a tile; moving then drags it. UIKit's long press -/// fails as soon as the finger moves first, so a swipe that starts on a tile -/// still scrolls the list around it. -private struct HoldToArrange: ViewModifier { - let space: String - let legacy: Legacy - let began: (CGPoint) -> Void - let moved: (CGPoint) -> Void - let ended: () -> Void - - func body(content: Content) -> some View { - #if os(visionOS) // No UIKit recognizers in SwiftUI there. - content.simultaneousGesture(legacy) - #else - if #available(iOS 18.0, *) { - content.gesture(HoldToDrag(space: space, began: began, moved: moved, ended: ended)) - } else { - content.simultaneousGesture(legacy) - } - #endif - } -} - -#if !os(visionOS) -@available(iOS 18.0, *) -private struct HoldToDrag: UIGestureRecognizerRepresentable { - let space: String - let began: (CGPoint) -> Void - let moved: (CGPoint) -> Void - let ended: () -> Void - - func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer { - let recognizer = UILongPressGestureRecognizer() - recognizer.minimumPressDuration = 0.35 - recognizer.allowableMovement = 10 - return recognizer - } - - func handleUIGestureRecognizerAction(_ recognizer: UILongPressGestureRecognizer, context: Context) { - let point = context.converter.location(in: .named(space)) - switch recognizer.state { - case .began: began(point) - case .changed: moved(point) - case .ended, .cancelled, .failed: ended() - default: break - } - } -} -#endif - -#if targetEnvironment(macCatalyst) -/// A right-click menu for one tile of a grid that sits in a single List row -/// (pinned agents, pinned chats). SwiftUI's `.contextMenu` can't be used there: -/// the row shows its first tile's menu for every tile. Only right- and -/// Control-clicks land on this view; other clicks, hovers and scrolls pass -/// through to the tile. -struct MacTileMenu: UIViewRepresentable { - typealias Item = TileMenuItem - - /// Read when the menu opens, so it shows the tile's current choices. - let items: () -> [Item] - - func makeCoordinator() -> Coordinator { Coordinator(items: items) } - - func makeUIView(context: Context) -> SecondaryClickView { - let view = SecondaryClickView() - view.backgroundColor = .clear - view.addInteraction(UIContextMenuInteraction(delegate: context.coordinator)) - return view - } - - func updateUIView(_ view: SecondaryClickView, context: Context) { - context.coordinator.items = items - } - - final class SecondaryClickView: UIView { - override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { - guard let event, event.buttonMask.contains(.secondary) || event.modifierFlags.contains(.control) else { - return nil - } - return super.hitTest(point, with: event) - } - } - - final class Coordinator: NSObject, UIContextMenuInteractionDelegate { - var items: () -> [Item] - /// What the open menu shows; its actions run these. - private var shown: [Item] = [] - - init(items: @escaping () -> [Item]) { - self.items = items - } - - func contextMenuInteraction( - _ interaction: UIContextMenuInteraction, - configurationForMenuAtLocation location: CGPoint - ) -> UIContextMenuConfiguration? { - shown = items() - guard !shown.isEmpty else { return nil } - let menu = TileMenuItem.menu(shown) - return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in menu } - } - } -} -#endif - -/// One choice in a pinned tile's menu. The same list draws as a SwiftUI menu -/// (`TileMenuContent`, a row's `.contextMenu`) and as a UIKit one (a tile's -/// own menu), so a pinned tile and its row offer the same things. -struct TileMenuItem { - let title: String - let systemImage: String - var isDestructive = false - var isEnabled = true - /// Draws a separator above this item. - var startsGroup = false - /// A submenu's choices; nil for an action. - var children: [TileMenuItem]? = nil - var identifier: String? = nil - var perform: @MainActor () -> Void = {} - - #if os(iOS) - @MainActor - static func menu(_ items: [TileMenuItem], title: String = "", image: UIImage? = nil) -> UIMenu { - var groups: [[UIMenuElement]] = [[]] - for item in items { - if item.startsGroup, !(groups.last?.isEmpty ?? true) { groups.append([]) } - let image = UIImage(systemName: item.systemImage) - if let children = item.children { - groups[groups.count - 1].append(menu(children, title: item.title, image: image)) - continue - } - var attributes: UIMenuElement.Attributes = [] - if item.isDestructive { attributes.insert(.destructive) } - if !item.isEnabled { attributes.insert(.disabled) } - let perform = item.perform - let action = UIAction(title: item.title, image: image, attributes: attributes) { _ in perform() } - action.accessibilityIdentifier = item.identifier - groups[groups.count - 1].append(action) - } - let children: [UIMenuElement] = groups.count == 1 - ? groups[0] - : groups.map { UIMenu(options: .displayInline, children: $0) } - return UIMenu(title: title, image: image, children: children) - } - #endif -} - -/// `TileMenuItem`s as SwiftUI menu content, for a row's `.contextMenu`. -struct TileMenuContent: View { - let items: [TileMenuItem] - - var body: some View { - ForEach(Array(items.enumerated()), id: \.offset) { _, item in - if item.startsGroup { Divider() } - if let children = item.children { - Menu { - TileMenuContent(items: children) - } label: { - Label(item.title, systemImage: item.systemImage) - } - .accessibilityIdentifier(item.identifier ?? item.title) - } else { - Button(item.title, systemImage: item.systemImage, role: item.isDestructive ? .destructive : nil, - action: item.perform) - .disabled(!item.isEnabled) - .accessibilityIdentifier(item.identifier ?? item.title) - } - } - } -} - -#if os(iOS) -/// The tiles' menu buttons, by tile, so the grid can open one when a tile is -/// let go without moving. -@MainActor -final class TileMenuAnchors { - private var buttons: [String: WeakButton] = [:] - - private struct WeakButton { weak var button: UIButton? } - - func register(_ button: UIButton, for id: String) { buttons[id] = WeakButton(button: button) } - - /// Opens the tile's menu beside it. False when it can't be opened here. - func present(_ id: String, items: [TileMenuItem]) -> Bool { - guard #available(iOS 17.4, *), !items.isEmpty, let button = buttons[id]?.button, button.window != nil else { - return false - } - button.menu = TileMenuItem.menu(items) - button.performPrimaryAction() - return true - } -} - -/// An invisible menu button the size of a tile. It never takes touches (the -/// tile's own tap and hold do); the grid opens its menu (`TileMenuAnchors`). -struct TileMenuAnchor: UIViewRepresentable { - let id: String - let anchors: TileMenuAnchors - - func makeUIView(context: Context) -> AnchorButton { - let button = AnchorButton(type: .custom) - button.showsMenuAsPrimaryAction = true - button.isAccessibilityElement = false - button.accessibilityElementsHidden = true - anchors.register(button, for: id) - return button - } - - func updateUIView(_ button: AnchorButton, context: Context) { - anchors.register(button, for: id) - } - - final class AnchorButton: UIButton { - override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { nil } - } -} -#endif diff --git a/Bighelp/Agents/AgentRowView.swift b/Bighelp/Agents/AgentRowView.swift deleted file mode 100644 index 89cb261a..00000000 --- a/Bighelp/Agents/AgentRowView.swift +++ /dev/null @@ -1,118 +0,0 @@ -import SwiftUI - -/// iMessage-style directory row: the avatar carries the live state, the name -/// and summary sit beside it, and every other action lives behind the -/// trailing ellipsis. -struct AgentRowView: View { - let agent: AgentProfile - let imageURL: URL? - let isPrimary: Bool - let isPinned: Bool - let canOpenChat: Bool - let onOpenChat: () -> Void - let onManage: () -> Void - var identifierPrefix = "agent" - var liveState: AgentLiveState = .idle - - @Environment(\.dynamicTypeSize) private var dynamicTypeSize - @ScaledMetric(relativeTo: .callout) private var nameSize: CGFloat = 16 - @ScaledMetric(relativeTo: .subheadline) private var summarySize: CGFloat = 14 - - static let avatarSize: CGFloat = 52 - - var body: some View { - HStack(alignment: .center, spacing: BighelpTokens.space4) { - Button(action: onOpenChat) { - HStack(alignment: .center, spacing: BighelpTokens.space12) { - AvatarView( - stableID: agent.id, displayName: agent.name, - imageURL: imageURL, size: Self.avatarSize, state: liveState - ) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - nameLine - summaryLine - } - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, alignment: .leading) - .alignmentGuide(.listRowSeparatorLeading) { $0[.leading] } - } - .padding(.vertical, 10) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) - .contentShape(.rect) - } - .buttonStyle(.plain) - .disabled(!canOpenChat) - .accessibilityLabel("\(agent.name), \(agent.role)") - .accessibilityValue(statusValue) - .accessibilityHint(canOpenChat ? "Opens this agent's chat." : "Chat is currently unavailable. More actions explains why.") - .accessibilityIdentifier("\(identifierPrefix).\(agent.id)") - - Button("More actions for \(agent.name)", systemImage: "ellipsis", action: onManage) - .labelStyle(.iconOnly) - .font(.bighelp(.body)) - .foregroundStyle(theme.secondaryText) - // A little over the 44pt minimum so pixel rounding never undercuts it. - .frame(width: 48, height: 48) - .contentShape(.rect) - .buttonStyle(.plain) - .accessibilityIdentifier("\(identifierPrefix).\(agent.id).more") - } - .accessibilityElement(children: .contain) - } - - private var nameLine: some View { - HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space4) { - Text(agent.name) - .font(.system(size: nameSize, weight: .semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(isAccessibilitySize ? nil : 1) - if isPrimary { - Image(systemName: "star.fill") - .font(.system(size: summarySize * 0.8, weight: .semibold)) - .foregroundStyle(theme.action) - .accessibilityLabel("Primary") - } - if isPinned { - Image(systemName: "pin.fill") - .font(.system(size: summarySize * 0.8, weight: .semibold)) - .foregroundStyle(theme.tertiaryText) - .accessibilityLabel("Pinned") - .accessibilityIdentifier("\(identifierPrefix).\(agent.id).pinned-badge") - } - } - } - - private var summaryLine: some View { - HStack(alignment: .firstTextBaseline, spacing: 6) { - if liveState != .idle { - Circle().fill(liveState.dotColor) - .frame(width: 8, height: 8) - .alignmentGuide(.firstTextBaseline) { $0[.bottom] } - .accessibilityHidden(true) - } - Text(summaryText) - .font(.system(size: summarySize)) - .foregroundStyle(theme.secondaryText) - .lineLimit(isAccessibilitySize ? nil : AgentRowPresentation.summaryLineLimit) - } - } - - private var summaryText: String { - if liveState != .idle { return liveState.label } - return agent.summary.isEmpty ? agent.role : agent.summary - } - - private var statusValue: String { - [ - liveState != .idle ? liveState.label : nil, - isPrimary ? "Primary agent" : nil, - isPinned ? "Pinned" : nil - ] - .compactMap { $0 }.joined(separator: ", ") - } - - private var isAccessibilitySize: Bool { dynamicTypeSize.isAccessibilitySize } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Agents/AgentRuntimeDefaultsSection.swift b/Bighelp/Agents/AgentRuntimeDefaultsSection.swift deleted file mode 100644 index 2ede4bb4..00000000 --- a/Bighelp/Agents/AgentRuntimeDefaultsSection.swift +++ /dev/null @@ -1,135 +0,0 @@ -import SwiftUI - -@MainActor -struct AgentRuntimeDefaultsSection: View { - @Bindable var model: AgentRuntimeDefaultsEditorModel - var allowsEdits = true - var scopes: [AgentRuntimeScope] = AgentRuntimeScope.allCases - - @Binding var modelPickerScope: AgentRuntimeScope? - - var body: some View { - Group { - if model.isLoading { - Section { - ProgressView("Loading model settings…") - } header: { - AgentStudioCaption(statusCaption) - } - .listRowBackground(theme.surface) - .accessibilityIdentifier("agent.runtime.loading") - } else if !model.hasLoaded { - Section { - recoveryMessage( - model.errorMessage - ?? "We couldn’t load this agent’s model defaults. Try again." - ) - Button("Try again") { - Task { await model.load() } - } - .foregroundStyle(theme.action) - .frame(minHeight: BighelpTokens.hitTarget) - .accessibilityIdentifier("agent.runtime.retry") - } header: { - AgentStudioCaption(statusCaption) - } - .listRowBackground(theme.surface) - } else { - if let errorMessage = model.errorMessage { - Section { - recoveryMessage(errorMessage) - } - .listRowBackground(theme.surface) - } - ForEach(scopes) { scope in - scopeSection(scope) - } - } - } - // Loading starts from the editor (AgentEditorView): a `.task` here would be - // attached to each section, restarting as they swap and flooding the host. - .onChange(of: allowsEdits) { _, canEdit in - if !canEdit { - modelPickerScope = nil - } - } - } - - private func scopeSection(_ scope: AgentRuntimeScope) -> some View { - let selection = model.draft[scope] - let canChangeModel = !model.providers.isEmpty && model.support.modelUnavailableReasons[scope] == nil - let canChangeReasoning = model.support.reasoningUnavailableReasons[scope] == nil - let isEditable = allowsEdits && (canChangeModel || canChangeReasoning) - return Section { - // The same picker as the chat's model control: model, reasoning, then apply. - BighelpModelChoiceRow( - providerID: selection.providerID, - providerName: providerName(for: selection.providerID), - modelID: selection.modelID, - detail: "Reasoning: \(reasoningTitle(for: scope))", - showsDefaultBadge: true, - isEnabled: isEditable - ) { - modelPickerScope = scope - } - .accessibilityLabel("Choose model and reasoning for \(scope.title)") - .accessibilityValue("\(modelLabel(for: selection)), reasoning \(reasoningTitle(for: scope))") - .accessibilityIdentifier("agent.runtime.\(scope.rawValue).model") - if scope == .mainChats { - AgentFastModeRow(model: model, allowsEdits: allowsEdits) - } - if let reason = model.support.modelUnavailableReasons[scope] { - Text(reason) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - if let reason = model.support.reasoningUnavailableReasons[scope] ?? model.support.reasoningNotes[scope] { - Text(reason) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - .accessibilityIdentifier("agent.runtime.\(scope.rawValue).reasoning-note") - } - } header: { - AgentStudioCaption(scope == .mainChats ? "Model" : scope.title) - } footer: { - Text(scope.detail) - } - .listRowBackground(theme.surface) - } - - private func reasoningTitle(for scope: AgentRuntimeScope) -> String { - guard model.support.reasoningUnavailableReasons[scope] == nil else { return "Inherited" } - let value = model.draft[scope].reasoningEffort - return AgentReasoningOption.all.first(where: { $0.value == value })?.title ?? value - } - - private var statusCaption: String { - scopes.contains(.mainChats) ? "Model" : "Subagent and task models" - } - - private func providerName(for providerID: String) -> String { - model.providers.first(where: { $0.id == providerID })?.name - ?? (providerID.isEmpty ? "Hermes" : providerID) - } - - private func modelName(for selection: AgentRuntimeSelection) -> String { - ModelNameCatalogStore.shared.displayName(for: selection.modelID) - } - - private func modelLabel(for selection: AgentRuntimeSelection) -> String { - guard !selection.modelID.isEmpty else { return "Default model" } - return "\(modelName(for: selection)) · \(providerName(for: selection.providerID))" - } - - private func recoveryMessage(_ text: String) -> some View { - Label(text, systemImage: "exclamationmark.triangle.fill") - .bighelpFont(.metadata) - .foregroundStyle(theme.danger) - .fixedSize(horizontal: false, vertical: true) - .accessibilityLabel(text) - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Agents/AgentStartPicker.swift b/Bighelp/Agents/AgentStartPicker.swift deleted file mode 100644 index 9de7cbd2..00000000 --- a/Bighelp/Agents/AgentStartPicker.swift +++ /dev/null @@ -1,217 +0,0 @@ -import SwiftUI - -/// 11pt bold, letterspaced, uppercase section caption used across the Agent Studio. -struct AgentStudioCaption: View { - let title: String - - init(_ title: String) { - self.title = title - } - - var body: some View { - Text(title) - .font(.bighelp(.caption2).weight(.bold)) - .tracking(0.9) - .textCase(.uppercase) - .foregroundStyle(theme.secondaryText) - .accessibilityAddTraits(.isHeader) - } - - @BighelpThemeReader private var theme -} - -/// Where a new agent starts: from scratch, a built-in personality, or one of -/// the person's saved templates. Picking one only fills in the editor; nothing -/// reaches Hermes until Create. -struct AgentStartPicker: View { - let model: AgentEditorModel - @Bindable var library: AgentTemplateLibrary - var myTemplates: MyTemplatesStore = .shared - /// Opens Browse all. The editor presents it from its form's root: this picker sits in a - /// section header, and a sheet hung there never gets the keyboard for its search. - let onBrowse: () -> Void - @State private var renaming: SavedAgentTemplate? - @State private var renameText = "" - /// The topic chip over the Templates rail. - @State private var railFilter = TemplateTopicFilter.all - - var body: some View { - VStack(alignment: .leading, spacing: BighelpTokens.space12) { - AgentStudioCaption("Start from") - Picker("Start from", selection: Binding(get: { model.startChoice }, - set: { model.showStartChoice($0) })) { - Text("Scratch").tag(AgentEditorModel.StartChoice.scratch) - Text("Templates").tag(AgentEditorModel.StartChoice.builtIn) - Text("My templates").tag(AgentEditorModel.StartChoice.saved) - } - .pickerStyle(.segmented) - .accessibilityIdentifier("agent.editor.start") - switch model.startChoice { - case .scratch: - note("Empty details. Write your agent's personality yourself in Instructions.") - case .builtIn: - let catalog = AgentSoulTemplate.all - let topics = TemplateTopics.sections(catalog, topics: TemplateCategory.agentTopics, category: \.category) - .compactMap(\.category) - if topics.count > 1 { - TemplateTopicChips(filters: [.all] + topics.map { .topic($0) }, selection: $railFilter, - identifier: "agent.editor.templates", inset: 0) - } - carousel { - ForEach(railTemplates(catalog)) { template in - card(title: template.title, subtitle: template.cardRole, detail: template.cardStrength, - credit: template.isCommunity ? template.credit : nil, - systemImage: template.systemImage, selected: "builtin:\(template.id)", - identifier: "agent.editor.template.\(template.id)") { - pick(template) - } - .accessibilityHint("Fills in its role, vibe and personality. Your agent's name goes into it.") - } - } - note(model.appliedTemplateID?.hasPrefix("builtin:") == true - ? "Its personality is in Instructions below, with your agent's name filled in." - : "Each is a full personality. Pick one, then give your agent its name.") - HStack { - Button(action: onBrowse) { - Label("Browse all \(AgentSoulTemplate.all.count)", systemImage: "square.grid.2x2") - .font(.bighelp(.footnote).weight(.semibold)) - } - .accessibilityIdentifier("agent.editor.templates.browse") - Spacer() - Link(destination: TemplateCatalogPolicy.submitURL) { - Label("Share yours", systemImage: "square.and.arrow.up") - .font(.bighelp(.footnote).weight(.semibold)) - } - .accessibilityIdentifier("agent.editor.templates.share") - } - case .saved: - let onComputer = myTemplates.templates - if !onComputer.isEmpty { - carousel { - ForEach(onComputer) { template in - card(title: template.title, subtitle: template.cardRole, detail: template.cardStrength, - systemImage: template.systemImage, selected: "builtin:\(template.id)", - identifier: "agent.editor.template.\(template.id)") { - pick(template) - } - .accessibilityHint("Fills in everything from this template. Your agent's name goes into it.") - } - } - note("Saved on your computer, so they're on all your devices.") - } - if library.templates.isEmpty { - if onComputer.isEmpty { - note("No saved templates yet. Save one from an agent's Edit screen or by holding it in Agents.") - .accessibilityIdentifier("agent.editor.saved-templates.empty") - } - } else { - carousel { - ForEach(library.templates) { template in - card(title: template.title, - subtitle: template.role.isEmpty ? "From \(template.sourceAgentName)" : template.role, - detail: template.summary, systemImage: "person.crop.square", - selected: "saved:\(template.id.uuidString)", - identifier: "agent.editor.saved-template.\(template.id.uuidString)") { - model.startFrom(template) - } - .accessibilityHint("Fills in everything from this template. Hold to rename or delete.") - .contextMenu { - Button("Rename", systemImage: "pencil") { - renameText = template.title - renaming = template - } - Button("Delete", systemImage: "trash", role: .destructive) { - library.delete(template.id) - } - } - } - } - note("Saved on this device. Hold one to rename or delete it.") - } - } - } - .frame(maxWidth: .infinity, alignment: .leading) - .task { await myTemplates.refresh() } - .alert("Rename template", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) { - TextField("Name", text: $renameText) - Button("Cancel", role: .cancel) { renaming = nil } - Button("Rename") { - if let template = renaming { library.rename(template.id, to: renameText) } - renaming = nil - } - } - } - - /// The rail keeps the catalog's order; a topic chip narrows it to that topic. - private func railTemplates(_ catalog: [AgentSoulTemplate]) -> [AgentSoulTemplate] { - guard case .topic(let topic) = railFilter else { return catalog } - let shown = catalog.filter { $0.category == topic } - return shown.isEmpty ? catalog : shown - } - - private func pick(_ template: AgentSoulTemplate) { - Self.pick(template, into: model) - } - - /// Fills the editor from a template and counts it toward Most used. - static func pick(_ template: AgentSoulTemplate, into model: AgentEditorModel) { - TemplateUsage.shared.recordUse(AgentTemplateBrowsing.usageID(template)) - model.startFrom(template) - } - - private func carousel(@ViewBuilder _ content: @escaping () -> Content) -> some View { - BighelpCardRail(content: content) - } - - private func note(_ text: String) -> some View { - Text(text) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - - private func card(title: String, subtitle: String, detail: String, credit: String? = nil, - systemImage: String, selected: String, - identifier: String, action: @escaping () -> Void) -> some View { - let isSelected = model.appliedTemplateID == selected - return Button(action: action) { - BighelpRailCard(isSelected: isSelected, width: 196, height: 176) { ink, secondary in - VStack(alignment: .leading, spacing: BighelpTokens.space4) { - Image(systemName: isSelected ? "checkmark.circle.fill" : systemImage) - .font(.bighelp(.title3)) - .foregroundStyle(isSelected ? theme.actionForeground : theme.action) - .frame(height: 28) - .accessibilityHidden(true) - Text(title) - .font(.bighelp(.headline)) - .foregroundStyle(ink) - .lineLimit(1) - Text(subtitle) - .font(.bighelp(.subheadline).weight(.medium)) - .foregroundStyle(secondary) - .lineLimit(2) - if !detail.isEmpty { - Text(detail) - .font(.bighelp(.caption)) - .foregroundStyle(secondary) - .lineLimit(credit == nil ? 3 : 2) - } - if let credit { - Text(verbatim: "by @\(credit)") - .font(.bighelp(.caption2)) - .foregroundStyle(secondary) - .lineLimit(1) - } - Spacer(minLength: 0) - } - .multilineTextAlignment(.leading) - } - } - .buttonStyle(.plain) - .accessibilityLabel("\(title), \(subtitle)") - .accessibilityAddTraits(isSelected ? .isSelected : []) - .accessibilityIdentifier(identifier) - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Agents/AgentStudioCaption.swift b/Bighelp/Agents/AgentStudioCaption.swift new file mode 100644 index 00000000..4dd0933f --- /dev/null +++ b/Bighelp/Agents/AgentStudioCaption.swift @@ -0,0 +1,21 @@ +import SwiftUI + +/// 11pt bold, letterspaced, uppercase section caption used across the Agent Studio. +struct AgentStudioCaption: View { + let title: String + + init(_ title: String) { + self.title = title + } + + var body: some View { + Text(title) + .font(.bighelp(.caption2).weight(.bold)) + .tracking(0.9) + .textCase(.uppercase) + .foregroundStyle(theme.secondaryText) + .accessibilityAddTraits(.isHeader) + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Agents/AgentsDirectoryComponents.swift b/Bighelp/Agents/AgentsDirectoryComponents.swift deleted file mode 100644 index ebecc212..00000000 --- a/Bighelp/Agents/AgentsDirectoryComponents.swift +++ /dev/null @@ -1,213 +0,0 @@ -import SwiftUI - -/// Uppercase, letterspaced section caption ("PINNED", "GROUP CHATS"). -struct AgentsSectionCaption: View { - let title: String - - @ScaledMetric(relativeTo: .caption2) private var size: CGFloat = 11 - - var body: some View { - Text(title.uppercased()) - .font(.system(size: size, weight: .bold)) - .tracking(size * 0.08) - .foregroundStyle(theme.secondaryText) - .accessibilityLabel(title) - .accessibilityAddTraits(.isHeader) - } - - @BighelpThemeReader private var theme -} - -/// The big pinned-agent look Agents and All agents share: a large avatar, -/// the name, and one short line under it. -enum PinnedAgentsLayout { - static let avatarSize: CGFloat = 88 - static let columns = [GridItem(.adaptive(minimum: 104, maximum: 150), spacing: BighelpTokens.space8, - alignment: .top)] -} - -/// A pinned tile's picture, name and line under it; the grid adds the gestures. -struct PinnedAgentTileLabel: View { - let name: String - var isLifted = false - /// The New agent slot's label is quieter than an agent's name. - var isPlaceholder = false - @ViewBuilder let avatar: () -> Avatar - @ViewBuilder let detail: () -> Detail - - var body: some View { - VStack(spacing: 6) { - avatar() - .frame(width: PinnedAgentsLayout.avatarSize, height: PinnedAgentsLayout.avatarSize) - .scaleEffect(isLifted ? 1.08 : 1) - .shadow(color: .black.opacity(isLifted ? 0.22 : 0), radius: 12, y: 6) - Text(name) - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(isPlaceholder ? theme.secondaryText : theme.primaryText) - .lineLimit(1) - detail() - .font(.bighelp(.caption)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - } - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) - .padding(.vertical, BighelpTokens.space4) - .contentShape(.rect) - } - - @BighelpThemeReader private var theme -} - -/// A grid tile for a pinned or featured agent: large live avatar, name, and -/// underneath what it's doing, or its role when it's idle. `AgentPinnedGrid` -/// handles taps, lifting and moving. -struct AgentFeaturedTile: View { - let agent: AgentProfile - let imageURL: URL? - let liveState: AgentLiveState - let isPrimary: Bool - var isLifted = false - - /// The role on one short line; the tile trails off if it's still too wide. - static func roleLine(_ role: String, limit: Int = 28) -> String? { - let line = role.split(whereSeparator: \.isNewline).first - .map { $0.trimmingCharacters(in: .whitespaces) } ?? "" - guard !line.isEmpty else { return nil } - guard line.count > limit else { return line } - return String(line.prefix(limit - 1)).trimmingCharacters(in: .whitespaces) + "…" - } - - var body: some View { - PinnedAgentTileLabel(name: agent.name, isLifted: isLifted) { - AvatarView( - stableID: agent.id, displayName: agent.name, - imageURL: imageURL, size: PinnedAgentsLayout.avatarSize, state: liveState - ) - .accessibilityHidden(true) - } detail: { - if liveState != .idle { - AgentLiveStateLabel(state: liveState, font: .caption) - } else if let role = Self.roleLine(agent.role) { - Text(role).truncationMode(.tail) - } - } - .accessibilityElement(children: .ignore) - .accessibilityLabel(agent.name) - .accessibilityValue([liveState == .idle ? Self.roleLine(agent.role) : liveState.label, - isPrimary ? "Primary agent" : nil].compactMap { $0 }.joined(separator: ", ")) - } -} - -/// Dashed "New" slot that trails the featured grid when creation is allowed. -struct AgentNewTile: View { - let action: () -> Void - - var body: some View { - Button(action: action) { - PinnedAgentTileLabel(name: "New agent", isPlaceholder: true) { - AgentDashedPlusCircle(size: PinnedAgentsLayout.avatarSize) - } detail: { - EmptyView() - } - } - .buttonStyle(.plain) - .accessibilityLabel("Create agent") - } -} - -/// The "start a group chat" row at the top of the group chats section. -struct AgentNewGroupRow: View { - let action: () -> Void - - @ScaledMetric(relativeTo: .callout) private var titleSize: CGFloat = 16 - @ScaledMetric(relativeTo: .subheadline) private var detailSize: CGFloat = 14 - - var body: some View { - Button(action: action) { - HStack(spacing: BighelpTokens.space12) { - AgentDashedPlusCircle(size: AgentRowView.avatarSize, tint: theme.action) - VStack(alignment: .leading, spacing: 2) { - Text("New group chat") - .font(.system(size: titleSize, weight: .semibold)) - .foregroundStyle(theme.action) - Text("Bring a few agents into one conversation") - .font(.system(size: detailSize)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - .frame(maxWidth: .infinity, alignment: .leading) - .alignmentGuide(.listRowSeparatorLeading) { $0[.leading] } - } - .padding(.vertical, 10) - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityLabel("New group") - .accessibilityHint("Starts a group chat with several agents.") - } - - @BighelpThemeReader private var theme -} - -struct AgentDashedPlusCircle: View { - let size: CGFloat - var tint: Color? = nil - - var body: some View { - Circle() - .strokeBorder(style: StrokeStyle(lineWidth: 1.5, dash: [4, 3])) - .foregroundStyle(tint ?? theme.tertiaryText) - .overlay { - Image(systemName: "plus") - .font(.system(size: size * 0.3, weight: .semibold)) - .foregroundStyle(tint ?? theme.secondaryText) - } - .frame(width: size, height: size) - .accessibilityHidden(true) - } - - @BighelpThemeReader private var theme -} - -/// Friendly first-run state for a host with no agents yet. -struct AgentsEmptyStateView: View { - let canCreate: Bool - let onCreate: () -> Void - - var body: some View { - VStack(spacing: BighelpTokens.space12) { - BighelpNoodleView(motion: .idle, size: 72) - Text("No agents yet") - .bighelpFont(.screenTitle) - .foregroundStyle(theme.primaryText) - .accessibilityAddTraits(.isHeader) - Text(canCreate - ? "Create a personal assistant and it will show up here, ready to chat." - : "Agents on this host appear here.") - .bighelpFont(.body) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - if canCreate { - Button(action: onCreate) { - Label("Create an agent", systemImage: "plus") - .bighelpFont(.label) - .frame(maxWidth: 280, minHeight: BighelpTokens.hitTarget) - } - .bighelpProminentButtonStyle() - .buttonBorderShape(.capsule) - .tint(theme.action) - .foregroundStyle(theme.actionForeground) - .padding(.top, BighelpTokens.space8) - .accessibilityIdentifier("agents.empty.create") - } - } - .padding(.horizontal, BighelpTokens.space32) - .padding(.vertical, BighelpTokens.space40) - .frame(maxWidth: .infinity) - .accessibilityElement(children: .contain) - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Agents/AgentsPresentation.swift b/Bighelp/Agents/AgentsPresentation.swift index 1ec7c4ab..99a221bf 100644 --- a/Bighelp/Agents/AgentsPresentation.swift +++ b/Bighelp/Agents/AgentsPresentation.swift @@ -1,234 +1,29 @@ import Foundation import SwiftUI +/// Something the shell does for a group chat, asked by a list that holds only the computer it was +/// drawn for. The shell refuses a request made for another computer. struct AgentWorkspaceActionRequest: Equatable, Sendable { let owner: WorkspaceOwner let action: AgentWorkspaceAction } enum AgentWorkspaceAction: Equatable, Sendable { - case openAgentChat(profileID: String) - case openAgentSessions(profileID: String) - case openAgentScheduledTasks(profileID: String) - /// The Agents list, filtered to group chats this agent is in. - case openAgentGroups(profileID: String) case openGroup(roomID: String) case createGroup(seedProfileID: String?) case openGroupSettings(roomID: String) case renameGroup(roomID: String, name: String) case deleteGroup(roomID: String) - case openHostStatus } -@MainActor @Observable -final class AgentGroupPreferences { - struct Entry: Codable { var pinned = false; var archived = false } - private var values: [String: [String: Entry]] - private let defaults: UserDefaults +/// The old Agents screen's pins and archives of group chats (`FleetStore` keeps those now). Only the +/// saved copy is left, erased with the rest of what this device keeps. +enum AgentGroupPreferences { private static let key = "loopdy.agents.groupPreferences.v1" static func erase(defaults: UserDefaults) { defaults.removeObject(forKey: key) } - init(defaults: UserDefaults = .standard) { - self.defaults = defaults - values = defaults.data(forKey: Self.key).flatMap { - try? JSONDecoder().decode([String: [String: Entry]].self, from: $0) - } ?? [:] - } - func entry(_ id: String, scope: String) -> Entry { values[scope]?[id] ?? Entry() } - func set(_ entry: Entry, id: String, scope: String) { - values[scope, default: [:]][id] = entry - if let data = try? JSONEncoder().encode(values) { defaults.set(data, forKey: Self.key) } - } -} - -enum AgentDirectoryPresentation { - enum DirectorySection: Hashable { - case groups - case agents - } - - static let sectionOrder: [DirectorySection] = [.groups, .agents] - - static func sectionOrder(filteredToProfileID _: String?) -> [DirectorySection] { - sectionOrder - } - - enum LoadingMode: Equatable { - case none, fullScreen, inline - } - - static func loadingMode(isLoading: Bool, hasProfiles: Bool) -> LoadingMode { - guard isLoading else { return .none } - return hasProfiles ? .inline : .fullScreen - } - - static func visibleProfiles(_ profiles: [AgentProfile], query: String = "") -> [AgentProfile] { - profiles.filter { - $0 != .bighelpLinkDefault - && matches(query, fields: [$0.name, $0.role, $0.summary, $0.id]) - } - } - - static func visibleGroups( - _ groups: [HermesBotModeRoomSummary], profiles: [AgentProfile], - query: String, profileID: String? - ) -> [HermesBotModeRoomSummary] { - groups.filter { room in - guard !room.isDisbanded, - profileID == nil || room.members.contains(where: { - $0.profile == profileID && $0.target["kind"]?.string == "local" - }) - else { return false } - let members = room.participants(profiles: profiles) - return matches(query, fields: [room.name] + members.flatMap { - [$0.displayName, $0.handle, $0.profileID] - }) - } - } - - static func selectedGroup( - in groups: [HermesBotModeRoomSummary], selectedID: String? - ) -> HermesBotModeRoomSummary? { - groups.first { $0.roomID == selectedID } ?? groups.first - } - - static func matches(_ query: String, fields: [String]) -> Bool { - query.split(whereSeparator: \.isWhitespace).allSatisfy { term in - fields.contains { $0.localizedStandardContains(String(term)) } - } - } -} - -enum AgentRowMenuAction: String, CaseIterable, Equatable, Sendable { - case openChat = "chat" - case edit - case viewSessions = "sessions" - case scheduledTasks = "schedules" - case groups - case duplicate - case shortcuts - case setPrimary = "primary" - case togglePin = "pin" - case saveTemplate = "template" - /// Last, and shown as destructive. - case delete - - var isDestructive: Bool { self == .delete } - - var title: String { - switch self { - case .openChat: "Message" - case .edit: "Edit" - case .viewSessions: "Past chats" - case .scheduledTasks: "Scheduled tasks" - case .groups: "Group chats" - case .duplicate: "Duplicate" - case .shortcuts: "Use with Siri" - case .setPrimary: "Use for new chats" - case .togglePin: "Pin" - case .saveTemplate: "Save as template" - case .delete: "Delete" - } - } - - var systemImage: String { - switch self { - case .openChat: "bubble.left.and.bubble.right" - case .edit: "pencil" - case .viewSessions: "clock.arrow.circlepath" - case .scheduledTasks: "calendar.badge.clock" - case .groups: "person.2" - case .duplicate: "plus.square.on.square" - case .shortcuts: "waveform" - case .setPrimary: "star" - case .togglePin: "pin" - case .saveTemplate: "square.and.arrow.down.on.square" - case .delete: "trash" - } - } - - var capability: WorkspaceCapability? { - switch self { - case .openChat: .canonicalAgentChat - case .edit: .profilesEdit - case .viewSessions: .sessionsRead - case .scheduledTasks: .schedulesRead - case .groups: .groupsRead - case .duplicate: .profilesClone - case .delete: .profilesEdit - case .shortcuts, .setPrimary, .togglePin, .saveTemplate: nil - } - } -} - -struct AgentActionItem: Identifiable, Equatable { - let action: AgentRowMenuAction - let title: String - let systemImage: String - let isEnabled: Bool - let detail: String? - let isSelected: Bool - let isUnsupported: Bool - - var id: AgentRowMenuAction { action } } enum AgentActionsPresentation { - static func items( - profileID: String, owner: WorkspaceOwner?, capabilities: WorkspaceCapabilities, - isPrimary: Bool, isPinned: Bool, canPin: Bool, canClone: Bool, - shortcutsAvailable: Bool, hasNavigation: Bool, - canDelete: Bool = false, canSaveTemplate: Bool = false - ) -> [AgentActionItem] { - AgentRowMenuAction.allCases.compactMap { action in - if action == .shortcuts && !shortcutsAvailable { return nil } - if action == .delete && !canDelete { return nil } - if action == .saveTemplate && !canSaveTemplate { return nil } - let availability: WorkspaceAvailability - if let owner { - availability = action.capability.map { - capabilities.availability(for: $0, owner: owner, profileID: profileID) - } ?? .available - } else { - availability = .unavailable(.notConnected) - } - var title = action.title - var symbol = action.systemImage - var enabled = availability.isAvailable - var detail = unavailableMessage(availability) - var selected = false - if action == .setPrimary { - selected = isPrimary - title = isPrimary ? "Primary Agent" : title - symbol = isPrimary ? "star.fill" : symbol - enabled = enabled && !isPrimary - if availability.isAvailable { - detail = isPrimary ? AgentActionPresentation.alreadyPrimaryHint : AgentActionPresentation.setPrimaryHint - } - } else if action == .togglePin { - selected = isPinned - title = isPinned ? "Unpin" : title - symbol = isPinned ? "pin.slash" : symbol - enabled = enabled && (isPinned || canPin) - if availability.isAvailable { - detail = isPinned ? AgentActionPresentation.unpinHint - : canPin ? AgentActionPresentation.pinHint : AgentActionPresentation.pinLimitHint - } - } else if action == .duplicate && !canClone { - enabled = false - detail = "Profile duplication is not available on this connection." - } else if [.openChat, .viewSessions, .scheduledTasks].contains(action), !hasNavigation { - enabled = false - detail = "This connection is not ready to open the workspace." - } - return AgentActionItem( - action: action, title: title, systemImage: symbol, - isEnabled: enabled, detail: detail, isSelected: selected, - isUnsupported: availability == .unavailable(.unsupportedOperation) - || availability == .unavailable(.unsupportedHost) - ) - } - } - static func unavailableMessage(_ availability: WorkspaceAvailability) -> String? { switch availability { case .available: nil @@ -237,71 +32,3 @@ enum AgentActionsPresentation { } } } - -enum AgentRowPresentation { - enum ActionAlignment: Equatable { - case center - var swiftUIValue: VerticalAlignment { .center } - } - - static let roleLineLimit = 2 - static let summaryLineLimit = 2 - static let textColumnCanShrink = true - static let actionAlignment = ActionAlignment.center - static let actionSystemImage: String? = "ellipsis" - static let showsNavigationDisclosureIndicator = false -} - -extension AgentDirectoryPresentation { - /// Agents shown in the directory's avatar grid: the user's pins in pin - /// order, or, when nothing is pinned, the first few agents with the - /// primary agent leading. - struct Featured: Equatable { - let profiles: [AgentProfile] - let isPinnedSelection: Bool - } - - static let featuredLimit = AgentActionPresentation.pinnedAgentLimit - - static func featured( - visible: [AgentProfile], pinnedIDs: [String], primaryID: String?, - limit: Int = featuredLimit - ) -> Featured { - let pinned = pinnedIDs.compactMap { id in visible.first { $0.id == id } } - if !pinned.isEmpty { - return Featured(profiles: Array(pinned.prefix(limit)), isPinnedSelection: true) - } - let ordered = visible.filter { $0.id == primaryID } + visible.filter { $0.id != primaryID } - return Featured(profiles: Array(ordered.prefix(limit)), isPinnedSelection: false) - } -} - -/// Live states derived only from authoritative Hermes state: what each agent's -/// Bot Chat is doing (`BotChatActivityStore`), and a Bot Mode approval waiting on -/// one of that agent's group memberships, which outranks working. Everything -/// else stays `.idle` rather than inventing status. -enum AgentLiveStatePresentation { - static func agentStates( - rooms: [HermesBotModeRoomSummary], - pendingApprovals: (String) -> [HermesBotModePendingApproval], - botChats: [String: BotChatActivity] = [:] - ) -> [String: AgentLiveState] { - var states: [String: AgentLiveState] = [:] - for (profile, activity) in botChats where activity.isOnTurn { states[profile] = activity.liveState } - for room in rooms where !room.isDisbanded { - for approval in pendingApprovals(room.roomID) { - guard let profile = room.members.first(where: { $0.memberID == approval.memberID })?.profile - else { continue } - states[profile] = .nudge - } - } - return states - } - - /// A group needing an approval outranks one that is simply working. - static func groupState(isWorking: Bool, hasPendingApprovals: Bool) -> AgentLiveState? { - if hasPendingApprovals { return .nudge } - if isWorking { return .thinking } - return nil - } -} diff --git a/Bighelp/Agents/AgentsSectionCaption.swift b/Bighelp/Agents/AgentsSectionCaption.swift new file mode 100644 index 00000000..8d34a69a --- /dev/null +++ b/Bighelp/Agents/AgentsSectionCaption.swift @@ -0,0 +1,19 @@ +import SwiftUI + +/// Uppercase, letterspaced section caption ("PINNED", "GROUP CHATS"). +struct AgentsSectionCaption: View { + let title: String + + @ScaledMetric(relativeTo: .caption2) private var size: CGFloat = 11 + + var body: some View { + Text(title.uppercased()) + .font(.system(size: size, weight: .bold)) + .tracking(size * 0.08) + .foregroundStyle(theme.secondaryText) + .accessibilityLabel(title) + .accessibilityAddTraits(.isHeader) + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Agents/AgentsView.swift b/Bighelp/Agents/AgentsView.swift deleted file mode 100644 index debdaabe..00000000 --- a/Bighelp/Agents/AgentsView.swift +++ /dev/null @@ -1,686 +0,0 @@ -import SwiftUI - -@MainActor -struct AgentsView: View { - let store: AgentDirectoryStore - let runtimeDefaultsClient: any AgentRuntimeDefaultsClient - let onSelect: (AgentProfile) -> Void - let onOpenSessions: (AgentProfile) -> Void - var onOpenHostStatus: (() -> Void)? = nil - var hostRuntime: HostRuntimeStore? = nil - var workspaceOwner: WorkspaceOwner? = nil - var capabilities: WorkspaceCapabilities = .disconnected - var botModeRooms: BotModeRoomStore? = nil - var cloneClient: (any AgentProfileCloneClient)? = nil - var shortcutsAvailable = false - var onAction: (@MainActor (AgentWorkspaceActionRequest) -> Void)? = nil - /// Set from elsewhere (the Chats rail's "Group chats") to show one agent's groups. - var groupFilterRequest: Binding = .constant(nil) - /// Set from all computers › New agent: opens the new-agent editor once this computer is connected. - var createRequest: Binding = .constant(false) - /// Which agents' Bot Chats are working or need you, kept current while this screen shows. - var botChatActivity: BotChatActivityStore? = nil - var botChatActivitySource: BotChatActivitySource? = nil - /// The sections, as cards that open their pages (Bots mode's); nil or empty shows nothing. - var sectionCards: AnyView? = nil - - @State private var query = "" - @State private var groupPreferences = AgentGroupPreferences() - @State private var showsArchivedGroups = false - @State private var renameGroup: HermesBotModeRoomSummary? - @State private var renameText = "" - @State private var deleteGroup: HermesBotModeRoomSummary? - @State private var groupFilterProfileID: String? - @State private var areGroupsExpanded = true - @State private var agentActions = AgentActions() - @State private var actionAgent: AgentProfile? - @Environment(\.agentDeletion) private var agentDeletion - @State private var activeOwner: WorkspaceOwner? - @State private var shownSignIn: WorkspaceSignIn? - @State private var actionOwner: WorkspaceOwner? - @State private var deferredAction: DeferredAgentAction? - /// A pinned agent is lifted: the list holds still while it moves. - @State private var isArrangingPinned = false - @Environment(\.accessibilityReduceMotion) private var reduceMotion - @Environment(\.scenePhase) private var scenePhase - - private var visibleProfiles: [AgentProfile] { - AgentDirectoryPresentation.visibleProfiles(store.profiles, query: query) - } - - private var visibleGroups: [HermesBotModeRoomSummary] { - AgentDirectoryPresentation.visibleGroups( - botModeRooms?.catalogRooms ?? [], profiles: store.profiles, - query: query, profileID: groupFilterProfileID - ) - } - - private var groupScope: String { workspaceOwner?.cacheScopeID ?? "unavailable" } - private func preference(_ group: HermesBotModeRoomSummary) -> AgentGroupPreferences.Entry { - groupPreferences.entry(group.roomID, scope: groupScope) - } - private func togglePin(_ group: HermesBotModeRoomSummary) { - var entry = preference(group); entry.pinned.toggle() - groupPreferences.set(entry, id: group.roomID, scope: groupScope) - } - private func toggleArchive(_ group: HermesBotModeRoomSummary) { - var entry = preference(group); entry.archived.toggle() - groupPreferences.set(entry, id: group.roomID, scope: groupScope) - } - - private var featured: AgentDirectoryPresentation.Featured { - AgentDirectoryPresentation.featured( - visible: visibleProfiles, pinnedIDs: store.pinnedAgentIDs, primaryID: store.primaryAgentID - ) - } - - private var liveStates: [String: AgentLiveState] { - AgentLiveStatePresentation.agentStates( - rooms: botModeRooms?.catalogRooms ?? [], pendingApprovals: { botModeRooms?.pendingApprovals(roomID: $0) ?? [] }, - botChats: botChatActivity?.liveActivities() ?? [:] - ) - } - - private func groupLiveState(_ group: HermesBotModeRoomSummary) -> AgentLiveState? { - guard let botModeRooms else { return nil } - return AgentLiveStatePresentation.groupState( - isWorking: botModeRooms.nativeRoomIsWorking(roomID: group.roomID), - hasPendingApprovals: !botModeRooms.pendingApprovals(roomID: group.roomID).isEmpty - ) - } - - /// The featured grid is a browsing aid; searching and group filtering - /// collapse the directory to plain results. - private var showsFeatured: Bool { - query.isEmpty && groupFilterProfileID == nil && !featured.profiles.isEmpty - } - - /// A host with no agents cannot have useful group chats, so its first-run - /// screen is just the friendly empty state. - private var isDirectoryEmpty: Bool { - query.isEmpty && groupFilterProfileID == nil && visibleProfiles.isEmpty && visibleGroups.isEmpty - && store.errorMessage == nil && !store.isLoading && !store.isInitialLoadPending - } - - var body: some View { - GeometryReader { geometry in - let states = liveStates - List { - if !isDirectoryEmpty { - BighelpSearchField(text: $query, prompt: "Search agents and groups", - accessibilityLabel: "Search agents and groups", - accessibilityIdentifier: "agents.search") - .bighelpListSearchRow() - } - if showsFeatured { featuredSection(states) } - if query.isEmpty, groupFilterProfileID == nil, let sectionCards { - Section { - sectionCards - .listRowInsets(EdgeInsets(top: BighelpTokens.space4, leading: 0, - bottom: BighelpTokens.space8, trailing: 0)) - .listRowSeparator(.hidden) - } - .listRowBackground(theme.canvas) - .listSectionSeparator(.hidden) - } - ForEach( - AgentDirectoryPresentation.sectionOrder(filteredToProfileID: groupFilterProfileID), - id: \.self - ) { section in - switch section { - case .groups: - if !isDirectoryEmpty { groupsSection } - case .agents: - agentsSection(states) - } - } - } - .listStyle(.plain) - .scrollDisabled(isArrangingPinned) - .textCase(nil) - .scrollContentBackground(.hidden) - .contentMargins(.horizontal, max(0, (geometry.size.width - 760) / 2), for: .scrollContent) - .contentMargins(.top, BighelpTokens.space4, for: .scrollContent) - .contentMargins(.bottom, BighelpTokens.space24, for: .scrollContent) - .environment(\.defaultMinListRowHeight, BighelpTokens.hitTarget) - .dismissesKeyboardOnScroll(true) - .accessibilityIdentifier("agents.screen") - .toolbar { - #if targetEnvironment(macCatalyst) - // A Mac list can't be pulled down to refresh. - ToolbarItem(placement: .primaryAction) { - Button("Refresh", systemImage: "arrow.clockwise") { - Task { await refresh() } - } - .keyboardShortcut("r") - .accessibilityIdentifier("agents.refresh") - } - #endif - ToolbarItem(placement: .primaryAction) { - Button("Create agent", systemImage: "plus", action: startCreating) - .disabled(!supports(.profilesCreate)) - .accessibilityIdentifier("agents.create") - } - } - .background(theme.canvas.ignoresSafeArea()) - } - .onAppear { - activeOwner = workspaceOwner - if let workspaceOwner { shownSignIn = workspaceOwner.signIn } - } - .onChange(of: createRequest.wrappedValue, initial: true) { _, _ in startRequestedCreation() } - .onChange(of: workspaceOwner?.signIn) { _, _ in startRequestedCreation() } - .onChange(of: groupFilterRequest.wrappedValue, initial: true) { _, profileID in - guard let profileID else { return } - groupFilterRequest.wrappedValue = nil - showGroups(of: profileID) - } - .onChange(of: workspaceOwner) { _, current in - activeOwner = current - // An actions sheet left open acts on the new connection. - if let current, actionOwner?.signIn == current.signIn { actionOwner = current } - // Disconnected, or back on the same computer and sign-in (bighelp - // reconnects after you've been away): menus and dialogs stay open. - guard let current, current.signIn != shownSignIn else { return } - let previousScope = shownSignIn?.authority.cacheScopeID - shownSignIn = current.signIn - deferredAction = nil - actionAgent = nil - renameGroup = nil - deleteGroup = nil - if previousScope != current.cacheScopeID { - groupPreferences = AgentGroupPreferences() - query = "" - showsArchivedGroups = false - groupFilterProfileID = nil - } - } - .task(id: workspaceOwner?.cacheScopeID) { - guard Self.shouldBootstrapStoreRefresh(for: workspaceOwner) else { return } - await store.loadIfNeededReportingErrors() - } - .botChatActivityUpdates(botChatActivity, source: botChatActivitySource, isActive: scenePhase == .active) - .task(id: workspaceOwner) { - guard Self.shouldBootstrapStoreRefresh(for: workspaceOwner) else { return } - if botModeRooms?.catalogState == .idle { - await botModeRooms?.refreshNativeRoomCatalog() - } - } - .bighelpRefreshable { await refresh() } - .bighelpSheet(item: $actionAgent, onDismiss: finishAgentActionSheet) { agent in - AgentActionSheet( - agent: agent, - imageURL: store.avatarURL(for: agent), - actions: actionItems(agent) - ) { action in - perform(action, profileID: agent.id, expectedOwner: actionOwner) - } - .presentationDetents([.medium, .large]) - .presentationDragIndicator(.visible) - .bighelpSheetSize(.standard) - } - .alert("Rename group", isPresented: Binding(get: { renameGroup != nil }, set: { if !$0 { renameGroup = nil } })) { - TextField("Group name", text: $renameText) - Button("Cancel", role: .cancel) { renameGroup = nil } - Button("Rename") { - if let group = renameGroup { dispatch(.renameGroup(roomID: group.roomID, name: renameText)) } - renameGroup = nil - }.disabled(renameText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) - } - .confirmationDialog("Delete this group?", isPresented: Binding(get: { deleteGroup != nil }, set: { if !$0 { deleteGroup = nil } }), titleVisibility: .visible) { - Button("Delete group", role: .destructive) { - if let group = deleteGroup { dispatch(.deleteGroup(roomID: group.roomID)) } - deleteGroup = nil - } - } message: { Text("This permanently deletes the group on Hermes and stops its active work.") } - .agentActionsPresentation(agentActions, config: actionsConfig) - } - - - private func featuredSection(_ states: [String: AgentLiveState]) -> some View { - let featured = featured - return Section { - AgentsSectionCaption(title: featured.isPinnedSelection ? "Pinned" : "Your agents") - .frame(maxWidth: .infinity, alignment: .leading) - .listRowInsets(EdgeInsets(top: BighelpTokens.space4, leading: BighelpTokens.space16, - bottom: 0, trailing: BighelpTokens.space16)) - .listRowSeparator(.hidden) - AgentPinnedGrid( - agents: featured.profiles, - canReorder: featured.isPinnedSelection, - imageURL: avatarURL, - liveState: { agent in states[agent.id] ?? .idle }, - isPrimary: isPrimary, - open: openFeatured, - manage: manage, - reorder: reorderPinned, - create: createAction, - isArranging: $isArrangingPinned - ) - .listRowInsets(EdgeInsets(top: BighelpTokens.space8, leading: BighelpTokens.space16, - bottom: BighelpTokens.space16, trailing: BighelpTokens.space16)) - .listRowSeparator(.hidden) - } - .listRowBackground(theme.canvas) - .listSectionSeparator(.hidden) - } - - private var groupsSection: some View { - let groups = visibleGroups.filter { preference($0).archived == showsArchivedGroups } - .sorted { preference($0).pinned && !preference($1).pinned } - return Section { - groupsCaption - .listRowInsets(EdgeInsets(top: BighelpTokens.space8, leading: BighelpTokens.space16, - bottom: 0, trailing: BighelpTokens.space4)) - .listRowSeparator(.hidden) - if canCreateGroup { - AgentNewGroupRow { dispatch(.createGroup(seedProfileID: groupFilterProfileID)) } - .accessibilityIdentifier("agents.groups.create") - .listRowInsets(Self.rowInsets) - } - if areGroupsExpanded { - if let profileID = groupFilterProfileID { - HStack { - Text("Groups with \(store.profiles.first(where: { $0.id == profileID })?.name ?? "this agent")") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.primaryText) - Spacer() - Button("Clear group filter", systemImage: "xmark.circle.fill") { - groupFilterProfileID = nil - } - .labelStyle(.iconOnly) - .buttonStyle(.plain) - .foregroundStyle(theme.secondaryText) - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - .accessibilityIdentifier("agents.groups.clear-filter") - } - .listRowInsets(Self.rowInsets) - } - groupStatus - .listRowInsets(Self.rowInsets) - ForEach(groups) { group in - AgentGroupRowView( - group: group, profiles: store.profiles, avatarDirectory: store.avatarDirectory, - peers: botModeRooms?.peerHosts, - isPinned: preference(group).pinned, liveState: groupLiveState(group) - ) { dispatch(.openGroup(roomID: group.roomID)) } - .listRowInsets(Self.rowInsets) - .contextMenu { - Button("Open chat", systemImage: "bubble.left.and.bubble.right") { - dispatch(.openGroup(roomID: group.roomID)) - } - Button(preference(group).pinned ? "Unpin" : "Pin", systemImage: "pin") { togglePin(group) } - Button("Rename", systemImage: "pencil") { renameText = group.name; renameGroup = group } - .disabled(!group.canRename) - Button(preference(group).archived ? "Unarchive" : "Archive", systemImage: "archivebox") { toggleArchive(group) } - Button("Group settings", systemImage: "slider.horizontal.3") { - dispatch(.openGroupSettings(roomID: group.roomID)) - } - Button("Delete", systemImage: "trash", role: .destructive) { deleteGroup = group } - .disabled(botModeRooms?.nativeCapabilities?.supports("groups.disband") != true) - } - .swipeActions(edge: .leading) { - Button(preference(group).pinned ? "Unpin" : "Pin", systemImage: "pin") { togglePin(group) } - .tint(theme.action) - } - .swipeActions(edge: .trailing, allowsFullSwipe: false) { - Button("Delete", systemImage: "trash", role: .destructive) { deleteGroup = group } - .disabled(botModeRooms?.nativeCapabilities?.supports("groups.disband") != true) - Button(preference(group).archived ? "Unarchive" : "Archive", systemImage: "archivebox") { toggleArchive(group) } - .tint(theme.secondaryText) - } - } - if groups.isEmpty, !visibleGroups.isEmpty { - Text(showsArchivedGroups ? "No archived groups." : "No groups to show.") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .listRowInsets(Self.rowInsets) - } - archivedGroupsRow - } - } - .listRowBackground(theme.canvas) - .listRowSeparatorTint(theme.separator) - .listSectionSeparator(.hidden) - } - - /// Like Mail's Archive: a full-width row after the list switches between - /// current and archived group chats. Hidden when nothing is archived. - @ViewBuilder - private var archivedGroupsRow: some View { - let archivedCount = visibleGroups.filter { preference($0).archived }.count - if showsArchivedGroups || archivedCount > 0 { - Button { - withAnimation(reduceMotion ? nil : .snappy(duration: BighelpTokens.stateDuration)) { - showsArchivedGroups.toggle() - } - } label: { - HStack(spacing: BighelpTokens.space12) { - Image(systemName: showsArchivedGroups ? "chevron.backward" : "archivebox") - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(theme.secondaryText) - .frame(width: 52) - Text(showsArchivedGroups ? "Back to group chats" : "Archived group chats (\(archivedCount))") - .font(.bighelp(.subheadline).weight(.medium)) - .foregroundStyle(theme.primaryText) - Spacer(minLength: 0) - } - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) - .contentShape(.rect) - } - .buttonStyle(.plain) - .listRowInsets(Self.rowInsets) - .accessibilityLabel(showsArchivedGroups ? "Show groups" : "Archived groups") - .accessibilityValue(showsArchivedGroups ? "" : "\(archivedCount)") - .accessibilityIdentifier("agents.groups.archived-toggle") - } - } - - private var groupsCaption: some View { - HStack(spacing: BighelpTokens.space4) { - Button { - withAnimation(reduceMotion ? nil : .easeInOut(duration: BighelpTokens.stateDuration)) { - areGroupsExpanded.toggle() - } - } label: { - HStack(spacing: BighelpTokens.space4) { - AgentsSectionCaption(title: showsArchivedGroups ? "Archived group chats" : "Group chats") - Image(systemName: areGroupsExpanded ? "chevron.down" : "chevron.right") - .font(.bighelp(.caption2).weight(.bold)) - .foregroundStyle(theme.tertiaryText) - .accessibilityHidden(true) - } - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - // Borderless, not plain: a plain button claims the whole list row, which - // would swallow taps meant for the archive toggle beside it. - .buttonStyle(.borderless) - .accessibilityLabel(showsArchivedGroups ? "Archived group chats" : "Group chats") - .accessibilityAddTraits(.isHeader) - .accessibilityValue(areGroupsExpanded ? "Expanded" : "Collapsed") - .accessibilityIdentifier("agents.groups.disclosure") - Spacer() - } - } - - @ViewBuilder - private var groupStatus: some View { - let state = botModeRooms?.catalogState ?? .unavailable("Connect to a compatible host to see its groups.") - switch state { - case .idle, .loading: - ProgressView(visibleGroups.isEmpty ? "Loading groups" : "Refreshing groups") - .accessibilityIdentifier("agents.groups.loading") - case .unavailable(let message), .failed(let message): - recovery(message, identifier: "agents.groups.error") { - Task { await botModeRooms?.refreshNativeRoomCatalog() } - } - case .loaded: - if visibleGroups.isEmpty { - Text(query.isEmpty && groupFilterProfileID == nil ? "No groups yet." : "No matching groups.") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .accessibilityIdentifier("agents.groups.empty") - } - } - } - - private func agentsSection(_ states: [String: AgentLiveState]) -> some View { - Section { - if !isDirectoryEmpty { - AgentsSectionCaption(title: query.isEmpty ? "All agents" : "Agents") - .frame(maxWidth: .infinity, alignment: .leading) - .listRowInsets(EdgeInsets(top: BighelpTokens.space16, leading: BighelpTokens.space16, - bottom: BighelpTokens.space4, trailing: BighelpTokens.space16)) - .listRowSeparator(.hidden) - } - if let error = store.errorMessage { - recovery(error, identifier: "agents.load-error") { - Task { await store.loadReportingErrors() } - } - .listRowInsets(Self.rowInsets) - } - if (store.isLoading || store.isInitialLoadPending) && store.profiles.isEmpty { - ProgressView(store.profiles.isEmpty ? "Loading agents" : "Refreshing agents") - .frame(maxWidth: .infinity) - .listRowInsets(Self.rowInsets) - .accessibilityIdentifier("agents.refreshing") - } else if isDirectoryEmpty { - AgentsEmptyStateView(canCreate: supports(.profilesCreate), onCreate: startCreating) - .listRowSeparator(.hidden) - .accessibilityIdentifier("agents.empty") - } else if visibleProfiles.isEmpty { - ContentUnavailableView( - query.isEmpty ? (store.errorMessage == nil ? "No agents yet" : "Agents unavailable") : "No matching agents", - systemImage: query.isEmpty ? "person.2" : "magnifyingglass", - description: Text(query.isEmpty ? "Agents on this host appear here." : "Try another name or description.") - ) - .listRowSeparator(.hidden) - .accessibilityIdentifier("agents.empty") - } - ForEach(visibleProfiles) { agent in row(agent, liveState: states[agent.id] ?? .idle) } - } - .listRowBackground(theme.canvas) - .listRowSeparatorTint(theme.separator) - .listSectionSeparator(.hidden) - } - - /// Rows sit directly on the canvas; separators start under the text - /// column (16 + 52 + 12 = 80pt), like Messages. - private static let rowInsets = EdgeInsets( - top: 0, leading: BighelpTokens.space16, bottom: 0, trailing: BighelpTokens.space8 - ) - - private func row(_ agent: AgentProfile, prefix: String = "agent", liveState: AgentLiveState = .idle) -> some View { - let actions = actionItems(agent) - let pin = actions.first { $0.action == .togglePin } - let edit = actions.first { $0.action == .edit } - return AgentRowView( - agent: agent, imageURL: store.avatarURL(for: agent), - isPrimary: store.isPrimary(agent.id), isPinned: store.isPinned(agent.id), - canOpenChat: actions.first { $0.action == .openChat }?.isEnabled == true, - onOpenChat: { perform(.openChat, profileID: agent.id, expectedOwner: workspaceOwner) }, - onManage: { actionOwner = workspaceOwner; actionAgent = agent }, - identifierPrefix: prefix, - liveState: liveState - ) - .listRowInsets(Self.rowInsets) - .swipeActions(edge: .leading, allowsFullSwipe: false) { - if let pin { - Button(pin.title, systemImage: pin.systemImage) { - perform(.togglePin, profileID: agent.id, expectedOwner: workspaceOwner) - } - .tint(theme.action) - .disabled(!pin.isEnabled) - } - } - .swipeActions(edge: .trailing, allowsFullSwipe: false) { - if let delete = actions.first(where: { $0.action == .delete }) { - Button("Delete", systemImage: delete.systemImage, role: .destructive) { - perform(.delete, profileID: agent.id, expectedOwner: workspaceOwner) - } - .disabled(!delete.isEnabled) - } - if let edit, !edit.isUnsupported { - Button("Edit", systemImage: edit.systemImage) { - perform(.edit, profileID: agent.id, expectedOwner: workspaceOwner) - } - .tint(theme.action) - .disabled(!edit.isEnabled) - } - } - .contextMenu { agentContextMenu(agent) } - .accessibilityAction(named: "Manage agent") { - actionOwner = workspaceOwner - actionAgent = agent - } - } - - private func refresh() async { - await store.loadReportingErrors() - await botModeRooms?.refreshNativeRoomCatalog() - } - - private func avatarURL(_ agent: AgentProfile) -> URL? { store.avatarURL(for: agent) } - private func isPrimary(_ agent: AgentProfile) -> Bool { store.isPrimary(agent.id) } - private func reorderPinned(_ ids: [String]) { store.reorderPinnedAgents(ids) } - private var createAction: (() -> Void)? { supports(.profilesCreate) ? { startCreating() } : nil } - - /// A pinned agent's chat, or its actions when it can't open one. - private func openFeatured(_ agent: AgentProfile) { - if actionItems(agent).first(where: { $0.action == .openChat })?.isEnabled == true { - perform(.openChat, profileID: agent.id, expectedOwner: workspaceOwner) - } else { - manage(agent) - } - } - - /// That agent's actions, the same sheet as Manage agent. - private func manage(_ agent: AgentProfile) { - actionOwner = workspaceOwner - actionAgent = agent - } - - @ViewBuilder - private func agentContextMenu(_ agent: AgentProfile) -> some View { - AgentActionMenuItems(actions: agentActions, agent: agent, config: actionsConfig) { action in - perform(action, profileID: agent.id, expectedOwner: workspaceOwner) - } - } - - private func recovery(_ message: String, identifier: String, retry: @escaping () -> Void) -> some View { - VStack(alignment: .leading, spacing: BighelpTokens.space8) { - Label(message, systemImage: "exclamationmark.triangle") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - HStack { - Button("Try again", action: retry) - .frame(minHeight: BighelpTokens.hitTarget) - .accessibilityIdentifier("\(identifier).retry") - if onOpenHostStatus != nil || onAction != nil { - Button("Host status") { - if onAction != nil { dispatch(.openHostStatus) } - else { onOpenHostStatus?() } - } - .frame(minHeight: BighelpTokens.hitTarget) - } - } - } - .buttonStyle(.plain) - .accessibilityIdentifier(identifier) - } - - private func actionItems(_ agent: AgentProfile) -> [AgentActionItem] { - agentActions.items(agent, actionsConfig) - } - - private var actionsConfig: AgentActionsConfig { - AgentActionsConfig(store: store, runtimeDefaultsClient: runtimeDefaultsClient, owner: workspaceOwner, - capabilities: capabilities, cloneClient: cloneClient, - shortcutsAvailable: shortcutsAvailable, onAction: onAction, agentDeletion: agentDeletion) - } - - private func supports(_ capability: WorkspaceCapability, profileID: String? = nil) -> Bool { - guard let workspaceOwner else { return false } - return capabilities.supports(capability, owner: workspaceOwner, profileID: profileID) - } - - private func capabilityReason(_ capability: WorkspaceCapability, profileID: String?) -> String { - guard let workspaceOwner else { return WorkspaceUnavailableReason.notConnected.message } - return AgentActionsPresentation.unavailableMessage( - capabilities.availability(for: capability, owner: workspaceOwner, profileID: profileID) - ) ?? WorkspaceUnavailableReason.unsupportedOperation.message - } - - private var canCreateGroup: Bool { - onAction != nil && botModeRooms?.offersNewGroupChat == true - } - - /// Direct native runtime owns the initial agent and room refresh so a view - /// mount cannot cancel its shared-store load or invalidate its catalog - /// capability negotiation. Link and fixture presentations retain their - /// view-owned bootstrap. - nonisolated static func shouldBootstrapStoreRefresh(for owner: WorkspaceOwner?) -> Bool { - owner?.authority.kind != .direct - } - - private func perform(_ action: AgentRowMenuAction, profileID: String, expectedOwner: WorkspaceOwner?) { - guard let owner = expectedOwner, owner == workspaceOwner, owner == activeOwner, - let agent = store.profiles.first(where: { $0.id == profileID }), - actionItems(agent).first(where: { $0.action == action })?.isEnabled == true else { - agentActions.actionError = "This action is no longer available. Reopen the agent's actions to see its current status." - return - } - if actionAgent != nil { - deferredAction = DeferredAgentAction(action: action, profileID: profileID, owner: owner) - actionAgent = nil - return - } - actionAgent = nil - if action == .groups { - showGroups(of: profileID) - } else { - agentActions.perform(action, agent: agent, config: actionsConfig) - } - } - - private func showGroups(of profileID: String) { - query = "" - groupFilterProfileID = profileID - areGroupsExpanded = true - } - - private func finishDeferredAction() { - guard let pending = deferredAction else { return } - deferredAction = nil - perform(pending.action, profileID: pending.profileID, expectedOwner: pending.owner) - } - - private func finishAgentActionSheet() { - finishDeferredAction() - } - - private func dispatch(_ action: AgentWorkspaceAction) { - guard let owner = workspaceOwner, owner == activeOwner, let onAction else { - agentActions.actionError = "The host connection changed. Try opening this action again." - return - } - - onAction(AgentWorkspaceActionRequest(owner: owner, action: action)) - } - - /// The studio itself offers scratch, built-in and saved templates. - private func startRequestedCreation() { - guard createRequest.wrappedValue, workspaceOwner != nil else { return } - createRequest.wrappedValue = false - // The "which computer?" sheet is still closing; a sheet presented now would be dropped. - Task { @MainActor in - try? await Task.sleep(for: .milliseconds(700)) - startCreating() - } - } - - private func startCreating() { - guard let owner = workspaceOwner, supports(.profilesCreate) else { - agentActions.actionError = "Agent creation is not available on this connection." - return - } - agentActions.editor = .creating( - store: store, - processor: AvatarImageProcessor(), - profileCloneSupport: supports(.profilesClone) - ? .nativeBundleOnly - : .unavailable("Native profile cloning is not available on this connection."), - isCurrent: { activeOwner?.signIn == owner.signIn } - ) - } - - @BighelpThemeReader private var theme -} - -private struct DeferredAgentAction { - let action: AgentRowMenuAction - let profileID: String - let owner: WorkspaceOwner -} diff --git a/Bighelp/Agents/AvatarCreatorView.swift b/Bighelp/Agents/AvatarCreatorView.swift index 196751e1..c0850aeb 100644 --- a/Bighelp/Agents/AvatarCreatorView.swift +++ b/Bighelp/Agents/AvatarCreatorView.swift @@ -10,7 +10,7 @@ enum AvatarCreatorResult { /// A petdex pet's first frame, ready to save; its moves play in chats. case pet(PetdexPet, avatar: Data) case photo(PhotosPickerItem) - /// A Bots mode mark: a shape in a color, with two eyes. + /// A bot's mark: a shape in a color, with two eyes. case mark(SimpleBotMark) } @@ -27,7 +27,7 @@ enum AvatarCreatorStart: Equatable { case pet(slug: String, picture: Data?) /// A photo, or no avatar at all when there's no picture. case photo(Data?) - /// A Bots mode mark. + /// A bot's mark. case mark(SimpleBotMark) } @@ -72,7 +72,7 @@ final class AvatarCreatorModel { } } - /// Bots mode's marks are offered where that mode opens the creator. + /// Marks are offered where the creator is opened for them. var offersBotMarks = false /// Opened from Edit avatar's PetDex: pets only, with no other categories. var petsOnly = false diff --git a/Bighelp/Agents/BotChatActivity.swift b/Bighelp/Agents/BotChatActivity.swift index 1fc05965..00628ad1 100644 --- a/Bighelp/Agents/BotChatActivity.swift +++ b/Bighelp/Agents/BotChatActivity.swift @@ -153,10 +153,10 @@ struct BotChatActivitySource { } var live: @MainActor () -> Live? - /// Multi-gateway: the other gateways' bots from their all-hosts copies, by `FleetID`. Only fresh + /// Every computer shown: the other gateways' bots from their all-hosts copies, by `FleetID`. Only fresh /// copies: an old one says nothing. var others: @MainActor () -> [String: BotChatActivity] = { [:] } - /// Multi-gateway: reads again the copies older than a minute (`FleetStore.refresh`), so the other + /// Every computer shown: reads again the copies older than a minute (`FleetStore.refresh`), so the other /// gateways stay current while the home shows. var refreshOthers: @MainActor () -> Void = {} } @@ -187,7 +187,7 @@ enum BotChatActivitySignals { } } -/// Each bot's Bot Chat state, for Bots mode and the Agents screen. While a screen that shows +/// Each bot's Bot Chat state, for the Bots view. While a screen that shows /// it is open and the app is active, it reads the gateway in use once per tick, in one request, /// quicker while something works; nothing runs otherwise, and what's shown is cleared then, since /// it would go stale. Each bot's state is observed on its own, so a row redraws only when its own @@ -231,7 +231,7 @@ final class BotChatActivityStore { return cells[key]?.value } - /// The gateway in use's bots that are busy, by profile ID (the Agents screen). + /// The gateway in use's bots that are busy, by profile ID (the Bots view). func liveActivities() -> [String: BotChatActivity] { _ = generation var result: [String: BotChatActivity] = [:] diff --git a/Bighelp/App/AppFixtureSetup.swift b/Bighelp/App/AppFixtureSetup.swift index 9949d973..9b91b7dd 100644 --- a/Bighelp/App/AppFixtureSetup.swift +++ b/Bighelp/App/AppFixtureSetup.swift @@ -103,6 +103,11 @@ enum AppFixtureSetup { let index = initialSessions.firstIndex(where: { $0.id == "demo-finance" }) { initialSessions[index] = ConversationFixtures.htmlAppsPreview } + // A bot's space draft in its chat, with Add to Today (the demo computer, `DemoSpacesClient`). + if usesFixtures, arguments.contains("-test-spaces"), + let index = initialSessions.firstIndex(where: { $0.id == "demo-finance" }) { + initialSessions[index] = ConversationFixtures.spacesPreview + } if usesFixtures, arguments.contains("-test-completed-turn-context"), let index = initialSessions.firstIndex(where: { $0.id == "demo-finance" }) { initialSessions[index] = ConversationFixtures.completedTurnContextPreview diff --git a/Bighelp/App/AppRoute.swift b/Bighelp/App/AppRoute.swift index cec9f6a3..1fdb7061 100644 --- a/Bighelp/App/AppRoute.swift +++ b/Bighelp/App/AppRoute.swift @@ -1,36 +1,9 @@ import Foundation -enum AppTab: String, CaseIterable, Identifiable { - case home, agents, sessions, inbox, profile, scheduledTasks - case feed, ideas, goals, apps - /// Pages ☰ opens, as tabs when the person pins them to the bottom bar. - case projects, kanban, workflows, usage - /// Code mode's home: coding sessions on the host's projects (Settings › Code mode). - case code - /// Every chat, as its own tab (App layout's Sessions). It's the Chat tab's list - /// (`selectedTab` stays `.sessions`); only the bottom bar tells them apart. - case sessionList - - /// The standard bottom bar: the agent's chat, then its Feed, Ideas, Goals and Apps. - /// Settings › Appearance › App layout changes it (`BighelpAppLayout.barTabs`). - static let allCases: [AppTab] = [.sessions, .feed, .ideas, .goals, .apps] - - /// One computer's pages, opened from ☰ or pinned to the bar. - var isHostPage: Bool { [.projects, .kanban, .workflows, .usage].contains(self) } - - /// Screens people stay on (Projects, Kanban, Workflows): from ☰ they open as screens of - /// their own, with ☰ in the corner. Quick ones (Usage, and Feed, Ideas or Goals when the - /// bottom bar doesn't hold them) slide in over where you are, with Back. - var isLongStay: Bool { [.projects, .kanban, .workflows, .code].contains(self) } - - /// Tabs drawn as the selected agent's board (no navigation bar). - var isAgentBoard: Bool { [.feed, .ideas, .goals, .apps].contains(self) } - - var id: Self { self } -} - +/// A page pushed over one of the home's three places (`HomeTab`). enum AppRoute: Hashable { case chat(conversationID: String) + /// The computer in use's own Sessions page (projects, imports from other apps), from Chats. case sessions case scheduledTasks case scheduledTask(id: String, agentID: String? = nil) @@ -44,37 +17,34 @@ enum AppRoute: Hashable { case project(id: String) /// Kanban: the host's boards, worked by its agents. case kanban - /// Workflows: stages run by agents on the host, with your sign-off (☰ › Workflows). + /// Workflows: stages run by agents on the host, with your sign-off (Work › Workflows). case workflows case workflow(id: String, startsRun: Bool) case workflowRun(id: String) case workflowSignoff(runID: String) /// All runs; the Mac's three-column monitor, with one selected. case workflowRuns(selected: String?) - /// Plans, limits and what the agents used (☰ › Usage). + /// Plans, limits and what the agents used (Settings › Usage, and a chat's ⋯). case usage - /// The all-hosts view's chat list: every host's chats. - case allHostsChats - /// Feed, Ideas, Goals or Files as a quick screen with Back, when the bottom bar doesn't hold it. - case board(AppTab) - /// A Code mode session's changes, with Ship. + /// Today's See all: every bot's Feed, Ideas or Goals, or one bot's (`TodayBoardPage`). + case board(AgentBoardItem.Kind, agentID: String? = nil) + /// Work filtered to one project, with its pull requests, worktrees and Dev Factory. + case work(projectID: String) + /// A coding session's changes, with Ship. case codeChanges(sessionID: String) - /// Orchestration mode's chat for a batch sent with Send all. + /// The chat for a batch sent with Send all. case codeBatch(id: UUID) - /// Dev Factory (☰ › Dev Factory in Code mode): its home, a recipe, one start's runs, a run's changes. + /// Dev Factory (the ⋯ of Work filtered to a project): its home, a recipe, one start's runs, a run's changes. case devFactory case devFactoryRecipe(id: String) case devFactoryGroup(id: String) case devFactoryChanges(runID: String) - /// Bots mode: a bot's profile, from its chat's name or a long press. `opening` is for code that + /// A bot's page, from its chat's name or a long press. `opening` is for code that /// shows a person one tab and sheet (an agent's drive); nil opens it as a tap does. case simpleBotProfile(agentID: String, opening: BotProfileOpening? = nil) /// A group chat's Group Settings, from its name, its ⋯ menu or a list of chats. /// `conversationID` is its open chat, for what that chat shows (tool calls). case groupSettings(roomID: String, conversationID: String? = nil) - /// A section's page (Bots mode's home or the Agents screen): its bots and group chats. + /// A section's page, from the Bots view: its bots and group chats. case simpleBotsSection(id: String) - - /// Screens about every computer, which stay put when the working computer changes. - var isAllHosts: Bool { self == .allHostsChats } } diff --git a/Bighelp/App/AppState.swift b/Bighelp/App/AppState.swift index 5e3e96b7..91c12426 100644 --- a/Bighelp/App/AppState.swift +++ b/Bighelp/App/AppState.swift @@ -15,39 +15,34 @@ struct SuspendedChat: Equatable { let text: String } -/// The chat the person was in when they left it for another place (Feed, Agents, Kanban…). The bar -/// tab it was under opens it again, as any tab keeps its place. -struct HeldChat: Equatable { - let conversationID: String - /// Picked from the full chat list: with Sessions in the bar, Sessions holds it, not Chat. - let openedFromList: Bool - - /// The bar tab that opens it again: Chat (`.sessions`) or Sessions (`.sessionList`). - func tab(sessionsInBar: Bool) -> AppTab { - openedFromList && sessionsInBar ? .sessionList : .sessions - } - - /// Chat is the chat of the agent in use, so it opens a 1:1 chat again only while that chat's - /// agent is in use (a board opened from it makes its agent the one in use). A group chat isn't - /// any one agent's. - static func fitsChat(members: [String], agentInUse: String?) -> Bool { - members.count != 1 || members.first == agentInUse - } -} - @MainActor @Observable final class AppState { - var selectedTab: AppTab = .sessions - /// The root a host or account change returns to: Chat, or Code in Code mode. - var homeTab: AppTab = .sessions + /// The home's tab and view, and what New chat and Today hold. One for the whole app: every + /// computer has its own `AppState`, and a chat opened on another computer keeps the tab. + let home: HomeSelection + /// The bar's tab. A pushed page stays over it; `select` clears the path. + var selectedTab: HomeTab { + get { home.tab } + set { home.tab = newValue } + } var path: [AppRoute] = [] - private(set) var activeConversationID: String? + /// The chat last opened (`activateConversation`). + private var activatedConversationID: String? + /// The chat the person opened last, while it is still on the stack. Back, a tab or anything + /// else that takes it off ends it: it once kept naming a chat that had closed, and the phone + /// tools and Needs you went on treating that chat as the open one. + var activeConversationID: String? { + guard let id = activatedConversationID, path.contains(.chat(conversationID: id)) else { return nil } + return id + } + /// The chat whose bot reaches this phone's tools: the chat opened last, also after Back to a list + /// while that bot still works. A bot that goes on working must not lose the phone's tools + /// because the person stepped out of its chat. + var deviceToolConversationID: String? { activatedConversationID } private(set) var pendingVoiceConversationID: String? /// Text a board "Ask" or "Discuss" leaves in the next new chat's composer. var pendingComposerText: String? - /// The chat left for another place; opening a chat, or another computer or account, forgets it. - private(set) var heldChat: HeldChat? /// The open chat's agent and text when the app left, while that chat had sent nothing. /// Hermes saves a chat only on its first message, so it can be gone on return. var suspendedChat: SuspendedChat? @@ -59,10 +54,6 @@ final class AppState { /// The bot whose own chat may take `pendingComposerText` even though it has history: a bot's /// Dashboard opens that bot's Bot Chat, never a new one. Only an empty message box takes it. var pendingComposerAgentID: String? - /// A chat picked from the full chat list isn't the Chat tab's own chat - /// (auto-opened, ☰ › New chat, the switcher, an agent tapped on Agents), so - /// tapping Chat leaves it. Both have ☰, the tab bar and the big-avatar header. - var chatOpenedFromList = false /// Chats that send their draft once connected: a branch made when Hermes refused a /// message because another Hermes process held the original (`continueInBranch`). var sendsDraftOnOpen: Set = [] @@ -76,35 +67,30 @@ final class AppState { /// What the Settings sheet's stack shows above its first page: `SettingsDestination` values. var settingsPath = NavigationPath() /// Set by `openNeedsYou()`, before the shell is on screen too; kept until the shell settles it - /// (`RootShellView.settleNeedsYouRequest`). - var isNeedsYouRequested = false + /// (`RootShellView.settleNeedsYouRequest`). One for the whole app (`HomeSelection`), so the shell + /// on screen sees a request whichever computer's `AppState` took it. + var isNeedsYouRequested: Bool { + get { home.isNeedsYouRequested } + set { home.isNeedsYouRequested = newValue } + } - /// The drawer reflects the destination on screen, while `selectedTab` - /// deliberately retains the root to return to when a pushed route closes. - var drawerSelectedTab: AppTab? { - path.isEmpty ? selectedTab : nil + /// Tests and previews get a selection of their own; the app passes `HomeSelection.shared`. + init(home: HomeSelection = HomeSelection()) { + self.home = home } - func select(_ tab: AppTab) { - // Leaving a chat for another place: the tab it was under opens it again. Chat and - // Sessions share a root, so moving between them leaves nothing behind. - if selectedTab == .sessions, tab != .sessions, tab != .sessionList, case .chat(let id)? = path.last { - heldChat = HeldChat(conversationID: id, openedFromList: chatOpenedFromList) - } - switch tab { - // The Activity tab of older builds and launch arguments: what it held waits in Needs you - // and in the chats, so it opens Chat. - case .home, .inbox, .sessionList: - selectedTab = .sessions - default: - selectedTab = tab - } - // Root tabs are destinations, not another level in the current route. - // Clearing the path prevents a stale pushed chat/session from winning - // the NavigationStack presentation after a tab or drawer selection. + /// A tab is a root, never another level in the current route: whatever was pushed closes. + func select(_ tab: HomeTab) { + selectedTab = tab path.removeAll() } + /// The first tab on one of its views (a link to Bots or to Chats). + func select(_ view: HomeConversationsView) { + home.view = view + select(.conversations) + } + func open(_ route: AppRoute) { path.append(route) } @@ -112,7 +98,7 @@ final class AppState { /// Switches to `tab` and opens `routes` on it. On the Mac they open a moment /// after the switch: pushed in the same update, the tab's title-bar search /// field stayed drawn over the pushed page's Back button and blocked it. - func select(_ tab: AppTab, thenOpen routes: [AppRoute]) { + func select(_ tab: HomeTab, thenOpen routes: [AppRoute]) { guard selectedTab != tab || !path.isEmpty else { path = routes return @@ -147,29 +133,19 @@ final class AppState { settingsPath = NavigationPath() } - func openSessions() { - select(.sessions) - } - - func openScheduledTasks() { - select(.scheduledTasks) - } - - /// An alert that names no chat: the shell opens Needs you when something waits, else the - /// home chat (`RootShellView.settleNeedsYouRequest`). + /// An alert that names no chat: the shell opens Needs you when something waits, else Today + /// (`RootShellView.settleNeedsYouRequest`). func openNeedsYou() { isNeedsYouRequested = true } func activateConversation(id: String, source: ConversationActivationSource) { - // The chat on screen now is the one a tab holds when the person leaves it. - heldChat = nil let route = AppRoute.chat(conversationID: id) // Already open (a notification, widget or link about it): go back to that copy. A second // copy would share its model, both would redraw every change, and Back would show it again. if let open = path.lastIndex(of: route) { path.removeSubrange(path.index(after: open)...) - activeConversationID = id + activatedConversationID = id return } switch source { @@ -181,11 +157,19 @@ final class AppState { case .sessions, .fork: path.append(route) } - activeConversationID = id + activatedConversationID = id } - /// The chat the person is in: the active one, else the chat on top of the path (the Chat tab's own - /// chat opens without activating). + /// New chat's blank chat leaves the stack once the chat that takes its place (a group chat) is + /// over it, so Back doesn't show an empty New chat. `isBlank`: nothing was sent in it. A chat + /// with a message is an ordinary chat and stays, whatever opens over it. + func dropBlankChat(_ blankID: String, under conversationID: String, isBlank: Bool) { + guard isBlank, blankID != conversationID, + path.contains(.chat(conversationID: conversationID)) else { return } + path.removeAll { $0 == .chat(conversationID: blankID) } + } + + /// The chat the person is in: the active one, else the chat on top of the path. var chatOnScreen: String? { if let activeConversationID { return activeConversationID } if case .chat(let id)? = path.last { return id } @@ -196,37 +180,22 @@ final class AppState { pendingVoiceConversationID = conversationID } - /// `keepsAllHostsScreens`: with every computer showing, its lists (All agents, All sessions, - /// every computer's tasks) stay up while the working computer changes; that computer's own - /// pages above them go. - func resetForHostBoundary(keepsAllHostsScreens: Bool = false) { - // The connections screen stays up while you switch hosts from it. - // Host-owned routes do not. + /// Another computer: its pages close and the tab stays. The connections screen stays up while + /// you switch computers from it. + func resetForHostBoundary() { let showsOnlyConnections = !path.isEmpty && path.allSatisfy { $0 == .workspaceConnections } - if keepsAllHostsScreens { - if ![.sessions, .scheduledTasks].contains(selectedTab) { selectedTab = .sessions } - path = Array(path.prefix { $0.isAllHosts }) - } else if !showsOnlyConnections { - selectedTab = homeTab - path.removeAll() - } - activeConversationID = nil + if !showsOnlyConnections { path.removeAll() } + activatedConversationID = nil pendingVoiceConversationID = nil clearComposerText() - chatOpenedFromList = false - // Its chat is the other computer's. - heldChat = nil dropPendingShare() } func resetForAccountBoundary() { - selectedTab = homeTab path.removeAll() - activeConversationID = nil + activatedConversationID = nil pendingVoiceConversationID = nil clearComposerText() - chatOpenedFromList = false - heldChat = nil dropPendingShare() } diff --git a/Bighelp/App/BighelpApp.swift b/Bighelp/App/BighelpApp.swift index dadd9c23..29de701e 100644 --- a/Bighelp/App/BighelpApp.swift +++ b/Bighelp/App/BighelpApp.swift @@ -189,6 +189,9 @@ struct BighelpApp: App { else { return nil } return (scope, demoAgents) }) + Self.wireSpaces(registry: hostRegistry, connections: connections, fleet: fleet, + nativeWorkspaces: nativeWorkspaces, demoHosts: demoHosts, demoAgents: demoAgents, + usesDemoWorkspace: usesDemoWorkspace) let nativeWorkspaceKey: @MainActor () -> BighelpShortcutWorkspaceKey? = { if usesDemoWorkspace, !connections.isDirectSelected { return nil } guard hostRegistry.connectionMode == .independent || connections.isDirectSelected else { return nil } @@ -576,7 +579,7 @@ struct BighelpApp: App { // Shortcuts) still needs the socket, as RootShellView's closer knows. guard BighelpShortcutService.holdsHostConnection == 0 else { return } nativeWorkspaces.suspend() - // Other gateways kept connected for the all-hosts view or Multi-gateway close too. + // Other gateways kept connected for Show every computer close too. hostRegistry.keepsOtherHostsConnected = false } } @@ -631,6 +634,8 @@ struct BighelpApp: App { #if DEBUG && targetEnvironment(simulator) ConnectorCardFixture.rootView() #endif + } else if let oneHomeFixture { + oneHomeFixture } else if BighelpLoaderGallery.isRequested { BighelpLoaderGallery.rootView() } else if isCarPlaySessionFixture { @@ -715,7 +720,7 @@ struct BighelpApp: App { .task(id: nativeWorkspaces.synchronizationKey) { await nativeWorkspaces.synchronize() } - // Bots mode's order, sections and bot settings from the person's computers. + // The Bots view's order, sections and bot settings from the person's computers. .task(id: Self.botsAppStateKey(connections: workspaceConnections, registry: hostRegistry, isActive: scenePhase == .active)) { guard scenePhase == .active else { return } @@ -807,6 +812,21 @@ struct BighelpApp: App { #endif } + /// One home's new screens alone on made-up data, each behind its own launch argument, before + /// the shell shows them. One home: the wiring step can drop the ones the shell shows. + private var oneHomeFixture: AnyView? { + #if DEBUG + let arguments = ProcessInfo.processInfo.arguments + if arguments.contains("-test-home-chrome") { return AnyView(HomeChromeFixture()) } + if arguments.contains(ChatsInboxFixture.launchArgument) { return AnyView(ChatsInboxFixture.view()) } + if arguments.contains(NewChatFixture.launchArgument) { return AnyView(NewChatFixture.makeView()) } + if arguments.contains(TodayFixture.launchArgument) { return AnyView(TodayFixture()) } + if arguments.contains(WorkFixture.launchArgument) { return AnyView(NavigationStack { WorkFixture.view() }) } + if arguments.contains(SpacesTodayFixture.launchArgument) { return AnyView(SpacesTodayFixture()) } + #endif + return nil + } + private var isModelsPageFixture: Bool { #if DEBUG && targetEnvironment(simulator) ProcessInfo.processInfo.arguments.contains(ModelAdministrationFixture.launchArgument) diff --git a/Bighelp/App/BighelpAppBotsState.swift b/Bighelp/App/BighelpAppBotsState.swift index f8435e40..73f49ffc 100644 --- a/Bighelp/App/BighelpAppBotsState.swift +++ b/Bighelp/App/BighelpAppBotsState.swift @@ -1,8 +1,8 @@ import SwiftUI extension BighelpApp { - /// Bots mode's choices on the person's computers (`BotsAppStateSync`): the gateway in use, and - /// the others the all-hosts view or Multi-gateway keeps connected. Demo mode's computer keeps + /// The Bots view's choices on the person's computers (`BotsAppStateSync`): the gateway in use, and + /// the others Show every computer keeps connected. Demo mode's computer keeps /// them in memory for the run. static func startBotsAppState(registry: BighelpHostRegistry, connections: WorkspaceConnectionStore, fleet: FleetStore, settings: SettingsStore, companions: CompanionStore, demo: DemoHosts?, @@ -69,7 +69,7 @@ extension BighelpApp { })) } - /// When Bots mode's choices are read from the computers: each new connection to the gateway in + /// When the Bots view's choices are read from the computers: each new connection to the gateway in /// use, coming back to bighelp, and other gateways kept connected or let go. static func botsAppStateKey(connections: WorkspaceConnectionStore, registry: BighelpHostRegistry, isActive: Bool) -> String { diff --git a/Bighelp/App/BighelpAppComposition.swift b/Bighelp/App/BighelpAppComposition.swift index 6528f3c6..ec39cbbb 100644 --- a/Bighelp/App/BighelpAppComposition.swift +++ b/Bighelp/App/BighelpAppComposition.swift @@ -40,21 +40,20 @@ struct BighelpAppComposition { || arguments.contains("-use-demo-fixtures") bighelpCardDataClient = BighelpCardStaticDataClient() let timing: DemoFixtureTiming = .immediate - let appState = AppState() - if arguments.contains("-start-inbox") { - appState.select(.inbox) - } - if usesFixtures, let index = arguments.firstIndex(of: "-initial-tab"), - arguments.indices.contains(index + 1), let tab = AppTab(rawValue: arguments[index + 1]) { - appState.select(tab) - } + let appState = AppState(home: .shared) #if DEBUG // A bighelp set up before the AI data agreement existed: tests forget the agreement. if arguments.contains("-test-forget-ai-data-agreement") { defaults.removeObject(forKey: AIDataConsent.key) } #endif let settings = SettingsStore(defaults: defaults) - // Built once per launch: Opens on picks one computer or all of them. - settings.applyLaunchLandingToAllHostsMode() + // Where the app opens, before anything is drawn. A link or an alert that opens the app + // picks its own place after this. + appState.home.land(on: settings.launchHomeLanding, view: settings.homeView) + if usesFixtures, let index = arguments.firstIndex(of: "-initial-tab"), + arguments.indices.contains(index + 1), let place = Self.initialPlace(arguments[index + 1]) { + appState.home.tab = place.tab + if let view = place.view { appState.home.view = view } + } let companion = CompanionStore(defaults: defaults) #if DEBUG if usesFixtures, let index = arguments.firstIndex(of: "-test-companion-adventure"), @@ -288,11 +287,6 @@ struct BighelpAppComposition { showsStoreScreenshots: arguments.contains(AppStoreScreenshotFixture.launchArgument), createsGroups: arguments.contains(BotModeCatalogFixtureClient.createsGroupsArgument) )) - // A real host's runtime reads what it can do at connect; the demo - // does it now, so New chat › Group chat shows from the start. - if arguments.contains(BotModeCatalogFixtureClient.createsGroupsArgument) { - Task { await botModeRooms.refreshNativeRoomCatalog() } - } if arguments.contains(BotModeActivityFixtureClient.launchArgument) { botModeRooms.configureNativeActivityClient(BotModeActivityFixtureClient()) } @@ -307,6 +301,10 @@ struct BighelpAppComposition { losesFirstStop: arguments.contains(TeamCallDemoGroupsClient.losesFirstStopArgument) )) } + // A real host's runtime reads its group chats, and what it can do with them, at connect. A demo + // with group chats has no runtime, so it reads them now: the Bots view and New chat list them + // from the start. + if usesFixtures, botModeRooms.usesNativeRooms { Task { await botModeRooms.refreshNativeRoomCatalog() } } #endif do { try BotModeRoomLoadingPolicy.load(botModeRooms, for: .startup) @@ -386,7 +384,6 @@ struct BighelpAppComposition { DeviceAccessCardStore.shared.permissions = deviceToolPermissions let appearanceTool = DeviceAppearanceTool(settings: settings) let navigationTool = DeviceNavigationTool(.init( - mode: { settings.currentMode }, nerdMode: { settings.nerdModeEnabled }, botName: { DriveNavigator.shared.agent($0)?.name }, open: { place, steps, bot, note, context in @@ -630,6 +627,8 @@ struct BighelpAppComposition { BighelpExternalSessionOpenCenter.shared.request(catalogSessionID: sessionID) return } + // The request is the whole app's (`HomeSelection`): the shell on screen reads the + // computer in use's `AppState`, not this one, and still sees it. appState?.openNeedsYou() } #if DEBUG @@ -692,9 +691,27 @@ struct BighelpAppComposition { conversationID = "demo-finance" } let route = AppRoute.chat(conversationID: conversationID) + // The chat a demo opens at launch shows this run's fixture. The store starts from the copy + // an earlier run saved, and a launch argument may have given this chat other content. + if let fixture = initialSessions.first(where: { $0.id == conversationID }), + sessionCatalog.session(id: conversationID) != fixture { + var records = sessionCatalog.records + if let index = records.firstIndex(where: { $0.id == conversationID }) { + records[index] = fixture + } else { + records.append(fixture) + } + _ = sessionCatalog.adopt(records) + } if featureStore.prepare(route) { appState.activateConversation(id: conversationID, source: .newChat) } + } else if usesFixtures, subagentStreamAcceptanceFixture == nil { + // A real host's runtime reads the chat list at connect. A demo's store starts from the copy + // an earlier run saved, and the one home's lists only draw what it holds, so a demo that + // opens on the home reads its chat list now. A chat opened at launch (above) reads it + // itself as it loads; a read before that would leave that chat on the saved copy. + Task { try? await sessionCatalog.load() } } self.appState = appState @@ -793,6 +810,19 @@ struct BighelpAppComposition { return { SilentVoiceInputLevelSource() } } + /// `-initial-tab` in demo runs: one of the three places, or a screen of the old shell by the + /// place that holds it now. + static func initialPlace(_ name: String) -> (tab: HomeTab, view: HomeConversationsView?)? { + if let tab = HomeTab(rawValue: name) { return (tab, nil) } + switch name { + case "bots", "agents": return (.conversations, .bots) + case "chats", "sessions", "sessionList": return (.conversations, .chats) + case "feed", "ideas", "goals": return (.today, nil) + case "projects", "kanban", "workflows", "scheduledTasks", "code": return (.work, nil) + default: return nil + } + } + static func initialAgentProfiles( usesFixtures: Bool, cachedAgentProfiles: [AgentProfile] diff --git a/Bighelp/App/BighelpHostSwitcherLockup.swift b/Bighelp/App/BighelpHostSwitcherLockup.swift deleted file mode 100644 index 7e27cbee..00000000 --- a/Bighelp/App/BighelpHostSwitcherLockup.swift +++ /dev/null @@ -1,57 +0,0 @@ -import SwiftUI - -/// The bighelp lockup in the top bar. Touch and hold it to switch hosts; on -/// the Mac, click it. -struct BighelpHostSwitcherLockup: View { - var demoHosts: DemoHosts? - @Environment(\.bighelpHostRegistry) private var registry - @Environment(\.bighelpScreen) private var screen - - var body: some View { - let hosts = BighelpMenuHosts.current(registry: registry, demoHosts: demoHosts) - if hosts.hosts.count + (hosts.add == nil ? 0 : 1) > 0 { - #if targetEnvironment(macCatalyst) - // A click that does nothing reads as broken on a Mac, where holding is rare. - Menu { hostItems(hosts) } label: { mark } - .accessibilityLabel(BighelpBrand.appName) - .accessibilityHint("Switch hosts.") - .accessibilityIdentifier("brand.host-switcher") - #else - Menu { hostItems(hosts) } label: { - mark - } primaryAction: {} - .accessibilityLabel(BighelpBrand.appName) - .accessibilityHint("Touch and hold to switch hosts.") - .accessibilityIdentifier("brand.host-switcher") - #endif - } else { - mark - } - } - - /// The iPhone Duo puts the bar's buttons down its side strip: the Noodle alone fits there. - @ViewBuilder - private var mark: some View { - if screen.usesSideBar { - BighelpNoodleMark(size: 26) - } else { - BighelpWordmark(height: 26) - } - } - - @ViewBuilder - private func hostItems(_ hosts: BighelpMenuHosts) -> some View { - Section("Switch host") { - ForEach(hosts.hosts) { host in - Button { hosts.select(host.id) } label: { - if host.isSelected { Label(host.name, systemImage: "checkmark") } else { Text(host.name) } - } - .accessibilityIdentifier("brand.host.\(host.id)") - } - } - if let add = hosts.add { - Button(action: add) { Label("Add host", systemImage: "plus") } - .accessibilityIdentifier("brand.host.add") - } - } -} diff --git a/Bighelp/App/BighelpIncomingURLRoute.swift b/Bighelp/App/BighelpIncomingURLRoute.swift index b9edbfa7..eb648497 100644 --- a/Bighelp/App/BighelpIncomingURLRoute.swift +++ b/Bighelp/App/BighelpIncomingURLRoute.swift @@ -22,7 +22,7 @@ enum BighelpIncomingURLRoute: Equatable, Sendable { /// "loopdy://voice?agent=…&host=…": the agent's Bot Chat in voice, from Start voice chat. /// No agent is the home agent of that computer. case voice(agentID: String?, hostID: UUID?) - /// "loopdy://agents", "loopdy://projects", "loopdy://settings": ☰'s pages. + /// "loopdy://agents", "loopdy://projects", "loopdy://settings": pages of the home. case agents case projects case settings @@ -32,7 +32,7 @@ enum BighelpIncomingURLRoute: Equatable, Sendable { case workflow(id: String, hostID: UUID?, startsRun: Bool) /// "loopdy://workflow-run/": one run, from the Workflows widget. case workflowRun(id: String) - /// "loopdy://usage": ☰ › Usage, from the Usage widget. + /// "loopdy://usage": Usage, from the Usage widget. case usage static func parse(_ url: URL) -> BighelpIncomingURLRoute? { diff --git a/Bighelp/App/BighelpKeyboard.swift b/Bighelp/App/BighelpKeyboard.swift index 2d0973f2..5372d5fe 100644 --- a/Bighelp/App/BighelpKeyboard.swift +++ b/Bighelp/App/BighelpKeyboard.swift @@ -15,31 +15,3 @@ enum BighelpKeyboard { ) } } - -/// ☰ as a glass button, for screens drawn over the app (the voice screen). -struct WorkspaceMenuButton: View { - let accessibilityIdentifier: String - let action: () -> Void - - init( - accessibilityIdentifier: String = "workspace.menu", - action: @escaping () -> Void - ) { - self.accessibilityIdentifier = accessibilityIdentifier - self.action = action - } - - var body: some View { - Button(action: action) { - Image(systemName: "line.3.horizontal") - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(.primary) - .frame(width: 44, height: 44) - .contentShape(.circle) - } - .buttonStyle(.plain) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - .accessibilityLabel("Menu") - .accessibilityIdentifier(accessibilityIdentifier) - } -} diff --git a/Bighelp/App/BighelpLanding.swift b/Bighelp/App/BighelpLanding.swift index 1a286e19..9fdf14ab 100644 --- a/Bighelp/App/BighelpLanding.swift +++ b/Bighelp/App/BighelpLanding.swift @@ -1,100 +1,36 @@ import Foundation -/// The screen bighelp opens on (Settings › Chat › Opens on). It applies to a -/// cold launch only, and a link, widget or notification that opens the app wins. -enum BighelpLandingScreen: String, CaseIterable, Identifiable, Sendable { +/// A screen the app could open on before the one home, as saved under `BighelpLanding.screenKey`. Only +/// read now: each maps to one of the home's four places (`HomeLanding`, Settings › Chat › Opens on). +enum BighelpLandingScreen: String, CaseIterable, Sendable { case agents case allAgents = "all-agents" case lastChat = "last-chat" case sessions case feed, ideas, goals, kanban, projects - var id: Self { self } - - var title: String { + /// Where the one home opens for a screen saved before it. + var homeLanding: HomeLanding { switch self { - case .agents: String(localized: "Agents") - case .allAgents: String(localized: "Agents (multi)") - case .lastChat: String(localized: "Last chat") - case .sessions: String(localized: "Sessions") - case .feed: String(localized: "Feed") - case .ideas: String(localized: "Ideas") - case .goals: String(localized: "Goals") - case .kanban: String(localized: "Kanban") - case .projects: String(localized: "Projects") + case .agents, .allAgents: .bots + case .sessions, .lastChat: .chats + case .feed, .ideas, .goals: .today + case .kanban, .projects: .work } } - - /// Every choice but every computer's agents starts with one agent. - var offersStartAgent: Bool { self != .allAgents && self != .sessions } -} - -/// What a cold launch was asked to open on. -enum BighelpLandingChoice: Equatable, Sendable { - /// Nothing picked: the agent's latest chat, as before. `opensChat` is the - /// older `loopdy.home.opens-chat` (no Settings row; the UI tests' older - /// flows pass NO to start on the chat list). - case standard(opensChat: Bool) - case chosen(BighelpLandingScreen) -} - -/// Where the launch goes once the computer's chats and agents are in. -enum BighelpLandingDestination: Equatable, Sendable { - case chatList, homeChat, agents, allAgents, board(AppTab), kanban, projects } enum BighelpLanding { static let screenKey = "loopdy.home.landing" + /// Saved by earlier versions and never read now; `HomeSettingsMigration` takes either as a sign of an + /// existing install. static let legacyOpensChatKey = "loopdy.home.opens-chat" - /// Agent IDs only mean something on their own computer, so Start with is - /// kept per computer (`cacheScopeID` → agent ID). static let startAgentKey = "loopdy.home.start-agent.by-scope" - /// How long Kanban gets to say whether a computer has it, the first time. - static let kanbanWait: Duration = .seconds(3) - - static func choice(screen: BighelpLandingScreen?, legacyOpensChat: Bool?) -> BighelpLandingChoice { - if let screen { return .chosen(screen) } - return .standard(opensChat: legacyOpensChat ?? true) - } - - /// Nil: wait for Kanban to answer. - static func destination(for choice: BighelpLandingChoice, kanbanAvailable: Bool?, kanbanWaitIsOver: Bool, - projectsAvailable: Bool) -> BighelpLandingDestination? { - let screen: BighelpLandingScreen - switch choice { - case .standard(let opensChat): return opensChat ? .homeChat : .chatList - case .chosen(let chosen): screen = chosen - } - switch screen { - case .agents: return .agents - case .allAgents: return .allAgents - case .lastChat: return .homeChat - case .sessions: return .chatList - case .feed: return .board(.feed) - case .ideas: return .board(.ideas) - case .goals: return .board(.goals) - case .projects: return projectsAvailable ? .projects : .homeChat - case .kanban: - switch kanbanAvailable { - case true?: return .kanban - case false?: return .homeChat - case nil: return kanbanWaitIsOver ? .homeChat : nil - } - } - } - - /// A picked screen decides the all-hosts view at launch; nothing picked, or a screen both views - /// have (Sessions, Last chat), leaves the switch as it was. - static func allHostsMode(for choice: BighelpLandingChoice) -> Bool? { - guard case .chosen(let screen) = choice, screen != .sessions, screen != .lastChat else { return nil } - return screen == .allAgents - } - /// The agent to start with, while it's still on that computer; nil is - /// Automatic (the agent you used last). - static func startAgent(stored: String?, agentIDs: [String], choice: BighelpLandingChoice) -> String? { - if case .chosen(let screen) = choice, !screen.offersStartAgent { return nil } - guard let stored, agentIDs.contains(stored) else { return nil } - return stored + /// Opens on as saved: one of the four, or an old screen mapped to its place. Nil when nothing was + /// picked, or the value is unknown. + static func homeLanding(stored: String?) -> HomeLanding? { + guard let stored else { return nil } + return HomeLanding(rawValue: stored) ?? BighelpLandingScreen(rawValue: stored)?.homeLanding } } diff --git a/Bighelp/App/BighelpMenu.swift b/Bighelp/App/BighelpMenu.swift index 53739a91..7ffaf598 100644 --- a/Bighelp/App/BighelpMenu.swift +++ b/Bighelp/App/BighelpMenu.swift @@ -47,407 +47,3 @@ struct BighelpMenuHosts { return BighelpMenuHosts(add: add) } } - -/// Where the menu can go. -struct BighelpMenuDestinations { - /// The all-hosts view's list, its home while it's on. When set, ☰'s Agents opens it - /// and the one-host places (Projects, Kanban, Workflows) stay out of the menu. - var onAllAgents: (() -> Void)? = nil - var newChatTitle = String(localized: "New chat") - var onNewChat: () -> Void - var onAllChats: () -> Void - /// Projects: related chats and folders together. - var onProjects: (() -> Void)? = nil - var onAgents: () -> Void - var onScheduledTasks: () -> Void - /// Kanban, when the host has Hermes' Kanban plugin. - var onKanban: (() -> Void)? = nil - /// Workflows, when the host's bighelp plugin has them. - var onWorkflows: (() -> Void)? = nil - /// Nerd Mode: the Hermes project folder chats run in. - var folder: (name: String, open: () -> Void)? - /// Shares from other apps waiting to be sent, while any wait (`PendingShareListView`). - var sharedWithBighelp: (count: Int, open: () -> Void)? = nil - /// Usage: plans, limits and what the agents used. None while no computer is connected. - var onUsage: (() -> Void)? = nil - var onSettings: () -> Void - /// ☰'s places in the person's order: whatever the bottom bar doesn't hold, - /// and always Agents and Settings (Appearance › App layout). - var places: [BighelpPlace] = BighelpAppLayout.standard.menuPlaces - /// Opens Feed, Ideas, Goals or Files when they aren't in the bottom bar. - var onBoard: ((AppTab) -> Void)? = nil - /// Feed, Ideas and Goals with something new, for a dot on their rows. - var unread: Set = [] - /// Approvals, questions and sign-offs waiting on the person (`NeedsYouDeckView`); nil with none. - var needsYou: (count: Int, open: () -> Void)? = nil - /// Code mode's own places, listed instead of the everyday ones while it's the home. - var code: Code? = nil - /// Settings › Code mode on: the switch between Chat and Code mode, on top. - var experience: ExperienceSwitch? = nil - - struct Code { - var onNewSession: () -> Void - /// The selected project's pull requests and worktrees; none until there's a project. - var onPullRequests: (() -> Void)? - var onWorktrees: (() -> Void)? - /// Coding recipes across projects; on computers with Workflows. - var onDevFactory: (() -> Void)? - } - - struct ExperienceSwitch { - let current: BighelpExperience - let select: (BighelpExperience) -> Void - } -} - -/// bighelp's one menu (☰). The first screen is short on purpose: New chat (top right), -/// Agents, Projects, Kanban, Workflows, Scheduled tasks, Usage and Settings, then recent chats -/// with See all. With all hosts showing, Agents is All agents and the one-host -/// places stay out, so each view keeps to its purpose. The host switcher is one -/// compact row on top; Nerd Mode's folder waits below the chats. Settings holds the rest -/// (the credential vault is in Settings › Connections). -struct BighelpMenu: View { - - let hosts: BighelpMenuHosts - let destinations: BighelpMenuDestinations - #if os(visionOS) - @Environment(\.openWindow) private var openWindow - @Environment(\.spatialAvatar) private var spatialAvatar - #endif - /// Runs before every choice: closes a sheet or drawer; nothing for a sidebar. - let close: () -> Void - var hasRecent = true - @ViewBuilder let recent: () -> Recent - - var body: some View { - List { - if let experience = destinations.experience { experienceSection(experience) } - mainSection - recentSection - moreSection - } - .listStyle(.insetGrouped) - .listSectionSpacing(16) - .environment(\.defaultMinListRowHeight, BighelpTokens.hitTarget) - .scrollContentBackground(.hidden) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .tint(theme.action) - .accessibilityIdentifier("navigation.menu") - } - - // MARK: Main - - private var mainSection: some View { - Section { - if let needsYou = destinations.needsYou, needsYou.count > 0 { - row( - String(localized: "Needs you"), - detail: String(localized: "\(needsYou.count) waiting"), - symbol: "hand.raised.fill", - id: "menu.needs-you", - isNew: true, - action: needsYou.open - ) - } - if let code = destinations.code { - codeRows(code) - } else { - // In the person's order (Appearance › App layout). With all hosts showing, Agents - // is All agents and the one-computer places ask which computer. - ForEach(destinations.places) { place in placeRow(place) } - } - } header: { - HStack(spacing: BighelpTokens.space8) { - if !hosts.hosts.isEmpty || hosts.add != nil { - hostSwitcher - if let allHosts = hosts.allHosts { allHostsToggle(allHosts) } - } - Spacer(minLength: 0) - newChatButton - } - .padding(.bottom, BighelpTokens.space4) - } - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - - @ViewBuilder - private func placeRow(_ place: BighelpPlace) -> some View { - switch place { - case .agents: - if let onAllAgents = destinations.onAllAgents { - row(String(localized: "Agents"), symbol: place.symbol, id: "menu.all-agents", action: onAllAgents) - } else { - row(String(localized: "Agents"), symbol: place.symbol, id: "menu.agents", action: destinations.onAgents) - } - case .projects: - if let onProjects = destinations.onProjects { - row(place.title, symbol: place.symbol, id: "menu.projects", action: onProjects) - } - case .kanban: - if let onKanban = destinations.onKanban { - row(place.title, symbol: place.symbol, id: "menu.kanban", action: onKanban) - } - case .workflows: - if let onWorkflows = destinations.onWorkflows { - row(place.title, symbol: place.symbol, id: "menu.workflows", action: onWorkflows) - } - case .sessions: - row(place.title, symbol: place.symbol, id: "menu.sessions", action: destinations.onAllChats) - case .scheduledTasks: - row(place.title, symbol: place.symbol, id: "menu.scheduled-tasks", action: destinations.onScheduledTasks) - case .usage: - if let onUsage = destinations.onUsage { - row(place.title, symbol: place.symbol, id: "menu.usage", action: onUsage) - } - case .settings: - row(place.title, symbol: place.symbol, id: "menu.settings", action: destinations.onSettings) - case .feed, .ideas, .goals, .files: - if let onBoard = destinations.onBoard { - row(place.title, symbol: place.symbol, id: "menu.\(place.rawValue)", - isNew: destinations.unread.contains(place.tab)) { onBoard(place.tab) } - } - } - } - - /// Chat or Code mode: which home the app shows. - private func experienceSection(_ experience: BighelpMenuDestinations.ExperienceSwitch) -> some View { - Section { - Picker("Mode", selection: Binding(get: { experience.current }, set: { value in - choose { experience.select(value) } - })) { - ForEach(BighelpExperience.allCases) { mode in - Text(mode.title).tag(mode) - } - } - .bighelpSegmentedPicker() - .labelsHidden() - .accessibilityIdentifier("menu.experience") - } - .listRowBackground(Color.clear) - .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) - } - - /// Code mode's places: its home, the project's pull requests and worktrees, then - /// Projects, Kanban and Settings. - @ViewBuilder - private func codeRows(_ code: BighelpMenuDestinations.Code) -> some View { - row(String(localized: "Sessions"), symbol: "chevron.left.forwardslash.chevron.right", id: "menu.code.sessions", action: code.onNewSession) - if let onProjects = destinations.onProjects { - row(BighelpPlace.projects.title, symbol: BighelpPlace.projects.symbol, id: "menu.projects", action: onProjects) - } - if let onPullRequests = code.onPullRequests { - row(String(localized: "Pull requests"), symbol: "arrow.triangle.pull", id: "menu.code.pull-requests", action: onPullRequests) - } - if let onWorktrees = code.onWorktrees { - row(String(localized: "Worktrees"), symbol: "square.stack.3d.up", id: "menu.code.worktrees", action: onWorktrees) - } - if let onDevFactory = code.onDevFactory { - row(String(localized: "Dev Factory"), symbol: "hammer", id: "menu.code.dev-factory", action: onDevFactory) - } - ForEach(destinations.places.filter { [.kanban, .settings].contains($0) }) { place in placeRow(place) } - } - - /// Compact rows, so the whole first screen fits without scrolling. - private static var rowInsets: EdgeInsets { BighelpMenuRowLayout.insets } - - /// New chat, its own button at the top right. Group chats start from its own picker ("Group chat"). - private var newChatButton: some View { - Button { choose(destinations.code?.onNewSession ?? destinations.onNewChat) } label: { - Image(systemName: "square.and.pencil") - .font(.bighelp(.body).weight(.semibold)) - // The person's color and its own ink: white after dark is the ink look's color. - .foregroundStyle(theme.actionForeground) - .frame(width: BighelpTokens.scaled(40), height: BighelpTokens.scaled(40)) - .background(theme.action, in: Circle()) - .contentShape(Circle()) - } - .bighelpPlainButtonStyle(.circle) - .textCase(nil) - .bighelpHelp(destinations.code == nil ? destinations.newChatTitle : String(localized: "New session"), shortcut: "⌘N") - .accessibilityLabel(destinations.code == nil ? destinations.newChatTitle : String(localized: "New session")) - .accessibilityIdentifier("menu.new-chat") - } - - /// The host you're on, as one row. Hosts and Add host are one tap away. - private var hostSwitcher: some View { - Menu { - Section(hosts.allHosts?.isOn == true ? String(localized: "Show") : String(localized: "Switch host")) { - if let allHosts = hosts.allHosts, allHosts.isOn { - Button { choose(allHosts.showAll) } label: { - if allHosts.isFocused { Text("All hosts") } else { Label("All hosts", systemImage: "checkmark") } - } - .accessibilityIdentifier("menu.host.all") - } - ForEach(hosts.hosts) { host in - Button { choose { hosts.select(host.id) } } label: { - if host.isSelected { Label(host.name, systemImage: "checkmark") } else { Text(host.name) } - } - .accessibilityIdentifier("menu.host.\(host.id)") - } - } - if let add = hosts.add { - Button { choose(add) } label: { Label("Add host", systemImage: "plus") } - .accessibilityIdentifier("menu.host.add") - } - } label: { - HStack(spacing: BighelpTokens.space8) { - Image(systemName: "desktopcomputer") - Text(hostTitle) - .lineLimit(1) - Image(systemName: "chevron.up.chevron.down") - .font(.bighelp(.caption2).weight(.semibold)) - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .padding(.horizontal, BighelpTokens.space12) - .frame(minHeight: 34) - .background(theme.surface, in: .capsule) - .contentShape(.capsule) - } - .textCase(nil) - .accessibilityLabel("Host: \(hostTitle)") - .accessibilityHint("Switch hosts or add one.") - .accessibilityIdentifier("menu.hosts") - } - - private var hostTitle: String { - if let allHosts = hosts.allHosts, allHosts.isOn { - return allHosts.isFocused ? hosts.hosts.first(where: \.isSelected)?.name ?? String(localized: "All hosts") : String(localized: "All hosts") - } - return hosts.hosts.first(where: \.isSelected)?.name ?? String(localized: "Choose a host") - } - - /// Shows every agent on every host in one list, or just this host's. - private func allHostsToggle(_ allHosts: BighelpMenuHosts.AllHosts) -> some View { - Button { choose(allHosts.toggle) } label: { - // What a tap shows: every host's bots, or back to one host's. - Image((allHosts.isOn ? BighelpGlyph.bot : .bots).assetName) - .resizable() - .renderingMode(.template) - .scaledToFit() - .frame(width: 20, height: 20) - .foregroundStyle(allHosts.isOn ? theme.actionForeground : theme.primaryText) - .frame(width: 34, height: 34) - .background(allHosts.isOn ? theme.action : theme.surface, in: .circle) - .contentShape(.circle) - } - .bighelpPointerButtonStyle(.borderless, outline: .circle) - .textCase(nil) - .bighelpIconLabel(allHosts.isOn ? String(localized: "Show one host") : String(localized: "Show all hosts")) - .accessibilityHint(allHosts.isOn - ? "Shows the selected host's agents and chats again." - : "Shows every agent on every host in one list.") - .accessibilityAddTraits(allHosts.isOn ? .isSelected : []) - .accessibilityIdentifier("menu.all-hosts") - } - - // MARK: Recent - - private var recentSection: some View { - Section { - if hasRecent { - recent() - } else { - Text("Your chats show up here.") - .bighelpFont(.metadata) - .foregroundStyle(theme.secondaryText) - } - } header: { - HStack { - Text("Recent sessions") - Spacer() - Button("See all") { choose(destinations.onAllChats) } - .font(.bighelp(.subheadline).weight(.semibold)) - .textCase(nil) - #if targetEnvironment(macCatalyst) - .bighelpPlainButtonStyle(padding: BighelpTokens.space4) - #endif - .accessibilityLabel("See all sessions") - .accessibilityIdentifier("menu.chats") - } - } - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - - // MARK: More - - @ViewBuilder - private var moreSection: some View { - if destinations.folder != nil || destinations.sharedWithBighelp != nil || isVision { - Section("More") { - if let shared = destinations.sharedWithBighelp { - row(String(localized: "Shared with bighelp"), detail: "\(shared.count)", symbol: "tray.and.arrow.down", - id: "menu.shared-with-bighelp", isNew: true, action: shared.open) - } - #if os(visionOS) - row(String(localized: "Simple mode"), symbol: "figure.stand", id: "menu.simple-mode") { - SpatialSimpleMode.enter(spatialAvatar, openWindow: openWindow) - } - #endif - if let folder = destinations.folder { - row(String(localized: "Folder"), detail: folder.name, symbol: "folder.badge.gearshape", id: "menu.folder", - action: folder.open) - } - } - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - } - - private var isVision: Bool { - #if os(visionOS) - true - #else - false - #endif - } - - private func row(_ title: String, detail: String? = nil, symbol: String, id: String, isNew: Bool = false, - action: @escaping () -> Void) -> some View { - Button { choose(action) } label: { - BighelpMenuRowLabel(title: title, detail: detail, symbol: symbol, trailing: isNew ? .new : .none) - .padding(.horizontal, BighelpMenuRowLayout.labelInset) - } - .bighelpPlainButtonStyle(BighelpMenuRowLayout.outline, padding: BighelpMenuRowLayout.highlightPadding) - .listRowInsets(Self.rowInsets) - .bighelpMenuRowSeparator() - .accessibilityIdentifier(id) - } - - private func choose(_ action: () -> Void) { - close() - action() - } - - @BighelpThemeReader private var theme -} - -extension View { - /// A dot on ☰ when Feed, Ideas or Goals has something new and ☰ is the way there - /// (it isn't in the bottom bar). - func bighelpMenuDot(_ isVisible: Bool) -> some View { - modifier(BighelpMenuDot(isVisible: isVisible)) - } -} - -private struct BighelpMenuDot: ViewModifier { - let isVisible: Bool - - func body(content: Content) -> some View { - content - .overlay(alignment: .topTrailing) { - if isVisible { - Circle() - .fill(theme.action) - .frame(width: 8, height: 8) - .allowsHitTesting(false) - .accessibilityHidden(true) - } - } - .accessibilityValue(isVisible ? "New items" : "") - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/App/BighelpMenuCommands.swift b/Bighelp/App/BighelpMenuCommands.swift index 109f85b8..11720dff 100644 --- a/Bighelp/App/BighelpMenuCommands.swift +++ b/Bighelp/App/BighelpMenuCommands.swift @@ -22,15 +22,6 @@ struct BighelpMenuCommands: Commands { Button(actions?.isSidebarOpen == true ? "Hide Sidebar" : "Show Sidebar") { actions?.toggleSidebar() } .keyboardShortcut("s", modifiers: [.command, .control]) .disabled(actions == nil) - // The Header mode switcher's modes. ⌘1–⌘5 are the tabs, so these add Control. - if let modeSwitch = actions?.modeSwitch { - Divider() - ForEach(Array(modeSwitch.modes.enumerated()), id: \.element) { index, mode in - Button(mode.title) { modeSwitch.select(mode) } - .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: [.command, .control]) - .disabled(mode == modeSwitch.current) - } - } } CommandGroup(after: .toolbar) { Button("Bigger Text") { BighelpInterfaceSize.shared.stepText(by: 1) } @@ -41,10 +32,10 @@ struct BighelpMenuCommands: Commands { .keyboardShortcut("0") } #if targetEnvironment(macCatalyst) - // The bottom bar's tabs, like a Mac app's View menu. iPad keeps its own keys. + // The home's three places, like a Mac app's View menu. iPad keeps its own keys. CommandGroup(before: .sidebar) { - ForEach(Array((actions?.tabs ?? AppTab.allCases).enumerated()), id: \.element) { index, tab in - Button(tab.commandTitle) { actions?.selectTab?(tab) } + ForEach(Array((actions?.tabs ?? HomeTabItem.standard(view: .chats)).enumerated()), id: \.element.id) { index, tab in + Button(tab.title) { actions?.selectTab?(tab.id) } .keyboardShortcut(KeyEquivalent(Character("\(index + 1)"))) .disabled(actions?.selectTab == nil) } @@ -62,22 +53,13 @@ struct BighelpMenuCommands: Commands { struct BighelpShellActions { let newChat: @MainActor () -> Void let openSettings: @MainActor () -> Void - /// ☰: the Mac's sidebar. + /// The Mac's sidebar. let isSidebarOpen: Bool let toggleSidebar: @MainActor () -> Void - /// Bots, Chat and Code (⌃⌘1–⌃⌘3) while the Header mode switcher is on. - var modeSwitch: BighelpModeSwitch? = nil - /// The bottom bar's tabs (Mac ⌘1–⌘5), while the bar shows. - var selectTab: (@MainActor (AppTab) -> Void)? = nil - /// The bar's tabs in its order (Appearance › App layout). - var tabs: [AppTab] = AppTab.allCases -} - -extension AppTab { - /// The bottom bar's tabs by name, for the menu bar. - var commandTitle: String { - self == .scheduledTasks ? String(localized: "Scheduled Tasks") : title - } + /// The home's three places (Mac ⌘1–⌘3). Picking one closes what is open over it. + var selectTab: (@MainActor (HomeTab) -> Void)? = nil + /// The places as the bar names them: the first follows the person's default view. + var tabs: [HomeTabItem] = [] } private struct BighelpShellActionsKey: FocusedValueKey { diff --git a/Bighelp/App/BighelpModePill.swift b/Bighelp/App/BighelpModePill.swift deleted file mode 100644 index a4aee352..00000000 --- a/Bighelp/App/BighelpModePill.swift +++ /dev/null @@ -1,55 +0,0 @@ -import SwiftUI - -/// Settings › Modes › Header mode switcher: Bots, Chat and Code in one compact pill at the top -/// of each home, as tall as the header's glass buttons. The mode showing sits in a darker capsule. -struct BighelpModePill: View { - let modeSwitch: BighelpModeSwitch - - @BighelpThemeReader private var theme - - private static let inset: CGFloat = 3 - - var body: some View { - HStack(spacing: 0) { - ForEach(modeSwitch.modes) { mode in - segment(mode) - } - } - .padding(Self.inset) - .bighelpNavigationGlass(in: Capsule()) - .fixedSize() - .accessibilityElement(children: .contain) - .accessibilityLabel("Mode") - .accessibilityIdentifier("mode.pill") - } - - private func segment(_ mode: BighelpMode) -> some View { - let isOn = mode == modeSwitch.current - return Button { - if !isOn { modeSwitch.select(mode) } - } label: { - Text(mode.title) - .font(.bighelp(.subheadline, weight: .semibold)) - .foregroundStyle(isOn ? theme.primaryText : theme.primaryText.opacity(0.75)) - .lineLimit(1) - .padding(.horizontal, BighelpTokens.scaled(13)) - .frame(height: HeaderButtonMetrics.glass - Self.inset * 2) - .background { - if isOn { - Capsule() - .fill(selectedFill) - .shadow(color: .black.opacity(theme.isDarkPalette ? 0 : 0.12), radius: 2, y: 1) - } - } - .contentShape(Capsule()) - } - .bighelpPlainButtonStyle(.capsule) - .accessibilityAddTraits(isOn ? .isSelected : []) - .accessibilityIdentifier("mode.pill.\(mode.rawValue)") - } - - /// Dark: nearly black, sunk into the glass. Light: a white page on the gray track. - private var selectedFill: Color { - theme.isDarkPalette ? Color.black.opacity(0.6) : theme.canvas - } -} diff --git a/Bighelp/App/BighelpSideMenu.swift b/Bighelp/App/BighelpSideMenu.swift index 37d2e498..40d8c972 100644 --- a/Bighelp/App/BighelpSideMenu.swift +++ b/Bighelp/App/BighelpSideMenu.swift @@ -1,7 +1,7 @@ import Observation import SwiftUI -/// Vision Pro and Mac: ☰ opens as a column beside the app instead of covering +/// Vision Pro and Mac: the sidebar opens as a column beside the app instead of covering /// it. The chat or list stays visible, only narrower. On the Mac it's the /// window's sidebar: it stays open while you pick chats and pages. @MainActor diff --git a/Bighelp/App/BighelpSplitColumn.swift b/Bighelp/App/BighelpSplitColumn.swift index fffba56a..56e784c2 100644 --- a/Bighelp/App/BighelpSplitColumn.swift +++ b/Bighelp/App/BighelpSplitColumn.swift @@ -1,7 +1,7 @@ import Observation import SwiftUI -/// The iPhone Duo open: the list (Bots mode's home, the chat list, or Code's home) as a column +/// The iPhone Duo open: the list (the Bots view, the Chats view or Work) as a column /// beside the page, with its own bar. What it opens is pushed on the app's one navigation stack, as /// everywhere else, so it shows beside the list and every rule about the open chat still holds. @MainActor diff --git a/Bighelp/App/ChatDestinationView.swift b/Bighelp/App/ChatDestinationView.swift index 9b72715f..3679af6d 100644 --- a/Bighelp/App/ChatDestinationView.swift +++ b/Bighelp/App/ChatDestinationView.swift @@ -24,8 +24,6 @@ struct ChatDestinationView: View { @State private var isHapticsSurfaceVisible = false @State private var projectChanges: ProjectChangesStore @State var voicePresentation: VoicePresentation? - /// Bots mode's voice: a bar over the chat instead of the voice screen. - @State var voiceBar: VoicePresentation? @State var attachmentFlow = ChatAttachmentFlowState() @State var isPhotoPickerPresented = false @State var isFilePickerPresented = false @@ -37,8 +35,6 @@ struct ChatDestinationView: View { @State var photoSelections: [PhotosPickerItem] = [] @State var attachmentErrorMessage: String? @State var attachmentRecoveryKind: PermissionKind? - /// ☰ from the voice screen: the menu opens once voice has closed. - @State private var opensMenuAfterVoice = false @State private var modelPickerRequest = 0 @State private var isProjectChangesPresented = false @State private var projectChangesPanelWidth: CGFloat = ProjectChangesPanelWidthPolicy.minimum @@ -49,7 +45,6 @@ struct ChatDestinationView: View { let featureStore: ShellFeatureStore let catalog: SessionCatalogStore let agents: AgentDirectoryStore - let agentEditorPresentation: ChatAgentEditorPresentation? let botModeRooms: BotModeRoomStore let skillsAndTools: SkillsAndToolsStore let hermesWorkspaces: HermesWorkspaceStore @@ -57,7 +52,6 @@ struct ChatDestinationView: View { let projectMove: ChatProjectMove? let userIdentity: UserIdentityStore let permissionCenter: PermissionCenter - let selectedTab: AppTab? let responseHapticsCoveredByRoot: Bool let appearanceAuthority: WorkspaceAuthority? let headerActions: ChatHeaderActions @@ -72,11 +66,14 @@ struct ChatDestinationView: View { let onOpenAgentSessions: (String) -> Void let onOpenApproval: (ApprovalRequest) -> Void let onForkMessage: ((String) -> Void)? - /// Code mode sessions: Markdown paths in messages open the viewer. + /// Coding sessions: Markdown paths in messages open the viewer. let hostFiles: HostFileLinkContext? /// ••• › Files: the chat's working folder on the computer. Asked for when Files opens, so it /// reads the connection there is then; nil (a group chat) lists the chat's own attachments. let chatFolders: (() -> ChatFolderContext?)? + /// One home: New chat's parts, for its blank chat only. The shell decides that from the chat's + /// id; this view only hands them on, and never reads the chat's messages to decide. + let newChat: ChatNewChatSlot? private var nativeSessionControls: NativeSessionControlsPresentation? { guard let native = model.nativeConversationClient else { return nil } @@ -107,7 +104,6 @@ struct ChatDestinationView: View { featureStore: ShellFeatureStore, catalog: SessionCatalogStore, agents: AgentDirectoryStore, - agentEditorPresentation: ChatAgentEditorPresentation?, botModeRooms: BotModeRoomStore, skillsAndTools: SkillsAndToolsStore, hermesWorkspaces: HermesWorkspaceStore, @@ -115,7 +111,6 @@ struct ChatDestinationView: View { projectGitClient: any ProjectGitClient, userIdentity: UserIdentityStore, permissionCenter: PermissionCenter, - selectedTab: AppTab?, responseHapticsCoveredByRoot: Bool, onNewChat: @escaping () -> Void, onOpenProviderAccounts: @escaping () -> Void, @@ -128,7 +123,8 @@ struct ChatDestinationView: View { onForkMessage: ((String) -> Void)?, appearanceAuthority: WorkspaceAuthority? = nil, hostFiles: HostFileLinkContext? = nil, - chatFolders: (() -> ChatFolderContext?)? = nil + chatFolders: (() -> ChatFolderContext?)? = nil, + newChat: ChatNewChatSlot? = nil ) { self.model = model self.appState = appState @@ -136,7 +132,6 @@ struct ChatDestinationView: View { self.featureStore = featureStore self.catalog = catalog self.agents = agents - self.agentEditorPresentation = agentEditorPresentation self.botModeRooms = botModeRooms self.skillsAndTools = skillsAndTools self.hermesWorkspaces = hermesWorkspaces @@ -144,11 +139,11 @@ struct ChatDestinationView: View { _projectChanges = State(initialValue: ProjectChangesStore(client: projectGitClient)) self.userIdentity = userIdentity self.permissionCenter = permissionCenter - self.selectedTab = selectedTab self.responseHapticsCoveredByRoot = responseHapticsCoveredByRoot self.appearanceAuthority = appearanceAuthority self.hostFiles = hostFiles self.chatFolders = chatFolders + self.newChat = newChat self.headerActions = ChatHeaderActions(newChat: onNewChat) self.onNewChat = onNewChat self.onOpenProviderAccounts = onOpenProviderAccounts @@ -172,7 +167,7 @@ struct ChatDestinationView: View { .accessibilityIdentifier("chat.canvas") .background { ChatReplyReading(model: model, reader: replyReader, - isOn: settings.autoSpeakRepliesEnabled && voicePresentation == nil && voiceBar == nil, + isOn: settings.autoSpeakRepliesEnabled && voicePresentation == nil, rate: settings.voiceSpeed.hermesTTSSpeed, makeOutput: { featureStore.makeReplySpeech(for: model.conversationID) }) } @@ -281,20 +276,13 @@ struct ChatDestinationView: View { ) } - /// Opens voice here, in the bar over a Bots mode chat when `inBar`. Live voice needs the chat's - /// session on the computer, and a chat that opened a moment ago (a cold Start voice chat, a tap - /// right after opening) is still getting it. Voice waits for it under the starting cover; it - /// once asked at once and showed "This chat is still opening" a second before it could start. - func openVoice(inBar: Bool = false) async { + /// Opens voice here. Live voice needs the chat's session on the computer, and a chat that opened a + /// moment ago (a cold Start voice chat, a tap right after opening) is still getting it. Voice + /// waits for it under the starting cover; it once asked at once and showed "This chat is still + /// opening" a second before it could start. + func openVoice() async { guard await waitForChatBeforeLiveVoice() else { return } - let presentation = makeVoice(agentVoice.mode) - if inBar { - withAnimation(.snappy(duration: 0.25)) { voiceBar = presentation } - // The cover's own end follows the full-screen voice; the bar ends it here. - VoiceLaunchState.shared.finish() - } else { - voicePresentation = presentation - } + voicePresentation = makeVoice(agentVoice.mode) } /// False when the wait was cancelled (the person moved on), so nothing opens. @@ -316,30 +304,6 @@ struct ChatDestinationView: View { return true } - /// The voice bar over a Bots mode chat, under its header. - @ViewBuilder - private var voiceBarOverlay: some View { - if let voiceBar, let agentID = model.memberIDs.first { - let profile = agents.profiles.first { $0.id == agentID } - SimpleBotVoiceBar( - presentation: voiceBar, agentID: agentID, agentName: profile?.name ?? "Your bot", - imageURL: profile.flatMap { agents.avatarURL(for: $0) }, permissionCenter: permissionCenter, - onSwitchMode: { mode in - // The bar is over one bot's chat: the switch is that bot's own choice. - settings.setVoiceConversationMode(mode, computer: voiceComputer, agentID: voiceAgentID) - self.voiceBar = makeVoice(mode) - }, - onEnded: { withAnimation(.snappy(duration: 0.25)) { self.voiceBar = nil } } - ) - .id(voiceBar.id) - .onChange(of: model.isSending, initial: true) { _, active in - voiceBar.model.reconcileAgentRun(isActive: active) - } - .padding(.top, 72) - .transition(.move(edge: .top).combined(with: .opacity)) - } - } - /// Live voice couldn't start: remember turn-based voice (listens on the /// phone, answers with the host's text-to-speech) where the agent's voice /// type comes from, its own or Settings', and reopen voice with it. @@ -369,7 +333,6 @@ struct ChatDestinationView: View { agentRole: identity?.role ?? "Hermes agent", agentStatus: model.nativeConversationClient == nil ? "Hermes" : "Direct Hermes", agents: agents, - agentEditorPresentation: agentEditorPresentation, dashboardModel: featureStore.dashboardModel, sessionCatalog: catalog, senderResolver: TimelineSenderResolver(userIdentity: userIdentity, agents: agents), @@ -384,10 +347,7 @@ struct ChatDestinationView: View { isProjectChangesPresented = true } }, - onVoiceTap: { - let inBar = homeChrome.isSimpleBots && model.memberIDs.count == 1 - Task { @MainActor in await openVoice(inBar: inBar) } - }, + onVoiceTap: { Task { @MainActor in await openVoice() } }, onApprovalTap: onOpenApproval, onPeopleTap: { isPeopleAndChatPresented = true }, onGroupSettingsTap: model.botModeRoomID == nil ? nil : { @@ -412,7 +372,8 @@ struct ChatDestinationView: View { onReferenceSend: sendReferences.action, foldCompletedTurns: settings.foldCompletedTurns, workStyle: settings.chatWorkStyle, - onForceRefresh: forceRefreshAction + onForceRefresh: forceRefreshAction, + newChat: newChat ) } } @@ -457,8 +418,6 @@ struct ChatDestinationView: View { } } } - // Over the edge-swipe strips, so they never take a tap meant for the bar. - .overlay(alignment: .top) { voiceBarOverlay } .overlay(alignment: .trailing) { if horizontalSizeClass == .regular, isProjectChangesPresented { GeometryReader { geometry in @@ -587,11 +546,7 @@ struct ChatDestinationView: View { .onChange(of: voicePresentation != nil) { _, isPresented in if isPresented { VoiceLaunchState.shared.finish() } } - .bighelpFullScreenCover(item: $voicePresentation, onDismiss: { - guard opensMenuAfterVoice else { return } - opensMenuAfterVoice = false - homeChrome.onMenu() - }) { presentation in + .bighelpFullScreenCover(item: $voicePresentation) { presentation in VoicePresentationContainer( presentation: presentation, agentID: model.memberIDs.first, @@ -600,7 +555,6 @@ struct ChatDestinationView: View { .flatMap { agents.avatarURL(for: $0) }, permissionCenter: permissionCenter, onEnded: { voicePresentation = nil }, - onWorkspaceTap: openMenuFromVoice, onUseTurnBased: useTurnBasedVoice, onTryAgain: tryLiveVoiceAgain, chatActivity: { [model] in model.liveActivityKind }, @@ -878,9 +832,7 @@ struct ChatDestinationView: View { side: ChatEdgeSide, containerWidth: CGFloat ) -> some View { - let action = side == .left - ? settings.effectiveLeftEdgeSwipeAction - : settings.effectiveRightEdgeSwipeAction + let action = side == .left ? settings.leftEdgeSwipeAction : settings.rightEdgeSwipeAction Color.clear .frame(width: WorkspaceEdgeSwipeResolver.activationEdgeWidth) .contentShape(Rectangle()) @@ -900,8 +852,8 @@ struct ChatDestinationView: View { ), translation: value.translation, containerWidth: containerWidth, - leftAction: settings.effectiveLeftEdgeSwipeAction, - rightAction: settings.effectiveRightEdgeSwipeAction + leftAction: settings.leftEdgeSwipeAction, + rightAction: settings.rightEdgeSwipeAction ) else { return } performChatEdgeAction(resolved) } @@ -914,12 +866,6 @@ struct ChatDestinationView: View { onEdgeAction(action) } - /// ☰ on the voice screen: the one menu, once voice has closed. - private func openMenuFromVoice() { - opensMenuAfterVoice = true - voicePresentation = nil - } - private var identity: ChatDestinationAgentIdentity? { ChatDestinationAgentResolver(catalog: catalog, agents: agents) .resolve( @@ -968,7 +914,6 @@ struct ChatDestinationView: View { @Environment(\.reflectiveVisionEnabled) var reflectiveVisionEnabled @Environment(\.reflectiveVisionCamera) var reflectiveVisionCamera @Environment(\.scenePhase) private var scenePhase - @Environment(\.agentHomeChrome) private var homeChrome private func armAttentionAutoOpen() { attentionAutoOpenUntil = .now.addingTimeInterval(8) diff --git a/Bighelp/App/NativeWorkspaceRuntime.swift b/Bighelp/App/NativeWorkspaceRuntime.swift index 8689c27a..c7227bc7 100644 --- a/Bighelp/App/NativeWorkspaceRuntime.swift +++ b/Bighelp/App/NativeWorkspaceRuntime.swift @@ -70,7 +70,8 @@ final class NativePluginStateRecord { @Observable final class NativeWorkspaceRuntime { let authority: WorkspaceAuthority - let appState = AppState() + /// This computer's own pages; the tab and the first tab's view are the whole app's. + let appState = AppState(home: .shared) let agents: AgentDirectoryStore let defaults: any AgentRuntimeDefaultsClient let sessions: SessionCatalogStore diff --git a/Bighelp/App/NewChatCoordinator.swift b/Bighelp/App/NewChatCoordinator.swift index 2d1bed4e..62e9ae64 100644 --- a/Bighelp/App/NewChatCoordinator.swift +++ b/Bighelp/App/NewChatCoordinator.swift @@ -40,8 +40,11 @@ final class NewChatCoordinator { typealias Creation = @MainActor (AgentProfile) async throws -> SessionRecord /// `creating` makes the chat on the computer in place of a plain new one. Either way the blank - /// canvas shows first, before any round trip. - func start(explicitAgentID: String? = nil, creating: Creation? = nil, + /// canvas shows first, before any round trip. `replacingBlankChat`: New chat's blank chat is on + /// top and another bot was picked for it, so the chat on screen is already a blank canvas; the + /// new chat takes its place once the computer has made it, in one step. A second canvas between + /// them replaced the top of the stack twice in a moment, and the stack sometimes kept the first. + func start(explicitAgentID: String? = nil, creating: Creation? = nil, replacingBlankChat: Bool = false, beforePresentation: @escaping @MainActor (String, String?) -> Void = { _, _ in }) async throws -> NewChatOutcome { if let inFlightStart { return try await inFlightStart.task.value @@ -50,7 +53,7 @@ final class NewChatCoordinator { let startID = UUID() let task = Task { @MainActor [self] in try await performStart(explicitAgentID: explicitAgentID, creating: creating, - beforePresentation: beforePresentation) + replacingBlankChat: replacingBlankChat, beforePresentation: beforePresentation) } inFlightStart = InFlightStart(id: startID, task: task) defer { @@ -61,7 +64,7 @@ final class NewChatCoordinator { return try await task.value } - private func performStart(explicitAgentID: String?, creating: Creation?, + private func performStart(explicitAgentID: String?, creating: Creation?, replacingBlankChat: Bool, beforePresentation: @escaping @MainActor (String, String?) -> Void) async throws -> NewChatOutcome { // Link may be reconnecting while the shell is already usable. Resolve // an active/default agent from the last known directory immediately so @@ -71,7 +74,8 @@ final class NewChatCoordinator { // cache remains a hard failure: Hermes must always receive an explicit // agent ID for a new session. if let cachedAgent = agents.resolvedAgent(explicitID: explicitAgentID) { - return try await openSession(for: cachedAgent, creating: creating, beforePresentation: beforePresentation) + return try await open(for: cachedAgent, creating: creating, replacingBlankChat: replacingBlankChat, + beforePresentation: beforePresentation) } try await agents.load() @@ -79,7 +83,25 @@ final class NewChatCoordinator { return .needsAgentSelection } - return try await openSession(for: agent, creating: creating, beforePresentation: beforePresentation) + return try await open(for: agent, creating: creating, replacingBlankChat: replacingBlankChat, + beforePresentation: beforePresentation) + } + + private func open(for agent: AgentProfile, creating: Creation?, replacingBlankChat: Bool, + beforePresentation: @MainActor (String, String?) -> Void) async throws -> NewChatOutcome { + guard replacingBlankChat, case .chat? = appState.path.last else { + return try await openSession(for: agent, creating: creating, beforePresentation: beforePresentation) + } + // The blank chat on screen stays until the computer has made this bot's. + let origin = appState.path + let session: SessionRecord + if let creating { session = try await creating(agent) } else { session = try await catalog.createDirect(agentID: agent.id) } + // The person moved on meanwhile: that navigation stands. + guard appState.path == origin else { return .opened(sessionID: session.id, agentID: agent.id) } + guard prepare(.chat(conversationID: session.id)) else { return .needsAgentSelection } + present(session.id, beforePresentation: beforePresentation) + if creating == nil { await placeInActiveProject(session, agent: agent) } + return .opened(sessionID: session.id, agentID: agent.id) } private func openSession(for agent: AgentProfile, creating: Creation?, @@ -155,41 +177,35 @@ final class NewChatCoordinator { } // A Bot Chat is made by the agent's own gateway, where Hermes puts it; it isn't moved. - if creating == nil, let hermesWorkspaces { - if hermesWorkspaces.catalogAgentID != agent.id || hermesWorkspaces.catalog == nil { - await hermesWorkspaces.load(agentID: agent.id) - } - guard hermesWorkspaces.catalogAgentID == agent.id, - let workspaceCatalog = hermesWorkspaces.catalog else { - return .opened(sessionID: session.id, agentID: agent.id) - } - if let workspaceID = workspaceCatalog.activeWorkspaceID { - guard await hermesWorkspaces.select( - id: workspaceID, - agentID: agent.id, - sessionID: session.id - ) else { - return .opened(sessionID: session.id, agentID: agent.id) - } - // The workspace client has already confirmed the move with - // Hermes' session.workspace.move and projects.for_cwd - // readback. Keep the catalog summary in sync immediately; - // the next authoritative session list will rehydrate the - // same association from the session's persisted cwd. - let workspaceName = HermesWorkspaceSelectionPresentation.selectedName( - store: hermesWorkspaces, sessionID: session.id - ) - catalog.reconcileSessionWorkspace( - id: hermesWorkspaces.workspaceID(forSessionID: session.id), - name: workspaceName, - sessionID: session.id - ) - } - } - + if creating == nil { await placeInActiveProject(session, agent: agent) } return .opened(sessionID: session.id, agentID: agent.id) } + /// Hermes starts a new chat in the bot's active project: the chat is moved there, and the chat + /// list says so at once. + private func placeInActiveProject(_ session: SessionRecord, agent: AgentProfile) async { + guard let hermesWorkspaces else { return } + if hermesWorkspaces.catalogAgentID != agent.id || hermesWorkspaces.catalog == nil { + await hermesWorkspaces.load(agentID: agent.id) + } + guard hermesWorkspaces.catalogAgentID == agent.id, let workspaceCatalog = hermesWorkspaces.catalog, + let workspaceID = workspaceCatalog.activeWorkspaceID, + await hermesWorkspaces.select(id: workspaceID, agentID: agent.id, sessionID: session.id) else { return } + // The workspace client has already confirmed the move with + // Hermes' session.workspace.move and projects.for_cwd + // readback. Keep the catalog summary in sync immediately; + // the next authoritative session list will rehydrate the + // same association from the session's persisted cwd. + let workspaceName = HermesWorkspaceSelectionPresentation.selectedName( + store: hermesWorkspaces, sessionID: session.id + ) + catalog.reconcileSessionWorkspace( + id: hermesWorkspaces.workspaceID(forSessionID: session.id), + name: workspaceName, + sessionID: session.id + ) + } + private func present(_ id: String, beforePresentation: @MainActor (String, String?) -> Void) { beforePresentation(id, appState.activeConversationID) var instant = Transaction() diff --git a/Bighelp/App/RootAgentHome.swift b/Bighelp/App/RootAgentHome.swift index d899abb7..e25c44e9 100644 --- a/Bighelp/App/RootAgentHome.swift +++ b/Bighelp/App/RootAgentHome.swift @@ -1,15 +1,8 @@ import OSLog import SwiftUI -/// The agent home: the Chat tab opens the selected agent's chat, and Feed, -/// Ideas, Goals and Apps show that agent's board. The avatar opens its profile, -/// the name switches agents or groups, and ☰ holds chats and the rest of the app. -struct NewChatPickerRequest: Identifiable { - let id = UUID() - let seed: String? - let owner: WorkspaceOwner -} - +// The bots' own chats and what follows the connection for the whole home: the shell's board, usage, +// the Dynamic Island and the sidebar's host. extension RootShellView { var homeAgent: AgentProfile? { agents.resolvedAgent(explicitID: nil) } @@ -57,105 +50,45 @@ extension RootShellView { guard let activity = agentIsland?.activity else { return } if case .chat(let id)? = appState.path.last, featureStore.preparedChatModel(id: id)?.memberIDs.first == activity.agentID { return } - if homeAgent?.id != activity.agentID { agents.select(activity.agentID) } if let working = sessionCatalog.recentSummaries(includeCronSessions: false).first(where: { $0.kind == .direct && $0.agentIDs.first == activity.agentID && featureStore.preparedChatModel(id: $0.id)?.isSending == true }) { - openAsHomeChat(working) + openSessionSelection(working) } else { - openHomeChat(replacing: true) - } - } - - /// Every phone chat uses the agent-home look (big live avatar), ☰ in the - /// top left and the tab bar. A chat picked from a list or opened about - /// something (Feed's Discuss, a task, a deeper page) goes back to it with - /// the edge swipe; ☰ reaches everything else. - var homeChrome: AgentHomeChrome { - // Bots mode: Back, the bot's name (its profile) and options; no ☰ or bar. - if simpleBotsOn { - return AgentHomeChrome(isSimpleBots: true, - onProfile: { appState.open(.simpleBotProfile(agentID: $0)) }) - } - return AgentHomeChrome( - isEnabled: true, - // All hosts too: a chat's agent is on the selected host, so its tabs are that agent's. - // Code mode has no bottom bar: its sessions return to its home through ☰ or Back. - showsTabBar: settings.experience != .code, - onMenu: { isHomeDrawerPresented.toggle() }, - onProfile: { profileAgentID = $0 }, - onSwitchAgent: { isAgentSwitcherPresented = true }, - onNewChat: { presentNewChatPicker(seed: $0) }, - onStartChat: { startHomeChat(with: $0) }, - tabSelection: tabSelection, - unreadTabs: boardUnreadTabs, - barTabs: barTabs - ) - } - - /// A chat's header chrome. The Chat tab's own chat (not one opened from a list, and not a Code - /// session) also carries the Header mode switcher. - func homeChrome(forChat id: String) -> AgentHomeChrome { - var chrome = homeChrome - if chrome.isEnabled, settings.currentMode == .chat, !fleetModeOn, !appState.chatOpenedFromList, - case .chat(let first)? = appState.path.first, first == id { - chrome.modeSwitch = modeSwitch + openCanonicalAgentChat(activity.agentID) } - return chrome - } - - /// Feed, Ideas and Goals with items the person hasn't seen yet. - var boardUnreadTabs: Set { - var tabs: Set = [] - if agentBoard.unreadCount(.feed) > 0 { tabs.insert(.feed) } - if agentBoard.unreadCount(.idea) > 0 { tabs.insert(.ideas) } - if agentBoard.unreadCount(.goal) > 0 { tabs.insert(.goals) } - return tabs - } - - var opensHomeChat: Bool { - // The all-hosts view opens on its list of agents. - guard !fleetModeOn else { return false } - let defaults = UserDefaults.standard - return defaults.object(forKey: "loopdy.home.opens-chat") == nil || defaults.bool(forKey: "loopdy.home.opens-chat") } - /// Opens the same canonical Bot Chat as the agent's entry in Hermes Desktop. - func openHomeChat(replacing: Bool = false) { - // Already there: tapping Chat again keeps the chat as it is. A chat - // with Back (picked from the list) isn't the home chat; Chat leaves it. - if !replacing, appState.selectedTab == .sessions, appState.path.count == 1, !appState.chatOpenedFromList, - case .chat = appState.path[0] { return } + /// The primary bot's own chat, pushed: an old Activity link, or an alert that names no chat + /// with nothing waiting. With no bot yet, the first tab. + func openPrimaryBotChat() { guard let agent = homeAgent else { - appState.select(.sessions) + appState.select(.conversations) return } - openCanonicalAgentChat(agent.id, fromList: false) + openCanonicalAgentChat(agent.id) } /// The tapped agent's Bot Chat; if the host can't give one, its latest chat or a new one. /// `startsVoice` opens voice on it. Cancelled only when the person moves on (another /// screen, tab or computer). - func openCanonicalAgentChat(_ profileID: String, fromList: Bool, startsVoice: Bool = false, - dissolvesOutgoing: Bool = false) { + func openCanonicalAgentChat(_ profileID: String, startsVoice: Bool = false, dissolvesOutgoing: Bool = false) { let saved = sessionCatalog.records.first(where: { $0.isBotChat && $0.agentIDs == [profileID] }) - // Bots mode: the opening loader covers the lookup and the chat's first load if they're slow. - let opening = simpleBotsOn - ? simpleBotsChatOpening.begin(agentID: profileID, name: agents.profiles.first { $0.id == profileID }?.name, - originPath: appState.path, - hasCachedContent: saved.map { hasCachedChatContent($0.id) } ?? false) - : nil + // The opening loader covers the lookup and the chat's first load if they're slow. + let opening = simpleBotsChatOpening.begin( + agentID: profileID, name: agents.profiles.first { $0.id == profileID }?.name, + originPath: appState.path, hasCachedContent: saved.map { hasCachedChatContent($0.id) } ?? false) // A Bot Chat opened before is saved here: open it at once (its chat loads from // Hermes as usual) rather than wait a second or two on the lookup. if let saved { - showAgentChat(saved, fromList: fromList, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) - if let opening { simpleBotsChatOpening.endIfNothingOpened(opening) } + showAgentChat(saved, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) + simpleBotsChatOpening.endIfNothingOpened(opening) return } guard let owner = currentWorkspaceOwner else { - if let opening { simpleBotsChatOpening.endIfNothingOpened(opening) } - actionErrorMessage = "Connect to this computer to open the agent’s chat." + simpleBotsChatOpening.endIfNothingOpened(opening) + actionErrorMessage = "Connect to this computer to open the bot’s chat." return } let originTab = appState.selectedTab @@ -177,30 +110,23 @@ extension RootShellView { }, present: { id in guard let record = sessionCatalog.session(id: id), record.kind == .direct, record.agentIDs == [profileID] else { - openLatestAgentChat(profileID, fromList: fromList, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) + openLatestAgentChat(profileID, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) return } - showAgentChat(record, fromList: fromList, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) + showAgentChat(record, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) }, failed: { - openLatestAgentChat(profileID, fromList: fromList, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) + openLatestAgentChat(profileID, startsVoice: startsVoice, dissolvesOutgoing: dissolvesOutgoing) }) - if let opening { - Task { @MainActor in - await lookup.value - simpleBotsChatOpening.endIfNothingOpened(opening) - } + Task { @MainActor in + await lookup.value + simpleBotsChatOpening.endIfNothingOpened(opening) } } - private func showAgentChat(_ record: SessionRecord, fromList: Bool, startsVoice: Bool, dissolvesOutgoing: Bool = false) { + /// The chat is pushed over where the person is, so Back returns there. + private func showAgentChat(_ record: SessionRecord, startsVoice: Bool, dissolvesOutgoing: Bool = false) { if dissolvesOutgoing { presentNewChatDissolve(record.id, replacing: appState.activeConversationID) } - var instant = Transaction() - instant.disablesAnimations = true - withTransaction(instant) { - appState.select(.sessions) - appState.chatOpenedFromList = fromList - openSession(record.summary) - } + openSession(record.summary) if startsVoice { appState.requestVoiceMode(for: record.id) } } @@ -222,129 +148,15 @@ extension RootShellView { /// Some hosts can't give an agent its Bot Chat: one already titled "Bot Chat" /// from Hermes' API server is hidden from the app but keeps the title. The /// agent still opens, on its latest chat or a new one, never an error. - private func openLatestAgentChat(_ profileID: String, fromList: Bool, startsVoice: Bool, - dissolvesOutgoing: Bool = false) { - var instant = Transaction() - instant.disablesAnimations = true - withTransaction(instant) { - if appState.selectedTab != .sessions { appState.select(.sessions) } - appState.chatOpenedFromList = fromList - if let latest = sessionCatalog.recentSummaries(includeCronSessions: false) - .first(where: { $0.kind == .direct && $0.agentIDs == [profileID] }) { - if dissolvesOutgoing { presentNewChatDissolve(latest.id, replacing: appState.activeConversationID) } - openSession(latest) - if startsVoice { appState.requestVoiceMode(for: latest.id) } - } else { - startNewChat(explicitAgentID: profileID, startsVoice: startsVoice) - } - } - } - - /// Opens a chat as the Chat tab's home chat. - func openAsHomeChat(_ summary: SessionSummary) { - appState.select(.sessions) - appState.chatOpenedFromList = false - openSessionSelection(summary) - } - - /// Opens Settings › Chat › Opens on once at launch, with its Start with - /// agent, after saved chats and agents have loaded. False while it waits - /// for Kanban's first answer. - @discardableResult - func openLaunchLandingIfNeeded(kanbanWaitIsOver: Bool = false) -> Bool { - // Never push under the "Unable to open" alert: iOS drops that push while - // the path keeps it, leaving the Chats list with no ☰ or tab bar. A link, - // widget or notification opening the app wins (it marks this done). - // Bots mode opens on its own home, the list of bots. - if simpleBotsOn, !didAutoOpenHomeChat { - didAutoOpenHomeChat = true - return true - } - guard !didAutoOpenHomeChat, actionErrorMessage == nil, !hasPendingOutsideOpen, - appState.selectedTab == .sessions, appState.path.isEmpty, - sessionCatalog.hasLoadedState, let owner = currentWorkspaceOwner, homeAgent != nil else { return true } - let choice = settings.launchLanding - let kanban = kanbanAvailability.host == owner.cacheScopeID ? kanbanAvailability.isAvailable : nil - guard let destination = BighelpLanding.destination(for: choice, kanbanAvailable: kanban, - kanbanWaitIsOver: kanbanWaitIsOver, - projectsAvailable: canOpenProjects) else { return false } - didAutoOpenHomeChat = true - // The all-hosts view opens on its list of agents. - guard !fleetModeOn else { return true } - if let agentID = BighelpLanding.startAgent(stored: settings.startAgentID(scope: owner.cacheScopeID), - agentIDs: agents.profiles.map(\.id), choice: choice), - homeAgent?.id != agentID { - agents.makeHomeAgent(agentID) - } - switch destination { - case .chatList: break - case .homeChat, .allAgents: openHomeChat() - case .agents: appState.select(.agents) - case .board(let tab): appState.select(tab) - case .kanban: openKanban() - case .projects: openProjects() - } - return true - } - - /// "Ask" and "Discuss": a new chat with this agent, the text ready to send. - func askAgent(_ text: String) { - appState.leaveComposerText(text) - startNewChat(explicitAgentID: homeAgent?.id) - } - - /// Let's do it: a new chat with this agent, the message sent at once. - func sendToAgent(_ text: String) { - appState.leaveComposerText(text, sendsAtOnce: true) - startNewChat(explicitAgentID: homeAgent?.id) - } - - /// A blueprint: a new chat with it in the message box, its blanks as chips. Nothing is sent. - func useBlueprint(_ text: String) { - appState.leaveComposerText(text, fillsBlanks: true) - startNewChat(explicitAgentID: homeAgent?.id) - } - - func switchHomeAgent(to agent: AgentProfile) { - if fleetModeOn { - // Stay in the all-hosts view: the agent's chat replaces this one, - // with Back to All agents. - var instant = Transaction() - instant.disablesAnimations = true - withTransaction(instant) { - appState.select(.sessions) - performFleetOpen(.agent(profileID: agent.id)) - } - return - } - // Over the primary agent too: a board opened from a chat makes that chat's agent primary. - agents.makeHomeAgent(agent.id) - if appState.selectedTab == .sessions { openHomeChat(replacing: true) } - } - - /// New chat in the bar, on every place it holds: a chat with the agent in use. On Sessions' - /// list it opens over the list, so Back goes back to it; anywhere else (Feed, Kanban…) it's - /// the Chat tab's new chat, as the boards' header button was. All agents has its own New - /// chat, bottom right, so the bar leaves it out there. - var barNewChat: (() -> Void)? { - guard !fleetModeOn else { return nil } - return { - if appState.selectedTab != .sessions, let agent = homeAgent { - startHomeChat(with: agent.id) - } else { - appState.chatOpenedFromList = true - startNewChat(explicitAgentID: nil) - } - } - } - - /// New chat's touch and hold: pick one agent for a 1:1 chat or several for a group. - func presentNewChatPicker(seed: String?) { - guard let owner = currentWorkspaceOwner else { - actionErrorMessage = "Connect to your Hermes host to start a chat." - return + private func openLatestAgentChat(_ profileID: String, startsVoice: Bool, dissolvesOutgoing: Bool = false) { + if let latest = sessionCatalog.recentSummaries(includeCronSessions: false) + .first(where: { $0.kind == .direct && $0.agentIDs == [profileID] }) { + if dissolvesOutgoing { presentNewChatDissolve(latest.id, replacing: appState.activeConversationID) } + openSession(latest) + if startsVoice { appState.requestVoiceMode(for: latest.id) } + } else { + startNewChat(explicitAgentID: profileID, startsVoice: startsVoice) } - newChatPicker = NewChatPickerRequest(seed: seed, owner: owner) } /// This chat › New Bot Chat, offered only in an agent's Bot Chat. @@ -400,38 +212,15 @@ extension RootShellView { return made } - /// A 1:1 chat from the New chat picker; that agent becomes the home agent. - func startHomeChat(with agentID: String) { - agents.select(agentID) - if appState.selectedTab != .sessions { appState.select(.sessions) } - appState.chatOpenedFromList = false - startNewChat(explicitAgentID: agentID) - } - - /// An agent tapped on Agents opens what Settings › Chat › A bot opens - /// asks for: its Bot Chat, its latest chat, or a new one. The all-hosts view - /// keeps its Back navigation (`openFleetAgent` is its version). + /// A bot tapped on the Bots view opens what Settings › Chat › A bot opens asks for: its Bot + /// Chat, its latest chat, or a new one. The chat is pushed; the primary bot stays who it is. func openAgentChat(_ agentID: String) { Telemetry.featureUsed(.agentOpened) - agents.select(agentID) switch settings.botChatExperience { - case .botChat: - openCanonicalAgentChat(agentID, fromList: fleetModeOn) - case .lastChat: - openLatestAgentChat(agentID, fromList: fleetModeOn, startsVoice: false) - case .newChat: - if appState.selectedTab != .sessions { appState.select(.sessions) } - appState.chatOpenedFromList = fleetModeOn - startNewChat(explicitAgentID: agentID) - } - } - - func inviteToGroup(seed: String?) { - guard let owner = groupCreationReadyOwner else { - actionErrorMessage = "Group chats need a connected Hermes host." - return + case .botChat: openCanonicalAgentChat(agentID) + case .lastChat: openLatestAgentChat(agentID, startsVoice: false) + case .newChat: startNewChat(explicitAgentID: agentID) } - handleAgentWorkspaceAction(AgentWorkspaceActionRequest(owner: owner, action: .createGroup(seedProfileID: seed))) } /// The selected host, when it can make group chats. @@ -440,18 +229,23 @@ extension RootShellView { return owner } - /// A group chat with these agents right away, named after them, then - /// opened: what New group chat's Create does, minus the form (All agents' - /// New chat › Group chat already picked who's in it). - func createGroupChat(with profileIDs: [String], peers: [HermesBotModePeerCandidate] = []) { + /// A group chat with these bots right away, named after them, then opened: what New Group + /// Chat's Create does, minus the form (New chat's To row already picked who's in it). + /// `firstMessage` is sent in it once it opens. `ended` is called once, however this ends: with + /// the group chat's ID once it is open, or nil when it couldn't be made or opened. New chat + /// keeps its text, and holds a second Send, until then. + func createGroupChat(with profileIDs: [String], peers: [HermesBotModePeerCandidate] = [], + firstMessage: String? = nil, ended: (@MainActor (String?) -> Void)? = nil) { guard let owner = groupCreationReadyOwner else { actionErrorMessage = "Group chats need a connected Hermes host." + ended?(nil) return } let profiles = profileIDs.compactMap { id in agents.profiles.first { $0.id == id } } guard profiles.count == profileIDs.count, (2...BotModeRoom.maximumMembers).contains(profiles.count + peers.count) else { - actionErrorMessage = "Those agents aren't all on this host anymore. Pick them again from New chat." + actionErrorMessage = "Those bots aren't all on this computer anymore. Pick them again from New chat." + ended?(nil) return } Task { @MainActor in @@ -461,13 +255,19 @@ extension RootShellView { name: BotModeCreateRoomView.automaticName(profiles.map(\.name) + peers.map(\.name)), profiles: profiles, peers: peers) // A reconnect meanwhile is still this computer. - guard isCurrentSignIn(owner), let current = currentWorkspaceOwner else { return } - openHostedGroup(room.id, owner: current, settings: false) + guard isCurrentSignIn(owner), let current = currentWorkspaceOwner else { + ended?(nil) + return + } + openHostedGroup(room.id, owner: current, settings: false, firstMessage: firstMessage, opened: ended) } catch is CancellationError { + ended?(nil) } catch let error as BotModePeerLinkError { + ended?(nil) guard isCurrentSignIn(owner) else { return } actionErrorMessage = error.message } catch { + ended?(nil) // The kind of failure only; never host data. Logger(subsystem: "app.loopdy.mobile", category: "BotMode") .error("Group chat create failed: \(String(reflecting: error), privacy: .public)") @@ -479,7 +279,7 @@ extension RootShellView { /// `AppState.openNeedsYou()` (an alert that names no chat). Once the computer is connected it reads /// the computer's list, so the question the alert was about is in it, then opens Needs you, or the - /// home chat when nothing waits. The request is kept until then: a cold launch can ask before the + /// primary bot's chat when nothing waits. The request is kept until then: a cold launch can ask before the /// computer answers, so it waits for the connection (the shell's task restarts when /// `needsYouListIsReady` changes) and gives up after `NeedsYouRequest.connectionWait`. Settings is /// closed first, since a sheet can't show over it. @@ -490,134 +290,19 @@ extension RootShellView { // Cancelled: the connection came up, or the request was settled or replaced. guard !Task.isCancelled, appState.isNeedsYouRequested else { return } appState.isNeedsYouRequested = false - leaveSettings { openHomeChat() } + leaveSettings { openPrimaryBotChat() } return } await featureStore.dashboardModel.refreshAfterExternalChange() guard !Task.isCancelled, appState.isNeedsYouRequested else { return } appState.isNeedsYouRequested = false if needsYouEntries.isEmpty { - leaveSettings { openHomeChat() } + leaveSettings { openPrimaryBotChat() } } else { leaveSettings { afterClosingHomeSheets { isNeedsYouPresented = true } } } } - /// Closes the open home sheet, then runs the next step once it is gone. - func afterClosingHomeSheets(_ action: @escaping @MainActor () -> Void) { - // The Mac's ☰ is a sidebar that stays open; with no sheet over it, - // there's nothing to wait for. - if BighelpPlatform.isMac, !isAgentSwitcherPresented, profileAgentID == nil { - action() - return - } - afterHomeSheet = action - isHomeDrawerPresented = false - isAgentSwitcherPresented = false - profileAgentID = nil - } - - func runAfterHomeSheet() { - let action = afterHomeSheet - afterHomeSheet = nil - action?() - } - - // MARK: Board tabs - - func boardContext(for agent: AgentProfile, onBack: (() -> Void)? = nil) -> AgentBoardContext { - AgentBoardContext( - agentID: agent.id, agentName: agent.name, imageURL: agents.avatarURL(for: agent), - activity: homeActivity, store: agentBoard, - onProfile: { profileAgentID = agent.id }, - onSwitchAgent: { isAgentSwitcherPresented = true }, - onAsk: askAgent, - onSend: sendToAgent, - onBlueprint: useBlueprint, - onMenu: { isHomeDrawerPresented.toggle() }, - onNewChat: { startHomeChat(with: agent.id) }, - onPickAgents: { presentNewChatPicker(seed: agent.id) }, - tools: appsTools(for: agent), - menuHasUnread: menuHasUnread, - onBack: onBack - ) - } - - @ViewBuilder - func agentBoardTab(_ tab: AppTab, onBack: (() -> Void)? = nil) -> some View { - if let agent = homeAgent { - let context = boardContext(for: agent, onBack: onBack) - switch tab { - case .feed: AgentFeedView(context: context) - case .ideas: AgentIdeasView(context: context) - case .goals: AgentGoalsView(context: context) - default: AgentAppsView(context: context, media: agentMedia) { appsArtifacts(agentID: agent.id) } - } - } else { - ContentUnavailableView("No agent yet", systemImage: "person.crop.circle.badge.questionmark", - description: Text("Connect to Hermes to see your agent's feed, ideas and goals.")) - } - } - - /// Feed, Ideas, Goals or Files as a quick screen, from ☰ while the bottom bar doesn't hold - /// it: over where you were, with Back where ☰ would be. - func agentBoardPage(_ tab: AppTab) -> some View { - agentBoardTab(tab, onBack: { [appState] in - if case .board? = appState.path.last { appState.path.removeLast() } - }) - .toolbar(.hidden, for: .navigationBar) - } - - /// From ☰: its tab when the bottom bar holds it, else a quick screen over where you are. - func openBoard(_ tab: AppTab) { - if barTabs.contains(tab) { - tabSelection.wrappedValue = tab - } else if appState.path.last != .board(tab) { - appState.path.append(.board(tab)) - } - } - - func appsTools(for agent: AgentProfile) -> [(title: String, systemImage: String, action: () -> Void)] { - [ - ("Files", "folder", { openWorkspaceDestination(.files) }), - ("Memory", "brain", { openWorkspaceDestination(.memory) }), - ("Skills & tools", "wrench.and.screwdriver", { openWorkspaceDestination(.skills) }), - ("Scheduled tasks", "calendar.badge.clock", { openScheduledTasks(filteredTo: agent.id) }), - ] - } - - /// Where Files finds agents' folders: the bighelp plugin on the selected host, or the demo's. - var configuredWorkspaceSource: (any ConfiguredWorkspaceSource)? { - if usesWorkspaceFixtures, workspaceConnections?.isDirectSelected != true { return DemoConfiguredWorkspace() } - guard let workspace = workspaceConnections?.workspace, - let http = workspaceConnections?.hosts.selectedWorkspace?.nativeClient else { return nil } - return HostConfiguredWorkspace(http: http, workspace: workspace) - } - - /// The Files target on screen now: nil once another connection is in use, another target once - /// another agent is, so a late reply for the last one never lands. - func currentFilesTarget(agentID: @escaping @MainActor () -> String?) -> @MainActor () -> WorkspaceFilesTarget? { - let workspace = workspaceConnections?.workspace - return { - guard workspaceConnections?.workspace === workspace, let owner = currentWorkspaceOwner else { return nil } - return WorkspaceFilesTarget(owner: owner, agentID: agentID()) - } - } - - /// Files in the agent home: the selected agent's own folder, and its folder chooser saves for it. - @ViewBuilder - func appsArtifacts(agentID: String) -> some View { - if let owner = currentWorkspaceOwner, let source = configuredWorkspaceSource { - let target = WorkspaceFilesTarget(owner: owner, agentID: agentID) - ConfiguredWorkspaceArtifactsView(hostName: workspaceHostName, target: target, source: source, - currentTarget: currentFilesTarget { homeAgent?.id }, isEmbedded: true) - .id(target) - } else { - ContentUnavailableView("No artifacts yet", systemImage: "square.on.circle", - description: Text("Files, pages and apps your agent makes show up here.")) - } - } - // MARK: Board data struct AgentBoardClientKey: Equatable { @@ -733,26 +418,6 @@ extension RootShellView { } } - /// Attached to the workspace shell only: host setup and onboarding have no - /// navigation destinations, so a chat pushed under them would be blank. - func homeAutoOpen(_ content: Content) -> some View { - content - .task(id: HomeAutoOpenKey(loaded: sessionCatalog.hasLoadedState, agentID: homeAgent?.id, - owner: currentWorkspaceOwner, kanban: kanbanAvailability.isAvailable)) { - // Let the shell register its destinations before pushing. - await Task.yield() - guard !openLaunchLandingIfNeeded() else { return } - // Kanban hasn't answered for this computer yet: a new answer - // restarts this; none in time opens the default. - try? await Task.sleep(for: BighelpLanding.kanbanWait) - guard !Task.isCancelled else { return } - openLaunchLandingIfNeeded(kanbanWaitIsOver: true) - } - .onChange(of: actionErrorMessage == nil) { _, cleared in - if cleared { openLaunchLandingIfNeeded() } - } - } - struct BoardPreloadKey: Equatable { let client: AgentBoardClientKey let agentID: String? @@ -766,13 +431,6 @@ extension RootShellView { let isActive: Bool } - struct HomeAutoOpenKey: Equatable { - let loaded: Bool - let agentID: String? - let owner: WorkspaceOwner? - let kanban: Bool? - } - // MARK: Dynamic Island pictures var activityAvatarKey: [String] { @@ -821,8 +479,7 @@ extension RootShellView { .task(id: providerUsageKey) { configureProviderUsage(providerUsageKey) } .task(id: agentBoardClientKey) { await configureKanban(agentBoardClientKey) } .task(id: agentBoardClientKey) { await configureWorkflows(agentBoardClientKey) } - // Loads the home agent's board up front, so new Feed, Ideas and Goals - // items show as dots on the tab bar before the tab is opened. + // Loads the primary bot's board up front: the widgets show it. .task(id: BoardPreloadKey(client: agentBoardClientKey, agentID: homeAgent?.id)) { guard agentBoard.isAvailable, let agentID = homeAgent?.id, agentBoard.agentID != agentID else { return } await agentBoard.load(agentID: agentID) @@ -868,138 +525,25 @@ extension RootShellView { } .onAppear { agentIsland?.onOpen = { openIslandChat() } } .task(id: activityAvatarKey) { await shareActivityAvatars() } + // A space's draft card in a chat leads to Today once its space is added. Each computer + // has its own navigation, so it's handed over again when that changes. + .onChange(of: ObjectIdentifier(appState), initial: true) { + SpaceDraftCardHost.openToday = { [appState] in appState.select(.today) } + } .modifier(PinnedAgentsWidgetHooks( agents: agents, fleet: fleet, isActive: scenePhase == .active, demo: usesWorkspaceFixtures && workspaceConnections?.isDirectSelected != true ? (sessionCatalog, featureStore.scheduledTasks) : nil)) - .bighelpSheet(isPresented: Binding(get: { profileAgentID != nil }, set: { if !$0 { profileAgentID = nil } }), - onDismiss: runAfterHomeSheet) { - if let id = profileAgentID, let agent = agents.profiles.first(where: { $0.id == id }) { - agentProfileSheet(agent) - } - } - .bighelpSheet(item: $newChatPicker) { request in - BotModeCreateRoomView(rooms: botModeRooms, agents: agents, seedProfileID: request.seed, - onStartDirect: { startHomeChat(with: $0) }) { roomID in - guard request.owner == currentWorkspaceOwner else { return } - openHostedGroup(roomID, owner: request.owner, settings: false) - } - .bighelpSheetSize(.standard) - } - .bighelpSheet(isPresented: $isAgentSwitcherPresented, onDismiss: runAfterHomeSheet) { - agentSwitcherSheet - } .modifier(MacSidebarMemory(isOpen: $isHomeDrawerPresented, canShow: !presentsFirstRunOnboarding && !needsInitialHostSetup)) .modifier(HomeMenuPresentation(isPresented: $isHomeDrawerPresented, onDismiss: runAfterHomeSheet, contentID: ObjectIdentifier(featureStore)) { - homeDrawer + // The Mac's and Vision Pro's column is kept outside the shell: drawn again from + // the stores each time they change, not a copy made when it opened. + BighelpLiveColumn { homeSidebar } }) } - private func agentProfileSheet(_ agent: AgentProfile) -> some View { - let owner = currentWorkspaceOwner - let canEdit = owner.map { currentWorkspaceCapabilities.supports(.profilesEdit, owner: $0, profileID: agent.id) } ?? false - // From a chat with this agent: that chat's model and reasoning. - let chat: ChatModel? = if case .chat(let id)? = appState.path.last, - let model = featureStore.preparedChatModel(id: id), - !model.isBotMode, model.memberIDs.first == agent.id { model } else { nil } - return AgentProfileSheet( - agent: agent, imageURL: agents.avatarURL(for: agent), activity: homeActivity, - isConnected: owner != nil, store: agentBoard, - schedules: (featureStore.scheduledTasks?.tasks ?? []).filter { $0.agentID == agent.id }, - onEdit: { - guard canEdit, let owner else { - actionErrorMessage = "Connect to this host before editing its agent profile." - return - } - afterClosingHomeSheets { - workspaceProfileEditor = .editing(agent, store: agents, processor: AvatarImageProcessor(), - isCurrent: { currentWorkspaceOwner?.signIn == owner.signIn }) - } - }, - onOpenSchedule: { task in afterClosingHomeSheets { openScheduledTask(task) } }, - chatControls: chat?.runtimeControls, - onChangeModel: chat.map { chat in { afterClosingHomeSheets { chat.requestSessionControls() } } }, - screenService: makeBotScreenService(), - screenChats: botScreenChats(for: agent) - ) - } - - private var homeGroups: [SessionSummary] { - sessionCatalog.recentSummaries(includeCronSessions: false).filter { $0.kind == .botMode } - } - - private var agentSwitcherSheet: some View { - let groups = homeGroups - return AgentSwitcherSheet( - agents: agents.profiles, - selectedID: homeAgent?.id, - imageURL: { agents.avatarURL(for: $0) }, - groups: groups.map { .init(id: $0.id, name: $0.title, memberCount: $0.agentIDs.count) }, - onSelect: { agent in afterClosingHomeSheets { switchHomeAgent(to: agent) } }, - onSelectGroup: { group in - guard let summary = groups.first(where: { $0.id == group.id }) else { return } - afterClosingHomeSheets { openAsHomeChat(summary) } - }, - onNewGroup: { afterClosingHomeSheets { inviteToGroup(seed: homeAgent?.id) } }, - onNewAgent: { afterClosingHomeSheets { appState.select(.agents) } }, - onManageAgents: { afterClosingHomeSheets { appState.select(.agents) } } - ) - } - - private var homeDrawer: some View { - AgentHomeDrawer( - chats: Array(sessionCatalog.recentSummaries(includeCronSessions: false).prefix(12)), - agent: { id in agents.profiles.first { $0.id == id }.map { ($0.name, agents.avatarURL(for: $0)) } }, - hosts: fleetMenuHosts, - destinations: fleetModeOn && settings.experience != .code ? fleetMenuDestinations : menuDestinations, - onOpen: { summary in afterClosingHomeSheets { openAsHomeChat(summary) } }, - fleetChats: fleetModeOn ? fleet.map { fleet in - (fleet, { chat in afterClosingHomeSheets { openFleetChat(chat) } }) - } : nil - ) - } - - /// Where the ☰ menu goes. Every menu entry point opens this one menu. - var menuDestinations: BighelpMenuDestinations { - BighelpMenuDestinations( - newChatTitle: homeAgent.map { String(localized: "New chat with \($0.name)") } ?? String(localized: "New chat"), - onNewChat: { - afterClosingHomeSheets { - if appState.selectedTab != .sessions { appState.select(.sessions) } - appState.chatOpenedFromList = false - startNewChat(explicitAgentID: homeAgent?.id) - } - }, - onAllChats: { afterClosingHomeSheets { openAllSessions() } }, - onProjects: canOpenProjects ? { afterClosingHomeSheets { openProjects() } } : nil, - onAgents: { afterClosingHomeSheets { appState.select(.agents) } }, - onScheduledTasks: { afterClosingHomeSheets { openScheduledTasks(filteredTo: nil) } }, - onKanban: canOpenKanban ? { afterClosingHomeSheets { openKanban() } } : nil, - onWorkflows: canOpenWorkflows ? { afterClosingHomeSheets { openWorkflows() } } : nil, - folder: settings.nerdModeEnabled - ? (name: activeHermesWorkspaceName, open: { afterClosingHomeSheets { presentHermesWorkspaces() } }) - : nil, - sharedWithBighelp: pendingSharesMenuRow, - onUsage: usage.isAvailable ? { afterClosingHomeSheets { showUsage() } } : nil, - onSettings: { afterClosingHomeSheets { openSettingsPage() } }, - places: settings.appLayout.menuPlaces, - onBoard: { tab in afterClosingHomeSheets { openBoard(tab) } }, - unread: boardUnreadTabs, - needsYou: menuNeedsYou, - code: settings.experience == .code ? codeMenu : nil, - experience: experienceSwitch - ) - } - - /// Something new in Feed, Ideas or Goals while ☰ is the only way there, a share waiting to be - /// sent, or something waiting in Needs you: a dot on ☰. - var menuHasUnread: Bool { - !boardUnreadTabs.subtracting(barTabs).isEmpty || PendingShareCenter.shared.waitingCount > 0 - || menuNeedsYou != nil - } - } // MARK: - Projects @@ -1037,7 +581,7 @@ extension RootShellView { return } projectsStore = ProjectsStore(source: source, profileID: workspaceAgentID) - showOneHostPageOnSessions([.projects]) + showOverWork([.projects]) } /// Hermes starts new chats in the current project's folder, so the @@ -1048,13 +592,11 @@ extension RootShellView { actionErrorMessage = hermesWorkspaces.errorMessage ?? "This project couldn't be opened. Try again." return } - appState.chatOpenedFromList = true startNewChat(explicitAgentID: workspaceAgentID) } } func openProjectChat(_ chat: ProjectsStore.Chat) { - appState.chatOpenedFromList = true if let id = chat.catalogID, let record = sessionCatalog.session(id: id) { openSessionSelection(record.summary) return @@ -1077,7 +619,7 @@ extension RootShellView { openSession(record.summary) } catch is CancellationError { } catch { - actionErrorMessage = "This chat couldn't be opened. Try again from All sessions." + actionErrorMessage = "This chat couldn't be opened. Try again from Chats." } } } diff --git a/Bighelp/App/RootChatSwitcher.swift b/Bighelp/App/RootChatSwitcher.swift index 95b3950c..a3f5c564 100644 --- a/Bighelp/App/RootChatSwitcher.swift +++ b/Bighelp/App/RootChatSwitcher.swift @@ -1,32 +1,30 @@ import SwiftUI -// The switcher beside a chat (`BighelpChatSwitcher`): Bots mode's top bots, Code mode's sessions. +// The switcher beside a chat (`BighelpChatSwitcher`): a coding session's other sessions, else the bots. extension RootShellView { - /// The column for the chat with `conversationID`, where one shows: nil in Chat mode (the side bar - /// is there), with the switcher turned off, or with fewer than two places to go. + /// The column for the chat with `conversationID`, where one shows: nil with the switcher turned + /// off, or with fewer than two places to go. func chatSwitcherColumn(for conversationID: String, agentID: String?) -> AnyView? { guard BighelpChatSwitcher.isShown(isOn: settings.chatSwitcherEnabled, screen: screen, horizontalSizeClass: horizontalSizeClass) else { return nil } - if simpleBotsOn { - let context = simpleBotsContext - guard SimpleBotsSwitcher.top(context).count > 1 else { return nil } - return AnyView(SimpleBotsSwitcher(context: context, currentAgentID: agentID)) - } - if appState.selectedTab == .code, let store = codeHome, store.scopeID == currentWorkspaceOwner?.cacheScopeID { + if let store = codeHome, store.scopeID == currentWorkspaceOwner?.cacheScopeID, + store.sessions.contains(where: { $0.id == conversationID }) { let reader = CodeChatStatusReader(catalog: sessionCatalog, features: featureStore) guard store.switcherSessions(reader: reader).count > 1 else { return nil } return AnyView(CodeSessionSwitcher(store: store, reader: reader, currentID: conversationID, onOpen: { session in - // In place of the chat that's open, so Back still goes to the Code home. + // In place of the chat that's open, so Back still goes to where it was opened from. if case .chat? = appState.path.last { appState.path.removeLast() } openCodeSession(session) })) } - return nil + let context = simpleBotsContext + guard SimpleBotsSwitcher.top(context).count > 1 else { return nil } + return AnyView(SimpleBotsSwitcher(context: context, currentAgentID: agentID)) } } -/// Code mode's switcher: reads the sessions again as their states change. +/// A coding session's switcher: reads the sessions again as their states change. private struct CodeSessionSwitcher: View { let store: CodeHomeStore let reader: CodeChatStatusReader diff --git a/Bighelp/App/RootCode.swift b/Bighelp/App/RootCode.swift index 25b0d9dc..89dee17b 100644 --- a/Bighelp/App/RootCode.swift +++ b/Bighelp/App/RootCode.swift @@ -1,44 +1,18 @@ import SwiftUI -/// Code mode's sheets over its home. +/// A project's sheets, over New chat's choices and Work filtered to the project. enum CodeSheet: String, Identifiable { case pullRequests, worktrees var id: String { rawValue } } -// Code mode (Settings › Code mode): its home, sessions, changes and ☰ entries. +// Coding sessions: the computer's Code store, a session's chat and changes, and Dev Factory. extension RootShellView { - /// Code mode needs a host that starts sessions in a chosen folder: native Hermes, or the demo. + /// A coding session needs a host that starts sessions in a chosen folder: native Hermes, or the demo. var canUseCodeMode: Bool { nativeRuntime != nil || (usesWorkspaceFixtures && workspaceConnections?.isDirectSelected != true) } - /// Shows the home `settings.experience` picks, and returns to it after host and account changes. - func applyExperience() { - // Bots mode's home is the Chat tab's place, whatever Code's choice. - let home: AppTab = settings.experience == .code && !simpleBotsOn ? .code : .sessions - guard appState.homeTab != home else { return } - appState.homeTab = home - appState.select(home) - } - - @ViewBuilder - var codeRootTab: some View { - Group { - if let store = codeHome, store.scopeID == currentWorkspaceOwner?.cacheScopeID { - CodeHomeView(context: codeContext(store)) - .bighelpSheet(item: $codeSheet) { sheet in codeSheetView(sheet, store: store) } - } else if canUseCodeMode { - ProgressView("Loading Code") - .frame(maxWidth: .infinity, maxHeight: .infinity) - } else { - ContentUnavailableView("Code needs your computer", systemImage: "laptopcomputer", - description: Text("Connect to a computer running Hermes, then come back to Code.")) - } - } - .task(id: currentWorkspaceOwner?.cacheScopeID) { prepareCodeHome() } - } - /// One Code home per computer, made on first use and kept through reconnects. func prepareCodeHome() { guard canUseCodeMode, let scope = currentWorkspaceOwner?.cacheScopeID else { return } @@ -68,25 +42,8 @@ extension RootShellView { loadCommands: { try await features.draftSlashCommands(agentID: $0, folder: $1) }) } - private func codeContext(_ store: CodeHomeStore) -> CodeHomeContext { - CodeHomeContext( - store: store, - status: CodeChatStatusReader(catalog: sessionCatalog, features: featureStore), - agents: agents.profiles, - avatarURL: { [agents] in agents.avatarURL(for: $0) }, - sections: fleet?.sections ?? [], - onOpenSession: { openCodeSession($0) }, - onOpenChanges: { appState.open(.codeChanges(sessionID: $0.id)) }, - onOpenBatch: { appState.open(.codeBatch(id: $0.id)) }, - onPullRequests: { codeSheet = .pullRequests }, - onWorktrees: { codeSheet = .worktrees }, - onRefreshActivity: { await nativeRuntime?.refreshActiveSessions() }, - connectionKey: currentWorkspaceOwner?.connectionGeneration.uuidString - ) - } - @ViewBuilder - private func codeSheetView(_ sheet: CodeSheet, store: CodeHomeStore) -> some View { + func codeSheetView(_ sheet: CodeSheet, store: CodeHomeStore) -> some View { switch sheet { case .pullRequests: CodePullRequestsSheet(projectName: store.project?.name ?? "This project", @@ -106,9 +63,8 @@ extension RootShellView { } } - /// Opens a Code mode session's chat over the Code home; Back returns to it. + /// Opens a coding session's chat over where the person is; Back returns there. func openCodeSession(_ session: CodeSessionRecord) { - appState.chatOpenedFromList = true guard let record = sessionCatalog.session(id: session.id) else { actionErrorMessage = "This session isn't on this computer anymore." return @@ -142,7 +98,7 @@ extension RootShellView { files: LiveHostTextFiles(client: client, owner: owner, profileID: profileID)) } - /// A Code mode session's chat links Markdown paths to the viewer, inside its folder. + /// A coding session's chat links Markdown paths to the viewer, inside its folder. func codeFileLinks(sessionID: String) -> HostFileLinkContext? { guard let session = codeHome?.sessions.first(where: { $0.id == sessionID }), let files = hostTextFiles(profileID: session.agentID) else { return nil } @@ -160,7 +116,7 @@ extension RootShellView { sendToSession: { try await starter.send($0, toSession: sessionID) })) } else { ContentUnavailableView("Changes aren't available", systemImage: "plus.forwardslash.minus", - description: Text("Open Code from the menu, then try again.")) + description: Text("Open Work, then try again.")) } } @@ -181,13 +137,14 @@ extension RootShellView { onOpenSession: { openCodeSession($0) }) } else { ContentUnavailableView("This batch isn't here anymore", systemImage: "square.stack.3d.up.slash", - description: Text("Open Code from the menu, then try again.")) + description: Text("Open Work, then try again.")) } } // MARK: Dev Factory - /// Opens Dev Factory over the IDE home, with the computer's store made on first use. + /// Opens Dev Factory over where the person is (a project's Work), with the computer's store + /// made on first use. func openDevFactory() { guard let scope = currentWorkspaceOwner?.cacheScopeID ?? (usesWorkspaceFixtures ? "demo" : nil) else { actionErrorMessage = "Connect to your computer to use Dev Factory." @@ -200,8 +157,8 @@ extension RootShellView { } devFactory = DevFactoryStore(scopeID: scope, client: client) } - appState.select(.code) - appState.open(.devFactory) + prepareCodeHome() + if appState.path.last != .devFactory { appState.open(.devFactory) } } private func devFactoryContext(_ store: DevFactoryStore) -> DevFactoryContext { @@ -238,7 +195,7 @@ extension RootShellView { } } else { ContentUnavailableView("Dev Factory isn't open", systemImage: "hammer", - description: Text("Open it from the menu in Code.")) + description: Text("Open it from a project in Work.")) } } @@ -261,40 +218,7 @@ extension RootShellView { canShip: false) } else { ContentUnavailableView("Changes aren't available", systemImage: "plus.forwardslash.minus", - description: Text("Add this project in Code to read its changes here.")) - } - } - - /// ☰ in Code mode: New session, Projects, Pull requests and Worktrees, then Kanban and Settings. - var codeMenu: BighelpMenuDestinations.Code { - BighelpMenuDestinations.Code( - onNewSession: { afterClosingHomeSheets { appState.select(.code) } }, - onPullRequests: codeHome?.project == nil ? nil : { - afterClosingHomeSheets { appState.select(.code); codeSheet = .pullRequests } - }, - onWorktrees: codeHome?.project == nil ? nil : { - afterClosingHomeSheets { appState.select(.code); codeSheet = .worktrees } - }, - onDevFactory: canOpenWorkflows ? { afterClosingHomeSheets { openDevFactory() } } : nil - ) - } - - /// ☰'s switch between Chat and Code, while Code mode is on in Settings. The Unified Mode - /// Toggle takes its place at the top of each home, so ☰ has none while that's on. - var experienceSwitch: BighelpMenuDestinations.ExperienceSwitch? { - guard settings.codeModeEnabled, !settings.unifiedModeToggleEnabled else { return nil } - return BighelpMenuDestinations.ExperienceSwitch(current: settings.experience) { experience in - afterClosingHomeSheets { settings.experience = experience } - } - } - - /// Settings › Modes › Header mode switcher: Bots, Chat and Code at the top of each home - /// (and ⌃⌘1–⌃⌘3 on the Mac). Nil while it's off. - var modeSwitch: BighelpModeSwitch? { - guard settings.unifiedModeToggleEnabled else { return nil } - // At once: the pill sits in a home's header, not in a sheet that has to close first. - return BighelpModeSwitch(modes: settings.availableModes, current: settings.currentMode) { mode in - settings.switchMode(mode) + description: Text("Add this project in Work to read its changes here.")) } } } diff --git a/Bighelp/App/RootDestinations.swift b/Bighelp/App/RootDestinations.swift index b3448d72..524bd464 100644 --- a/Bighelp/App/RootDestinations.swift +++ b/Bighelp/App/RootDestinations.swift @@ -11,14 +11,18 @@ extension RootShellView { } else { switch (route, featureStore.preparedModel(for: route)) { case (.workspaceSettings, _): - routeWithWorkspaceMenu { workspaceSettings() } + workspaceSettings() case (.projects, _): if let context = projectsContext { ProjectsHomeView(context: context) } else { ContentUnavailableView("Projects aren't available", systemImage: "folder", - description: Text("Connect to your computer, then open Projects from the menu.")) + description: Text("Connect to your computer, then open Projects from Work.")) } + case (.sessions, let prepared): + sessionsDestination({ if case .sessions(let model)? = prepared { model } else { nil } }()) + case (.work(let projectID), _): + workProjectPage(projectID) case (.kanban, _): kanbanDestination case (.workflows, _), (.workflow, _), (.workflowRun, _), (.workflowSignoff, _), (.workflowRuns, _): @@ -38,82 +42,73 @@ extension RootShellView { chat: conversationID.flatMap(featureStore.preparedChatModel(id:))) case (.simpleBotsSection(let id), _): SimpleBotsHomeView(context: simpleBotsContext, sectionID: id) - case (.board(let tab), _): - agentBoardPage(tab) - case (.allHostsChats, _): - if let fleet { - fleetChats(fleet) - } else { - ContentUnavailableView("All sessions", systemImage: "bubble.left.and.bubble.right") - } + case (.board(let kind, let agentID), _): + todayBoardPage(kind, agentID: agentID) case (.project(let id), _): if let context = projectsContext { ProjectDetailView(projectID: id, context: context) } else { ContentUnavailableView("Projects aren't available", systemImage: "folder", - description: Text("Connect to your computer, then open Projects from the menu.")) + description: Text("Connect to your computer, then open Projects from Work.")) } case (.workspaceConnections, _): - routeWithWorkspaceMenu { - if let hostRegistry { - BighelpHostsPage(registry: hostRegistry) - .accessibilityIdentifier("workspace.connections") - } else { - WorkspaceUnavailableView(destination: .instances, hostName: workspaceHostName, - reason: "Host selection is unavailable in this presentation.") - } + if let hostRegistry { + BighelpHostsPage(registry: hostRegistry) + .accessibilityIdentifier("workspace.connections") + } else { + WorkspaceUnavailableView(destination: .instances, hostName: workspaceHostName, + reason: "Host selection is unavailable in this presentation.") } case (.workspaceManagement(let destination), _): - routeWithWorkspaceMenu { - if destination == .logs { - if let connections = workspaceConnections, let owner = currentWorkspaceOwner, - connections.owner == owner, let workspace = connections.workspace, - workspace.owner == owner, let direct = connections.hosts.selectedWorkspace?.nativeClient { - HermesLogsDestinationView(hostName: workspaceHostName, owner: owner, - http: direct, workspace: workspace, currentOwner: { - guard connections.workspace === workspace else { return nil } - return currentWorkspaceOwner - }) - .id(owner) - } else { - WorkspaceUnavailableView(destination: .logs, hostName: workspaceHostName, - reason: "Logs require an available direct authenticated Hermes connection.") - } - } else if destination == .voice { - VoiceSettingsView(settings: settings, agents: agents.profiles, - selectedAgentID: workspaceAgentID, - client: voiceSettingsClient, scope: voiceSettingsScope, - isCurrent: voiceSettingsIsCurrent) - } else if destination == .permissions { - PermissionsSettingsView(center: permissionCenter) - } else if destination == .sessionMaintenance || destination == .profileLifecycle { - if let coordinator = lifecycleCoordinator, - isCurrentSignIn(coordinator.owner), let profileID = lifecycleProfileID, - profileID == workspaceAgentID { - if destination == .sessionMaintenance { - coordinator.sessionMaintenanceView(profileID: profileID) - } else { - coordinator.profileLifecycleView(selectedProfileID: profileID) - } + if destination == .logs { + if let connections = workspaceConnections, let owner = currentWorkspaceOwner, + connections.owner == owner, let workspace = connections.workspace, + workspace.owner == owner, let direct = connections.hosts.selectedWorkspace?.nativeClient { + HermesLogsDestinationView(hostName: workspaceHostName, owner: owner, + http: direct, workspace: workspace, currentOwner: { + guard connections.workspace === workspace else { return nil } + return currentWorkspaceOwner + }) + .id(owner) + } else { + WorkspaceUnavailableView(destination: .logs, hostName: workspaceHostName, + reason: "Logs require an available direct authenticated Hermes connection.") + } + } else if destination == .voice { + VoiceSettingsView(settings: settings, agents: agents.profiles, + selectedAgentID: workspaceAgentID, + client: voiceSettingsClient, scope: voiceSettingsScope, + isCurrent: voiceSettingsIsCurrent) + } else if destination == .permissions { + PermissionsSettingsView(center: permissionCenter) + } else if destination == .sessionMaintenance || destination == .profileLifecycle { + if let coordinator = lifecycleCoordinator, + isCurrentSignIn(coordinator.owner), let profileID = lifecycleProfileID, + agents.profiles.contains(where: { $0.id == profileID }) { + if destination == .sessionMaintenance { + coordinator.sessionMaintenanceView(profileID: profileID) } else { - WorkspaceUnavailableView(destination: destination, hostName: workspaceHostName, - reason: "Reopen this feature for the selected host and profile.") + coordinator.profileLifecycleView(selectedProfileID: profileID) } - } else if let kind = CapabilitiesManagementKind(destination: destination), opensNativeCapabilities(kind) { - nativeCapabilitiesDestination(kind, destination: destination) - } else if opensHostAdministration(destination) { - hostAdministrationDestination(destination) - } else if let managementStore { - WorkspaceManagementView(store: managementStore, destination: destination, - onOpenExisting: openWorkspaceDestination) } else { WorkspaceUnavailableView(destination: destination, hostName: workspaceHostName, - reason: "This feature requires an available native host connection.") + reason: "Reopen this feature for the selected host and profile.") } + } else if let kind = CapabilitiesManagementKind(destination: destination), opensNativeCapabilities(kind) { + nativeCapabilitiesDestination(kind, destination: destination) + } else if opensHostAdministration(destination) { + hostAdministrationDestination(destination) + } else if let managementStore { + WorkspaceManagementView(store: managementStore, destination: destination, + onOpenExisting: openWorkspaceDestination) + } else { + WorkspaceUnavailableView(destination: destination, hostName: workspaceHostName, + reason: "This feature requires an available native host connection.") } case (.chat(let conversationID), .chat(let model)?): let switcher = chatSwitcherColumn(for: conversationID, agentID: model.memberIDs.count == 1 ? model.memberIDs.first : nil) + let newChat = newChatSlot(forChat: conversationID, model: model) ChatDestinationView( model: model, appState: appState, @@ -121,7 +116,6 @@ extension RootShellView { featureStore: featureStore, catalog: sessionCatalog, agents: agents, - agentEditorPresentation: chatAgentEditorPresentation(for: model), botModeRooms: botModeRooms, skillsAndTools: skillsAndTools, hermesWorkspaces: hermesWorkspaces, @@ -129,17 +123,15 @@ extension RootShellView { projectGitClient: projectGitClient, userIdentity: userIdentity, permissionCenter: permissionCenter, - selectedTab: appState.drawerSelectedTab, responseHapticsCoveredByRoot: isHomeDrawerPresented - || isHostStatusPresented - || isHermesWorkspacePresented || actionErrorMessage != nil, - onNewChat: { startNewChat(explicitAgentID: nil) }, + || isHostStatusPresented || actionErrorMessage != nil, + onNewChat: { openNewChat() }, onOpenProviderAccounts: { openWorkspaceDestination(.keys) }, onNewBotChat: botChatRestart(conversationID), onContinueInBranch: { continueInBranch(from: model, $0) }, consumesSendOnOpen: { appState.sendsDraftOnOpen.remove($0) != nil }, onEdgeAction: { performWorkspaceAction($0) }, - onOpenAgentSessions: { openAllSessions(filteredTo: $0) }, + onOpenAgentSessions: { openSessions(filteredTo: $0) }, onOpenApproval: { openApproval(request: $0) }, @@ -148,32 +140,28 @@ extension RootShellView { }, appearanceAuthority: currentWorkspaceOwner?.authority, hostFiles: codeFileLinks(sessionID: conversationID), - chatFolders: { chatFolders(for: model) } + chatFolders: { chatFolders(for: model) }, + newChat: newChat ) + // New chat's Worktrees sheet presents from its own chat: the root is covered. + .modifier(CodeSheetsIfShown(isShown: newChat != nil, root: self)) .environment(\.chatCardInteractions, cardInteractions(for: model)) - .environment(\.agentHomeChrome, homeChrome(forChat: conversationID)) + // Every chat is a pushed page: Back, the bot (its page) and ⋯. + .environment(\.agentHomeChrome, .pushedChat(onProfile: { openBotPage(fromChat: $0) })) .environment(\.chatDissolveTransition, chatDissolve) .environment(connectionKeeper) .bighelpSideColumn(screen, isShown: switcher != nil) { switcher } case (.scheduledTasks, .scheduledTasks(let store)?): - routeWithWorkspaceMenu { - ScheduledTasksView(store: store, agents: agents, onOpen: openScheduledTask) - } + ScheduledTasksView(store: store, agents: agents, onOpen: openScheduledTask) case (.scheduledTask(let id, let agentID), .scheduledTasks(let store)?): - routeWithWorkspaceMenu { - ScheduledTaskDetailView(store: store, taskID: id, agents: agents, agentID: agentID) - } + ScheduledTaskDetailView(store: store, taskID: id, agents: agents, agentID: agentID) case (.skillsAndTools, _): - routeWithWorkspaceMenu { - SkillsAndToolsCatalogView( - store: skillsAndTools, - agentID: agents.resolvedAgent(explicitID: nil)?.id ?? "default" - ) - } + SkillsAndToolsCatalogView( + store: skillsAndTools, + agentID: agents.resolvedAgent(explicitID: nil)?.id ?? "default" + ) case (.approval, .approval(let model)?): - routeWithWorkspaceMenu { - ApprovalDestinationView(model: model) - } + ApprovalDestinationView(model: model) case (.chat(let conversationID), nil) where appState.suspendedChat?.chatID == conversationID || featureStore.hasRetiredUnsentChat(id: conversationID): // An unsent chat on screen lost its session (Hermes dropped it while the app was away @@ -198,3 +186,14 @@ extension RootShellView { } } + +/// New chat's project sheets, only on the chat that is New chat: two chats in the stack must not +/// both present the same sheet. +private struct CodeSheetsIfShown: ViewModifier { + let isShown: Bool + let root: RootShellView + + func body(content: Content) -> some View { + if isShown { root.codeSheets(content) } else { content } + } +} diff --git a/Bighelp/App/RootFleet.swift b/Bighelp/App/RootFleet.swift index b963d476..9cc1398a 100644 --- a/Bighelp/App/RootFleet.swift +++ b/Bighelp/App/RootFleet.swift @@ -1,184 +1,16 @@ import SwiftUI -/// The all-hosts view: every agent on every host in one list. Lists come from -/// all hosts; opening anything first makes its host the selected one, and -/// screens that belong to one host (Settings, Projects…) ask which host. +/// Every computer in the one home (Settings › Your computers › Show every computer): the Bots and +/// Chats views list every computer's, and opening anything first makes its computer the one in use. extension RootShellView { - /// Bots mode wins: its home stays, and its Multi-gateway switch lists every host instead. - var fleetModeOn: Bool { settings.allHostsMode && fleet != nil && !settings.simpleBotsEnabled } + /// Every computer's bots and chats are on screen, and the other computers stay connected. + var showsEveryHost: Bool { settings.showsEveryComputer && fleet != nil } - /// Bots mode's home lists every host's bots. - var simpleBotsMultiGatewayOn: Bool { - settings.simpleBotsEnabled && settings.simpleBotsMultiGateway && fleet != nil - } - - /// Every host's data is on screen: the all-hosts view, or Bots mode's Multi-gateway. - var showsEveryHost: Bool { fleetModeOn || simpleBotsMultiGatewayOn } - - func setAllHostsMode(_ on: Bool) { - settings.allHostsMode = on - fleetFocus = nil - fleetChatsFilter = FleetChatsFilter() - appState.chatOpenedFromList = false - appState.select(.sessions) - if on { - recordLiveFleet() - fleet?.refresh() - } else if opensHomeChat { - openHomeChat(replacing: true) - } - } - - /// ☰'s host row, with the all-hosts switch beside it. While all hosts show, picking a - /// computer narrows the lists to it and works on it, without leaving all hosts; the - /// switch beside it shows one computer again. - var fleetMenuHosts: BighelpMenuHosts { - var hosts = BighelpMenuHosts.current(registry: hostRegistry, demoHosts: demoHosts) - guard let fleet else { return hosts } - let isOn = fleetModeOn - if isOn { - // The same computers as the all-hosts chips, the focused one marked. - hosts.hosts = fleet.hosts.map { .init(id: $0.id.uuidString, name: $0.name, isSelected: $0.id == fleetFocus) } - hosts.select = { id in focusFleet(UUID(uuidString: id)) } - } - hosts.allHosts = .init(isOn: isOn, isFocused: fleetFocus != nil, - showAll: { focusFleet(nil) }, toggle: { setAllHostsMode(!isOn) }) - return hosts - } - - /// Narrows every all-hosts list to one computer (nil: all of them). On All sessions the - /// computer becomes the working one, so its own Sessions screen can show. - func focusFleet(_ hostID: UUID?) { - fleetFocus = hostID - fleetChatsFilter = FleetChatsFilter(app: fleetChatsFilter.app) - if appState.path.last == .allHostsChats { workOnFocusedFleetHost() } - } - - /// The focused computer becomes the working one (where its own screens open), staying in all hosts. - func workOnFocusedFleetHost() { - guard let fleet, fleetModeOn, let hostID = fleetFocus, hostID != fleet.selectedHostID, - fleet.canOpen(hostID) else { return } - recordLiveFleet() - fleet.select(hostID) - } - - // MARK: Places that look the same in either mode - - /// Every chat: every computer's while all show, else this computer's Sessions list. - func openAllSessions(filteredTo agentID: String? = nil) { - guard fleetModeOn else { - openSessions(filteredTo: agentID) - return - } - fleetChatsFilter = FleetChatsFilter( - agentID: agentID.flatMap { id in fleet?.selectedHostID.map { FleetID.make($0, id) } }) - openFleetChats() - } - - /// The agents: All agents while all computers show, else this computer's Agents. - func openAgentsList() { - if fleetModeOn { - appState.chatOpenedFromList = false - appState.select(.sessions) - } else { - appState.select(.agents) - } - } - - /// Settings belongs to one computer: while all show, the focused one, or ask which. - /// Settings is a quick screen: a sheet over where you are. Back steps through its - /// pages and Done closes it. With several computers, All hosts asks which first. - func openSettingsPage() { - if fleetModeOn { fleetGate(.settings) } else { isUnifiedSettingsPresented = true } - } - - /// A one-computer page (Projects, Kanban, Workflows) over the all-hosts list it was - /// opened from, so Back goes there again. - func showOneHostPage(_ routes: [AppRoute]) { - let base = fleetModeOn ? Array(appState.path.prefix { $0.isAllHosts }) : [] - appState.path = base + routes - } - - /// One host's pages on the Sessions tab; from another tab, after the switch - /// (`AppState.select(_:thenOpen:)`). - func showOneHostPageOnSessions(_ routes: [AppRoute]) { - // A long-stay page (Projects, Kanban, Workflows) is a screen of its own with ☰, and so is - // anything pinned to the bottom bar. What opens on it (a workflow, a run) slides in with Back. - if let first = routes.first, let tab = Self.pinnableTab(first), tab.isLongStay || barTabs.contains(tab) { - appState.select(tab, thenOpen: Array(routes.dropFirst())) - return - } - if appState.selectedTab != .sessions { - appState.select(.sessions, thenOpen: routes) - } else { - showOneHostPage(routes) - } - } - - /// The tab a page becomes when it's pinned to the bottom bar. - static func pinnableTab(_ route: AppRoute) -> AppTab? { - switch route { - case .projects: .projects - case .kanban: .kanban - case .workflows: .workflows - case .usage: .usage - default: nil - } - } - - /// ☰'s destinations while all hosts show: lists span hosts, and a screen - /// that belongs to one host asks which. - var fleetMenuDestinations: BighelpMenuDestinations { - var destinations = menuDestinations - destinations.onAllAgents = { afterClosingHomeSheets { appState.chatOpenedFromList = false; appState.select(.sessions) } } - destinations.newChatTitle = "New chat" - destinations.onNewChat = { afterClosingHomeSheets { isFleetNewChatPresented = true } } - destinations.onAllChats = { afterClosingHomeSheets { openAllSessions() } } - destinations.onAgents = { afterClosingHomeSheets { fleetGate(.agents) } } - destinations.onSettings = { afterClosingHomeSheets { fleetGate(.settings) } } - // Every host's tasks in one list. - destinations.onScheduledTasks = { afterClosingHomeSheets { - _ = featureStore.prepareScheduledTasks(filteredTo: nil) - appState.chatOpenedFromList = false - appState.openScheduledTasks() - } } - // Projects and Kanban belong to one computer: the focused one, or ask which. - destinations.onProjects = canOpenProjects ? { afterClosingHomeSheets { fleetGate(.projects) } } : nil - destinations.onKanban = canOpenKanban ? { afterClosingHomeSheets { fleetGate(.kanban) } } : nil - // Workflows ask which computer, then open that one's. - destinations.onWorkflows = { afterClosingHomeSheets { fleetGate(.workflows) } } - // Usage covers every host while all show; no host to pick. - if let folder = destinations.folder { - destinations.folder = (name: folder.name, open: { afterClosingHomeSheets { fleetGate(.folder) } }) - } - return destinations - } - - func openFleetChats() { - if appState.selectedTab != .sessions { appState.select(.sessions) } - appState.path = [.allHostsChats] - // A computer picked on All agents opens its own Sessions here too. - workOnFocusedFleetHost() - } - - // MARK: Opening across hosts - - /// An agent tapped on the all-hosts Agents list, on its own computer: what - /// Settings › Chat › A bot opens asks for, as `openAgentChat` does. - func openFleetAgent(_ agent: FleetAgent) { - switch settings.botChatExperience { - case .botChat: - openFleet(.agent(profileID: agent.profileID), on: agent.hostID) - case .lastChat: - if let chat = fleet?.latestChat(for: agent) { openFleetChat(chat) } else { startFleetChat(with: agent) } - case .newChat: - startFleetChat(with: agent) - } - } + // MARK: Opening across computers /// An agent from a widget, Shortcut or link: its Bot Chat, or with `startsVoice` /// its Bot Chat in voice. A link naming another computer switched there first - /// (`holdsLinkForItsComputer`); no agent is the home agent. + /// (`holdsLinkForItsComputer`). The primary bot stays who it is. func openIncomingAgentChat(agentID: String?, hostID: UUID?, startsVoice: Bool = false) { let place = hostID.flatMap { id in fleet?.hosts.first { $0.id == id }?.name } ?? "this computer" Task { @MainActor in @@ -191,14 +23,13 @@ extension RootShellView { return } guard startsVoice else { - performFleetOpen(.agent(profileID: agent.id)) + openCanonicalAgentChat(agent.id) return } VoiceLaunchState.shared.update(agent: .init(id: agent.id, name: agent.name, imageURL: agents.avatarURL(for: agent))) - // Voice talks with the agent on its home chat, like tapping it on home. - if homeAgent?.id != agent.id { agents.select(agent.id) } - openCanonicalAgentChat(agent.id, fromList: false, startsVoice: true) + // Voice talks with the bot in its own Bot Chat. + openCanonicalAgentChat(agent.id, startsVoice: true) } } @@ -207,65 +38,7 @@ extension RootShellView { appSessionID: chat.appSessionID), on: chat.hostID) } - func openFleetTask(_ task: FleetTask) { - openFleet(.task(jobID: task.jobID, profileID: task.profileID), on: task.hostID) - } - - func startFleetChat(with agent: FleetAgent) { - openFleet(.newChat(profileID: agent.profileID), on: agent.hostID) - } - - /// A group chat's actions from the all-hosts list. Renaming and deleting - /// act on the selected host, the way the Agents screen does them. - func performFleetGroupAction(_ group: FleetGroup, _ action: FleetGroupAction) { - guard case .open = action else { - guard group.hostID == fleet?.selectedHostID, let owner = currentWorkspaceOwner else { return } - switch action { - case .rename(let name): - handleAgentWorkspaceAction(.init(owner: owner, action: .renameGroup(roomID: group.roomID, name: name))) - case .delete: - handleAgentWorkspaceAction(.init(owner: owner, action: .deleteGroup(roomID: group.roomID))) - case .open: break - } - return - } - openFleet(.group(roomID: group.roomID), on: group.hostID) - } - - /// A group chat with the agents picked in New chat. They're all on one - /// host; that host becomes the selected one first. - /// The first agent's computer is the group's home; agents on other - /// computers join it through their own computers. - func startFleetGroupChat(with agents: [FleetAgent]) { - guard let hostID = agents.first?.hostID, let fleet else { return } - let peers = agents.filter { $0.hostID != hostID }.map { - HermesBotModePeerCandidate(hostID: $0.hostID.uuidString, hostName: fleet.hostName($0.hostID), - profileID: $0.profileID, name: $0.name) - } - openFleet(.newGroup(profileIDs: agents.filter { $0.hostID == hostID }.map(\.profileID), peers: peers), on: hostID) - } - - func fleetHome(_ fleet: FleetStore) -> FleetHomeView { - FleetHomeView(fleet: fleet, onOpen: { openFleetAgent($0) }, onNewChat: { isFleetNewChatPresented = true }, - onSetPinned: { setFleetPin($0, $1) }, onGroupAction: { performFleetGroupAction($0, $1) }, - onOpenRoutines: { openFleet(.routines(profileID: $0.profileID), on: $0.hostID) }, - onNewAgent: { fleetGate(.newAgent) }, onOpenChat: { openFleetChat($0) }, - hostFilter: fleetFocusBinding) - } - - var fleetFocusBinding: Binding { - Binding(get: { fleetFocus }, set: { focusFleet($0) }) - } - - /// All sessions while every computer shows. A picked computer gets its own Sessions screen. - func fleetChats(_ fleet: FleetStore) -> FleetChatsView { - FleetChatsView(fleet: fleet, hostFilter: fleetFocusBinding, filter: $fleetChatsFilter, - onOpen: { openFleetChat($0) }, hostSessions: { fleetHostSessions($0) }, - otherApps: otherAppChats, onOpenOtherApp: { openFleetOtherAppChat($0) }, - onChange: { changeFleetChat($0, $1) }) - } - - /// A chat's Rename or Archive from All sessions. On the selected computer it goes + /// A chat's Rename or Archive from Chats. On the selected computer it goes /// through its sessions, as on its own Sessions screen; on another, straight to it. func changeFleetChat(_ chat: FleetChat, _ change: FleetChatChange) { guard let fleet else { return } @@ -296,44 +69,6 @@ extension RootShellView { } } - /// A chat still in Codex or Claude Code: its computer's own Sessions screen - /// opens (staying in all hosts) and shows it, ready to bring in. - func openFleetOtherAppChat(_ chat: FleetOtherAppChat) { - guard let fleet else { return } - guard chat.hostID == fleet.selectedHostID || fleet.canOpen(chat.hostID) else { - actionErrorMessage = "\(fleet.hostName(chat.hostID)) can't be opened from here." - return - } - requestedOtherAppChat = chat.item - focusFleet(chat.hostID) - } - - /// The focused computer's Sessions screen, as one-computer mode shows it, once it's the - /// working computer and connected. - private func fleetHostSessions(_ hostID: UUID) -> AnyView? { - guard hostID == fleet?.selectedHostID, isFleetHostReady else { return nil } - if case .sessions(let model)? = featureStore.preparedModel(for: .sessions) { - return AnyView(oneHostSessions(model)) - } - return AnyView(ProgressView("Loading sessions") - .frame(maxWidth: .infinity, maxHeight: .infinity) - .task { _ = featureStore.prepareSessions(filteredTo: nil) }) - } - - /// Settings, Projects and other one-host screens: on the focused computer, else with - /// several, ask which one first; with one, just open it. - func fleetGate(_ destination: FleetDestination) { - guard let fleet, fleetModeOn, fleet.hosts.count > 1 else { - performFleetOpen(.destination(destination)) - return - } - if let focus = fleetFocus, fleet.hosts.contains(where: { $0.id == focus }), fleet.canOpen(focus) { - openFleet(.destination(destination), on: focus) - return - } - fleetGateRequest = destination - } - /// Opens now on the selected host; otherwise switches hosts and opens /// once that host's connection is ready. func openFleet(_ open: FleetOpen, on hostID: UUID) { @@ -343,50 +78,67 @@ extension RootShellView { return } guard fleet.canOpen(hostID) else { + _ = home.takeNewChatHandoff(after: .refused) actionErrorMessage = "\(fleet.hostName(hostID)) is a sample host in this demo." return } recordLiveFleet() let previous = fleet.selectedHostID + // The tab stays: what opens is pushed over it on the other computer, so Back goes there. fleet.pendingOpen = FleetPendingOpen(hostID: hostID, open: open, returnHostID: previous) - appState.chatOpenedFromList = false - // An all-hosts list stays under what opens, so Back goes there again. - let onAllHostsList = appState.path.first?.isAllHosts == true - || (appState.path.isEmpty && [.sessions, .scheduledTasks].contains(appState.selectedTab)) - if !onAllHostsList { appState.select(.sessions) } fleet.select(hostID) returnIfFleetHostDoesNotAnswer(hostID, previous: previous) } - /// Cancel on Multi-gateway's loader: back to the computer the tap came from. + /// The header's computer menu on Today and Work: that computer becomes the one in use, with + /// nothing to open there. One that doesn't answer gives the selection back, as a tapped bot's + /// computer does, so neither the app nor its next launch is left on it. + func selectFleetHost(_ hostID: UUID) { + guard let fleet, hostID != fleet.selectedHostID else { return } + recordLiveFleet() + let previous = fleet.selectedHostID + // A tap that waited for another computer is given up: the person picked this one. + fleet.pendingOpen = nil + _ = home.takeNewChatHandoff(after: .cancelled) + fleet.select(hostID) + returnIfFleetHostDoesNotAnswer(hostID, previous: previous, opensSomething: false) + } + + /// Cancel on the opening loader: back to the computer the tap came from. func cancelPendingFleetOpen() { guard let fleet, let pending = fleet.pendingOpen else { return } fleet.pendingOpen = nil + _ = home.takeNewChatHandoff(after: .cancelled) if let back = pending.returnHostID, fleet.selectedHostID == pending.hostID { fleet.select(back) } } /// A tapped agent's computer that doesn't answer gives the selection back to the one that /// worked, so the app (and its next launch) isn't left on a computer that's down, and - /// Multi-gateway's "Connecting to…" line ends. The one that worked stays connected while - /// every host shows, so going back is at once. - private func returnIfFleetHostDoesNotAnswer(_ hostID: UUID, previous: UUID?) { + /// the opening loader ends. The one that worked stays connected while + /// every host shows, so going back is at once. `opensSomething`: a tap waits for this computer + /// (`pendingOpen`), and it is ready once that can open. Without one (the header's computer + /// menu) the wait is for the computer alone, and a connection is enough. + private func returnIfFleetHostDoesNotAnswer(_ hostID: UUID, previous: UUID?, opensSomething: Bool = true) { guard let fleet, let previous, previous != hostID else { return } + // With nothing to open, "still waited for" is "still the computer in use". + let waitedFor: @MainActor () -> UUID? = { opensSomething ? fleet.pendingOpen?.hostID : hostID } Task { @MainActor in // Selecting it starts its connection; this makes sure an attempt runs now. await nativeWorkspaceStore?.reconnect() let wait = BighelpShortcutConnectionWait.Host( - isWanted: { FleetSwitchFallback.isWaiting(for: hostID, pending: fleet.pendingOpen?.hostID, + isWanted: { FleetSwitchFallback.isWaiting(for: hostID, pending: waitedFor(), selected: fleet.selectedHostID) }, isConnecting: { nativeWorkspaceStore?.isConnecting == true }, isConnected: { nativeWorkspaceStore?.isConnected == true }, - isReady: { isFleetHostReady }, + isReady: { opensSomething ? isFleetHostReady : true }, synchronize: {}) let ready = (try? await BighelpShortcutConnectionWait.untilReady(wait, timeout: FleetSwitchFallback.timeout)) ?? false guard FleetSwitchFallback.shouldReturn(ready: ready, waitingFor: hostID, - pending: fleet.pendingOpen?.hostID, + pending: waitedFor(), selected: fleet.selectedHostID) else { return } fleet.pendingOpen = nil + _ = home.takeNewChatHandoff(after: .unanswered) fleet.select(previous) actionErrorMessage = FleetSwitchFallback.message(unreachable: fleet.hostName(hostID), stillOn: fleet.hostName(previous)) @@ -402,8 +154,8 @@ extension RootShellView { guard let fleet, let pending = fleet.pendingOpen, pending.hostID == fleet.selectedHostID, isFleetHostReady else { return } fleet.pendingOpen = nil - // Bots mode: the chat's own opening loader takes over from the gateway's, with no gap. - simpleBotsChatOpening.showsNextAtOnce = simpleBotsOn + // The chat's own opening loader takes over from the computer's, with no gap. + simpleBotsChatOpening.showsNextAtOnce = true performFleetOpen(pending.open) simpleBotsChatOpening.showsNextAtOnce = false } @@ -439,17 +191,19 @@ extension RootShellView { } func performFleetOpen(_ open: FleetOpen) { + // New chat's text and To row, if they came with the switch. Taken whatever opens, so + // nothing else ever starts with them later. + let handoff = home.takeNewChatHandoff(after: .opened) switch open { case .agent(let profileID): - agents.select(profileID) - openCanonicalAgentChat(profileID, fromList: true) + openAgentChat(profileID) case .newChat(let profileID): - agents.select(profileID) - if appState.selectedTab != .sessions { appState.select(.sessions) } - appState.chatOpenedFromList = true - startNewChat(explicitAgentID: profileID) + // New chat's pick of a bot on this computer came with the switch: its text and its To row. + if let text = handoff?.text, !text.isEmpty { appState.leaveComposerText(text) } + startNewChat(explicitAgentID: profileID, tracksNewChat: handoff?.followsPick == true, + // The chat is made: the box the text came from lets it go. + opened: { _ in handoff?.delivered() }) case .chat(let profileID, let storedSessionID, let appSessionID): - appState.chatOpenedFromList = true if let appSessionID, let record = sessionCatalog.session(id: appSessionID) { openSessionSelection(record.summary) } else if let record = sessionCatalog.records.first(where: { @@ -465,7 +219,7 @@ extension RootShellView { } catch is CancellationError { } catch { actionErrorMessage = "This chat couldn't be opened. " - + (HermesRefusalMessage.sentence(in: error) ?? "Try again from All sessions.") + + (HermesRefusalMessage.sentence(in: error) ?? "Try again from Chats.") } } } @@ -476,36 +230,27 @@ extension RootShellView { guard let owner = currentWorkspaceOwner else { return } handleAgentWorkspaceAction(.init(owner: owner, action: .openGroupSettings(roomID: roomID))) case .newGroup(let profileIDs, let peers): - createGroupChat(with: profileIDs, peers: peers) + let session = newChatSession + createGroupChat(with: profileIDs, peers: peers, firstMessage: handoff?.text) { openedID in + session.groupEnded() + // The group chat has the text: the box it came from lets it go. + if openedID != nil { handoff?.delivered() } + } case .routines(let profileID): - if simpleBotsOn { openSimpleBotRoutines(profileID) } else { openScheduledTasks(filteredTo: profileID) } + openScheduledTasks(filteredTo: profileID) case .botProfile(let profileID): appState.open(.simpleBotProfile(agentID: profileID)) case .task(let jobID, let profileID): - if appState.selectedTab != .scheduledTasks { appState.select(.scheduledTasks) } + // The bot's routines, and the task over them. + openScheduledTasks(filteredTo: profileID) openPrepared(.scheduledTask(id: jobID, agentID: profileID)) - case .destination(let destination): - switch destination { - case .settings: isUnifiedSettingsPresented = true - case .agents: appState.select(.agents) - case .newAgent: - // That computer's Agents screen opens its new-agent editor once it's connected. - agentCreateRequest = true - appState.select(.agents) - case .projects: - if canOpenProjects { openProjects() } else { actionErrorMessage = "Projects aren't available on this host." } - case .kanban: - if canOpenKanban { openKanban() } else { actionErrorMessage = "Kanban isn't set up on this host." } - case .workflows: openWorkflows() - case .folder: presentHermesWorkspaces() - } } } // MARK: The selected host's live data - /// What changes the selected host's part of the list. Nil when the - /// all-hosts view is off, so nothing is computed then. + /// What changes the selected host's part of the lists. Nil unless every computer shows, so + /// nothing is computed then. struct LiveFleetKey: Equatable { let hostID: UUID let agents: [AgentProfile] @@ -526,15 +271,6 @@ extension RootShellView { ) } - /// Pin or unpin from All agents: the selected host's agent list saves its - /// own pins (and its limit); the fleet saves another host's. - func setFleetPin(_ agent: FleetAgent, _ pinned: Bool) { - if agent.hostID == fleet?.selectedHostID { - guard pinned ? agents.pinAgent(agent.profileID) : agents.unpinAgent(agent.profileID) else { return } - } - fleet?.setPinned(agent, pinned) - } - func recordLiveFleet() { guard let fleet, let key = liveFleetKey else { return } let chats = key.chats.compactMap { summary -> FleetChat? in @@ -543,7 +279,8 @@ extension RootShellView { hostID: key.hostID, profileID: profileID, storedSessionID: sessionCatalog.session(id: summary.id)?.remoteStoredID ?? summary.id, appSessionID: summary.id, title: summary.title, preview: summary.preview, - updatedAt: summary.updatedAt, isActive: summary.isActive, origin: summary.origin + updatedAt: summary.updatedAt, isActive: summary.isActive, origin: summary.origin, + isPinned: summary.isPinned ) } let agentRows = key.agents.map { profile in @@ -571,82 +308,8 @@ extension RootShellView { } } -/// The all-hosts view's sheets: which host a one-host screen is for, and -/// whom to start a new chat with. -/// A choice runs once its sheet is gone, so the next screen can present. -struct FleetSheets: ViewModifier { - let fleet: FleetStore? - @Binding var gate: FleetDestination? - @Binding var isNewChatPresented: Bool - let onGate: (FleetDestination, UUID) -> Void - let onNewChat: (FleetAgent) -> Void - /// None when the selected host can't make group chats. - let onNewGroup: (([FleetAgent]) -> Void)? - /// Settings' own Appearance and Chat pages, for Fleet settings. - var appPage: ((SettingsMenuSection) -> AnyView)? - @State private var pickedHost: (destination: FleetDestination, hostID: UUID)? - @State private var pickedAgent: FleetAgent? - @State private var pickedGroup: [FleetAgent]? - - func body(content: Content) -> some View { - content - .bighelpSheet(item: $gate, onDismiss: { - guard let picked = pickedHost else { return } - pickedHost = nil - onGate(picked.destination, picked.hostID) - }) { destination in - if let fleet { - FleetHostPicker(fleet: fleet, destination: destination, appPage: appPage) { hostID in - pickedHost = (destination, hostID) - gate = nil - } - } - } - .bighelpSheet(isPresented: $isNewChatPresented, onDismiss: { - if let group = pickedGroup { - pickedGroup = nil - onNewGroup?(group) - } - guard let agent = pickedAgent else { return } - pickedAgent = nil - onNewChat(agent) - }) { - if let fleet { - FleetAgentPicker(fleet: fleet, onPick: { agent in - pickedAgent = agent - isNewChatPresented = false - }, onPickGroup: onNewGroup.map { _ in { agents in - pickedGroup = agents - isNewChatPresented = false - } }) - } - } - } -} - extension RootShellView { - /// The all-hosts view's own buttons: back to one host, and a new chat - /// with any agent. - @ToolbarContentBuilder - var fleetToolbar: some ToolbarContent { - ToolbarItem(placement: .topBarTrailing) { - // One bot: a tap goes back to one host. - Button { setAllHostsMode(false) } label: { - Image(BighelpGlyph.bot.assetName) - .resizable() - .renderingMode(.template) - .scaledToFit() - .frame(width: 22, height: 22) - .foregroundStyle(theme.action) - .bighelpToolbarIcon() - } - .bighelpIconLabel("Show one host") - .accessibilityHint("Shows the selected host's agents and chats again.") - .accessibilityIdentifier("fleet.toggle") - } - } - - /// The computers changed: the all-hosts view and widgets' Gateway choice follow. + /// The computers changed: the home's lists and widgets' Gateway choice follow. func syncFleetHosts() { guard let fleet else { return } fleet.syncHosts() @@ -661,7 +324,7 @@ extension RootShellView { } } -/// Keeps the all-hosts view current: the selected host's live data, a tap +/// Keeps every computer's lists current: the selected host's live data, a tap /// waiting for its host, the configured hosts, and no reads in the background. struct FleetHooks: ViewModifier { let liveKey: RootShellView.LiveFleetKey? @@ -690,8 +353,7 @@ struct FleetHooks: ViewModifier { } /// Sections made on another device (or in Hermes Desktop) that the gateway in use's own agents are -/// in, for Bots mode and the Agents screen, which read those agents live rather than from every -/// host's copies. +/// in, for the Bots view, which reads those agents live rather than from every host's copies. struct FleetSectionAdoption: ViewModifier { let placements: [AgentListPlacement] let adopt: ([AgentListPlacement]) -> Void diff --git a/Bighelp/App/RootFreshSession.swift b/Bighelp/App/RootFreshSession.swift index 957d1684..0a487e8b 100644 --- a/Bighelp/App/RootFreshSession.swift +++ b/Bighelp/App/RootFreshSession.swift @@ -39,7 +39,6 @@ extension RootShellView { withTransaction(instant) { appState.path.removeLast() if let record = sessionCatalog.session(id: id) { - appState.chatOpenedFromList = true openSession(record.summary) } else { actionErrorMessage = "This chat isn't available right now. Open it again from your chats." diff --git a/Bighelp/App/RootHome.swift b/Bighelp/App/RootHome.swift new file mode 100644 index 00000000..6b73f77d --- /dev/null +++ b/Bighelp/App/RootHome.swift @@ -0,0 +1,494 @@ +import SwiftUI + +// The one home: its three roots (Bots or Chats, Today, Work), their headers, the bar and the sidebar. +extension RootShellView { + /// The tab, the first tab's view and what New chat and Today hold, above every computer. + var home: HomeSelection { appState.home } + + // MARK: The bar and the headers + + /// A tab is a root: picking one closes whatever was pushed (the sidebar and ⌘1–⌘3 pick over a chat). + var tabSelection: Binding { + Binding(get: { appState.selectedTab }, set: { appState.select($0) }) + } + + /// The first place is named after the view the person opens on; Today's dot is Needs you. + var homeTabItems: [HomeTabItem] { + HomeTabItem.standard(view: settings.homeView, todayHasNew: !needsYouEntries.isEmpty) + } + + /// iPad at regular width has the slide-in panel, Mac and Vision Pro the column. iPhone has neither. + var sidebarIsAvailable: Bool { + BighelpPlatform.isMac || BighelpPlatform.usesTabOrnament || horizontalSizeClass == .regular + } + + /// What every root's header starts from: the person's circle, which opens Settings, and the + /// sidebar button where there's a sidebar. + func homeHeaderContext(title: String? = nil) -> HomeHeaderContext { + var context = HomeHeaderContext(personName: userIdentity.identity.displayName, + personImageURL: userIdentity.avatarURL(), + onOpenSettings: { isUnifiedSettingsPresented = true }) + context.title = title + if sidebarIsAvailable { context.onToggleSidebar = { isHomeDrawerPresented.toggle() } } + return context + } + + /// Bots | Chats, for this run; Settings › Chat › Opens on picks the one a launch starts on. + var homeViewSwitch: HomeViewSwitch { + HomeViewSwitch(current: home.view) { home.view = $0 } + } + + /// Today and Work show the computer in use: with two or more, the header switches it. A + /// computer that doesn't answer gives the selection back (`selectFleetHost`). + private var homeHeaderComputer: HomeHeaderComputer? { + let hosts = BighelpMenuHosts.current(registry: hostRegistry, demoHosts: demoHosts) + guard let name = hosts.hosts.first(where: \.isSelected)?.name else { return nil } + return HomeHeaderComputer(name: name, hosts: hosts.hosts, select: { id in + if fleet != nil, let hostID = UUID(uuidString: id), hostRegistry?.hosts.isEmpty == false { + selectFleetHost(hostID) + } else { + hosts.select(id) + } + }) + } + + @ViewBuilder + func homeRoot(_ tab: HomeTab) -> some View { + switch tab { + case .conversations: conversationsRoot + case .today: todayRoot + case .work: workRoot + } + } + + // MARK: Bots and Chats + + @ViewBuilder + var conversationsRoot: some View { + switch home.view { + case .bots: SimpleBotsHomeView(context: simpleBotsContext) + case .chats: ChatsInboxView(context: chatsInboxContext) + } + } + + private var chatsInboxContext: ChatsInboxContext { + var header = homeHeaderContext() + header.viewSwitch = homeViewSwitch + if let newGroupChatAction { + header.newItems = [.groupChat] + header.onNew = { _ in newGroupChatAction() } + } + let catalog = sessionCatalog + let features = featureStore + return ChatsInboxContext( + catalog: catalog, agents: agents, fleet: fleet, showsEveryComputer: showsEveryHost, + rooms: botModeRooms.catalogRooms, + codeSessionIDs: Set(codeHome?.sessions.map(\.id) ?? []), + activity: botChatActivity, activitySource: botChatActivitySource, + unsentDraft: { features.unsentDraft($0) }, + // Nothing says so while the keeper's quiet tries run. + isConnected: nativeWorkspaceStore == nil || connectionKeeper.state != .disconnected, + header: AnyView(HomeHeaderBar(context: header)), + onOpen: { openInboxChat($0) }, + onChange: { changeInboxChat($0, $1) }, + onRefresh: { try? await catalog.load(requireAuthoritativeRefresh: true) }, + onNewChat: { openNewChat() }, + onOpenArchived: { appState.openSettings(at: [.section(.chat)]) }, + onOpenThisComputer: { openSessions(filteredTo: nil) }) + } + + private func openInboxChat(_ target: ChatsInboxTarget) { + switch target { + case .session(let summary): openSessionSelection(summary) + case .fleetChat(let chat): openFleetChat(chat) + case .group(let group): openFleet(.group(roomID: group.roomID), on: group.hostID) + } + } + + /// A row's long-press change. The computer in use's chats change through its catalog; another + /// computer's go straight to it (rename and archive only: it keeps no pins or read state here). + private func changeInboxChat(_ row: ChatsInboxRow, _ change: ChatsInboxChange) { + switch row.source { + case .session(let summary): + if let roomID = summary.hostedRoomID, case .rename(let name) = change, let owner = currentWorkspaceOwner { + handleAgentWorkspaceAction(.init(owner: owner, action: .renameGroup(roomID: roomID, name: name))) + return + } + Task { @MainActor in + do { + switch change { + case .pin(let pinned): try await sessionCatalog.setSessionPinned(id: summary.id, pinned: pinned) + case .unread(let unread): try await sessionCatalog.setSessionUnread(id: summary.id, unread: unread) + case .rename(let title): try await sessionCatalog.renameSession(id: summary.id, title: title) + case .archive: try await sessionCatalog.archiveSession(id: summary.id) + } + } catch is CancellationError { + } catch { + actionErrorMessage = String(localized: "bighelp couldn't change this chat. Try again.") + } + } + case .fleetChat(let chat): + switch change { + case .rename(let title): changeFleetChat(chat, .rename(title)) + case .archive: changeFleetChat(chat, .archive) + case .pin, .unread: break + } + case .fleetGroup: + break + } + } + + /// The computer in use's own Sessions page, pushed from Chats: projects, imports from other + /// apps and one bot's chats. + @ViewBuilder + func sessionsDestination(_ model: SessionsModel?) -> some View { + if let model { + oneHostSessions(model) + } else { + ProgressView("Loading chats") + .frame(maxWidth: .infinity, maxHeight: .infinity) + .task { _ = featureStore.prepareSessions(filteredTo: nil) } + } + } + + /// Every bot the home lists: every computer's while they show, else the computer in use's. + var homeBots: [SimpleBotsBot] { + if let gateways = simpleBotsGateways { return gateways.bots.filter { !$0.isHidden } } + return agents.profiles.filter { $0.placement?.isHidden != true } + .map { SimpleBotsBot($0, imageURL: agents.avatarURL(for: $0)) } + } + + // MARK: Today + + private var spacesBridge: SpacesTodayBridge { SpacesTodayBridge { spacePage = $0 } } + + var todayRoot: some View { + let bridge = spacesBridge + let layout = home.todayLayout + return TodayView(context: todayContext(bridge)) + .onAppear { layout.ownedChanges = bridge.ownedChanges } + .task(id: scenePhase == .active) { + guard scenePhase == .active else { return } + await TodaySpacesModel.shared.watch() + } + .spacesDeleteConfirmation($deletingSpace, bridge: bridge, layout: layout) + .bighelpFullScreenCover(item: $spacePage) { item in + if let page = item.space.page { + // A space's page never sends a message. + HTMLAppScreen(app: page.card(title: item.space.title, description: item.space.description), + agentID: item.space.agentID, connection: TodaySpacesModel.shared.pageConnection(item), + send: { _ in throw SpacesError.other(code: nil) }) + } + } + } + + private func todayContext(_ bridge: SpacesTodayBridge) -> TodayContext { + var header = homeHeaderContext(title: String(localized: "Today")) + header.computer = homeHeaderComputer + header.trailing = AnyView(TodayEditButton(isEditing: $isEditingToday)) + let boards = todayBoardsContext + let shares = PendingShareCenter.shared + var context = TodayContext( + header: AnyView(HomeHeaderBar(context: header)), + needsYou: todayNeedsYou, + onOpenNeedsYou: { isNeedsYouPresented = true }, + pendingShares: shares.waitingCount > 0 + ? TodayPendingShares(count: shares.waitingCount, open: { shares.showList() }) : nil, + panels: [TodayBoardsPanel.descriptor] + bridge.descriptors(from: TodaySpacesModel.shared.items), + makePanel: { panel in + panel.kind == SpacesTodayBridge.kind ? bridge.panel(for: panel) + : AnyView(TodayBoardsPanel(context: boards, size: panel.size)) + }, + layout: home.todayLayout, isEditing: $isEditingToday, + onDeletePanel: { deletingSpace = $0 }, + activity: botChatActivity, activitySource: botChatActivitySource) + context.aboveGrid = AnyView(SpacesTodayNotes(notes: bridge.notes)) + // The box asks a bot on the computer in use for a space. Where that computer's plugin has + // no spaces, the note above says to update it, and the box would only lead to a dead end. + let computer = SpacesHost.current() + let lacksSpaces = computer.map { computer in + TodaySpacesModel.shared.statuses.contains { $0.scope == computer.scope && $0.phase == .needsPluginUpdate } + } ?? false + if !isEditingToday, !lacksSpaces { + context.belowGrid = AnyView(TodayCreateBox( + bots: computer?.bots ?? [], + primaryBotID: agents.primaryAgentID ?? agents.profiles.first(where: \.isDefault)?.id + ) { agentID, text in + appState.leaveComposerText(String(localized: "Make me a space for Today: \(text)")) + startNewChat(explicitAgentID: agentID) + }) + } + context.panelMenu = { bridge.menuItems(for: $0) } + return context + } + + /// The card's count and its first entry: who asks, and what kind of answer it waits for. + private var todayNeedsYou: TodayNeedsYouSummary? { + let entries = needsYouEntries + guard let first = entries.first else { return nil } + let profile = first.agent.flatMap { agent in agents.profiles.first { $0.id == agent.id } } + return TodayNeedsYouSummary(count: entries.count, agentID: first.agent?.id, botName: first.title, + line: first.kind.title, imageURL: profile.flatMap { agents.avatarURL(for: $0) }) + } + + var todayBoardsContext: TodayBoardsContext { + TodayBoardsContext( + store: home.todayBoards, bots: homeBots, shellBoard: agentBoard, + // The bot's own board, where the item opens in full. + onOpenItem: { agentID, item in openTodayBoard(item.kind, agentID: agentID) }, + onSeeAll: { kind, agentID in openTodayBoard(kind, agentID: agentID) }, + onAsk: { agentID, text in askSimpleBot(agentID, text, fillsBlanks: false) }) + } + + /// A bot's Feed, Ideas or Goals from outside (the Watch, a widget): Today, then its board. + func showOverToday(_ kind: AgentBoardItem.Kind, agentID: String?) { + appState.select(.today, thenOpen: [.board(kind, agentID: agentID)]) + } + + private func openTodayBoard(_ kind: AgentBoardItem.Kind, agentID: String?) { + let route = AppRoute.board(kind, agentID: agentID) + if appState.path.last != route { appState.open(route) } + } + + /// See all: every bot's Feed, Ideas or Goals, or one bot's board. + func todayBoardPage(_ kind: AgentBoardItem.Kind, agentID: String?) -> some View { + TodayBoardPage(context: todayBoardsContext, kind: kind, agentID: agentID, + makeBoardContext: { bot, store in + let id = bot.profileID + // The page has Back and the bot chips, so the board gets no buttons of its own. + return AgentBoardContext( + agentID: id, agentName: bot.name, imageURL: bot.imageURL, activity: .idle, store: store, + onProfile: { appState.open(.simpleBotProfile(agentID: id)) }, onSwitchAgent: {}, + onAsk: { askSimpleBot(id, $0, fillsBlanks: false) }, + onSend: { askSimpleBot(id, $0, fillsBlanks: false, sendsAtOnce: true) }, + onBlueprint: { askSimpleBot(id, $0, fillsBlanks: true) }) + }, + onBack: { [appState] in + if case .board? = appState.path.last { appState.path.removeLast() } + }) + } + + // MARK: Work + + var workRoot: some View { + var header = homeHeaderContext(title: String(localized: "Work")) + header.computer = homeHeaderComputer + return WorkView(context: workContext(header: AnyView(HomeHeaderBar(context: header)), projectID: nil)) + } + + /// Work filtered to one project, pushed: its pull requests, worktrees and Dev Factory in ⋯. + func workProjectPage(_ projectID: String) -> some View { + let store = codeHome + let actions = WorkProjectActions( + onPullRequests: { codeSheet = .pullRequests }, + onWorktrees: { codeSheet = .worktrees }, + onDevFactory: canOpenWorkflows ? { openDevFactory() } : nil, + openPullRequests: store?.git?.pullRequests.count ?? 0) + var context = workContext(header: nil, projectID: projectID) + context.projectActions = actions + return codeSheets(WorkView(context: context)) + .navigationTitle(store?.projects.first { $0.id == projectID }?.name ?? String(localized: "Project")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .topBarTrailing) { WorkProjectMenu(actions: actions) } } + // The sheets read the store's project. + .task(id: projectID) { await store?.selectProject(projectID) } + } + + private func workContext(header: AnyView?, projectID: String?) -> WorkContext { + var doors: [WorkDoor] = [] + if canOpenProjects { doors.append(WorkDoor(kind: .projects, open: { openProjects() })) } + if canOpenKanban { doors.append(WorkDoor(kind: .tasks, open: { openKanban() })) } + if canOpenWorkflows { + doors.append(WorkDoor(kind: .workflows, count: workflowsStore.map { $0.workflows.count }, + open: { openWorkflows() })) + } + if let schedules = featureStore.scheduledTasks { + doors.append(WorkDoor(kind: .schedules, count: schedules.tasks.isEmpty ? nil : schedules.tasks.count, + open: { openScheduledTasks(filteredTo: nil) })) + } + let scope = currentWorkspaceOwner?.cacheScopeID + return WorkContext( + header: header, projectID: projectID, + code: codeHome.flatMap { $0.scopeID == scope ? $0 : nil }, + codeStatus: CodeChatStatusReader(catalog: sessionCatalog, features: featureStore), + dashboard: featureStore.dashboardModel, + activity: botChatActivity, activitySource: botChatActivitySource, + workflows: workflowsStore, kanban: kanbanModel, schedules: featureStore.scheduledTasks, + agents: agents, + onOpen: { openWork($0) }, + doors: doors, + onRefresh: { await refreshWork() }, + connectionKey: [currentWorkspaceOwner?.connectionGeneration.uuidString ?? "none", + String(canOpenKanban), String(canOpenWorkflows)].joined(separator: "|")) + } + + /// Work reads every store it shows. Kanban's and Workflows' are made here too, where the computer + /// has them: before, only their own pages made them. + private func refreshWork() async { + prepareCodeHome() + if canOpenKanban, kanbanModel == nil, let service = makeKanbanService() { + kanbanModel = KanbanBoardModel(service: service, agents: kanbanAgents) + } + if canOpenWorkflows { prepareWorkflowsStore() } + await codeHome?.load() + await featureStore.dashboardModel.load() + await workflowsStore?.load() + if let kanbanModel { + if kanbanModel.snapshot == nil { await kanbanModel.start() } else { await kanbanModel.refresh() } + } + if let schedules = featureStore.scheduledTasks, schedules.loadState == .idle { await schedules.load() } + await nativeRuntime?.refreshActiveSessions() + } + + private func openWork(_ target: WorkTarget) { + switch target { + case .codeSession(let id), .chat(let id): + guard let record = sessionCatalog.session(id: id) else { + actionErrorMessage = "This chat isn't on this computer anymore." + return + } + openSessionSelection(record.summary) + case .codeChanges(let id): + appState.open(.codeChanges(sessionID: id)) + case .codeBatch(let id): + appState.open(.codeBatch(id: id)) + case .bot(let id): + openSimpleBotChat(id) + case .workflowRun(let id): + guard prepareWorkflowsStore() != nil else { return } + appState.open(.workflowRun(id: id)) + case .kanbanTask(let id): + openKanban(task: id) + case .scheduledTask(let task): + openPrepared(.scheduledTask(id: task.jobID, agentID: task.profileID)) + } + } + + /// A page of Work's (Projects, Kanban, Workflows, a task) from outside it (a link, a widget, an + /// alert, Needs you): Work, then the page, so Back goes to Work. + func showOverWork(_ routes: [AppRoute]) { + appState.select(.work, thenOpen: routes) + } + + // MARK: The sidebar + + /// iPad's slide-in panel and the Mac's and Vision Pro's column: the three places, recent chats + /// and what has no other door. + var homeSidebar: some View { + HomeSidebar(context: HomeSidebarContext( + items: homeTabItems, + selection: appState.path.isEmpty ? appState.selectedTab : nil, + onSelect: { tab in afterClosingHomeSheets { appState.select(tab) } }, + recent: sidebarRecentChats, + onSeeAll: { afterClosingHomeSheets { appState.select(.chats) } }, + more: sidebarLinks, + onNewChat: { afterClosingHomeSheets { openNewChat() } }, + onOpenSettings: { afterClosingHomeSheets { isUnifiedSettingsPresented = true } })) + } + + private var sidebarRecentChats: [HomeSidebarChat] { + let bots = homeBots + return sessionCatalog.recentSummaries(includeCronSessions: false).prefix(8).map { summary in + let members = summary.agentIDs.compactMap { id in bots.first { $0.profileID == id } } + let bot = summary.kind == .direct ? members.first : nil + let face: AnyView = if let bot { + AnyView(SimpleBotFace(agentID: bot.profileID, name: bot.name, imageURL: bot.imageURL, size: 30)) + } else { + AnyView(SimpleBotsGroupFace(members: members, size: 30)) + } + return HomeSidebarChat(id: summary.id, title: summary.title, + subtitle: bot?.name ?? String(localized: "Group chat"), face: face, + isUnread: summary.isUnread, updatedAt: summary.updatedAt, + open: { afterClosingHomeSheets { openSessionSelection(summary) } }) + } + } + + private var sidebarLinks: [HomeSidebarLink] { + var links: [HomeSidebarLink] = [] + let waiting = needsYouEntries.count + if waiting > 0 { + links.append(HomeSidebarLink(id: "needs-you", title: String(localized: "Needs you"), symbol: "hand.raised", + detail: "\(waiting)", showsDot: true, + action: { afterClosingHomeSheets { isNeedsYouPresented = true } })) + } + if let shared = pendingSharesMenuRow { + links.append(HomeSidebarLink(id: "shared", title: String(localized: "Shared with bighelp"), + symbol: "tray.and.arrow.down", detail: "\(shared.count)", showsDot: true, + action: shared.open)) + } + if usage.isAvailable { + links.append(HomeSidebarLink(id: "usage", title: String(localized: "Usage"), symbol: "chart.bar", + action: { afterClosingHomeSheets { showUsage() } })) + } + #if os(visionOS) + links.append(HomeSidebarLink(id: "simple-mode", title: String(localized: "Simple mode"), symbol: "figure.stand", + action: { SpatialSimpleMode.enter(spatialAvatar, openWindow: openWindow) })) + #endif + return links + } + + /// Runs `action` once the iPad's panel has closed, so what it opens can present. The Mac's and + /// Vision Pro's column stays, and with no panel open there's nothing to wait for. + func afterClosingHomeSheets(_ action: @escaping @MainActor () -> Void) { + guard isHomeDrawerPresented, !BighelpPlatform.isMac, !BighelpPlatform.usesTabOrnament else { + action() + return + } + afterHomeSheet = action + isHomeDrawerPresented = false + } + + func runAfterHomeSheet() { + let action = afterHomeSheet + afterHomeSheet = nil + action?() + } +} + +/// The home's places around its roots: the bar on iPhone, iPad and the Mac, the ornament on Vision Pro +/// and the side strip on the iPhone Duo. Only a root shows them: a pushed page has Back. Its own +/// modifier keeps the shell's body small enough to type-check. +struct HomeBars: ViewModifier { + /// Nothing is pushed over the root. + let isAtRoot: Bool + let isKeyboardVisible: Bool + let selection: Binding + let items: [HomeTabItem] + let onNewChat: () -> Void + let bottomInset: CGFloat + let selectedTint: Color + let tint: Color + + @Environment(\.bighelpScreen) private var screen + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private var showsBar: Bool { + isAtRoot && !isKeyboardVisible && !BighelpPlatform.usesTabOrnament && !screen.usesSideBar + } + + func body(content: Content) -> some View { + content + #if os(visionOS) + // Beside the window, not along its bottom edge by the close control. + .ornament(visibility: isAtRoot ? .visible : .hidden, + attachmentAnchor: .scene(.leading), contentAlignment: .trailing) { + HomeTabOrnament(selection: selection, items: items, onNewChat: onNewChat) + } + #endif + .safeAreaInset(edge: .bottom, spacing: 0) { + if showsBar { + HomeTabBar(selection: selection, items: items, onNewChat: onNewChat, + homeIndicatorSink: HomeTabBar.homeIndicatorSink(forBottomInset: bottomInset)) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } + } + // The iPhone Duo: the places go down the side strip with the screen's own buttons. + .toolbar { + if isAtRoot && !isKeyboardVisible && screen.usesSideBar { + HomeStripTabs(selection: selection, items: items, onNewChat: onNewChat, + selectedTint: selectedTint, tint: tint) + } + } + .animation(reduceMotion ? nil : .snappy(duration: BighelpTokens.transitionDuration), value: showsBar) + } +} diff --git a/Bighelp/App/RootKanban.swift b/Bighelp/App/RootKanban.swift index 1ff0bc18..e7245757 100644 --- a/Bighelp/App/RootKanban.swift +++ b/Bighelp/App/RootKanban.swift @@ -51,8 +51,9 @@ extension RootShellView { var canOpenKanban: Bool { kanbanAvailability.isAvailable == true } + /// Its page is open, or Work, which lists its cards. private var isKanbanPageOpen: Bool { - appState.selectedTab == .kanban || appState.path.contains { route in + appState.selectedTab == .work || appState.path.contains { route in if case .kanban = route { true } else { false } } } @@ -79,7 +80,7 @@ extension RootShellView { return } #endif - showOneHostPageOnSessions([.kanban]) + showOverWork([.kanban]) } @ViewBuilder @@ -92,7 +93,7 @@ extension RootShellView { .accessibilityIdentifier("kanban.connecting") } else { ContentUnavailableView("Kanban isn't available", systemImage: "rectangle.split.3x1", - description: Text("Connect to your computer, then open Kanban from the menu.")) + description: Text("Connect to your computer, then open Tasks from Work.")) } } } diff --git a/Bighelp/App/RootMarketplace.swift b/Bighelp/App/RootMarketplace.swift index e3d60886..0e3a57ba 100644 --- a/Bighelp/App/RootMarketplace.swift +++ b/Bighelp/App/RootMarketplace.swift @@ -119,22 +119,3 @@ extension RootShellView { currentOwner: current, actionStatusClient: status)) } } - -/// Makes the Marketplace once, when its page first shows, and keeps it while the page is on the -/// stack: `navigationDestination` builds its view again on every update. -struct MarketplaceHost: View { - let make: @MainActor () -> MarketplaceContext - - @State private var context: MarketplaceContext? - - var body: some View { - Group { - if let context { - MarketplaceView(context: context) - } else { - Color.clear - } - } - .onAppear { if context == nil { context = make() } } - } -} diff --git a/Bighelp/App/RootNavigationViews.swift b/Bighelp/App/RootNavigationViews.swift index ed224285..e2d5695b 100644 --- a/Bighelp/App/RootNavigationViews.swift +++ b/Bighelp/App/RootNavigationViews.swift @@ -1,49 +1,5 @@ import SwiftUI -@MainActor -struct AgentsShellView: View { - let agents: AgentDirectoryStore - let runtimeDefaultsClient: any AgentRuntimeDefaultsClient - let onSelect: (AgentProfile) -> Void - let onOpenSessions: (AgentProfile) -> Void - let onOpenHostStatus: () -> Void - let hostRuntime: HostRuntimeStore? - let workspaceOwner: WorkspaceOwner? - let capabilities: WorkspaceCapabilities - let botModeRooms: BotModeRoomStore - let cloneClient: (any AgentProfileCloneClient)? - let shortcutsAvailable: Bool - let onAction: @MainActor (AgentWorkspaceActionRequest) -> Void - var groupFilterRequest: Binding = .constant(nil) - var createRequest: Binding = .constant(false) - var botChatActivity: BotChatActivityStore? = nil - var botChatActivitySource: BotChatActivitySource? = nil - /// Bots mode's section cards, between Pinned and the rest. - var sectionCards: AnyView? = nil - - var body: some View { - AgentsView( - store: agents, - runtimeDefaultsClient: runtimeDefaultsClient, - onSelect: onSelect, - onOpenSessions: onOpenSessions, - onOpenHostStatus: onOpenHostStatus, - hostRuntime: hostRuntime, - workspaceOwner: workspaceOwner, - capabilities: capabilities, - botModeRooms: botModeRooms, - cloneClient: cloneClient, - shortcutsAvailable: shortcutsAvailable, - onAction: onAction, - groupFilterRequest: groupFilterRequest, - createRequest: createRequest, - botChatActivity: botChatActivity, - botChatActivitySource: botChatActivitySource, - sectionCards: sectionCards - ) - } -} - @MainActor struct ApprovalDestinationView: View { @State private var model: ApprovalModel @@ -68,21 +24,13 @@ struct ApprovalDestinationView: View { } -enum ConversationRootNavigationPresentation { - static let composeAccessibilityIdentifier = "root.new-chat" -} - -/// The Chats compose action: a large, tinted Liquid Glass circle that floats -/// over the list like the iMessage compose affordance, instead of a small -/// toolbar glyph. +/// New chat beside the home's bar: a large, tinted Liquid Glass circle, like the iMessage compose +/// button, instead of a small toolbar glyph. struct RootComposeButton: View { static let diameter: CGFloat = 60 - var identifier = ConversationRootNavigationPresentation.composeAccessibilityIdentifier + let identifier: String var systemImage = "square.and.pencil" - /// Bigger where it's the screen's one main action (All agents). var size: CGFloat = RootComposeButton.diameter - /// Touch and hold (right-click on the Mac): the picker, for another agent or a group. - var onLongPress: (() -> Void)? let action: () -> Void @BighelpThemeReader private var theme @@ -90,33 +38,12 @@ struct RootComposeButton: View { @ScaledMetric(relativeTo: .title2) private var glyph: CGFloat = 24 @State private var taps = 0 - @ViewBuilder var body: some View { - if let onLongPress { - // A tap and a hold on one control: as gestures, so the hold never also counts as a tap. - glyphCircle - .onTapGesture(perform: tap) - .onLongPressGesture(minimumDuration: 0.4) { - BighelpHaptics.tap() - onLongPress() - } - .newChatRightClickMenu(startTitle: String(localized: "New chat"), start: tap, pick: onLongPress) - .bighelpHover(in: Circle()) - .sensoryFeedback(.impact(weight: .light), trigger: taps) - .accessibilityElement() - .accessibilityAddTraits(.isButton) - .bighelpIconLabel("New chat", shortcut: "⌘N") - .accessibilityHint(NewChatButtonCopy.pickHint) - .accessibilityAction { tap() } - .accessibilityAction(named: "Pick agents") { onLongPress() } - .accessibilityIdentifier(identifier) - } else { - Button(action: tap) { glyphCircle } - .bighelpPointerButtonStyle(BighelpPressFeedbackStyle(), outline: .circle) - .sensoryFeedback(.impact(weight: .light), trigger: taps) - .bighelpIconLabel("New chat", shortcut: "⌘N") - .accessibilityIdentifier(identifier) - } + Button(action: tap) { glyphCircle } + .bighelpPointerButtonStyle(BighelpPressFeedbackStyle(), outline: .circle) + .sensoryFeedback(.impact(weight: .light), trigger: taps) + .bighelpIconLabel("New chat", shortcut: "⌘N") + .accessibilityIdentifier(identifier) } private var glyphCircle: some View { diff --git a/Bighelp/App/RootNeedsYou.swift b/Bighelp/App/RootNeedsYou.swift index 7d450907..503f4dce 100644 --- a/Bighelp/App/RootNeedsYou.swift +++ b/Bighelp/App/RootNeedsYou.swift @@ -58,17 +58,14 @@ extension RootShellView { currentConversationID: { appState.chatOnScreen }, entries: { needsYouEntries }, openConversation: { conversationID in - if let record = sessionCatalog.session(id: conversationID) { - appState.chatOpenedFromList = true - openSession(record.summary) - } + if let record = sessionCatalog.session(id: conversationID) { openSession(record.summary) } }, openAgentChat: { agentID in - openCanonicalAgentChat(agentID, fromList: true) + openCanonicalAgentChat(agentID) }, openWorkflowSignoff: { runID in guard prepareWorkflowsStore() != nil else { return } - showOneHostPageOnSessions([.workflows, .workflowSignoff(runID: runID)]) + showOverWork([.workflows, .workflowSignoff(runID: runID)]) }, refresh: { // Both read what the app already has from the computer; neither asks an agent anything. @@ -93,12 +90,6 @@ extension RootShellView { NeedsYouRequestKey(isRequested: appState.isNeedsYouRequested, listIsReady: needsYouListIsReady) } - /// ☰'s Needs you row, only while something waits. - var menuNeedsYou: (count: Int, open: () -> Void)? { - let count = needsYouEntries.count - guard count > 0 else { return nil } - return (count: count, open: { afterClosingHomeSheets { isNeedsYouPresented = true } }) - } } struct NeedsYouRequestKey: Equatable { @@ -108,6 +99,6 @@ struct NeedsYouRequestKey: Equatable { enum NeedsYouRequest { /// How long a request waits for the computer's connection before it gives up and opens the - /// home chat (a cold launch from an alert can ask before the computer answers). + /// primary bot's chat (a cold launch from an alert can ask before the computer answers). static let connectionWait = Duration.seconds(10) } diff --git a/Bighelp/App/RootNewChat.swift b/Bighelp/App/RootNewChat.swift new file mode 100644 index 00000000..1ea2ce6b --- /dev/null +++ b/Bighelp/App/RootNewChat.swift @@ -0,0 +1,208 @@ +import SwiftUI + +// New chat: the round button beside the bar opens the new chat's own screen, which is the ordinary +// chat with a To row, the bots to pick from and, for one bot, the choices that make it a coding +// session (`ChatNewChatSlot`). One bot is a chat, two to six a group chat. +extension RootShellView { + var newChatSession: NewChatSession { home.newChat } + + /// The round button, ⌘N and the New chat swipe. Nobody is picked yet: the blank chat under the + /// To row is the primary bot's until a pick makes it another bot's. + func openNewChat() { + newChatSession.start() + startNewChat(explicitAgentID: nil, tracksNewChat: true) + } + + /// New chat's parts for its own blank chat, and nil for every other chat. Decided from the + /// chat's id, never from its messages: the chat stops drawing them once something is sent. + func newChatSlot(forChat id: String, model: ChatModel) -> ChatNewChatSlot? { + guard id == newChatSession.conversationID else { return nil } + let session = newChatSession + let context = newChatContext + let store = newChatCodeStore + // Send holds stores only, never this view: the message box keeps it while the chat is open. + let fleet = self.fleet, appState = self.appState + let relay = NewChatSendRelay( + session: session, model: model, store: store, + hostInUse: { fleet?.selectedHostID }, + showProject: { appState.select(.work, thenOpen: [.work(projectID: $0)]) }) + let bot = session.recipients.count == 1 ? session.recipients.first : nil + let choices: AnyView? = if let store, let bot { + AnyView(NewChatChoicesHost(model: model, session: session, store: store, agentID: bot.profileID, + onWorktrees: { codeSheet = .worktrees }, + onSendAll: { _ = relay.send(holdsReferences: false) })) + } else { + nil + } + let isBotsChat = bot.map { bot in + (bot.hostID == nil || bot.hostID == fleet?.selectedHostID) && model.memberIDs == [bot.profileID] + } ?? false + return ChatNewChatSlot( + toRow: AnyView(NewChatToRow(context: context)), + people: AnyView(NewChatPeopleList(context: context)), + choicesRow: choices, + sendOverride: { relay.send(holdsReferences: $0) }, + // A group chat's or a coding session's first message goes as text only. + offersAttachments: bot != nil && session.project == nil, + isOneBotsChat: isBotsChat) + } + + /// The computer in use's Code store, where it can start coding sessions. + private var newChatCodeStore: CodeHomeStore? { + guard let store = codeHome, store.scopeID == currentWorkspaceOwner?.cacheScopeID else { return nil } + return store + } + + private var newChatRules: NewChatGroupRules { + NewChatGroupRules(hostInUse: showsEveryHost ? fleet?.selectedHostID : nil, + canMakeGroups: botModeRooms.makesGroupChats, + seatableProfiles: botModeRooms.nativeCapabilities?.seatableProfiles) + } + + private var newChatContext: NewChatContext { + let bots = homeBots + let groups = simpleBotsGateways?.groups ?? SimpleBotsHomeProjection.groups( + sessionCatalog.recentSummaries(includeCronSessions: false), rooms: botModeRooms.catalogRooms, + hostID: nil, bots: bots) + return NewChatContext( + session: newChatSession, bots: bots, + hosts: showsEveryHost ? fleet?.hosts ?? [] : [], + groups: groups, rules: newChatRules, + activity: botChatActivity, activitySource: botChatActivitySource, + isLoading: bots.isEmpty && !agents.knowsProfiles && !usesWorkspaceFixtures, + onRecipientsChanged: { newChatRecipientsChanged($0) }, + onOpenGroup: { openNewChatGroup($0) }, + onSendRequest: { performNewChatRequest($0) }) + } + + /// The To row changed. One bot picked: the blank chat becomes that bot's, so the message box, + /// its model control and Send are its own. Text already typed goes with it. A bot on another + /// computer makes that computer the one in use first; the To row stays (`HomeSelection`). + /// `fromSend`: Send found the chat wasn't the picked bot's yet, so a wait is said in words. + private func newChatRecipientsChanged(_ recipients: [SimpleBotsBot], fromSend: Bool = false) { + let session = newChatSession + let blank = session.conversationID.flatMap { featureStore.preparedChatModel(id: $0) } + let pick = NewChatPick.decide(recipients: recipients, blankMembers: blank?.memberIDs, + hasFleet: fleet != nil, hostInUse: fleet?.selectedHostID) + if pick == .keep { return } + // Attachments and references can't move to another chat. The pick waits until they're out + // of the box, and the line under the To row says so. + if let blank, blank.holdsAttachmentsOrReferences { + session.show(.pickKeepsAttachments) + return + } + switch pick { + case .keep: + return + case .switchComputer(let hostID, let profileID): + home.handOffNewChat(NewChatHandoff(text: blank?.draft, followsPick: true, source: blank)) + openFleet(.newChat(profileID: profileID), on: hostID) + case .start(let profileID): + // Send moved nothing yet: the line says the bot's chat is on its way, and the text is + // in its box when it's there. + if fromSend { session.show(.starting) } + // One chat starts at a time. This pick gets its chat when the start under way ends + // (`newChatStartEnded`). + guard !isStartingNewChat else { + newChatPickGate.hold() + return + } + if let text = blank?.draft, !text.isEmpty { appState.leaveComposerText(text) } + startNewChat(explicitAgentID: profileID, tracksNewChat: true) + } + } + + /// A chat finished starting (`finishNewChatOpening`). A pick that came meanwhile gets its chat + /// now: the To row is read again, so the latest pick wins and the To row and the chat under it + /// agree. Not after a start that failed: its alert and Try Again stand, and Send asks again. + func newChatStartEnded() { + let session = newChatSession + if session.note == .starting, !session.isStartingGroup { session.show(nil) } + guard newChatPickGate.release(), actionErrorMessage == nil, + let blankID = session.conversationID, appState.path.last == .chat(conversationID: blankID), + featureStore.preparedChatModel(id: blankID)?.isBlankForNewChat != false else { return } + newChatRecipientsChanged(session.recipients) + } + + /// A group chat the person already has, picked at the bottom of the people list: it opens in + /// the blank chat's place. + private func openNewChatGroup(_ group: SimpleBotsGroup) { + if let hostID = group.hostID, let fleet, hostID != fleet.selectedHostID { + openFleet(.group(roomID: group.roomID), on: hostID) + } else if let summary = group.summary, summary.hostedRoomID == nil { + openSessionSelection(summary) + } else if let owner = currentWorkspaceOwner { + openHostedGroup(group.summary?.hostedRoomID ?? group.roomID, owner: owner, settings: false, + opened: { if let id = $0 { dropNewChatBlank(under: id) } }) + } else if group.summary != nil { + actionErrorMessage = "This group is no longer available on the selected host." + } + } + + /// What New chat's Send left for the shell (`NewChatSendRelay`, through the To row). + private func performNewChatRequest(_ request: NewChatRequest) { + switch request { + case .followPick: newChatRecipientsChanged(newChatSession.recipients, fromSend: true) + case .startGroup: startNewChatGroup(newChatSession.recipients) + } + } + + /// Two to six bots: a group chat on the first bot's computer, the others joining from theirs, + /// and the box's text as its first message. The box keeps the text until the group chat has it, + /// so a group chat that can't be made loses nothing. + private func startNewChatGroup(_ recipients: [SimpleBotsBot]) { + let session = newChatSession + let blank = session.conversationID.flatMap { featureStore.preparedChatModel(id: $0) } + let text = blank?.draft ?? "" + let rules = newChatRules + let parts = NewChatRecipients.split(recipients, rules: rules) + let peers = NewChatRecipients.peerCandidates(recipients, rules: rules) { fleet?.hostName($0) ?? "" } + let message = text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : text + if let home = parts.home.first?.hostID, let fleet, home != fleet.selectedHostID { + self.home.handOffNewChat(NewChatHandoff(text: message, followsPick: false, source: blank)) + openFleet(.newGroup(profileIDs: parts.home.map(\.profileID), peers: peers), on: home) + } else { + createGroupChat(with: parts.home.map(\.profileID), peers: peers, firstMessage: message) { [weak blank] openedID in + session.groupEnded() + guard let openedID else { return } + if let blank, blank.draft == text { blank.draft = "" } + dropNewChatBlank(under: openedID) + } + } + } + + /// The chat that takes New chat's place (a group chat) leaves no blank chat under it for Back. + /// Only New chat's own paths call this, and only a chat with nothing sent goes: a chat that + /// was New chat's and has a message stays on the stack, whatever opens over it. + func dropNewChatBlank(under conversationID: String) { + guard let blank = newChatSession.conversationID else { return } + appState.dropBlankChat(blank, under: conversationID, + isBlank: featureStore.preparedChatModel(id: blank)?.isBlankForNewChat == true) + } + + /// Pull requests and Worktrees for the Code store's project, over New chat or a project's Work. + func codeSheets(_ content: Content) -> some View { + content.bighelpSheet(item: $codeSheet) { sheet in + if let store = codeHome { codeSheetView(sheet, store: store) } + } + } +} + +/// New chat's choices row for the one picked bot. The message box's text shape is read here, so a +/// key redraws this small view and never the shell that built it. +private struct NewChatChoicesHost: View { + let model: ChatModel + let session: NewChatSession + let store: CodeHomeStore + let agentID: String + let onWorktrees: @MainActor () -> Void + let onSendAll: @MainActor () -> Void + + var body: some View { + NewChatChoicesRow(context: NewChatChoicesContext( + session: session, store: store, agentID: agentID, hasText: model.draftShape.hasText, + draft: { model.draft }, clearDraft: { model.draft = "" }, + onWorktrees: onWorktrees, onSendAll: onSendAll)) + .equatable() + } +} diff --git a/Bighelp/App/RootPendingShares.swift b/Bighelp/App/RootPendingShares.swift index 005d8fd7..b6b6e057 100644 --- a/Bighelp/App/RootPendingShares.swift +++ b/Bighelp/App/RootPendingShares.swift @@ -22,12 +22,11 @@ extension RootShellView { open: { share, destination, name in openPendingShare(share, at: destination, agentName: name) }, openChat: { id in guard let record = sessionCatalog.session(id: id) else { return } - appState.chatOpenedFromList = true openSession(record.summary) }) } - /// The same, from inside Bots mode's Settings: a chat opens once Settings has closed. + /// The same, from inside Settings: a chat opens once Settings has closed. var settingsPendingShareContext: PendingShareReviewContext { let context = pendingShareContext return PendingShareReviewContext( @@ -36,7 +35,7 @@ extension RootShellView { openChat: { id in leaveSettings { context.openChat(id) } }) } - /// ☰ › Shared with bighelp, while any share waits: every one, put off ones too. + /// The sidebar's Shared with bighelp, while any share waits: every one, put off ones too. var pendingSharesMenuRow: (count: Int, open: () -> Void)? { let center = PendingShareCenter.shared guard center.waitingCount > 0 else { return nil } @@ -77,7 +76,6 @@ extension RootShellView { if let record { appState.handOff(PendingShareHandoff(share: share, inbox: inbox, destination: destination, since: .now, onDropped: { center.release($0) })) - appState.chatOpenedFromList = true openSession(record.summary) return } diff --git a/Bighelp/App/RootPresentationContracts.swift b/Bighelp/App/RootPresentationContracts.swift index 9a41059c..d5a77e6a 100644 --- a/Bighelp/App/RootPresentationContracts.swift +++ b/Bighelp/App/RootPresentationContracts.swift @@ -37,9 +37,9 @@ enum SessionRestorePresentationPolicy { } static func canComplete( - originTab: AppTab, + originTab: HomeTab, originPath: [AppRoute], - currentTab: AppTab, + currentTab: HomeTab, currentPath: [AppRoute] ) -> Bool { currentTab == originTab && currentPath == originPath @@ -47,9 +47,9 @@ enum SessionRestorePresentationPolicy { static func ownsRestore( route: AppRoute, - originTab: AppTab, + originTab: HomeTab, originPath: [AppRoute], - currentTab: AppTab, + currentTab: HomeTab, currentPath: [AppRoute] ) -> Bool { canComplete( @@ -101,7 +101,7 @@ enum ProjectChangesTargetResolver { struct SessionRestoreRequest: Equatable { let token = UUID() let sessionID: String - let originTab: AppTab + let originTab: HomeTab let originPath: [AppRoute] } diff --git a/Bighelp/App/RootScheduledAlerts.swift b/Bighelp/App/RootScheduledAlerts.swift index 1e41e200..a5857544 100644 --- a/Bighelp/App/RootScheduledAlerts.swift +++ b/Bighelp/App/RootScheduledAlerts.swift @@ -12,13 +12,8 @@ extension RootShellView { /// A tapped scheduled task alert's job, where Scheduled tasks shows it with its runs. func openScheduledAlertTask(_ task: ScheduledTask) { - guard simpleBotsOn else { - performFleetOpen(.task(jobID: task.id, profileID: task.agentID)) - return - } - // Bots mode has no tab bar: the bot's routines open over its home, and the task over them. - openSimpleBotRoutines(task.agentID) - openPrepared(.scheduledTask(id: task.id, agentID: task.agentID)) + // The bot's routines open over where the person is, and the task over them. + performFleetOpen(.task(jobID: task.id, profileID: task.agentID)) } /// A tapped scheduled task alert whose job is gone, or whose job the phone can't find: the diff --git a/Bighelp/App/RootShellView.swift b/Bighelp/App/RootShellView.swift index 5fa258e1..dedcffd5 100644 --- a/Bighelp/App/RootShellView.swift +++ b/Bighelp/App/RootShellView.swift @@ -45,20 +45,14 @@ struct RootShellView: View { @State var actionErrorMessage: String? /// The tap (a Live Activity, an alert) whose new computer is still connecting; its timer runs once. @State private var externalOpenWaitID: UUID? - /// Feed, Ideas, Goals and Apps fold the bottom menu while scrolled down. - /// All hosts: the chat you left for Feed, Ideas or Goals, which the Chat tab goes back to. - @State var fleetLastChatID: String? @State var isHostStatusPresented = false @State private var actionErrorShowsHostStatus = false @State var hostRuntime: HostRuntimeStore? /// A widget or notification link that arrived before the host answered. @State private var pendingIncomingURL: URL? - /// Opens Agents filtered to one agent's group chats (from the Chats rail's menu). - @State var agentGroupFilterRequest: String? - @State var agentCreateRequest = false /// Offered as "Try Again" in the error alert. @State var actionErrorRetry: (@MainActor () -> Void)? - @State var isHermesWorkspacePresented = false + @State var sessionRestoreRequest: SessionRestoreRequest? @State var sessionRestoreTask: Task? @State var canonicalChatCoordinator = CanonicalChatCoordinator() @@ -71,27 +65,19 @@ struct RootShellView: View { @State var lifecycleCoordinator: NativeWorkspaceLifecycleCoordinator? @State var lifecycleProfileID: String? @State var lifecyclePresentationID: UUID? - @State var workspaceProfileEditor: AgentEditorModel? + @State var isGroupCreationPresented = false @State var groupCreationSeed: String? @State var groupCreationOwner: WorkspaceOwner? - /// The chat header's New chat: one agent starts a 1:1 chat, several a group. - @State var newChatPicker: NewChatPickerRequest? - @State private var isStartingNewChat = false + @State var isStartingNewChat = false @State private var newChatStartID: UUID? + /// A New chat pick that came while a chat was starting (`newChatStartEnded`). + @State var newChatPickGate = NewChatPickGate() @State private var fixtureCanonicalSessions: [String: String] = [:] @State var workspaceFixtureGeneration = UUID() /// Demo runs' connection; `-demo-reconnects-on-return` makes each return a reconnect. @State var workspaceFixtureConnection = UUID() @State private var cardInteractionStore = BighelpCardInteractionStore() - /// The all-hosts view asking which host a one-host screen is for. - @State var fleetGateRequest: FleetDestination? - /// All hosts narrowed to one computer (its chips, or ☰'s computer row); nil shows every computer. - @State var fleetFocus: UUID? - @State var fleetChatsFilter = FleetChatsFilter() - /// A Codex or Claude Code chat picked on All sessions, previewed once its computer's Sessions shows. - @State var requestedOtherAppChat: HermesForeignSessionItem? - @State var isFleetNewChatPresented = false @Environment(\.workspaceConnections) var workspaceConnections @Environment(\.scenePhase) var scenePhase @Environment(\.bighelpScreen) var screen @@ -110,38 +96,41 @@ struct RootShellView: View { @State private var isKeyboardVisible = false @State private var rootBottomSafeArea: CGFloat = 0 @State private var afterSettingsDismiss: (() -> Void)? - // Agent home (Muse-style): board data, the profile, the switcher and the ☰ drawer. + /// Today's Edit, a space's page and the space Delete asks about. + @State var isEditingToday = false + @State var spacePage: TodaySpace? + @State var deletingSpace: TodayPanelDescriptor? + /// The connection the shell's board follows; Today's boards and a bot's Dashboard read through it. @State var agentBoard = AgentBoardStore() - /// Provider Usage for the connected host; opened from chat ⋯, ☰ and the context window. + /// Provider Usage for the connected host; opened from chat ⋯, Settings and the context window. @State var providerUsage = ProviderUsageStore() @State var usage = UsageStore() @State var agentMedia = AgentMediaStore() - /// Which bots are working or need you, for Bots mode and the Agents screen. + /// Which bots are working or need you, for the home's three roots. @State var botChatActivity = BotChatActivityStore() - @State var profileAgentID: String? - @State var isAgentSwitcherPresented = false + /// The sidebar: iPad's slide-in panel, the Mac's and Vision Pro's column. iPhone has none. @State var isHomeDrawerPresented = false /// This shell, for the open Duo's list: a new shell replaces the list the last one showed. @State var splitColumnShellID = UUID() - @State var didAutoOpenHomeChat = false /// The connection the shell's Feed, Ideas and Goals were last set up for (`configureAgentBoard`). @State var agentBoardConfiguredKey: AgentBoardClientKey? /// The open Projects screens' chats and project details. @State var projectsStore: ProjectsStore? - /// Code mode's home for the selected computer (`cacheScopeID`), kept through reconnects. + /// Coding sessions on the selected computer (`cacheScopeID`), kept through reconnects. @State var codeHome: CodeHomeStore? @State var codeSheet: CodeSheet? @State var devFactory: DevFactoryStore? @State var kanbanModel: KanbanBoardModel? @State var kanbanAvailability = KanbanAvailability() @State var kanbanTaskToOpen: String? - /// The connected computer's Workflows (☰ › Workflows), when its plugin has them. + /// The connected computer's Workflows, when its plugin has them. @State var workflowsStore: WorkflowsStore? @State var workflowsAvailability = WorkflowsAvailability() @State var isNeedsYouPresented = false @State var didPresentDemoNeedsYou = false #if os(visionOS) @Environment(\.openWindow) var openWindow + @Environment(\.spatialAvatar) var spatialAvatar #endif /// Runs after a home sheet closes, so the next sheet can open. @State var afterHomeSheet: (@MainActor () -> Void)? @@ -160,30 +149,6 @@ struct RootShellView: View { || ProcessInfo.processInfo.arguments.contains("-disable-demo-delays") } - func chatAgentEditorPresentation(for model: ChatModel) -> ChatAgentEditorPresentation? { - guard !model.isBotMode, let owner = currentWorkspaceOwner, - let profileID = model.memberIDs.first, - agents.profiles.contains(where: { $0.id == profileID }) else { return nil } - let capabilities = currentWorkspaceCapabilities - guard capabilities.supports(.profilesEdit, owner: owner, profileID: profileID) else { return nil } - let canReadDefaults = capabilities.supports(.modelsRead, owner: owner, profileID: profileID) - let canEditDefaults = capabilities.supports(.agentDefaultsEdit, owner: owner, profileID: profileID) - let unavailable: WorkspaceCapability? = canReadDefaults - ? (canEditDefaults ? nil : .agentDefaultsEdit) : .modelsRead - let readOnlyReason = unavailable.flatMap { - AgentActionsPresentation.unavailableMessage(capabilities.availability(for: $0, owner: owner, profileID: profileID)) - ?? WorkspaceUnavailableReason.unsupportedOperation.message - } - return ChatAgentEditorPresentation(profileID: profileID, store: agents, - runtimeDefaultsClient: canReadDefaults ? agentRuntimeDefaults : nil, - runtimeDefaultsReadOnlyReason: readOnlyReason, - isCurrent: { - currentWorkspaceOwner == owner && model.memberIDs.first == profileID - && agents.profiles.contains(where: { $0.id == profileID }) - && currentWorkspaceCapabilities.supports(.profilesEdit, owner: owner, profileID: profileID) - }) - } - func cardInteractions(for model: ChatModel) -> ChatCardInteractionHandler? { guard let owner = currentWorkspaceOwner, let profile = model.memberIDs.first else { return nil } let scope = ChatCardInteractionScope(authorityID: owner.cacheScopeID, @@ -225,12 +190,6 @@ struct RootShellView: View { .modifier(AIDataConsentGate(inFirstSetup: presentsFirstRunOnboarding || hostRegistry?.isWorkspaceReady != true, usesDemoData: usesWorkspaceFixtures)) .modifier(pendingShareReview) - .modifier(FleetSheets( - fleet: fleet, gate: $fleetGateRequest, isNewChatPresented: $isFleetNewChatPresented, - onGate: { destination, hostID in openFleet(.destination(destination), on: hostID) }, - onNewChat: startFleetChat, - onNewGroup: newGroupChatAction == nil ? nil : { startFleetGroupChat(with: $0) }, - appPage: fleetAppPage)) .modifier(FleetHooks( liveKey: liveFleetKey, readiness: fleetOpenReadiness, hostsKey: fleetHostsKey, scenePhase: scenePhase, keepsConnected: keepsFleetHostsConnected, @@ -260,10 +219,7 @@ struct RootShellView: View { isHostSettled: nativeRuntime.map { $0.isReady && !$0.isSuspended && !$0.isRefreshing } ?? true, signIn: $workspaceSignIn, close: closeWorkspacePresentations, reattach: reattachWorkspacePresentations)) - .bighelpSheet(item: $workspaceProfileEditor) { editor in - AgentEditorView(model: editor, runtimeDefaultsClient: agentRuntimeDefaults, onCompleted: { _ in }) - .environment(\.agentDeletion, agentDeletionAction) - } + .bighelpSheet(isPresented: $isGroupCreationPresented) { BotModeCreateRoomView(rooms: botModeRooms, agents: agents, seedProfileID: groupCreationSeed, sectionChoice: groupSectionChoice) { roomID in @@ -278,7 +234,7 @@ struct RootShellView: View { .modifier(HostSetupSheet(registry: hostRegistry, isActive: !isUnifiedSettingsPresented)) .onChange(of: hostRegistry?.selectedHostID) { _, _ in chatDissolve.cancel() - appState.resetForHostBoundary(keepsAllHostsScreens: fleetModeOn) + appState.resetForHostBoundary() } .task(id: hostRegistry?.selectedHostID) { connectionKeeper.bind { [hostRegistry] in @@ -360,11 +316,11 @@ struct RootShellView: View { .onChange(of: actionErrorMessage != nil) { _, failed in if failed { VoiceLaunchState.shared.finish() } } .modifier(LostChatHooks(featureStore: featureStore, attach: watchForLostChats)) .modifier(DriveShellHooks(appState: appState, featureStore: featureStore, agents: agents, - settings: settings, usesDemoFixtures: usesDemoFixtures)) + usesDemoFixtures: usesDemoFixtures)) .modifier(BighelpShortcutParameterUpdates(agents: agents, scheduledTasks: featureStore.scheduledTasks, rooms: botModeRooms, catalog: sessionCatalog)) .modifier(PendingLinkRetry(acceptsLinks: acceptsIncomingLinks, acceptsChatStarts: acceptsChatStarts, - retry: openPendingIncomingChatIfNeeded)) + hasNavigation: hasOwnNavigation, retry: openPendingIncomingChatIfNeeded)) .onChange(of: BighelpExternalSessionOpenCenter.shared.pending, initial: true) { _, open in if let open { openExternalSession(open) } } @@ -400,15 +356,9 @@ struct RootShellView: View { HostSetupView(registry: registry, allowsDismiss: false) } else if nativeWorkspaceStore != nil { if nativeRuntime != nil, !signInEndedBeforeOpening { workspace } - // Multi-gateway: the bots stay on screen while the tapped one's gateway connects. - else if simpleBotsMultiGatewayOn, let pending = fleet?.pendingOpen { simpleBotsSwitching(to: pending.hostID) } - else if fleetModeOn, let fleet { - FleetConnectingView( - fleet: fleet, hostFilter: fleetFocusBinding, onOpen: openFleetAgent, - isConnecting: nativeWorkspaceStore?.isConnecting == true || nativeRuntime?.isRefreshing == true - || nativeWorkspaceStore?.isConnected == true, - retry: { Task { await nativeWorkspaceStore?.reconnect() } }) - } + // Every computer shows: the home stays on screen, from the computers' saved copies, + // while the tapped one's computer connects. + else if showsEveryHost, fleet?.pendingOpen != nil { conversationsRoot } else if nativeWorkspaceHasProblem { nativeWorkspace } // A moment, as the app starts: the saved workspace opens once iOS lets its files be read. else { theme.canvas.ignoresSafeArea().accessibilityIdentifier("native-workspace.opening") } @@ -453,7 +403,6 @@ struct RootShellView: View { managementStore = nil _ = capabilitiesPresentations.removeAll() for page in administrationPresentations.removeAll() { page.retire() } - workspaceProfileEditor = nil lifecycleCoordinator = nil lifecycleProfileID = nil lifecyclePresentationID = nil @@ -462,6 +411,8 @@ struct RootShellView: View { } private func completeFirstRunOnboarding() { + // "How do you want to start?" was just answered: this run opens there too. + home.land(on: settings.homeLanding, view: settings.homeView) didCompleteForcedFirstRunOnboarding = true #if DEBUG guard !isForcedFirstRunOnboarding else { return } @@ -532,9 +483,7 @@ struct RootShellView: View { isConnecting: isWorking, isFirstConnection: !connectionKeeper.hasConnected) } - var workspace: some View { - homeAutoOpen(workspaceShell) - } + var workspace: some View { workspaceShell } private var workspaceShell: some View { GeometryReader { geometry in @@ -588,125 +537,17 @@ struct RootShellView: View { .accessibilityIdentifier("session.restore.loading") } - @ViewBuilder - private var hostAwareAgentsTab: some View { - AgentsShellView( - agents: agents, - runtimeDefaultsClient: agentRuntimeDefaults, - onSelect: { openAgentChat($0.id) }, - onOpenSessions: { openSessions(filteredTo: $0.id) }, - onOpenHostStatus: { isHostStatusPresented = true }, - hostRuntime: currentHostRuntime, - workspaceOwner: currentWorkspaceOwner, - capabilities: currentWorkspaceCapabilities, - botModeRooms: botModeRooms, - cloneClient: workspaceConnections?.cloneClient, - shortcutsAvailable: usesWorkspaceFixtures - || (nativeRuntime != nil && currentWorkspaceOwner != nil) -, - onAction: handleAgentWorkspaceAction, - groupFilterRequest: $agentGroupFilterRequest, - createRequest: $agentCreateRequest, - botChatActivity: botChatActivity, - botChatActivitySource: botChatActivitySource, - sectionCards: AnyView(SimpleBotsSectionsArea(context: simpleBotsContext)) - ) - // The one main action, where a thumb rests, as on All agents. - .overlay(alignment: .bottomTrailing) { - if appState.path.isEmpty { - RootComposeButton(identifier: "agents.new-chat", size: 72) { - if currentWorkspaceOwner != nil { presentNewChatPicker(seed: nil) } - else { startNewChat(explicitAgentID: nil) } - } - .padding(.trailing, BighelpTokens.space20) - .padding(.bottom, BighelpTokens.space12) - } - } - } - - /// The Header mode switcher in the root bar, in place of the brand: on the Chat tab's list (when it - /// opens on a list, or on all hosts) and on Code's home. The Chat tab's own chat and Bots' home - /// draw their own headers with it. - var barModeSwitch: BighelpModeSwitch? { - [.sessions, .code].contains(appState.selectedTab) && !simpleBotsOn ? modeSwitch : nil - } - - /// Feed, Ideas, Goals and Apps draw their own header (the agent's avatar). - private var showsAgentBoard: Bool { - appState.path.isEmpty && showsAgentBoard(appState.selectedTab) - } - - func showsAgentBoard(_ tab: AppTab) -> Bool { tab.isAgentBoard } - private var shell: some View { rootTabs .toolbar(.hidden, for: .tabBar) - // Boards and Bots mode's home draw their own header. The home's stays hidden while a - // chat is pushed over it too: its bar (with ☰) showed through for the length of Back. - .toolbar(showsAgentBoard || simpleBotsHomeIsRoot || splitList != nil ? .hidden : .automatic, for: .navigationBar) - .navigationTitle(showsAgentBoard || simpleBotsHomeIsRoot ? "" : rootNavigationTitle) - // One title size on every tab: the bar's. A large title kept the size of the tab before - // (small after Feed or Kanban, large after Chat), so the same screen looked different. - .navigationBarTitleDisplayMode(.inline) - .toolbar { - // ☰ always opens chats, agents, tasks and settings, on iPad too. Always part of the - // root screen's bar (a pushed chat has its own, and boards hide it): added only once - // a chat closed, it was sometimes dropped mid-switch, and Agents had no ☰. - ToolbarItem(placement: .topBarLeading) { rootMenuButton } - if let barModeSwitch { - // The Header mode switcher takes the bar's middle on the Chat list; hosts stay in ☰. - ToolbarItem(placement: .principal) { BighelpModePill(modeSwitch: barModeSwitch) } - } else { - // Ember lives only in chrome: the brand bar on root screens. - // Touch and hold it to switch hosts. - BighelpBrandToolbarItem(demoHosts: demoHosts) - } - // All agents has its own options there instead (☰ switches back to one host). - if fleetModeOn, appState.path.isEmpty, appState.selectedTab == .scheduledTasks { fleetToolbar } - } - #if os(visionOS) - // Beside the window, not along its bottom edge by the close control. - .ornament(visibility: visionTabsVisible ? .visible : .hidden, - attachmentAnchor: .scene(.leading), contentAlignment: .trailing) { - VisionTabOrnament(selection: tabSelection, tabs: barTabs, unread: boardUnreadTabs, - onNewChat: appState.path.isEmpty ? barNewChat : nil) - } - #endif - .safeAreaInset(edge: .bottom, spacing: 0) { - if showsBottomNavigation && !BighelpPlatform.usesTabOrnament && !screen.usesSideBar { - FloatingTabBar(selection: tabSelection, tabs: barTabs, - onNewChat: barNewChat, - onPickAgents: { presentNewChatPicker(seed: homeAgent?.id) }, - homeIndicatorSink: FloatingTabBar.homeIndicatorSink(forBottomInset: rootBottomSafeArea), - unread: boardUnreadTabs) - .transition(.move(edge: .bottom).combined(with: .opacity)) - } - } + // Every root draws its own header (`HomeHeaderBar`); a pushed page has the bar's or its own. + .toolbar(.hidden, for: .navigationBar) + .modifier(HomeBars(isAtRoot: appState.path.isEmpty, isKeyboardVisible: isKeyboardVisible, + selection: tabSelection, items: homeTabItems, onNewChat: { openNewChat() }, + bottomInset: rootBottomSafeArea, selectedTint: theme.action, tint: theme.secondaryText)) .onGeometryChange(for: CGFloat.self) { $0.safeAreaInsets.bottom } action: { rootBottomSafeArea = $0 } - // The iPhone Duo: the bar's places go down the side strip with the screen's own buttons. - .toolbar { - if showsBottomNavigation && screen.usesSideBar { - BighelpStripTabs(selection: tabSelection, tabs: barTabs, unread: boardUnreadTabs, - onNewChat: barNewChat, - selectedTint: theme.action, tint: theme.secondaryText) - } - } // The iPhone Duo open: the list beside the page. .onChange(of: splitColumnKey, initial: true) { updateSplitColumn() } - // Chat or Code mode: the launch's choice, then ☰'s switch. - .onChange(of: settings.experience, initial: true) { applyExperience() } - // Bots mode on or off: back to that mode's home, whatever was open. - .onChange(of: settings.simpleBotsEnabled) { - appState.path.removeAll() - appState.homeTab = .sessions - applyExperience() - appState.select(appState.homeTab) - } - // It has no ☰: the Mac's sidebar, kept open between launches, closes too. - .onChange(of: simpleBotsOn, initial: true) { _, on in - if on { isHomeDrawerPresented = false } - } - .animation(reduceMotion ? nil : .snappy(duration: BighelpTokens.transitionDuration), value: showsBottomNavigation) .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in isKeyboardVisible = true } @@ -737,15 +578,7 @@ struct RootShellView: View { }) { settingsSheetContent } - .bighelpSheet(isPresented: $isHermesWorkspacePresented) { - HermesWorkspacePickerView( - store: hermesWorkspaces, - agentID: workspaceAgentID - ) - .presentationDetents([.medium, .large]) - .presentationDragIndicator(.visible) - .bighelpSheetSize(.standard) - } + .onChange(of: appState.path) { previousPath, path in let bindsPendingCanvas: Bool = { guard case .chat(let previousID)? = previousPath.last, @@ -784,7 +617,7 @@ struct RootShellView: View { } } - /// The Settings sheet, the same one in every mode. Its stack's path lives in `AppState`, and + /// The Settings sheet, from the person's circle on every root. Its stack's path lives in `AppState`, and /// `SettingsDestination` values pushed on it draw here. private var settingsSheetContent: some View { // Done on every page closes Settings; Back steps through its pages. @@ -799,92 +632,12 @@ struct RootShellView: View { .modifier(HostSetupSheet(registry: hostRegistry, isActive: true)) } - private var showsBottomNavigation: Bool { - appState.path.isEmpty && !isKeyboardVisible && showsTabsOnRoot - } - - /// Vision Pro's tab strip on root screens. The agent's own chat draws its - /// own: a screen covered by a pushed one doesn't show its ornaments. - private var visionTabsVisible: Bool { - appState.path.isEmpty && showsTabsOnRoot - } - - /// The bottom bar: Chat, then what the person pinned (Appearance › App layout). - var barTabs: [AppTab] { settings.appLayout.barTabs } - - /// The all-hosts view is just its list. Feed, Ideas and Goals keep the bar if - /// something opens them, so its Chat tab always leads back, and so do the pages - /// pinned to it. Not on Agents unless it's pinned: pick an agent first, so Feed, - /// Ideas and Goals are clearly its own. - private var showsTabsOnRoot: Bool { - let tab = appState.selectedTab - // Code mode's message box sits where the bar would; ☰ goes everywhere else. - // Bots mode has no bar: its home is the whole app. - guard tab != .code, !simpleBotsOn else { return false } - let pinned = tab != .sessions && barTabs.contains(tab) - return (tab != .agents || pinned) && (!fleetModeOn || tab.isAgentBoard || pinned) - } - + /// The three places. The shell switches the root itself: a hidden TabView creates a UIKit + /// containment boundary that drops feature search and toolbar actions. On the open iPhone Duo a + /// list shows left of the fold instead, and the page beside it waits for a pick. @ViewBuilder var rootTabs: some View { - // The conversation shell owns navigation. A hidden TabView creates a - // UIKit containment boundary that drops feature search and toolbar actions. - switch appState.selectedTab { - case .agents: - hostAwareAgentsTab - case .scheduledTasks: - scheduledTasksRootTab - case .profile: - workspaceSettings() - // Home and Inbox were the Activity screen; they open Chat now. - case .sessions, .sessionList, .home, .inbox: - if let splitList, splitList.isList { splitPlaceholder(splitList) } else if simpleBotsOn { simpleBotsHome } else { sessionsRootTab } - case .feed, .ideas, .goals, .apps: - agentBoardTab(appState.selectedTab) - // Pinned to the bottom bar: the page ☰ opens, as a tab. - case .projects: - routeDestination(.projects) - case .kanban: - routeDestination(.kanban) - case .workflows: - routeDestination(.workflows) - case .usage: - routeDestination(.usage) - case .code: - if let splitList, splitList.isList { splitPlaceholder(splitList) } else { codeRootTab } - } - } - - /// ☰: chats, places, agents and Settings. The root's bar has it, and the open Duo's list. - var rootMenuButton: some View { - Button { - isHomeDrawerPresented.toggle() - } label: { - Image(systemName: "line.3.horizontal").bighelpToolbarIcon() - .bighelpMenuDot(menuHasUnread) - } - .bighelpIconLabel(String(localized: "Chats and menu"), shortcut: "⌃⌘S") - .accessibilityIdentifier("home.drawer.open") - } - - var rootNavigationTitle: String { - switch appState.selectedTab { - case .sessions, .sessionList, .home, .inbox: - fleetModeOn ? String(localized: "All agents") : String(localized: "Sessions") - case .agents: String(localized: "Agents") - // Its tab's name: the long one didn't fit beside its buttons. - case .scheduledTasks: String(localized: "Tasks") - case .profile: String(localized: "Settings") - case .feed: String(localized: "Feed") - case .ideas: String(localized: "Ideas") - case .goals: String(localized: "Goals") - case .apps: String(localized: "Apps") - case .projects: String(localized: "Projects") - case .kanban: String(localized: "Kanban") - case .workflows: String(localized: "Workflows") - case .usage: String(localized: "Usage") - case .code: String(localized: "Code") - } + if let splitList, splitList.isList { splitPlaceholder(splitList) } else { homeRoot(appState.selectedTab) } } @ViewBuilder @@ -918,13 +671,11 @@ struct RootShellView: View { @ViewBuilder private func edgeGestureSurface(side: EdgeSide, containerWidth: CGFloat) -> some View { - let action = side == .left - ? settings.effectiveLeftEdgeSwipeAction - : settings.effectiveRightEdgeSwipeAction + let action = side == .left ? settings.leftEdgeSwipeAction : settings.rightEdgeSwipeAction Color.clear .frame(width: WorkspaceEdgeSwipeResolver.activationEdgeWidth) .contentShape(Rectangle()) - // Below the header row, so ☰ and ⋯ in the corners (Feed, Ideas, Goals, Apps) keep their taps. + // Below the header row, so the buttons in its corners keep their taps. .padding(.top, HeaderButtonMetrics.glass + 2 * HeaderButtonMetrics.slop + BighelpTokens.space8) .allowsHitTesting(action != .none && !isHomeDrawerPresented && (side == .left || WorkspaceEdgeSwipeResolver.trailingEdgeIsActive( @@ -939,8 +690,8 @@ struct RootShellView: View { start: CGPoint(x: startX, y: value.startLocation.y), translation: value.translation, containerWidth: containerWidth, - leftAction: settings.effectiveLeftEdgeSwipeAction, - rightAction: settings.effectiveRightEdgeSwipeAction + leftAction: settings.leftEdgeSwipeAction, + rightAction: settings.rightEdgeSwipeAction ) else { return } performWorkspaceAction(resolved) } @@ -948,165 +699,41 @@ struct RootShellView: View { .accessibilityHidden(true) } - /// Every way into the menu (☰, edge swipes, inner pages) opens the same ☰ sheet. - private func presentMenu() { - BighelpKeyboard.dismiss() - // ☰ toggles: the Mac and Vision Pro sidebar stays reachable while open. - isHomeDrawerPresented.toggle() - } - - /// Where an edge swipe goes, from any screen (a chat included) and in either mode. + /// Where an edge swipe goes, from any screen (a chat included). func performWorkspaceAction(_ action: WorkspaceSwipeAction) { BighelpKeyboard.dismiss() - if simpleBotsOn, performSimpleBotsSwipe(action) { return } switch action { case .quickWorkspace: - presentMenu() + // The sidebar where there is one; the phone has none, so its chats. + if sidebarIsAvailable { isHomeDrawerPresented.toggle() } else { appState.select(.chats) } case .newChat: - if fleetModeOn { isFleetNewChatPresented = true } else { startNewChat(explicitAgentID: nil) } + openNewChat() case .sessions: - if fleetModeOn { - // Back to the list the chat came from: All sessions, else All agents. - appState.chatOpenedFromList = false - if appState.path.first?.isAllHosts == true { - appState.path = Array(appState.path.prefix { $0.isAllHosts }) - } else { - appState.select(.sessions) - } - } else { - openAllSessions() - } + appState.select(.chats) case .agents: - openAgentsList() - case .home, .inbox: - // All hosts has no home chat; its home is All agents. - if fleetModeOn { openAgentsList() } else { openHomeChat() } + appState.select(.bots) + case .home: + appState.select(.conversations) case .profile: - openSettingsPage() - case .nextMode: - settings.switchMode(settings.nextMode) - case .botsMode, .chatMode, .codeMode: - if let mode = action.mode { settings.switchMode(mode) } + openBotPageOrSettings() case .none: break } } - /// The bar's lit tab. With Sessions in the bar, every chat's list, and a chat picked - /// from it, is Sessions; Chat is the agent's own chat. - private var selectedBarTab: AppTab { - guard appState.selectedTab == .sessions, !fleetModeOn, barTabs.contains(.sessionList) else { - return appState.selectedTab - } - if appState.path.isEmpty { return .sessionList } - if appState.chatOpenedFromList, appState.path.count == 1, case .chat = appState.path[0] { return .sessionList } - return .sessions - } - - var tabSelection: Binding { - Binding( - get: { selectedBarTab }, - set: { tab in - // Chat from a chat is where you already are, not a trip to the list. - if tab == .sessions, selectedBarTab == .sessions, case .chat? = appState.path.last { return } - // From a chat, its agent's Feed, Ideas and Goals; and the switch is a swap like - // Feed to Ideas, not the chat sliding away. - if fleetModeOn, case .chat(let id)? = appState.path.last { fleetLastChatID = id } - if tab.isAgentBoard, case .chat(let id)? = appState.path.last, - let members = featureStore.preparedChatModel(id: id)?.memberIDs, members.count == 1, - members[0] != homeAgent?.id { - _ = agents.setPrimaryAgent(members[0]) - } - var transaction = Transaction() - // Chat opens its chat as a page under the hood; from any tab it swaps in like - // the others instead of sliding in like a page turn. - transaction.disablesAnimations = !appState.path.isEmpty || tab == .sessions - withTransaction(transaction) { selectTab(tab) } - } - ) - } - - private func selectTab(_ tab: AppTab) { - if tab == .sessionList { - if openHeldChat(under: tab) { return } - openAllSessions() - return - } - // All hosts has no home chat: Chat goes back to the chat you were in, else to All agents. - if tab == .sessions, fleetModeOn, appState.path.isEmpty, let id = fleetLastChatID, - let record = sessionCatalog.session(id: id) { - appState.chatOpenedFromList = true - openSession(record.summary) - return - } - if tab == .sessions, opensHomeChat { - // The chat you left under Chat opens again; otherwise Chat is the agent's own chat. - // ☰ and swipe-back reach the full list either way. - if openHeldChat(under: tab) { return } - openHomeChat() - } else if tab == .sessions { - openSessions(filteredTo: nil) - } else if tab == .scheduledTasks { - openScheduledTasks(filteredTo: nil) - } else if tab.isHostPage { - openHostPageTab(tab) + /// In a chat with one bot, that bot's page; anywhere else, Settings. + private func openBotPageOrSettings() { + if case .simpleBotProfile? = appState.path.last { return } + if case .chat(let id)? = appState.path.last, let model = featureStore.preparedChatModel(id: id), + !model.isBotMode, let botID = model.memberIDs.first { + appState.open(.simpleBotProfile(agentID: botID)) } else { - appState.select(tab) - } - } - - /// The chat the person left under `tab` (Chat or Sessions) for another place, while this - /// computer still lists it. False when there's none, and the tab opens as it always has. Chat - /// skips a 1:1 chat whose agent is no longer the one in use: it opens that agent's chat instead. - private func openHeldChat(under tab: AppTab) -> Bool { - guard !fleetModeOn, let held = appState.heldChat, - held.tab(sessionsInBar: barTabs.contains(.sessionList)) == tab, - let record = sessionCatalog.session(id: held.conversationID), - tab == .sessionList || HeldChat.fitsChat(members: record.agentIDs, agentInUse: homeAgent?.id) - else { return false } - appState.select(.sessions) - // A chat from the list keeps Back to the list. - appState.chatOpenedFromList = held.openedFromList - // A group chat opens its room, as it did from the list. - openSessionSelection(record.summary) - return true - } - - /// Projects, Kanban, Workflows or Usage from the bottom bar: opened the way ☰ opens - /// them (which makes a pinned one a tab), without ☰'s wait for its sheet to close. - /// Where this computer has none, the tab says so. - private func openHostPageTab(_ tab: AppTab) { - switch tab { - case .projects where canOpenProjects: - if fleetModeOn { fleetGate(.projects) } else { openProjects() } - case .kanban where canOpenKanban: - if fleetModeOn { fleetGate(.kanban) } else { openKanban() } - case .workflows: - if fleetModeOn { fleetGate(.workflows) } else { openWorkflows() } - case .usage where usage.isAvailable: - showUsage() - default: - appState.select(tab) - } - } - - @ViewBuilder - var sessionsRootTab: some View { - if fleetModeOn, let fleet { - fleetHome(fleet) - } else if case .sessions(let model)? = featureStore.preparedModel(for: .sessions) { - oneHostSessions(model) - } else { - ProgressView("Loading sessions") - .frame(maxWidth: .infinity, maxHeight: .infinity) - .task { - _ = featureStore.prepareSessions(filteredTo: nil) - } + isUnifiedSettingsPresented = true } } - /// One computer's Sessions screen: the Chat list in one-computer mode, and a picked - /// computer's chip on All sessions. + /// One computer's Sessions page, pushed from Chats: projects, imports from other apps, one + /// bot's chats. func oneHostSessions(_ model: SessionsModel) -> SessionsView { SessionsView( model: model, @@ -1115,15 +742,11 @@ struct RootShellView: View { organizeByProjects: settings.organizeChatsByProjects, sessionOrganizationAccountID: sessionOrganizationAccountID, sessionOrganizationHostID: sessionOrganizationHostID, - onStartChat: { appState.chatOpenedFromList = true; startNewChat(explicitAgentID: $0) }, - onNewGroupChat: newGroupChatAction.map { action in { appState.chatOpenedFromList = true; action() } }, - onSelect: { appState.chatOpenedFromList = true; openSessionSelection($0) }, - agentActionsConfig: agentActionsConfig, + onStartChat: { startNewChat(explicitAgentID: $0) }, + onNewGroupChat: newGroupChatAction, + onSelect: { openSessionSelection($0) }, otherApps: otherAppChats, onOpenBroughtIn: { openBroughtInChat($0) }, - // All sessions and a picked computer's Sessions share the Hermes, Codex, Claude Code choice. - appFilter: fleetModeOn ? $fleetChatsFilter.app : nil, - requestedOtherAppChat: $requestedOtherAppChat, projectMove: chatProjectMove ) } @@ -1149,7 +772,6 @@ struct RootShellView: View { /// A chat brought in from Codex or Claude Code opens like any other, once Hermes lists it. func openBroughtInChat(_ storedSessionID: String) { if let record = sessionCatalog.session(id: storedSessionID) { - appState.chatOpenedFromList = true openSession(record.summary) return } @@ -1158,16 +780,15 @@ struct RootShellView: View { do { let record = try await sessionCatalog.resolveStoredSession(profileID: profileID, storedSessionID: storedSessionID) - appState.chatOpenedFromList = true openSession(record.summary) } catch is CancellationError { } catch { - actionErrorMessage = "The chat is in Hermes now, but it couldn't be opened. Find it in Sessions." + actionErrorMessage = "The chat is in Hermes now, but it couldn't be opened. Find it in Chats." } } } - /// Group chats use Hermes' hosted rooms, the same path as Agents › New group chat. + /// + › New Group Chat: Hermes' hosted rooms, made in the New Group Chat sheet. var newGroupChatAction: (() -> Void)? { // The room store's own answer, not the published capability: that comes only after the whole // connection's refresh, so New Group Chat took 10 seconds or more after every return to the app. @@ -1177,20 +798,6 @@ struct RootShellView: View { } } - @ViewBuilder - private var scheduledTasksRootTab: some View { - if fleetModeOn, let fleet { - FleetTasksView(fleet: fleet, hostFilter: fleetFocusBinding, onOpen: openFleetTask) - // This host's own tasks, as its Scheduled tasks screen would load them. - .task { if featureStore.scheduledTasks?.loadState == .idle { await featureStore.scheduledTasks?.load() } } - } else if let store = featureStore.scheduledTasks { - ScheduledTasksView(store: store, agents: agents, showsInlineHeading: true, onOpen: openScheduledTask) - } else { - ContentUnavailableView("Scheduled Tasks", systemImage: "calendar.badge.clock", - description: Text("Scheduled work is unavailable for this connection.")) - } - } - func leaveSettings(perform action: @escaping () -> Void) { if isUnifiedSettingsPresented { afterSettingsDismiss = action @@ -1200,17 +807,12 @@ struct RootShellView: View { } } - /// Settings' Appearance or Chat page alone, for Fleet settings. - func fleetAppPage(_ section: SettingsMenuSection) -> AnyView { - AnyView(workspaceSettings().opening(section)) - } - func workspaceSettings() -> SettingsView { SettingsView( settings: settings, userIdentity: userIdentity, agents: agents.profiles, personalities: personalities, permissionCenter: permissionCenter, - onOpenSessions: { leaveSettings { openSessions(filteredTo: nil) } }, + onOpenSessions: { leaveSettings { appState.select(.chats) } }, onOpenScheduledTasks: { leaveSettings { openScheduledTasks(filteredTo: nil) } }, onClearLocalCache: { if let nativeRuntime { return await nativeRuntime.refreshLocalCache() } @@ -1219,7 +821,6 @@ struct RootShellView: View { voiceSettingsScope: voiceSettingsScope, voiceSettingsClient: voiceSettingsClient, voiceSettingsIsCurrent: voiceSettingsIsCurrent, agentDirectory: agents, - landingScope: currentWorkspaceOwner?.cacheScopeID, onOpenWorkspaceDestination: { destination in leaveSettings { openWorkspaceDestination(destination) } }, @@ -1237,8 +838,7 @@ struct RootShellView: View { usage: providerUsage, pendingShares: settingsPendingShareContext, archivedChats: settingsArchivedChats, - computerTimeZone: computerTimeZoneSettings(), - onSetAllHosts: fleet == nil ? nil : { (on: Bool) in setAllHostsMode(on) } + computerTimeZone: computerTimeZoneSettings() ) } @@ -1249,10 +849,7 @@ struct RootShellView: View { catalog: sessionCatalog, agentName: { id in agents.profiles.first { $0.id == id }?.name ?? id }, onOpen: { summary in - leaveSettings { - appState.chatOpenedFromList = true - openSession(summary) - } + leaveSettings { openSession(summary) } }) } @@ -1342,51 +939,41 @@ struct RootShellView: View { ) } - func routeWithWorkspaceMenu( - @ViewBuilder content: () -> Content - ) -> some View { - content() - .toolbar { - if settings.nerdModeEnabled { - ToolbarItem(placement: .topBarTrailing) { - // The native toolbar supplies its own Liquid Glass surface. - Button { - presentMenu() - } label: { - Image(systemName: "line.3.horizontal").bighelpToolbarIcon() - } - .bighelpIconLabel(String(localized: "Menu")) - .accessibilityIdentifier("workspace.menu") - } - } - } - } - /// The menu bar's New Chat (⌘N), Settings (⌘,), sidebar (⌃⌘S), modes (⌃⌘1–⌃⌘3, with the Unified - /// Mode Toggle on) and, on the Mac, tabs (⌘1–⌘5). + + /// The menu bar's New Chat (⌘N), Settings (⌘,), sidebar (⌃⌘S) and, on the Mac, the three + /// places (⌘1–⌘3). private var menuCommandActions: BighelpShellActions { - var actions = BighelpShellActions( - newChat: { startNewChat(explicitAgentID: nil) }, + let selection = tabSelection + return BighelpShellActions( + newChat: { openNewChat() }, openSettings: { isUnifiedSettingsPresented = true }, isSidebarOpen: isHomeDrawerPresented, toggleSidebar: { isHomeDrawerPresented.toggle() }, - modeSwitch: modeSwitch + selectTab: { selection.wrappedValue = $0 }, + tabs: homeTabItems ) - if appState.path.isEmpty, !fleetModeOn { - let selection = tabSelection - actions.selectTab = { tab in selection.wrappedValue = tab } - actions.tabs = barTabs - } - return actions } /// `opened` gets the chat Hermes made, after the local canvas it showed first has passed it on. - func startNewChat(explicitAgentID: String?, startsVoice: Bool = false, + /// `tracksNewChat`: this is New chat's own blank chat, so each ID it shows under (the canvas, + /// then Hermes' chat) is the one that draws the To row (`newChatSlot(forChat:model:)`). When + /// New chat's blank chat is already on top (another bot was picked for it), the new one takes + /// its place in one step. + func startNewChat(explicitAgentID: String?, startsVoice: Bool = false, tracksNewChat: Bool = false, opened: (@MainActor (String) -> Void)? = nil) { + let replacesBlankChat = tracksNewChat && newChatSession.conversationID != nil + && appState.path.last == newChatSession.conversationID.map { .chat(conversationID: $0) } + // New chat's choices row reads this computer's projects. + if tracksNewChat { prepareCodeHome() } runNewChatStart(retry: { startNewChat(explicitAgentID: explicitAgentID, startsVoice: startsVoice, - opened: opened) }) { - let outcome = try await newChatCoordinator.start(explicitAgentID: explicitAgentID, - beforePresentation: presentNewChatDissolve) + tracksNewChat: tracksNewChat, opened: opened) }) { + let outcome = try await newChatCoordinator.start( + explicitAgentID: explicitAgentID, replacingBlankChat: replacesBlankChat, + beforePresentation: { next, previous in + presentNewChatDissolve(next, replacing: previous) + if tracksNewChat { newChatSession.conversationID = next } + }) guard case .opened(let id, _) = outcome else { return } if startsVoice { appState.requestVoiceMode(for: id) } opened?(id) @@ -1450,23 +1037,16 @@ struct RootShellView: View { withAnimation(reduceMotion ? nil : .easeInOut(duration: BighelpTokens.stateDuration)) { isStartingNewChat = false } + newChatStartEnded() } - var activeHermesWorkspaceName: String { - hermesWorkspaces.catalog?.workspaces.first(where: \.isActive)?.name - ?? "Workspace" - } + var workspaceAgentID: String { agents.resolvedAgent(explicitID: nil)?.id ?? "default" } - func presentHermesWorkspaces() { - Task { @MainActor in - try? await Task.sleep(for: .milliseconds(180)) - isHermesWorkspacePresented = true - } - } + func openApproval(requestID: String) { Task { @@ -1487,14 +1067,16 @@ struct RootShellView: View { appState.open(.approval(requestID: request.id)) } + /// The computer in use's Sessions page over where the person is; `agentID` shows one bot's chats. func openSessions(filteredTo agentID: String?) { guard featureStore.prepareSessions(filteredTo: agentID) else { return } - appState.openSessions() + if appState.path.last != .sessions { appState.open(.sessions) } } + /// Scheduled tasks over where the person is; `agentID` shows one bot's routines. func openScheduledTasks(filteredTo agentID: String?) { guard featureStore.prepareScheduledTasks(filteredTo: agentID) else { return } - appState.openScheduledTasks() + if appState.path.last != .scheduledTasks { appState.open(.scheduledTasks) } } fileprivate func openErrorPresentations(_ content: Content) -> some View { @@ -1551,9 +1133,6 @@ struct RootShellView: View { // The way back from Shortcuts to a phone-tool call: not a screen to open. if DeviceToolHandoff.shared.handleCallback(url) { return } guard let route = BighelpIncomingURLRoute.parse(url) else { return } - // A link opening the app wins over Settings › Chat › Opens on, and keeps the mode you were in. - didAutoOpenHomeChat = true - settings.restoreAllHostsModeForOutsideOpen() if holdsLinkForItsComputer(url) { return } // Opened while the app starts or comes back, a link found no workspace // ("host unavailable") or opened its chat under an alert. It waits for @@ -1562,22 +1141,31 @@ struct RootShellView: View { pendingIncomingURL = url return } + // A page or Settings opens in the computer's own navigation, which isn't here yet as the + // app starts: opened now, it went into one that is then replaced, and never showed. + if route.opensAPage, !hasOwnNavigation { + pendingIncomingURL = url + return + } switch route { case .home: // Notifications and older links named the Activity inbox. Updates, - // approvals and questions now live in the agent's chat. - openHomeChat() + // approvals and questions now live in the bot's chat. + openPrimaryBotChat() case .chat(let sessionID): openIncomingChat(sessionID: sessionID) case .agent(let tab, let agentID): - // From the Watch: that agent's Feed, Ideas or Goals. - if let agentID { _ = agents.setPrimaryAgent(agentID) } + // From the Watch and the widgets: that bot's Feed, Ideas or Goals over Today. The + // primary bot stays who it is. switch tab { - case "feed": appState.select(.feed) - case "ideas": appState.select(.ideas) - case "goals": appState.select(.goals) - case "apps": appState.select(.apps) - default: openHomeChat() + case "feed": showOverToday(.feed, agentID: agentID) + case "ideas": showOverToday(.idea, agentID: agentID) + case "goals": showOverToday(.goal, agentID: agentID) + case "apps": + if let id = agentID ?? homeAgent?.id { + appState.open(.simpleBotProfile(agentID: id, opening: BotProfileOpening(tab: .files))) + } + default: openPrimaryBotChat() } case .newChat(let agentID): startIncomingNewChat(agentID: agentID) @@ -1586,12 +1174,14 @@ struct RootShellView: View { case .voice(let agentID, let hostID): openIncomingAgentChat(agentID: agentID, hostID: hostID, startsVoice: true) case .scheduledTasks: - appState.select(.scheduledTasks) + guard featureStore.prepareScheduledTasks(filteredTo: nil) else { return } + showOverWork([.scheduledTasks]) case .scheduledTask(let id): - appState.select(.scheduledTasks) - openPrepared(.scheduledTask(id: id, agentID: nil)) + guard featureStore.prepareScheduledTasks(filteredTo: nil), + (try? featureStore.prepareForUserNavigation(.scheduledTask(id: id, agentID: nil))) == true else { return } + showOverWork([.scheduledTasks, .scheduledTask(id: id, agentID: nil)]) case .sessions: - appState.select(.sessions) + appState.select(.chats) case .kanban(let board, let task): openKanban(board: board, task: task) case .approval(let id): @@ -1603,11 +1193,11 @@ struct RootShellView: View { } openHostedGroup(roomID, owner: owner, settings: false) case .agents: - appState.select(.agents) + appState.select(.bots) case .projects: openProjects() case .settings: - openSettingsPage() + isUnifiedSettingsPresented = true case .workflows: openWorkflows() case .workflow(let id, _, let startsRun): @@ -1633,9 +1223,8 @@ struct RootShellView: View { actionErrorMessage = "\(host.name) is a sample host in this demo." return true } - if fleetModeOn { recordLiveFleet() } + recordLiveFleet() pendingIncomingURL = url - appState.chatOpenedFromList = false fleet.select(hostID) return true } @@ -1723,10 +1312,6 @@ struct RootShellView: View { /// Managed notifications and Live Activities verify a durable Hermes /// coordinate; resolve it through the visible catalog and open that row. func openExternalSession(_ open: BighelpExternalSessionOpen) { - // A notification opening the app wins over Settings › Chat › Opens on, and keeps the mode - // you were in: All hosts stays All hosts, so ☰ matches it. - didAutoOpenHomeChat = true - settings.restoreAllHostsModeForOutsideOpen() switch open.target { case .catalog(let sessionID): guard BighelpExternalSessionOpenCenter.shared.consume(open) else { return } @@ -1851,13 +1436,6 @@ struct RootShellView: View { } } - /// A link, widget, Shortcut or notification waiting for the host: the - /// launch's landing screen gives way to it. - var hasPendingOutsideOpen: Bool { - pendingIncomingURL != nil || BighelpIncomingLinkCenter.shared.pending != nil - || BighelpExternalSessionOpenCenter.shared.pending != nil - } - /// Widgets, notifications and Shortcuts open once the host answers: its /// workspace is loaded and not suspended or reconnecting. private var acceptsIncomingLinks: Bool { @@ -1877,7 +1455,19 @@ struct RootShellView: View { return nativeRuntime.chatsOwner == owner } + /// The navigation that pushed pages and Settings show in is the one on screen. Each computer has + /// its own (`NativeWorkspaceRuntime.appState`); until its workspace opens, the shell is handed + /// the app's first one, which the computer's then replaces. The demo has only the first. + private var hasOwnNavigation: Bool { + usesDemoFixtures || nativeRuntime != nil + } + private func openPendingIncomingChatIfNeeded() { + // A page link waited only for the navigation it shows in, never for the computer to answer. + if hasOwnNavigation, let url = pendingIncomingURL, BighelpIncomingURLRoute.parse(url)?.opensAPage == true { + pendingIncomingURL = nil + handleIncomingURL(url) + } // A link that only starts a chat goes first; handling it again holds it if it came too soon. if !acceptsIncomingLinks, acceptsChatStarts, let url = pendingIncomingURL, BighelpIncomingURLRoute.parse(url)?.startsAChat == true { @@ -1900,7 +1490,7 @@ struct RootShellView: View { func openSession(_ session: SessionSummary) { let route = AppRoute.chat(conversationID: session.id) let simpleBotsOpening = beginSimpleBotsChatOpening(session) - defer { if let simpleBotsOpening { noteSimpleBotsChatOpened(simpleBotsOpening, route: route) } } + defer { noteSimpleBotsChatOpened(simpleBotsOpening, route: route) } // On screen already (a notification or link about it): keep it as it is, any load it // has under way included, and catch up from the host. if appState.path.last == route, featureStore.preparedModel(for: route) != nil { @@ -2069,12 +1659,22 @@ private extension BighelpIncomingURLRoute { switch self { case .home, .chat, .newChat, .agentChat, .voice, .kanban, .approval, .group, .projects, .workflows, .workflow, .workflowRun: true - // Feed, Ideas, Goals and Agents show their saved items and refresh themselves; waiting for + // Today, Bots and Chats show their saved items and refresh themselves; waiting for // the host before even switching tabs made these links feel broken. case .agent, .agents, .scheduledTasks, .scheduledTask, .sessions, .settings, .usage: false } } + /// Routes that push a page or open Settings. They need nothing from the computer, only the + /// navigation they show in (`RootShellView.hasOwnNavigation`). A link that only picks a tab or + /// a view needs neither: those are the whole app's. + var opensAPage: Bool { + switch self { + case .agent, .scheduledTasks, .scheduledTask, .settings, .usage: true + default: false + } + } + /// Routes that start or open one agent's chat, and read nothing from the chat list. var startsAChat: Bool { switch self { @@ -2089,12 +1689,15 @@ private extension BighelpIncomingURLRoute { private struct PendingLinkRetry: ViewModifier { let acceptsLinks: Bool let acceptsChatStarts: Bool + /// The computer's own navigation is on screen: a link to a page can open in it. + let hasNavigation: Bool let retry: () -> Void func body(content: Content) -> some View { content .onChange(of: acceptsLinks) { _, ready in if ready { retry() } } .onChange(of: acceptsChatStarts) { _, ready in if ready { retry() } } + .onChange(of: hasNavigation) { _, ready in if ready { retry() } } } } diff --git a/Bighelp/App/RootSimpleBots.swift b/Bighelp/App/RootSimpleBots.swift index 5b8718c5..0697688e 100644 --- a/Bighelp/App/RootSimpleBots.swift +++ b/Bighelp/App/RootSimpleBots.swift @@ -1,52 +1,32 @@ import SwiftUI -// Bots mode (Settings › Bots mode): its home in place of the Chat -// tab, its short Settings, bot profiles, and how its chats look. +// The Bots view of the first tab, the bot page, and the loader that covers a chat while it opens. extension RootShellView { - /// Bots mode wins over the all-hosts view and Opens on (`fleetModeOn`). - var simpleBotsOn: Bool { settings.simpleBotsEnabled } - - /// The home is the tab's root, whatever is pushed over it: no bar, no ☰; the person's circle opens Settings. - var simpleBotsHomeIsRoot: Bool { - simpleBotsOn && appState.selectedTab == .sessions - } - - var simpleBotsHome: some View { - SimpleBotsHomeView(context: simpleBotsContext) - } - - /// Multi-gateway while the gateway of a tapped bot connects: the home, from every gateway's copy, - /// under the opening loader. What was tapped opens once it's connected (`openPendingFleetIfReady`). - func simpleBotsSwitching(to hostID: UUID) -> some View { - simpleBotsHome - } - - /// Multi-gateway: a bot on another gateway opens once that gateway is connected and its chats + /// Every computer shown: a bot on another gateway opens once that gateway is connected and its chats /// are loaded, often a few seconds. The Noodle loader covers the whole wait, from the tap to /// the chat, so the screen never looks stuck; Cancel goes back to where the tap came from. @ViewBuilder var simpleBotsOpeningLoader: some View { #if DEBUG // Demo hosts can't be switched to; this shows the loader for screenshots. - if settings.simpleBotsEnabled, ProcessInfo.processInfo.arguments.contains("-test-simple-bots-opening") { + if ProcessInfo.processInfo.arguments.contains("-test-simple-bots-opening") { SimpleBotsOpeningOverlay(botName: "Mina Shah", gatewayName: "Studio Mac", onCancel: {}) } #endif - if simpleBotsMultiGatewayOn, let fleet, let pending = fleet.pendingOpen { + if showsEveryHost, let fleet, let pending = fleet.pendingOpen { SimpleBotsOpeningOverlay( botName: pending.profileID.flatMap { fleet.agent(hostID: pending.hostID, profileID: $0)?.name }, gatewayName: fleet.hostName(pending.hostID), onCancel: cancelPendingFleetOpen) .transition(.opacity) - } else if simpleBotsOn { + } else { SimpleBotsChatOpeningLayer(opening: simpleBotsChatOpening, readiness: { simpleBotsChatOpeningReadiness }, onCancel: cancelSimpleBotsChatOpening) } } - /// Bots mode: a chat opening from a list, a search, a profile or a link. Nil outside it. - func beginSimpleBotsChatOpening(_ session: SessionSummary) -> UUID? { - guard simpleBotsOn else { return nil } + /// A chat opening from a list, a search, a bot page or a link. + func beginSimpleBotsChatOpening(_ session: SessionSummary) -> UUID { let agentID = session.kind == .direct && session.agentIDs.count == 1 ? session.agentIDs[0] : nil let name = agentID.flatMap { id in agents.profiles.first { $0.id == id }?.name } ?? session.title return simpleBotsChatOpening.begin(agentID: agentID, name: name, originPath: appState.path, @@ -103,24 +83,19 @@ extension RootShellView { personName: userIdentity.identity.displayName, personImageURL: userIdentity.avatarURL(), scope: owner?.cacheScopeID ?? "local", canCreateBots: usesWorkspaceFixtures || supports(.profilesCreate), - onOpenBot: { openSimpleBotChat($0) }, - onOpenSession: { summary in - appState.chatOpenedFromList = true - openSession(summary) - }, + onOpenBot: { openAgentChat($0) }, + onOpenSession: { openSession($0) }, onOpenSettings: { isUnifiedSettingsPresented = true }, onOpenProfile: { appState.open(.simpleBotProfile(agentID: $0)) }, - onNewChat: { agentID in - appState.chatOpenedFromList = true - startNewChat(explicitAgentID: agentID) - }, + onNewChat: { startNewChat(explicitAgentID: $0) }, makeCreator: { makeSimpleBotCreator() }, gateways: simpleBotsGateways, activity: botChatActivity, activitySource: botChatActivitySource, - modeSwitch: modeSwitch, + viewSwitch: homeViewSwitch, + onToggleSidebar: sidebarIsAvailable ? { isHomeDrawerPresented.toggle() } : nil, fleet: fleet, - onNewGroupChat: newGroupChatAction.map { action in { appState.chatOpenedFromList = true; action() } }, + onNewGroupChat: newGroupChatAction, onGroupSettings: { roomID in guard let owner else { return } handleAgentWorkspaceAction(.init(owner: owner, action: .openGroupSettings(roomID: roomID))) @@ -134,22 +109,21 @@ extension RootShellView { rooms: botModeRooms.catalogRooms, onOpenGroup: { roomID in guard let owner else { return } - appState.chatOpenedFromList = true handleAgentWorkspaceAction(.init(owner: owner, action: .openGroup(roomID: roomID))) } ) } - /// New Group Chat's Section row in Bots mode: the group chat goes in the picked section once it's made. + /// New Group Chat's Section row: the group chat goes in the picked section once it's made. var groupSectionChoice: BotModeCreateSectionChoice? { - guard simpleBotsOn, let fleet, let hostID = fleet.selectedHostID, !fleet.sections.isEmpty else { return nil } + guard let fleet, let hostID = fleet.selectedHostID, !fleet.sections.isEmpty else { return nil } return BotModeCreateSectionChoice(sections: fleet.sections) { roomID, sectionID in fleet.file(groupKey: FleetID.make(hostID, "group/" + roomID), in: sectionID) } } /// Where the bots' working states come from: the gateway in use's plugin route, else what stock - /// Hermes tells the app of its Bot Chats; with Multi-gateway, also the other gateways' fresh + /// Hermes tells the app of its Bot Chats; with every computer shown, also the other gateways' fresh /// all-hosts copies. The closures hold only stores, so each tick reads what's current. var botChatActivitySource: BotChatActivitySource { let agents = agents, catalog = sessionCatalog, connections = workspaceConnections @@ -179,20 +153,20 @@ extension RootShellView { fallback: { BotChatActivitySignals.botChats(catalog.records) }) }, others: { - guard settings.simpleBotsEnabled, settings.simpleBotsMultiGateway, let fleet else { return [:] } + guard settings.showsEveryComputer, let fleet else { return [:] } return BotChatActivitySignals.fleet(fleet.snapshots, now: Date()) }, refreshOthers: { - guard settings.simpleBotsEnabled, settings.simpleBotsMultiGateway else { return } + guard settings.showsEveryComputer else { return } fleet?.refresh() }) } - /// Multi-gateway: every gateway's bots. The one in use is live, or its all-hosts copy until its agents + /// Show every computer: every computer's bots. The one in use is live, or its all-hosts copy until its agents /// are known (the home stays on screen while it connects); the others come from their copies, which /// stay current because those gateways stay connected (`keepsFleetHostsConnected`). - private var simpleBotsGateways: SimpleBotsGateways? { - guard simpleBotsMultiGatewayOn, let fleet else { return nil } + var simpleBotsGateways: SimpleBotsGateways? { + guard showsEveryHost, let fleet else { return nil } let selected = fleet.selectedHostID let liveKnown = nativeRuntime != nil && agents.knowsProfiles var bots: [SimpleBotsBot] = [], latest: [String: SimpleBotsLatest] = [:], pinned: [String] = [] @@ -236,7 +210,7 @@ extension RootShellView { ?? shown.first { $0.hostID == selected && $0.isDefault }?.id ?? shown.first(where: \.isDefault)?.id return SimpleBotsGateways( selectedHostID: selected, bots: bots, latest: latest, pinnedIDs: pinned, primaryID: primaryID, - filter: settings.simpleBotsGatewayFilter ? fleet.hosts : nil, + filter: fleet.hosts.count > 1 ? fleet.hosts : nil, open: { open, hostID in openFleet(open, on: hostID) }, setPinned: { bot, pin in if bot.profile != nil, bot.hostID == fleet.selectedHostID { @@ -265,37 +239,21 @@ extension RootShellView { groups: groups) } - /// The edge swipes in Bots mode (`effectiveLeftEdgeSwipeAction`): from the left back to your - /// bots, from the right this bot's profile (the primary bot's on the home). False for anything else. - func performSimpleBotsSwipe(_ action: WorkspaceSwipeAction) -> Bool { - switch action { - case .agents: - appState.select(.sessions) - appState.path.removeAll() - return true - case .profile: - let chatBot: String? = if case .chat(let id)? = appState.path.last { - featureStore.preparedChatModel(id: id)?.memberIDs.first - } else { nil } - guard let botID = chatBot ?? agents.primaryAgentID ?? agents.profiles.first(where: \.isDefault)?.id - else { return true } - if case .simpleBotProfile(let shown, _)? = appState.path.last, shown == botID { return true } - appState.open(.simpleBotProfile(agentID: botID)) - return true - default: - return false + /// The bot's page over its chat, from its name in the chat's header or ⋯ › Bot page. It is pushed + /// one turn of the run loop after the tap: pushed inside the tap's own update, the navigation + /// stack sometimes kept the new path and showed nothing (the page never drew; about one tap in + /// three in `HomeShellUITests`). + func openBotPage(fromChat agentID: String) { + DispatchQueue.main.async { [appState] in + if case .simpleBotProfile(agentID, _)? = appState.path.last { return } + appState.open(.simpleBotProfile(agentID: agentID)) } } - /// A bot's chat over the home, with Back: its Bot Chat, like everywhere else. + /// A bot's own Bot Chat, pushed with Back, whatever Settings › Chat › A bot opens says: what a + /// Dashboard's Ask, Needs you and Work's background row lead to. func openSimpleBotChat(_ agentID: String) { - openCanonicalAgentChat(agentID, fromList: true) - } - - /// Its scheduled tasks as a page with Back, not the Tasks tab Bots mode doesn't show. - func openSimpleBotRoutines(_ agentID: String) { - guard featureStore.prepareScheduledTasks(filteredTo: agentID) else { return } - appState.open(.scheduledTasks) + openCanonicalAgentChat(agentID) } /// A new bot, made the way New agent makes one: a copy of the default bot's setup where the host can. @@ -320,19 +278,21 @@ extension RootShellView { let canEdit = usesWorkspaceFixtures || (owner.map { currentWorkspaceCapabilities.supports(.profilesEdit, owner: $0, profileID: agentID) } ?? false) let agent = agents.profiles.first { $0.id == agentID } + let capabilities = currentWorkspaceCapabilities + let editReason: String? = canEdit ? nil : owner.map { + AgentActionsPresentation.unavailableMessage( + capabilities.availability(for: .profilesEdit, owner: $0, profileID: agentID)) + ?? WorkspaceUnavailableReason.unsupportedOperation.message + } ?? WorkspaceUnavailableReason.notConnected.message + let canDuplicate = workspaceConnections?.cloneClient != nil + && owner.map { capabilities.supports(.profilesClone, owner: $0, profileID: agentID) } == true return SimpleBotProfileContext( agents: agents, scheduledTasks: featureStore.scheduledTasks, screenService: makeBotScreenService(), screenChats: agent.map(botScreenChats(for:)) ?? [], canEdit: canEdit, onOpenChat: { openSimpleBotChat($0) }, onOpenRoutine: { openScheduledTask($0) }, - onEditDetails: { profile in - // The demo has no computer, and its editor opens all the same. - guard owner != nil || usesWorkspaceFixtures else { return } - let signIn = owner?.signIn - workspaceProfileEditor = .editing(profile, store: agents, processor: AvatarImageProcessor(), - isCurrent: { currentWorkspaceOwner?.signIn == signIn }) - }, + makeModelDefaults: { id in let capabilities = currentWorkspaceCapabilities guard usesWorkspaceFixtures || owner.map({ @@ -359,7 +319,28 @@ extension RootShellView { configureShellBoard: { await configureAgentBoard($0) }, onAsk: { id, text in askSimpleBot(id, text, fillsBlanks: false) }, onSend: { id, text in askSimpleBot(id, text, fillsBlanks: false, sendsAtOnce: true) }, - onBlueprint: { id, text in askSimpleBot(id, text, fillsBlanks: true) }) + onBlueprint: { id, text in askSimpleBot(id, text, fillsBlanks: true) }), + editUnavailableReason: editReason, + makeEditor: { profile in + guard owner != nil || usesWorkspaceFixtures else { return nil } + let signIn = owner?.signIn + return .editing(profile, store: agents, processor: AvatarImageProcessor(), + isCurrent: { currentWorkspaceOwner?.signIn == signIn }) + }, + // The page is pushed only once its computer is the one in use (`performFleetOpen`). + openingComputer: nil, + onNewChat: { startNewChat(explicitAgentID: $0) }, + onOpenChats: { openSessions(filteredTo: $0) }, + pinning: BotProfilePinning(isPinned: { agents.isPinned($0) }, canPin: { agents.canPin($0) }, + setPinned: { id, pin in _ = pin ? agents.pinAgent(id) : agents.unpinAgent(id) }), + offersShortcuts: usesWorkspaceFixtures || (nativeRuntime != nil && owner != nil), + makeDuplicate: canDuplicate ? { profile in + guard let owner, let client = workspaceConnections?.cloneClient else { return nil } + return AgentDuplicateModel(source: profile, owner: owner, client: client, + isCurrent: { currentWorkspaceOwner == owner }) + } : nil, + onManageBots: { id in _ = openLifecycleDestination(.profileLifecycle, reattaching: false, profileID: id) }, + deletion: agentDeletionAction ) } diff --git a/Bighelp/App/RootSplit.swift b/Bighelp/App/RootSplit.swift index 9eb2949a..09a6994b 100644 --- a/Bighelp/App/RootSplit.swift +++ b/Bighelp/App/RootSplit.swift @@ -1,12 +1,13 @@ import SwiftUI -// The iPhone Duo open (`BighelpSplitColumn`): Bots mode's home, the chat list or Code's home beside -// the page, and the chat they open pushed beside them on the one navigation stack. +// The iPhone Duo open (`BighelpSplitColumn`): the tab's root left of the fold, and the chat it opens +// pushed beside it on the one navigation stack. extension RootShellView { enum SplitList: Hashable { - case bots, chats, code - /// Any other page, while a chat opened from it is open: the page stays left of the fold. - case page(AppTab) + /// The first tab (Bots or Chats) and Work: always beside the page. + case conversations, work + /// Today, while a chat opened from it is open: it stays left of the fold. + case page(HomeTab) /// A list that stays beside the page; the stack's own root shows a placeholder instead. var isList: Bool { @@ -15,22 +16,16 @@ extension RootShellView { } } - /// What the open Duo shows left of the fold for the tab showing now; nil anywhere else. Bots - /// mode's home, the chat list and Code's home always; any other page while one of its chats is - /// open, so a chat never lies across the fold. + /// What the open Duo shows left of the fold for the tab showing now; nil anywhere else. The + /// first tab and Work always; Today while one of its chats is open, so a chat never lies + /// across the fold. var splitList: SplitList? { guard screen.posture == .open else { return nil } switch appState.selectedTab { - case .sessions, .sessionList: - if simpleBotsOn { return .bots } - // All agents has its own wide home. - if !fleetModeOn { return .chats } - case .code: - if !simpleBotsOn { return .code } - default: - break + case .conversations: return .conversations + case .work: return .work + case .today: return showsChatOverPage ? .page(.today) : nil } - return showsChatOverPage ? .page(appState.selectedTab) : nil } /// A chat (or Code's batch chat) is open over a page. @@ -44,22 +39,15 @@ extension RootShellView { /// Changes when another list, or another computer's, should show. var splitColumnKey: String { let list: String = switch splitList { - case .bots: "bots" - case .chats: "chats" - case .code: "code" + case .conversations: "conversations:\(home.view.rawValue)" + case .work: "work" case .page(let tab): "page:\(tab.rawValue)" case nil: "none" } - // A new shell (another computer, all hosts on or off, a new runtime) brings its own stores, - // and the chat list and Code's home are made once the computer answers. Their stores don't - // tell the column when that happens, so the column is drawn again then. - let ready: String = switch splitList { - case .chats: featureStore.preparedModel(for: .sessions) == nil ? "loading" : "ready" - case .code: codeHome?.scopeID ?? "loading" - default: "" - } + // A new shell (another computer, a new runtime) brings its own stores, which don't tell + // the column when that happens, so the column is drawn again then. return [list, currentWorkspaceOwner?.cacheScopeID ?? "local", splitColumnShellID.uuidString, - nativeRuntime.map { "\(ObjectIdentifier($0).hashValue)" } ?? "-", fleet == nil ? "" : "fleet", ready] + nativeRuntime.map { "\(ObjectIdentifier($0).hashValue)" } ?? "-", fleet == nil ? "" : "fleet"] .joined(separator: "|") } @@ -69,59 +57,26 @@ extension RootShellView { splitColumn.hide() return } - // The list the root would have made, made before the column first draws it. - if list == .chats, featureStore.preparedModel(for: .sessions) == nil { - _ = featureStore.prepareSessions(filteredTo: nil) + let tab: HomeTab = switch list { + case .conversations: .conversations + case .work: .work + case .page(let tab): tab } splitColumn.show(splitColumnKey) { - AnyView(splitColumnList(list) + // Every root draws its own header, so the column's bar stays hidden. + AnyView(BighelpLiveColumn { homeRoot(tab) } + .toolbar(.hidden, for: .navigationBar) .environment(\.agentDeletion, agentDeletionAction) .environment(\.providerUsage, providerUsage)) } } - @ViewBuilder - private func splitColumnList(_ list: SplitList) -> some View { - switch list { - case .bots: - // Bots mode's home draws its own header. - BighelpLiveColumn { simpleBotsHome } - .toolbar(.hidden, for: .navigationBar) - case .chats: - BighelpLiveColumn { sessionsRootTab } - .navigationTitle(String(localized: "Sessions")) - .navigationBarTitleDisplayMode(.inline) - .toolbar { splitColumnToolbar } - case .code: - BighelpLiveColumn { codeRootTab } - .navigationTitle(String(localized: "Code")) - .navigationBarTitleDisplayMode(.inline) - .toolbar { splitColumnToolbar } - case .page: - // Boards draw their own header; the rest have the page's title and ☰. - BighelpLiveColumn { rootTabs } - .toolbar(showsAgentBoard(appState.selectedTab) ? .hidden : .automatic, for: .navigationBar) - .navigationTitle(rootNavigationTitle) - .navigationBarTitleDisplayMode(.inline) - .toolbar { splitColumnToolbar } - } - } - - /// ☰ and the brand (or the Header mode switcher) move from the page's bar to the list's. - @ToolbarContentBuilder - private var splitColumnToolbar: some ToolbarContent { - ToolbarItem(placement: .topBarLeading) { rootMenuButton } - if let barModeSwitch { - ToolbarItem(placement: .principal) { BighelpModePill(modeSwitch: barModeSwitch) } - } - } - /// The page beside the list before anything is open in it. func splitPlaceholder(_ list: SplitList) -> some View { let message = switch list { - case .bots: String(localized: "Pick a bot to chat with.") - case .chats: String(localized: "Pick a chat, or start a new one.") - case .code: String(localized: "Pick a session, or send a new one.") + case .conversations where home.view == .bots: String(localized: "Pick a bot to chat with.") + case .conversations: String(localized: "Pick a chat, or start a new one.") + case .work: String(localized: "Pick something to open.") case .page: "" } return BighelpSplitPlaceholder(message: message) diff --git a/Bighelp/App/RootUsage.swift b/Bighelp/App/RootUsage.swift index 9a4d3801..e122dde0 100644 --- a/Bighelp/App/RootUsage.swift +++ b/Bighelp/App/RootUsage.swift @@ -1,7 +1,7 @@ import SwiftUI -/// ☰ › Usage: one page for plans, limits and what the agents used. With All -/// hosts on it covers every computer; otherwise the one in use. +/// Usage (Settings, a chat's ⋯, the sidebar): one page for plans, limits and what the bots used. +/// With every computer showing it covers them all; otherwise the one in use. extension RootShellView { /// What the Usage page reads: the sign-in (a reconnect keeps it), demo data /// or not, whether All hosts is on, and the shell it opens in. @@ -14,14 +14,14 @@ extension RootShellView { /// The selected host's navigation and agents come with its runtime, which /// can arrive after its sign-in (opening the app with All hosts on). Opening /// Usage goes through the shell configured last, so a new one configures it - /// again; otherwise ☰ › Usage pushed onto a stack nothing showed (#99). + /// again; otherwise Usage pushed onto a stack nothing showed (#99). let navigation: ObjectIdentifier } var usageReaderKey: UsageReaderKey { let fixtures = usesWorkspaceFixtures && workspaceConnections?.isDirectSelected != true return UsageReaderKey(signIn: currentWorkspaceOwner?.signIn ?? workspaceSignIn, fixtures: fixtures, - allHosts: fleetModeOn, hostID: usageHostID, hostName: workspaceHostName, + allHosts: showsEveryHost, hostID: usageHostID, hostName: workspaceHostName, navigation: ObjectIdentifier(appState)) } @@ -64,15 +64,10 @@ extension RootShellView { } } - /// Usage over whatever is open, so Back returns there; its tab when it's pinned. + /// Usage over whatever is open, so Back returns right there. func openUsage() { guard appState.path.last != .usage else { return } - if barTabs.contains(.usage) { - appState.select(.usage) - } else { - // A quick screen: over whatever is open, so Back returns right there. - appState.path.append(.usage) - } + appState.path.append(.usage) } var usageDestination: some View { diff --git a/Bighelp/App/RootWorkflows.swift b/Bighelp/App/RootWorkflows.swift index b6e20478..1711b53d 100644 --- a/Bighelp/App/RootWorkflows.swift +++ b/Bighelp/App/RootWorkflows.swift @@ -13,7 +13,7 @@ extension RootShellView { return DirectHermesWorkflowsClient(currentWorkspace: { [weak connections] in connections?.workspace }) } - /// Checks the host for Workflows whenever it (re)connects, so ☰ shows the + /// Checks the host for Workflows whenever it (re)connects, so Work shows the /// row only where it works. The same computer keeps its row and its store; /// only a clear answer from the host changes the row (`WorkflowsAvailability`). func configureWorkflows(_ key: AgentBoardClientKey) async { @@ -29,28 +29,33 @@ extension RootShellView { // A page that showed before the computer answered gets its data now. if workflowsStore == nil, isWorkflowsPageOpen { prepareWorkflowsStore() } await workflowsAvailability.check { try await client.support() } + // A computer with Workflows has its store read at once, not only once Work opens: Today's + // Needs you card, the tab's dot and the sidebar's row count a waiting sign-off from it. + let hasWorkflows: Bool = if case .available? = workflowsAvailability.support { true } else { false } + if hasWorkflows { prepareWorkflowsStore() } // What the page shows comes from the new connection, not the closed one. - if isWorkflowsPageOpen { await workflowsStore?.load() } + if isWorkflowsPageOpen || hasWorkflows { await workflowsStore?.load() } } + /// Its page is open, or Work, which lists its runs. private var isWorkflowsPageOpen: Bool { - appState.selectedTab == .workflows || appState.path.contains { route in + appState.selectedTab == .work || appState.path.contains { route in if case .workflows = route { true } else { false } } } - /// ☰ shows Workflows for any connected computer. Where the plugin lacks them + /// Work shows Workflows for any connected computer. Where the plugin lacks them /// or says this computer can't run them, the Workflows page says why and /// what to do, so a slow or failed check never hides the feature. var canOpenWorkflows: Bool { workflowsAvailability.host != nil || workflowsAvailability.isAvailable == true } - /// Opens ☰ › Workflows over the chat, so Back returns there. + /// Opens Workflows over Work, so Back returns there. func openWorkflows() { guard prepareWorkflowsStore() != nil else { actionErrorMessage = "Connect to your computer to use Workflows." return } - showOneHostPageOnSessions([.workflows]) + showOverWork([.workflows]) } /// Opens one workflow (a Shortcut or a link): its flow, or its Run sheet straight away. @@ -59,13 +64,13 @@ extension RootShellView { actionErrorMessage = "Connect to your computer to use Workflows." return } - showOneHostPageOnSessions([.workflows, .workflow(id: id, startsRun: startsRun)]) + showOverWork([.workflows, .workflow(id: id, startsRun: startsRun)]) } /// Opens one run (a widget, a link or a notification later). func openWorkflows(run: String) { guard prepareWorkflowsStore() != nil else { return } - showOneHostPageOnSessions([.workflows, BighelpPlatform.isMac ? .workflowRuns(selected: run) : .workflowRun(id: run)]) + showOverWork([.workflows, BighelpPlatform.isMac ? .workflowRuns(selected: run) : .workflowRun(id: run)]) } /// A tapped workflow alert names its run only as a chat reference (`workflow.run.`, @@ -122,7 +127,7 @@ extension RootShellView { .accessibilityIdentifier("workflows.connecting") } else { ContentUnavailableView("Workflows aren't available", systemImage: "flowchart", - description: Text("Connect to your computer, then open Workflows from the menu.")) + description: Text("Connect to your computer, then open Workflows from Work.")) } } } diff --git a/Bighelp/App/RootWorkspaceActions.swift b/Bighelp/App/RootWorkspaceActions.swift index a1ca9889..049cacb5 100644 --- a/Bighelp/App/RootWorkspaceActions.swift +++ b/Bighelp/App/RootWorkspaceActions.swift @@ -218,12 +218,11 @@ extension RootShellView { guard let owner = currentWorkspaceOwner, let profile = agents.resolvedAgent(explicitID: nil), currentWorkspaceCapabilities.supports(.profilesEdit, owner: owner, profileID: profile.id) else { - actionErrorMessage = "Connect to this host before editing its agent profile." + actionErrorMessage = "Connect to this computer before editing its bot." return false } - // A reconnect to the same computer keeps the editor usable. - workspaceProfileEditor = .editing(profile, store: agents, processor: AvatarImageProcessor(), - isCurrent: { currentWorkspaceOwner?.signIn == owner.signIn }) + // Every door to a bot opens its page. + appState.open(.simpleBotProfile(agentID: profile.id)) case .instances: appState.open(.workspaceConnections) case .voice, .permissions: @@ -314,18 +313,8 @@ extension RootShellView { return nil } - /// Deleting from the Agents screen or the agent editor. Same lifecycle path - /// as Profiles, with no navigation beyond leaving a chat that was retired. - /// Lets other screens (the Chats rail) offer the Agents list's hold menu. - var agentActionsConfig: AgentActionsConfig { - AgentActionsConfig( - store: agents, runtimeDefaultsClient: agentRuntimeDefaults, owner: currentWorkspaceOwner, - capabilities: currentWorkspaceCapabilities, cloneClient: workspaceConnections?.cloneClient, - shortcutsAvailable: usesWorkspaceFixtures || (nativeRuntime != nil && currentWorkspaceOwner != nil), - onAction: handleAgentWorkspaceAction, agentDeletion: agentDeletionAction - ) - } - + /// Deleting from a bot's page. Same lifecycle path as Profiles, with no navigation beyond leaving a + /// chat that was retired. var agentDeletionAction: AgentDeletionAction? { if usesWorkspaceFixtures, nativeRuntime == nil { // The demo has no computer: the agent leaves its own list, and its screens close the same way. @@ -371,7 +360,7 @@ extension RootShellView { sessionRestoreTask?.cancel() sessionRestoreTask = nil sessionRestoreRequest = nil - appState.openSessions() + appState.select(.chats) } }) do { @@ -392,11 +381,9 @@ extension RootShellView { closeScreens(ofDeletedAgent: profileID, chats: retired.ids) } - /// The deleted agent's editor, profile and chats leave the screen, so the person lands where - /// they were before them (Bots mode's home, the Agents list) instead of on a page for an agent - /// that isn't there. + /// The deleted bot's page and chats leave the screen, so the person lands where they were before + /// them instead of on a page for a bot that isn't there. func closeScreens(ofDeletedAgent profileID: String, chats: Set) { - if workspaceProfileEditor?.editingAgentID == profileID { workspaceProfileEditor = nil } appState.path.removeAll { route in switch route { case .simpleBotProfile(let agentID, _): agentID == profileID @@ -406,7 +393,9 @@ extension RootShellView { } } - func openLifecycleDestination(_ destination: WorkspaceDestination, reattaching: Bool) -> Bool { + /// `profileID`: Manage bots from a bot's page opens on that bot; else the bot in use. + func openLifecycleDestination(_ destination: WorkspaceDestination, reattaching: Bool, + profileID: String? = nil) -> Bool { let presentationID = UUID() do { guard let coordinator = try makeLifecycleCoordinator(isShown: { lifecyclePresentationID == presentationID }) @@ -417,7 +406,7 @@ extension RootShellView { return false } lifecycleCoordinator = coordinator - lifecycleProfileID = workspaceAgentID + lifecycleProfileID = profileID ?? (reattaching ? (lifecycleProfileID ?? workspaceAgentID) : workspaceAgentID) lifecyclePresentationID = presentationID if !reattaching { appState.open(.workspaceManagement(destination)) } return true @@ -459,7 +448,7 @@ extension RootShellView { guard currentWorkspaceOwner == owner else { throw WorkspaceClientError.ownerChanged } if isShown() { switch result.change { - case .renamed, .deleted: appState.openSessions() + case .renamed, .deleted: appState.select(.conversations) default: break } } @@ -470,7 +459,7 @@ extension RootShellView { sessionRestoreTask?.cancel() sessionRestoreTask = nil sessionRestoreRequest = nil - appState.openSessions() + appState.select(.chats) } }) } @@ -481,17 +470,6 @@ extension RootShellView { return } switch request.action { - case .openAgentSessions(let id): - openSessions(filteredTo: id) - case .openAgentGroups(let id): - agentGroupFilterRequest = id - appState.select(.agents) - case .openAgentScheduledTasks(let id): - openScheduledTasks(filteredTo: id) - case .openHostStatus: - isHostStatusPresented = true - case .openAgentChat(let id): - openAgentChat(id) case .openGroup(let id): openHostedGroup(id, owner: request.owner, settings: false) case .openGroupSettings(let id): @@ -532,9 +510,15 @@ extension RootShellView { } } - func openHostedGroup(_ id: String, owner: WorkspaceOwner, settings: Bool) { + /// `firstMessage`: New chat's text for a group chat it just made, sent there once it opens. + /// `opened` is called once: with the chat's ID when it is on screen, else nil. + func openHostedGroup(_ id: String, owner: WorkspaceOwner, settings: Bool, firstMessage: String? = nil, + opened: (@MainActor (String?) -> Void)? = nil) { Task { @MainActor in - guard currentWorkspaceOwner == owner else { return } + guard currentWorkspaceOwner == owner else { + opened?(nil) + return + } do { let room = try await botModeRooms.openNativeRoom(roomID: id) guard currentWorkspaceOwner == owner else { throw WorkspaceClientError.ownerChanged } @@ -543,14 +527,26 @@ extension RootShellView { title: room.title, remoteSource: "hermes-room", botModeRoomID: room.id), ownerIsCurrent: { currentWorkspaceOwner == owner } ) + if let firstMessage, !firstMessage.isEmpty { + sessionCatalog.updateDraft(firstMessage, for: record.id) + appState.sendsDraftOnOpen.insert(record.id) + } let route = AppRoute.chat(conversationID: record.id) guard featureStore.prepare(route), case .chat(let model)? = featureStore.preparedModel(for: route) else { throw WorkspaceClientError.unavailable(.unsupportedOperation) } - if settings { appState.open(.groupSettings(roomID: room.id, conversationID: model.conversationID)) } - else { appState.activateConversation(id: record.id, source: .sessions) } + if settings { + appState.open(.groupSettings(roomID: room.id, conversationID: model.conversationID)) + opened?(nil) + } else { + appState.activateConversation(id: record.id, source: .sessions) + // New chat's own paths take its blank chat off the stack here (`dropNewChatBlank`). + // A group chat opened any other way (a link, an alert, Chats) leaves the stack as it is. + opened?(record.id) + } } catch { + opened?(nil) guard currentWorkspaceOwner == owner else { return } actionErrorMessage = "Hermes could not open this group. " + (HermesRefusalMessage.sentence(in: error) ?? "Check the host and try again.") diff --git a/Bighelp/App/RootWorkspaceServices.swift b/Bighelp/App/RootWorkspaceServices.swift index 5648a197..8e0f801a 100644 --- a/Bighelp/App/RootWorkspaceServices.swift +++ b/Bighelp/App/RootWorkspaceServices.swift @@ -113,8 +113,8 @@ extension RootShellView { } var nativeDeviceToolTrigger: String { - let coordinate = appState.activeConversationID.flatMap { nativeRuntime?.bridge.currentCoordinate(for: $0) } - return "\(nativeWorkspaceStore?.nativeClient?.isConnected == true):\(voiceSettingsScope ?? "none"):\(appState.activeConversationID ?? "none"):\(coordinate?.storedSessionID ?? "none"):\(coordinate?.runtimeSessionID ?? "none"):\(permissionCenter.deviceTools.revision):\(hostRegistry?.deviceToolFeatureReadinessToken ?? 0):\(deviceToolsOpen):\(UIApplication.shared.isProtectedDataAvailable)" + let coordinate = appState.deviceToolConversationID.flatMap { nativeRuntime?.bridge.currentCoordinate(for: $0) } + return "\(nativeWorkspaceStore?.nativeClient?.isConnected == true):\(voiceSettingsScope ?? "none"):\(appState.deviceToolConversationID ?? "none"):\(coordinate?.storedSessionID ?? "none"):\(coordinate?.runtimeSessionID ?? "none"):\(permissionCenter.deviceTools.revision):\(hostRegistry?.deviceToolFeatureReadinessToken ?? 0):\(deviceToolsOpen):\(UIApplication.shared.isProtectedDataAvailable)" } /// Whether the phone's channel runs: while bighelp is active or inactive (a notification pulled @@ -128,16 +128,16 @@ extension RootShellView { func runNativeDeviceTools() async { #if DEBUG if usesDemoFixtures, let call = permissionCenter.demoAppearanceCall, let scope = currentDeviceToolScope, - let conversationID = appState.activeConversationID, scenePhase == .active { + let conversationID = appState.deviceToolConversationID, scenePhase == .active { await call.send(scope: scope, isCurrent: { - appState.activeConversationID == conversationID && scenePhase == .active + appState.deviceToolConversationID == conversationID && scenePhase == .active }) return } if usesDemoFixtures, let call = permissionCenter.demoAccessCall, let scope = currentDeviceToolScope, - let conversationID = appState.activeConversationID, scenePhase == .active { + let conversationID = appState.deviceToolConversationID, scenePhase == .active { await call.send(scope: scope, conversationID: conversationID, isCurrent: { - appState.activeConversationID == conversationID && Self.deviceToolsOpenNow + appState.deviceToolConversationID == conversationID && Self.deviceToolsOpenNow }) return } @@ -154,7 +154,7 @@ extension RootShellView { // Off, but a card in the chat can turn it on when an agent asks for it. let askable = DeviceAccessAsk.askable(permissions) guard !enabled.isEmpty || !askable.isEmpty else { permissionCenter.nativeDeviceToolStatus = nil; return } - guard let conversationID = appState.activeConversationID, + guard let conversationID = appState.deviceToolConversationID, let coordinate = nativeRuntime?.bridge.currentCoordinate(for: conversationID), coordinate.owner == owner else { NativeDeviceToolSession.log.notice("no channel: the chat has no session yet") @@ -180,7 +180,7 @@ extension RootShellView { enabled: enabled, askable: askable, isAvailable: { permissions.scope == scope && permissions.revision == revision && Self.deviceToolsOpenNow && UIApplication.shared.isProtectedDataAvailable - && appState.activeConversationID == conversationID + && appState.deviceToolConversationID == conversationID }, isPaused: { !Self.deviceToolsOpenNow }, isAnswering: { features.preparedChatModel(id: conversationID)?.isSending == true }, handle: guarded) @@ -252,32 +252,6 @@ extension RootShellView { OnDeviceSpeechEngine.isSupported ? OnDeviceVoiceSettingsClient(host: client, computer: computer) : client } - var pluginUpdateScope: String? { - guard nativeWorkspaceStore == nil else { return nil } - #if DEBUG - if usesDemoFixtures, ProcessInfo.processInfo.arguments.contains("-plugin-update-fixture") { - return "fixture-plugin-update" - } - #endif - return nil - } - - var pluginUpdateIsCurrent: @MainActor () -> Bool { - #if DEBUG - if usesDemoFixtures, ProcessInfo.processInfo.arguments.contains("-plugin-update-fixture") { return { true } } - #endif - return { false } - } - - var pluginUpdateClient: (any PluginUpdateClient)? { - #if DEBUG - if usesDemoFixtures, ProcessInfo.processInfo.arguments.contains("-plugin-update-fixture") { - return PluginUpdatePreviewClient() - } - #endif - return nil - } - var hostRuntimeScope: String? { guard nativeWorkspaceStore == nil else { return nil } #if DEBUG diff --git a/Bighelp/App/ShellFeatureStore.swift b/Bighelp/App/ShellFeatureStore.swift index 81780fb9..be88ddbc 100644 --- a/Bighelp/App/ShellFeatureStore.swift +++ b/Bighelp/App/ShellFeatureStore.swift @@ -172,12 +172,12 @@ final class ShellFeatureStore { // views, and are retired when presentation resumes or the account changes. private var backgroundActivityProjections: [String: BackgroundActivityProjection] = [:] - // MARK: Code mode + // MARK: Coding sessions /// True when sessions here have Hermes' own settings (a live host, not the demo). var hasNativeSessionControls: Bool { sessionControlMessaging is any SessionYOLOControlling } - /// Turns a session's YOLO setting (no approval prompts) on or off; Code mode's YOLO mode. + /// Turns a session's YOLO setting (no approval prompts) on or off; a coding session's YOLO mode. func setSessionYOLO(_ on: Bool, sessionID: String, agentID: String) async throws { guard let controls = sessionControlMessaging as? any SessionYOLOControlling else { throw WorkspaceClientError.unavailable(.unsupportedOperation) @@ -420,7 +420,7 @@ final class ShellFeatureStore { approvalModels[requestID].map(PreparedRouteModel.approval) case .skillsAndTools, .workspaceSettings, .workspaceManagement, .workspaceConnections, - .projects, .project, .kanban, .usage, .allHostsChats, .board, + .projects, .project, .kanban, .usage, .board, .work, .workflows, .workflow, .workflowRun, .workflowSignoff, .workflowRuns, .codeChanges, .codeBatch, .devFactory, .devFactoryRecipe, .devFactoryGroup, .devFactoryChanges, .simpleBotProfile, .groupSettings, .simpleBotsSection: nil @@ -507,7 +507,7 @@ final class ShellFeatureStore { return true case .skillsAndTools, .workspaceSettings, .workspaceManagement, .workspaceConnections, - .projects, .project, .kanban, .usage, .allHostsChats, .board, + .projects, .project, .kanban, .usage, .board, .work, .workflows, .workflow, .workflowRun, .workflowSignoff, .workflowRuns, .codeChanges, .codeBatch, .devFactory, .devFactoryRecipe, .devFactoryGroup, .devFactoryChanges, .simpleBotProfile, .groupSettings, .simpleBotsSection: return true diff --git a/Bighelp/App/WorkspaceEdgeSwipeResolver.swift b/Bighelp/App/WorkspaceEdgeSwipeResolver.swift index ed1af916..479863c7 100644 --- a/Bighelp/App/WorkspaceEdgeSwipeResolver.swift +++ b/Bighelp/App/WorkspaceEdgeSwipeResolver.swift @@ -27,10 +27,10 @@ enum WorkspaceEdgeSwipeResolver { return nil } - /// Feed, Ideas and Goals rows swipe left to dismiss. The trailing strip sat over the right - /// end of every row and took those drags first (opening New chat), so it steps aside there. - /// A chat pushed over a board keeps it. - static func trailingEdgeIsActive(tab: AppTab, pathIsEmpty: Bool) -> Bool { - !(pathIsEmpty && [.feed, .ideas, .goals].contains(tab)) + /// Today's rows swipe. The trailing strip sat over the right end of every row and took those + /// drags first (opening New chat), so it steps aside on Today's root. A chat pushed over it + /// keeps the swipe. + static func trailingEdgeIsActive(tab: HomeTab, pathIsEmpty: Bool) -> Bool { + !(pathIsEmpty && tab == .today) } } diff --git a/Bighelp/AppState/BotsAppState.swift b/Bighelp/AppState/BotsAppState.swift index 83441b5a..e1ff8094 100644 --- a/Bighelp/AppState/BotsAppState.swift +++ b/Bighelp/AppState/BotsAppState.swift @@ -4,7 +4,7 @@ import Foundation struct BotsAppStateHost: Equatable, Sendable { /// This phone's own ID for it (the host registry's), different on every device. let hostKey: String - /// Its sign-ins' cache scopes (`WorkspaceOwner.cacheScopeID`): Bots mode's order and the voices are kept by these. + /// Its sign-ins' cache scopes (`WorkspaceOwner.cacheScopeID`): the Bots view's order and the voices are kept by these. let scopes: [String] /// Where its bots' faces are kept on this phone (`CompanionSurfaceScope.computer`). let faceScope: String @@ -18,10 +18,10 @@ struct BotsPhoneState: Equatable { var sections: [FleetSection] = [] /// A group chat's section, by `FleetGroup.id`. var groupSections: [String: String] = [:] - /// Group chats pinned on Bots mode's home and ones hidden from it, by `FleetGroup.id`. + /// Group chats pinned on the Bots view and ones hidden from it, by `FleetGroup.id`. var pinnedGroups: [String] = [] var hiddenGroups: [String] = [] - /// Multi-gateway's primary bot (`FleetID`). + /// Show every computer's primary bot (`FleetID`). var primary: String? /// `AgentVoiceChoices`, by its entry keys. var voices: [String: AgentVoiceChoices.Choice] = [:] @@ -33,7 +33,7 @@ struct BotsPhoneState: Equatable { var pins: [String: AgentDirectoryStore.SavedPins] = [:] } -/// Bots mode's choices as the computers keep them (`native-app-state-v1`), named so every device +/// The Bots view's choices as the computers keep them (`native-app-state-v1`), named so every device /// means the same thing: a bot is `/` and a group chat `/`, by the ID each computer's plugin makes for itself. The host ID this phone makes is its own, /// so it never leaves the phone. Hosts without a computer ID (their plugin doesn't keep app state) @@ -43,7 +43,7 @@ struct BotsPhoneState: Equatable { /// `bots.layout` (v1): `sections` [{id, name}], `groupSections` {group: section}, `home` {computer: /// {list, top, pinned, unpinned, primary}} for one gateway's home (pins and the primary bot are this /// app's own, kept on the phone per sign-in, not on the profiles), `multiGatewayHome` {list, top}, -/// `primary` (Multi-gateway's), and `pinnedGroups` and `hiddenGroups` [`/`]. List and top items +/// `primary` (Show every computer's), and `pinnedGroups` and `hiddenGroups` [`/`]. List and top items /// are `bot//` and `group//`. /// /// `bots.settings` (v1): `bots` {bot: {voice, mark, pet, character}}. @@ -318,7 +318,7 @@ enum BotsAppState { } } - /// A Multi-gateway home's item (`bot:/`, `group:/group/`; on top, bots' + /// An item of the Bots view with every computer shown (`bot:/`, `group:/group/`; on top, bots' /// bare `FleetID`s and pinned group chats' items) by the computer. Orders saved before group chats /// were named by their gateway have `group:hermes-room:` for the gateway in use. static func portableMultiItem(_ item: String, names: Names, top: Bool = false) -> String? { diff --git a/Bighelp/AppState/BotsAppStateSync.swift b/Bighelp/AppState/BotsAppStateSync.swift index 118f8078..a7057c31 100644 --- a/Bighelp/AppState/BotsAppStateSync.swift +++ b/Bighelp/AppState/BotsAppStateSync.swift @@ -1,7 +1,7 @@ import Foundation import Observation -/// The stores that keep Bots mode's choices on this phone. +/// The stores that keep the Bots view's choices on this phone. @MainActor struct BotsAppStateStores { let order: SimpleBotsOrderStore @@ -55,7 +55,7 @@ struct BotsAppStateStores { } } -/// Keeps Bots mode's choices (the order of the home, sections, the primary bot and each bot's +/// Keeps the Bots view's choices (the order of the home, sections, the primary bot and each bot's /// voice, mark, pet and character) on the person's computers, and the newest of them on this phone. /// A change in any of those stores becomes patches (`BotsAppState` shapes) and goes to every /// computer reached; each sync reads them all and puts the newest on this phone. The stores stay diff --git a/Bighelp/Approvals/NeedsYouDeckView.swift b/Bighelp/Approvals/NeedsYouDeckView.swift index 504347c5..01b06633 100644 --- a/Bighelp/Approvals/NeedsYouDeckView.swift +++ b/Bighelp/Approvals/NeedsYouDeckView.swift @@ -144,7 +144,7 @@ extension EnvironmentValues { } /// Needs you: every approval, question and sign-off that waits on the person, one per tab, each -/// answered here. It opens from ☰ and, for a chat's own prompts (`focusedClient`), from that chat. +/// answered here. It opens from Today's Needs you card and the sidebar and, for a chat's own prompts (`focusedClient`), from that chat. @MainActor struct NeedsYouDeckView: View { var context: NeedsYouDeckContext? = nil diff --git a/Bighelp/Board/AgentBoardViews.swift b/Bighelp/Board/AgentBoardViews.swift index 939cab55..aa09cc97 100644 --- a/Bighelp/Board/AgentBoardViews.swift +++ b/Bighelp/Board/AgentBoardViews.swift @@ -17,18 +17,24 @@ struct AgentBoardContext { let onSend: (String) -> Void /// Opens a chat with this agent with a blueprint in its message box, its blanks as chips. let onBlueprint: (String) -> Void - /// The Chat tab's header controls, so every board has ☰, New chat and ⋯ too. - let onMenu: () -> Void - let onNewChat: () -> Void - let onPickAgents: () -> Void - /// This agent's places on the host, for ⋯ (Files, Memory, Skills & tools…). - let tools: [(title: String, systemImage: String, action: () -> Void)] - /// Something new on a board that's only in ☰, for a dot on ☰. - var menuHasUnread = false - /// Opened as a quick screen (from ☰, not in the bottom bar): Back where ☰ would be. + /// Opens this agent's chat, from New chat on a board in a sheet. + var onNewChat: () -> Void = {} + /// A board in a sheet (a bot's Dashboard › See all): Back and New chat float over it. Nil on a page + /// that draws its own Back over the board (Today's See all). var onBack: (() -> Void)? = nil } +extension View { + /// Back and New chat over a board that was opened in a sheet. + func boardSheetButtons(_ context: AgentBoardContext) -> some View { + overlay(alignment: .top) { + if let onBack = context.onBack { + AgentBoardHeaderButtons(agentName: context.agentName, onBack: onBack, onNewChat: context.onNewChat) + } + } + } +} + // MARK: - Shared pieces /// A board page. A List, not a ScrollView: only List rows get swipe actions, so Feed, Ideas and @@ -52,8 +58,7 @@ struct BoardScroll: View { let side = max(BighelpTokens.space20, (geometry.size.width - 720) / 2 + BighelpTokens.space20) List { Group { - // Between ☰ and New chat, as on the chat: the avatar opens the profile, the name - // switches agents. + // The avatar opens the bot's page. AgentHeroHeader(agentID: context.agentID, displayName: context.agentName, imageURL: context.imageURL, activity: context.activity, avatarSize: 56, onAvatarTap: context.onProfile, onNameTap: context.onSwitchAgent) @@ -76,7 +81,7 @@ struct BoardScroll: View { .contentMargins(.bottom, 120, for: .scrollContent) } .scrollIndicators(.hidden) - .overlay(alignment: .top) { AgentBoardHeaderButtons(context: context) } + .boardSheetButtons(context) .bighelpRefreshable { await context.store.load(agentID: context.agentID) } .task(id: context.agentID) { if context.store.agentID != context.agentID || context.store.state == .idle { @@ -1325,95 +1330,3 @@ struct IdeaDetailSheet: View { @BighelpThemeReader private var theme } - -// MARK: - Apps - -struct AgentAppsView: View { - enum Segment: String, CaseIterable, Identifiable { - case artifacts = "Artifacts", media = "Media" - var id: String { rawValue } - } - - let context: AgentBoardContext - let media: AgentMediaStore - @ViewBuilder let artifacts: () -> Artifacts - @State private var segment: Segment = .artifacts - @State private var preview: ChatAttachment? - - var body: some View { - VStack(spacing: BighelpTokens.space12) { - AgentHeroHeader(agentID: context.agentID, displayName: context.agentName, - imageURL: context.imageURL, activity: context.activity, - onAvatarTap: context.onProfile, onNameTap: context.onSwitchAgent) - .frame(maxWidth: .infinity) - .padding(.top, BighelpTokens.space8) - .overlay(alignment: .top) { AgentBoardHeaderButtons(context: context) } - Picker("Show", selection: $segment) { - ForEach(Segment.allCases) { Text($0.rawValue).tag($0) } - } - .bighelpSegmentedPicker() - .padding(.horizontal, BighelpTokens.space20) - .accessibilityIdentifier("board.apps.segment") - switch segment { - case .artifacts: - artifacts() - .frame(maxWidth: .infinity, maxHeight: .infinity) - case .media: - mediaGrid - } - } - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .task(id: context.agentID) { - if context.store.agentID != context.agentID { await context.store.load(agentID: context.agentID) } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("board.apps") - } - - /// Pictures and videos the agent sent or made, then pictures from its posts. - private var mediaGrid: some View { - let pictures = context.store.items.filter { !$0.dismissed }.flatMap { item in - item.pictures.map { (item, $0) } - } - return ScrollView { - if media.items.isEmpty, pictures.isEmpty { - if media.state == .loading || media.state == .idle { - ProgressView().padding(.top, BighelpTokens.space32) - } else { - ContentUnavailableView("No media yet", systemImage: "photo.on.rectangle", - description: Text(emptyMediaText)) - .padding(.top, BighelpTokens.space24) - } - } else { - LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 2), count: 3), spacing: 2) { - ForEach(media.items) { item in - AgentMediaTile(item: item, store: media) { - Task { preview = await media.attachment(for: item) } - } - } - ForEach(Array(pictures.enumerated()), id: \.offset) { _, entry in - BoardPictureView(item: entry.0, picture: entry.1, store: context.store) - .aspectRatio(1, contentMode: .fill) - .frame(minWidth: 0, maxWidth: .infinity) - .clipped() - } - } - .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) - .padding(.horizontal, BighelpTokens.space20) - } - } - .bighelpRefreshable { await media.load(agentID: context.agentID) } - .task(id: context.agentID) { await media.load(agentID: context.agentID) } - .bighelpSheet(item: $preview) { ChatAttachmentPreviewView(attachment: $0).bighelpSheetSize(.large) } - .padding(.bottom, 100) - .accessibilityIdentifier("board.media") - } - - private var emptyMediaText: String { - media.state == .unavailable - ? "Pictures and videos \(context.agentName) sends you show up here once the bighelp plugin on your Hermes host is updated." - : "Pictures and videos \(context.agentName) sends you or makes show up here." - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Board/AgentHomeChrome.swift b/Bighelp/Board/AgentHomeChrome.swift index c78f2e4e..f01ee21e 100644 --- a/Bighelp/Board/AgentHomeChrome.swift +++ b/Bighelp/Board/AgentHomeChrome.swift @@ -1,48 +1,23 @@ import SwiftUI -/// Hooks the shell gives a chat so it can draw the agent-home look: the -/// big live avatar, the ☰ drawer, New chat, and the bottom bar under the composer. +/// What the shell gives a chat it pushed: `onProfile` opens the bot's page, from the header's pill and +/// from ⋯ › Bot page. A chat drawn outside the shell (a fixture, a test) has neither, and no New chat +/// parts. struct AgentHomeChrome { - var isEnabled = false - /// Bots mode's chat header: Back, the bot (its profile) and options, no New chat. - var isSimpleBots = false - /// The tab bar under the message box. Every chat on one computer has it, - /// whether it's the Chat tab's own or opened from the list, Agents or Feed. - var showsTabBar = false - var onMenu: @MainActor () -> Void = {} + var isPushedChat = false var onProfile: @MainActor (String) -> Void = { _ in } - var onSwitchAgent: @MainActor () -> Void = {} - /// Opens the New chat picker (one agent, or several for a group). - var onNewChat: @MainActor (String?) -> Void = { _ in } - /// Starts a new chat with this agent right away. - var onStartChat: @MainActor (String) -> Void = { _ in } - var tabSelection: Binding? - /// Board tabs with something new, for the dots on the tab bar. - var unreadTabs: Set = [] - /// The bar's tabs: Chat, then what's pinned (Appearance › App layout). - var barTabs: [AppTab] = AppTab.allCases - /// The Header mode switcher, on the Chat tab's own chat only (Settings › Modes). - var modeSwitch: BighelpModeSwitch? - /// New chat lives in the bar under the message box. A chat without that bar (Code mode, the - /// iPhone Duo's side strip, Vision Pro's tab ornament) keeps it in the header. - func barHoldsNewChat(screen: BighelpScreenGeometry) -> Bool { - showsTabBar && !screen.usesSideBar && !BighelpPlatform.usesTabOrnament + /// The chrome of every chat the shell pushes. + static func pushedChat(onProfile: @escaping @MainActor (String) -> Void) -> AgentHomeChrome { + AgentHomeChrome(isPushedChat: true, onProfile: onProfile) } } -/// Equal when what it shows is the same. Its actions are the shell's own, the same every time -/// (they read live state when tapped), and the tab selection is read live where it's used. -/// Compared as a whole, every shell update redrew the chat on screen, its header and its -/// message box, which made Chat mode's chats slower than Bots mode's. +/// Equal when what it shows is the same. Its action is the shell's own, the same every time (it reads +/// live state when tapped). Compared as a whole, every shell update redrew the chat on screen, its +/// header and its message box. extension AgentHomeChrome: Equatable { - static func == (lhs: Self, rhs: Self) -> Bool { - lhs.isEnabled == rhs.isEnabled && lhs.isSimpleBots == rhs.isSimpleBots - && lhs.showsTabBar == rhs.showsTabBar && (lhs.tabSelection == nil) == (rhs.tabSelection == nil) - && lhs.unreadTabs == rhs.unreadTabs && lhs.barTabs == rhs.barTabs - && (lhs.modeSwitch == nil) == (rhs.modeSwitch == nil) - && lhs.modeSwitch?.modes == rhs.modeSwitch?.modes && lhs.modeSwitch?.current == rhs.modeSwitch?.current - } + static func == (lhs: Self, rhs: Self) -> Bool { lhs.isPushedChat == rhs.isPushedChat } } private struct AgentHomeChromeKey: EnvironmentKey { @@ -56,81 +31,32 @@ extension EnvironmentValues { } } -/// Every chat's header: ☰ on the left, the live avatar and name in the -/// middle, chat options on the right (New chat too where there's no bar). ☰ is in the same place as -/// on the other root screens; the edge swipe goes back to where the chat opened from. -struct AgentHomeChatHeader: View { - let agentID: String - let displayName: String - let imageURL: URL? - let activity: AgentActivityKind - var status: String? = nil - /// The chat's title when Settings › Chat › Chat title is on. - var sessionTitle: String? = nil - /// Group chats show their own identity control instead of one agent. - let groupIdentity: AnyView? +/// Every chat's header. Back goes to where the person came from, the middle says who the +/// chat is with (a bot's pill opens its page) and ⋯ holds the chat's options. A new chat with +/// nothing sent says "New chat" there, with its To row under the buttons across the whole lane. +struct ChatPushedHeader: View { + /// The bot's pill, or a group chat's name. + let identity: AnyView + /// A new chat's To row (`ChatNewChatSlot.toRow`), which takes the identity's place. + var toRow: AnyView? = nil let options: AnyView - let chrome: AgentHomeChrome - /// Full screen height, for the Auto avatar size. - var screenHeight: CGFloat = 0 - let beforeAction: () -> Void - @Environment(\.bighelpScreen) private var screen + let onBack: () -> Void + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + @BighelpThemeReader private var theme var body: some View { - ZStack(alignment: .top) { - Group { - if let groupIdentity { - groupIdentity - } else { - VStack(spacing: 0) { - Button { - beforeAction() - chrome.onProfile(agentID) - } label: { - ChatAgentIdentityPill(agentID: agentID, name: displayName, imageURL: imageURL, - sessionTitle: sessionTitle) - } - .buttonStyle(.plain) - .accessibilityLabel(displayName) - .accessibilityValue(status ?? activity.label) - .accessibilityHint("Opens its profile") - .accessibilityIdentifier("chat.identity") - } - .padding(.horizontal, (HeaderButtonMetrics.glass + 2 * HeaderButtonMetrics.slop) - * (chrome.barHoldsNewChat(screen: screen) ? 1 : 2)) - .padding(.top, HeaderButtonMetrics.slop) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("chat.header-surface") - } - } - .frame(maxWidth: .infinity) - // The mode pill takes the top row's middle, so the agent steps down below it. - .padding(.top, chrome.modeSwitch == nil ? 0 : HeaderButtonMetrics.glass + HeaderButtonMetrics.slop) - HStack(alignment: .top) { - Button { - beforeAction() - chrome.onMenu() - } label: { - Image(systemName: "line.3.horizontal") - .font(.bighelp(.title3).weight(.semibold)) - // On the glyph, where the top bar's ☰ shows it. - .bighelpMenuDot(!chrome.unreadTabs.subtracting(chrome.barTabs).isEmpty) - .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - .padding(HeaderButtonMetrics.slop) - .contentShape(.rect) + VStack(spacing: 0) { + ZStack(alignment: .top) { + Group { + if toRow == nil { identity } else { newChatTitle } } - .buttonStyle(.plain) - .accessibilityLabel("Chats and menu") - .accessibilityIdentifier("chat.menu") - Spacer(minLength: 0) - if let modeSwitch = chrome.modeSwitch { - BighelpModePill(modeSwitch: modeSwitch) - .padding(.top, HeaderButtonMetrics.slop) + // Clear of Back and ⋯ at every text size: the pill's name truncates instead. + .padding(.horizontal, HeaderButtonMetrics.glass + 2 * HeaderButtonMetrics.slop) + .padding(.top, HeaderButtonMetrics.slop) + .frame(maxWidth: .infinity) + HStack(alignment: .top) { + backButton Spacer(minLength: 0) - } - HStack(spacing: 0) { - if !chrome.barHoldsNewChat(screen: screen) { newChatButton } options .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) .bighelpNavigationGlass(in: Circle(), isInteractive: true) @@ -138,11 +64,45 @@ struct AgentHomeChatHeader: View { .contentShape(.rect) } } + // Only the buttons' row: Back sits where a root screen's top bar puts its first button. + .bighelpHeaderButtonsPlacement() + if let toRow { + // It scrolls sideways inside its own bounds, so large text never pushes the buttons. + toRow + .frame(maxWidth: horizontalSizeClass == .regular ? ChatCanvasLayout.regularLaneMaximumWidth : .infinity) + .frame(maxWidth: .infinity) + } } } + + private var backButton: some View { + Button(action: onBack) { + Image(systemName: "chevron.left") + .font(.bighelp(.title3).weight(.semibold)) + .foregroundStyle(theme.primaryText) + .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) + .bighelpNavigationGlass(in: Circle(), isInteractive: true) + .padding(HeaderButtonMetrics.slop) + .contentShape(.rect) + } + .buttonStyle(.plain) + .accessibilityLabel("Back") + .accessibilityIdentifier("chat.back") + } + + private var newChatTitle: some View { + Text("New chat") + .font(.bighelp(.title3, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .lineLimit(1) + .minimumScaleFactor(0.7) + .frame(minHeight: HeaderButtonMetrics.glass) + .accessibilityAddTraits(.isHeader) + .accessibilityIdentifier("new-chat.title") + } } -/// Chat and Bots share the same bounded glass identity surface. +/// The bot a chat is with: its face and name in one bounded glass pill. struct ChatAgentIdentityPill: View { let agentID: String let name: String @@ -178,117 +138,32 @@ struct ChatAgentIdentityPill: View { } } -extension AgentHomeChatHeader { - /// Tap: a new chat with this agent. Touch and hold: the picker, for another - /// agent or a group. A group chat has no one agent, so a tap opens the picker. - var newChatButton: some View { - let isDirect = groupIdentity == nil - let pickAgents = { - beforeAction() - chrome.onNewChat(isDirect ? agentID : nil) - } - return Image(systemName: "square.and.pencil") - .font(.bighelp(.title3).weight(.semibold)) - .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - .padding(HeaderButtonMetrics.slop) - .contentShape(.rect) - .onTapGesture { - guard isDirect else { return pickAgents() } - beforeAction() - chrome.onStartChat(agentID) - } - .onLongPressGesture(minimumDuration: 0.4) { - BighelpHaptics.tap() - pickAgents() - } - .newChatRightClickMenu(startTitle: isDirect ? "New chat with \(displayName)" : nil, - start: { beforeAction(); chrome.onStartChat(agentID) }, pick: pickAgents) - .accessibilityElement() - .accessibilityAddTraits(.isButton) - .accessibilityLabel(isDirect ? "New chat with \(displayName)" : "New chat") - .accessibilityHint(isDirect - ? NewChatButtonCopy.pickHint - : "Pick one agent for a chat, or several for a group chat.") - .accessibilityAction { - if isDirect { beforeAction(); chrome.onStartChat(agentID) } else { pickAgents() } - } - .accessibilityAction(named: "Pick agents") { pickAgents() } - .accessibilityIdentifier("chat.home.new-chat") - } -} - -/// Feed, Ideas, Goals and Apps: the Chat tab's ☰, New chat and ⋯, floating -/// over the board so they stay in reach while it scrolls. +/// A board opened in a sheet (a bot's Dashboard › See all): Back and New chat, floating over the +/// board so they stay in reach while it scrolls. struct AgentBoardHeaderButtons: View { - let context: AgentBoardContext + let agentName: String + let onBack: () -> Void + let onNewChat: () -> Void var body: some View { HStack(alignment: .top) { - if let onBack = context.onBack { - Button(action: onBack) { glyph("chevron.left") } - .buttonStyle(.plain) - .accessibilityLabel("Back") - .accessibilityIdentifier("board.back") - } else { - Button(action: context.onMenu) { glyph("line.3.horizontal", dot: context.menuHasUnread) } - .buttonStyle(.plain) - .accessibilityLabel("Chats and menu") - .accessibilityIdentifier("home.drawer.open") - } + Button(action: onBack) { glyph("chevron.left") } + .buttonStyle(.plain) + .accessibilityLabel("Back") + .accessibilityIdentifier("board.back") Spacer() - HStack(spacing: 0) { - // A board opened with Back has no bar, so it keeps New chat up here. - if context.onBack != nil { newChatButton } - Menu { - Button("Agent profile", systemImage: "person.crop.circle", action: context.onProfile) - Divider() - ForEach(Array(context.tools.enumerated()), id: \.offset) { _, tool in - Button(tool.title, systemImage: tool.systemImage, action: tool.action) - } - } label: { - // Glass goes around the menu, not in its label, or it takes the tap. - Image(systemName: "ellipsis") - .font(.bighelp(.title3).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) - .contentShape(.rect) - } - .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - .padding(HeaderButtonMetrics.slop) - .contentShape(.rect) - .accessibilityLabel("More for \(context.agentName)") - .accessibilityIdentifier("board.more") - } + Button(action: onNewChat) { glyph("square.and.pencil") } + .buttonStyle(.plain) + .accessibilityLabel("New chat with \(agentName)") + .accessibilityIdentifier("board.new-chat") } .bighelpHeaderButtonsPlacement() } - /// Tap: a new chat with this agent. Touch and hold: the picker, for another agent or a group. - private var newChatButton: some View { - glyph("square.and.pencil") - .onTapGesture(perform: context.onNewChat) - .onLongPressGesture(minimumDuration: 0.4) { - BighelpHaptics.tap() - context.onPickAgents() - } - .newChatRightClickMenu(startTitle: "New chat with \(context.agentName)", - start: context.onNewChat, pick: context.onPickAgents) - .accessibilityElement() - .accessibilityAddTraits(.isButton) - .accessibilityLabel("New chat with \(context.agentName)") - .accessibilityHint(NewChatButtonCopy.pickHint) - .accessibilityAction { context.onNewChat() } - .accessibilityAction(named: "Pick agents") { context.onPickAgents() } - .accessibilityIdentifier("board.new-chat") - } - - private func glyph(_ systemImage: String, dot: Bool = false) -> some View { + private func glyph(_ systemImage: String) -> some View { Image(systemName: systemImage) .font(.bighelp(.title3).weight(.semibold)) .foregroundStyle(theme.primaryText) - .bighelpMenuDot(dot) .frame(width: HeaderButtonMetrics.glass, height: HeaderButtonMetrics.glass) .bighelpNavigationGlass(in: Circle(), isInteractive: true) .padding(HeaderButtonMetrics.slop) @@ -312,9 +187,9 @@ enum HeaderButtonMetrics { static let slop: CGFloat = 5 #endif - /// From the screen's side to the first glass button: where the top bar puts ☰ on - /// Agents and the other root screens, so ☰ never moves between them and Chat, Feed, - /// Ideas, Goals and Files. Measured on iOS 26: 16 points on iPhone, 10 on iPad. + /// From the screen's side to the first glass button: where a top bar puts its first button, so + /// Back and the home's header buttons sit in one place on every screen. Measured on iOS 26: + /// 16 points on iPhone, 10 on iPad. static func edgeInset(regularWidth: Bool) -> CGFloat { if BighelpPlatform.usesTabOrnament { return 22 } if BighelpPlatform.isMac { return 12 } @@ -347,27 +222,3 @@ private struct HeaderButtonsPlacement: ViewModifier { .padding(.top, HeaderButtonMetrics.topInset - HeaderButtonMetrics.slop) } } - -enum NewChatButtonCopy { - static var pickHint: String { - BighelpPlatform.isMac - ? "Right-click to pick other agents or start a group." - : "Touch and hold to pick other agents or start a group." - } -} - -extension View { - /// The Mac has no touch and hold: right-click offers the same choices. - @ViewBuilder - func newChatRightClickMenu(startTitle: String?, start: @escaping () -> Void, - pick: @escaping () -> Void) -> some View { - #if targetEnvironment(macCatalyst) - contextMenu { - if let startTitle { Button(startTitle, systemImage: "square.and.pencil", action: start) } - Button("Pick Agents or Start a Group…", systemImage: "person.2", action: pick) - } - #else - self - #endif - } -} diff --git a/Bighelp/Board/AgentHomeDrawer.swift b/Bighelp/Board/AgentHomeDrawer.swift deleted file mode 100644 index 5a422a3f..00000000 --- a/Bighelp/Board/AgentHomeDrawer.swift +++ /dev/null @@ -1,190 +0,0 @@ -import SwiftUI - -/// ☰: bighelp's one menu (hosts, chats, and everywhere else). A sheet on -/// iPhone, a panel from the leading edge on iPad, a sidebar on Mac and Vision -/// Pro (see HomeMenuPresentation). -struct AgentHomeDrawer: View { - let chats: [SessionSummary] - let agent: (String) -> (name: String, imageURL: URL?)? - let hosts: BighelpMenuHosts - let destinations: BighelpMenuDestinations - let onOpen: (SessionSummary) -> Void - /// In the all-hosts view, recent chats come from every host. - var fleetChats: (fleet: FleetStore, open: (FleetChat) -> Void)? = nil - @Environment(\.dismiss) private var dismiss - @Environment(\.homeMenuClose) private var panelClose - - var body: some View { - NavigationStack { - BighelpMenu(hosts: hosts, destinations: destinations, close: close, hasRecent: hasRecent) { - AnyView(recentChats) - } - .navigationTitle("Menu") - .navigationBarTitleDisplayMode(.inline) - // A Mac sidebar has no title bar of its own. - .toolbar(BighelpPlatform.isMac ? .hidden : .automatic, for: .navigationBar) - .toolbar { - // The Mac's sidebar stays; ☰ and View › Hide Sidebar put it away. - if !BighelpPlatform.isMac { - ToolbarItem(placement: .confirmationAction) { - Button("Done", action: close) - .accessibilityIdentifier("menu.done") - } - } - } - } - .presentationDragIndicator(.visible) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("home.drawer") - } - - /// The panel isn't a presentation, so `dismiss` would do nothing there. - private func close() { - if let panelClose { panelClose() } else { dismiss() } - } - - private var hasRecent: Bool { - if let fleetChats { return !fleetChats.fleet.chats().isEmpty } - return !chats.isEmpty - } - - @ViewBuilder - private var recentChats: some View { - if let fleetChats { - ForEach(fleetChats.fleet.chats().prefix(12)) { chat in - Button { - close() - fleetChats.open(chat) - } label: { - FleetChatRow(chat: chat, fleet: fleetChats.fleet, compact: true) - .padding(.horizontal, BighelpMenuRowLayout.labelInset) - } - .bighelpPlainButtonStyle(BighelpMenuRowLayout.outline, padding: BighelpMenuRowLayout.highlightPadding) - .listRowInsets(BighelpPlatform.isMac ? BighelpMenuRowLayout.insets : nil) - .bighelpMenuRowSeparator() - .accessibilityIdentifier("menu.fleet-chat.\(chat.title)") - } - } else { - sessionChats - } - } - - private var sessionChats: some View { - ForEach(chats) { chat in - Button { - close() - onOpen(chat) - } label: { - BighelpMenuChatRow(chat: chat, agent: agent) - .padding(.horizontal, BighelpMenuRowLayout.labelInset) - } - .bighelpPlainButtonStyle(BighelpMenuRowLayout.outline, padding: BighelpMenuRowLayout.highlightPadding) - .listRowInsets(BighelpPlatform.isMac ? BighelpMenuRowLayout.insets : nil) - .bighelpMenuRowSeparator() - .accessibilityIdentifier("menu.chat.\(chat.id)") - } - } -} - -extension EnvironmentValues { - @Entry var homeMenuClose: (@MainActor () -> Void)? -} - -/// Presents ☰ like a side menu on iPad: it slides in from the leading edge -/// over a dimmed screen, and a tap outside closes it. iPhone keeps the sheet. -/// The panel is a see-through full-screen cover so it sits above the title bar. -struct HomeMenuPresentation: ViewModifier { - @Binding var isPresented: Bool - let onDismiss: () -> Void - /// A new host/runtime supplies new stores and actions, not just new values. - var contentID: ObjectIdentifier? = nil - @ViewBuilder let menu: () -> Menu - - @Environment(\.horizontalSizeClass) private var horizontalSizeClass - @Environment(\.accessibilityReduceMotion) private var reduceMotion - @Environment(\.bighelpSideMenu) private var sideMenu - @State private var isCoverPresented = false - @State private var isPanelVisible = false - - static var panelWidth: CGFloat { 380 } - - func body(content: Content) -> some View { - if let sideMenu { - // Vision Pro and Mac: a column beside the app, which narrows to make - // room. The Mac's stays open while you pick chats and pages. - content.onChange(of: isPresented, initial: true) { _, presented in - if presented { showSideMenu(sideMenu) } else { sideMenu.hide() } - } - .onChange(of: contentID) { - if isPresented { showSideMenu(sideMenu) } - } - } else if horizontalSizeClass == .regular { - content - .bighelpFullScreenCover(isPresented: $isCoverPresented, onDismiss: onDismiss) { - panel.presentationBackground(.clear) - } - .onChange(of: isPresented, initial: true) { _, presented in - presented ? open() : close() - } - } else { - content.bighelpSheet(isPresented: $isPresented, onDismiss: onDismiss, content: menu) - } - } - - private func showSideMenu(_ sideMenu: BighelpSideMenu) { - // Build inside a SwiftUI update, not the presentation callback, so - // readiness keeps updating. contentID also replaces captured stores. - let panel = BighelpDeferredSection { menu() } - .environment(\.homeMenuClose, { if !BighelpPlatform.isMac { isPresented = false } }) - sideMenu.show(AnyView(panel)) { - isPresented = false - onDismiss() - } - } - - private var slide: Animation? { reduceMotion ? nil : .snappy(duration: 0.28) } - - private func open() { - guard !isCoverPresented else { return } - // The cover itself appears instantly; the panel does the sliding. - var instant = Transaction() - instant.disablesAnimations = true - withTransaction(instant) { isCoverPresented = true } - } - - private func close() { - guard isCoverPresented else { return } - withAnimation(slide) { - isPanelVisible = false - } completion: { - var instant = Transaction() - instant.disablesAnimations = true - withTransaction(instant) { isCoverPresented = false } - } - } - - private var panel: some View { - ZStack(alignment: .leading) { - if isPanelVisible { - Color.black.opacity(0.24) - .ignoresSafeArea() - .contentShape(.rect) - .onTapGesture { isPresented = false } - .accessibilityHidden(true) - .transition(.opacity) - menu() - .environment(\.homeMenuClose, { isPresented = false }) - .frame(width: Self.panelWidth) - .frame(maxHeight: .infinity) - .clipShape(.rect(topLeadingRadius: 0, bottomLeadingRadius: 0, - bottomTrailingRadius: 28, topTrailingRadius: 28)) - .shadow(color: .black.opacity(0.18), radius: 24, x: 6) - .ignoresSafeArea(.container, edges: .vertical) - .accessibilityAction(.escape) { isPresented = false } - .transition(.move(edge: .leading)) - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) - .onAppear { withAnimation(slide) { isPanelVisible = true } } - } -} diff --git a/Bighelp/Board/AgentLiveAvatar.swift b/Bighelp/Board/AgentLiveAvatar.swift index b30a584f..49c8b1f3 100644 --- a/Bighelp/Board/AgentLiveAvatar.swift +++ b/Bighelp/Board/AgentLiveAvatar.swift @@ -46,7 +46,7 @@ struct AgentLiveAvatar: View { var showsBadge = true /// How the face rests with no work (voice mode shows listening). var restingState: AgentLiveState = .idle - /// A photo moves with the work; Bots mode's calm home keeps it still and badges it instead. + /// A photo moves with the work; the calm Bots view keeps it still and badges it instead. var movesPhoto = true @Environment(\.companionStore) private var companionStore @@ -244,7 +244,7 @@ struct AgentHeroHeader: View { if showsName { namePillLabel(line: "Updating…").hidden() } - // Plain text under the avatar, as Bots mode names its bots; the blur under the header + // Plain text under the avatar, as the Bots view names its bots; the blur under the header // keeps it readable over the messages. Button(action: onNameTap) { namePillLabel(line: statusLine ?? sessionTitle) diff --git a/Bighelp/Board/AgentProfileSheet.swift b/Bighelp/Board/AgentProfileSheet.swift deleted file mode 100644 index 1b23a6be..00000000 --- a/Bighelp/Board/AgentProfileSheet.swift +++ /dev/null @@ -1,614 +0,0 @@ -import SwiftUI - -/// Tapping an agent's avatar: what it has been doing, what you approved, its -/// screen, what it runs on a schedule, and who it is (vibe, SOUL, MEMORY). -struct AgentProfileSheet: View { - enum Tab: String, CaseIterable, Identifiable { - case activity, approvals, screen, schedules, identity - var id: String { rawValue } - var title: String { - switch self { - case .activity: "Activity" - case .approvals: "Approvals" - case .screen: "Screen" - case .schedules: "Schedules" - case .identity: "Identity" - } - } - var systemImage: String { - switch self { - case .activity: "list.bullet" - case .approvals: "checkmark.shield" - case .screen: "display" - case .schedules: "clock.badge.checkmark" - case .identity: "touchid" - } - } - } - - let agent: AgentProfile - let imageURL: URL? - let activity: AgentActivityKind - let isConnected: Bool - let store: AgentBoardStore - let schedules: [ScheduledTask] - let onEdit: () -> Void - let onOpenSchedule: (ScheduledTask) -> Void - /// Opened from a chat: that chat's model and reasoning, with Change. - var chatControls: SessionRuntimeControlModel? = nil - var onChangeModel: (() -> Void)? = nil - /// The agent's screen (Hermes Bot Screen). Its tab shows only once the host answers. - var screenService: (any BotScreenService)? = nil - /// The agent's chats open in the app, for what it's doing on its screen. - var screenChats: [ChatModel] = [] - @State private var tab: Tab = .activity - @State private var screen: BotScreenTabModel? - @State private var document: (title: String, body: AgentIdentityDocuments.Document)? - @Environment(\.dismiss) private var dismiss - - var body: some View { - ScrollView { - VStack(spacing: BighelpTokens.space16) { - header - if let chatControls { chatModelCard(chatControls) } - tabBar - content - .frame(maxWidth: .infinity, alignment: .leading) - } - .padding(.horizontal, BighelpTokens.space20) - .padding(.bottom, BighelpTokens.space32) - .frame(maxWidth: 720) - .frame(maxWidth: .infinity) - } - .scrollIndicators(.hidden) - .overlay(alignment: .topLeading) { - Button { dismiss() } label: { - Image(systemName: "xmark") - .font(.bighelp(.title3).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .frame(width: 44, height: 44) - .contentShape(.circle) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - } - .buttonStyle(.plain) - #if targetEnvironment(macCatalyst) - .keyboardShortcut(.cancelAction) - #endif - .padding(BighelpTokens.space16) - .accessibilityLabel("Close") - .accessibilityIdentifier("agent.profile.close") - } - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .bighelpSheetSize(.standard) - .task(id: agent.id) { await store.loadLogs(agentID: agent.id) } - .task(id: agent.id) { - guard let screenService else { return } - let model = BotScreenTabModel(agentID: agent.id, service: screenService) - screen = model - await model.load() - } - .bighelpSheet(isPresented: Binding(get: { document != nil }, set: { if !$0 { document = nil } })) { - if let document { - IdentityDocumentView(title: document.title, document: document.body) - .bighelpSheetSize(.standard) - } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("agent.profile") - } - - private var header: some View { - VStack(spacing: BighelpTokens.space8) { - AgentLiveAvatar(agentID: agent.id, displayName: agent.name, imageURL: imageURL, - activity: activity, size: 108) - .overlay(alignment: .bottomTrailing) { - Button(action: onEdit) { - Image(systemName: "pencil") - .font(.system(size: 15, weight: .bold)) - .foregroundStyle(theme.primaryText) - .frame(width: 36, height: 36) - .contentShape(.circle) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - } - .buttonStyle(.plain) - .offset(x: 4, y: 4) - .accessibilityLabel("Edit \(agent.name)") - .accessibilityIdentifier("agent.profile.edit") - } - .padding(.top, BighelpTokens.space32) - Text(agent.name) - .font(.bighelp(.title).weight(.bold)) - .foregroundStyle(theme.primaryText) - Label(isConnected ? "Connected" : "Offline", systemImage: isConnected ? "bolt.circle.fill" : "bolt.slash.circle") - .font(.bighelp(.body).weight(.medium)) - .foregroundStyle(isConnected ? Color.green : theme.secondaryText) - .accessibilityIdentifier("agent.profile.connection") - } - } - - private func chatModelCard(_ controls: SessionRuntimeControlModel) -> some View { - VStack(alignment: .leading, spacing: BighelpTokens.space8) { - Text("THIS CHAT") - .font(.system(size: 11, weight: .bold)) - .tracking(0.9) - .foregroundStyle(theme.secondaryText) - .accessibilityAddTraits(.isHeader) - ChatModelSummaryRow(controls: controls, onChange: onChangeModel) - .padding(.horizontal, BighelpTokens.space16) - .padding(.vertical, BighelpTokens.space8) - .background(theme.surface, in: .rect(cornerRadius: 18)) - } - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var tabBar: some View { - HStack(spacing: 4) { - ForEach(visibleTabs) { item in - let selected = tab == item - Button { - withAnimation(.snappy) { tab = item } - } label: { - Image(systemName: item.systemImage) - .font(.bighelp(.title3).weight(.semibold)) - .foregroundStyle(selected ? theme.primaryText : theme.secondaryText) - .frame(maxWidth: .infinity, minHeight: 48) - .background { - if selected { - Capsule().fill(theme.primaryText.opacity(0.1)) - } - } - .contentShape(.capsule) - } - .buttonStyle(.plain) - .accessibilityLabel(item.title) - .accessibilityAddTraits(selected ? [.isButton, .isSelected] : .isButton) - .accessibilityIdentifier("agent.profile.tab.\(item.rawValue)") - } - } - .padding(4) - .background(Capsule().fill(theme.incomingMessageBackground)) - } - - private var visibleTabs: [Tab] { - Tab.allCases.filter { $0 != .screen || screen?.showsTab == true } - } - - @ViewBuilder - private var content: some View { - switch tab { - case .activity: activityList - case .approvals: approvalsList - case .screen: - if let screen, screen.showsTab { - AgentScreenTab(model: screen, agentName: agent.name, chats: screenChats) - } - case .schedules: schedulesList - case .identity: identityPanel - } - } - - // MARK: Activity - - @ViewBuilder - private var activityList: some View { - if store.activity.isEmpty { - emptyState(symbol: "list.bullet", text: store.logState == .loading - ? "Loading…" : "When \(agent.name) uses tools for you, what it did shows up here.") - } else { - ForEach(dayGroups(store.activity, date: \.createdAt), id: \.title) { group in - sectionTitle(group.title) - ForEach(group.items) { entry in - HStack(alignment: .top, spacing: BighelpTokens.space12) { - Image(systemName: entry.kind.systemImage) - .font(.system(size: 18, weight: .semibold)) - .foregroundStyle(theme.primaryText) - .frame(width: 48, height: 48) - .background(Circle().fill(theme.incomingMessageBackground)) - VStack(alignment: .leading, spacing: 2) { - Text(entry.headline) - .font(.bighelp(.headline)) - .foregroundStyle(theme.primaryText) - if !entry.summary.isEmpty { - Text(entry.summary) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - } - Text(entry.createdAt.formatted(date: .omitted, time: .shortened)) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.tertiaryText) - } - } - .padding(.vertical, BighelpTokens.space4) - .accessibilityElement(children: .combine) - } - } - } - } - - // MARK: Approvals - - @ViewBuilder - private var approvalsList: some View { - if store.approvals.isEmpty { - emptyState(symbol: "checkmark.shield", text: store.logState == .loading - ? "Loading…" : "Things \(agent.name) asked permission for, and what you decided, show up here.") - } else { - sectionTitle("Approvals history") - ForEach(store.approvals) { entry in - HStack(alignment: .top, spacing: BighelpTokens.space12) { - Image(systemName: entry.wasAllowed ? "checkmark.shield" : "xmark.shield") - .font(.system(size: 18, weight: .semibold)) - .foregroundStyle(entry.wasAllowed ? theme.primaryText : theme.danger) - .frame(width: 40, height: 40) - .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(theme.incomingMessageBackground)) - VStack(alignment: .leading, spacing: 2) { - Text(entry.description.isEmpty ? entry.command : entry.description) - .font(.bighelp(.headline)) - .foregroundStyle(theme.primaryText) - if !entry.sessionTitle.isEmpty { - Text(entry.sessionTitle) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - } - Text("\(entry.decisionLabel) · \(entry.createdAt.formatted(.relative(presentation: .named)))") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.tertiaryText) - } - } - .padding(.vertical, BighelpTokens.space4) - .accessibilityElement(children: .combine) - } - } - } - - // MARK: Schedules - - @ViewBuilder - private var schedulesList: some View { - if schedules.isEmpty { - emptyState(symbol: "clock", text: "Reminders and recurring jobs \(agent.name) runs for you show up here.") - } else { - ForEach(scheduleGroups, id: \.title) { group in - sectionTitle(group.title) - ForEach(group.items) { task in - Button { onOpenSchedule(task) } label: { - HStack(alignment: .top, spacing: BighelpTokens.space12) { - Image(systemName: "calendar") - .font(.system(size: 20, weight: .semibold)) - .foregroundStyle(theme.primaryText) - .frame(width: 44, height: 44) - .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(theme.incomingMessageBackground)) - .overlay(alignment: .bottomTrailing) { - Image(systemName: task.isPaused ? "pause.circle.fill" : "clock.fill") - .font(.system(size: 14, weight: .bold)) - .foregroundStyle(task.isPaused ? theme.secondaryText : Color.orange) - .background(Circle().fill(theme.canvas)) - .offset(x: 4, y: 4) - } - VStack(alignment: .leading, spacing: 2) { - Text(task.name) - .font(.bighelp(.headline)) - .foregroundStyle(theme.primaryText) - Text(task.isPaused ? "Paused" : task.scheduleDescription) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - if let next = task.nextRun, !task.isPaused { - Text(next.formatted(date: .omitted, time: .shortened)) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.tertiaryText) - } - } - Spacer(minLength: 0) - } - .contentShape(.rect) - } - .buttonStyle(.plain) - .padding(.vertical, BighelpTokens.space4) - } - } - } - } - - private var scheduleGroups: [(title: String, items: [ScheduledTask])] { - var groups: [(title: String, items: [ScheduledTask])] = [] - func title(_ task: ScheduledTask) -> String { - switch task.schedule { - case .once: "Reminders" - case .daily: "Daily" - case .weekly, .repeating: "Weekly" - case .monthly: "Monthly" - case .naturalLanguage, .hermes: "Other" - } - } - for key in ["Reminders", "Daily", "Weekly", "Monthly", "Other"] { - let items = schedules.filter { title($0) == key } - .sorted { ($0.nextRun ?? .distantFuture) < ($1.nextRun ?? .distantFuture) } - if !items.isEmpty { groups.append((key, items)) } - } - return groups - } - - // MARK: Identity - - private var identityPanel: some View { - VStack(alignment: .leading, spacing: BighelpTokens.space12) { - Text(agent.name) - .font(.bighelp(.title2).weight(.bold)) - .foregroundStyle(theme.primaryText) - if !agent.role.isEmpty { - Text(agent.role) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - } - if !agent.summary.isEmpty { - Text("VIBE") - .font(.bighelp(.caption).monospaced().weight(.semibold)) - .tracking(1.5) - .foregroundStyle(theme.tertiaryText) - .padding(.top, BighelpTokens.space4) - Text(agent.summary) - .font(.bighelp(.body)) - .foregroundStyle(theme.primaryText) - } - Button(action: onEdit) { - Label("Edit", systemImage: "pencil") - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .frame(maxWidth: .infinity, minHeight: 50) - .background(Capsule().fill(theme.incomingMessageBackground)) - } - .buttonStyle(.plain) - .padding(.vertical, BighelpTokens.space8) - .accessibilityIdentifier("agent.profile.identity.edit") - HStack(spacing: BighelpTokens.space12) { - identityCard(title: "SOUL", symbol: "heart.fill", colors: [Color(hex: "B97A86"), Color(hex: "8E5B69")], - document: store.identity?.soul ?? .init(text: agent.instructions), - identifier: "agent.profile.soul") - identityCard(title: "MEMORY", symbol: "message.fill", colors: [Color(hex: "A8B23A"), Color(hex: "737A1F")], - document: memoryDocument, identifier: "agent.profile.memory") - } - } - } - - private var memoryDocument: AgentIdentityDocuments.Document { - guard let identity = store.identity else { return .init() } - let combined = [identity.memory.text, identity.user.text.isEmpty ? "" : "## About you\n" + identity.user.text] - .filter { !$0.isEmpty }.joined(separator: "\n\n") - return .init(text: combined, updatedAt: [identity.memory.updatedAt, identity.user.updatedAt].compactMap { $0 }.max(), - truncated: identity.memory.truncated || identity.user.truncated) - } - - private func identityCard(title: String, symbol: String, colors: [Color], - document: AgentIdentityDocuments.Document, identifier: String) -> some View { - Button { - self.document = (title == "SOUL" ? "Soul" : "Memory", document) - } label: { - VStack(alignment: .leading, spacing: 2) { - Text(title) - .font(.bighelp(.title2).weight(.heavy)) - .foregroundStyle(.white) - Text("ACCESS WITH CARE") - .font(.bighelp(.caption2).monospaced()) - .tracking(1.5) - .foregroundStyle(.white.opacity(0.7)) - Spacer(minLength: BighelpTokens.space24) - HStack(alignment: .bottom) { - Text(document.updatedAt?.formatted(.dateTime.month(.twoDigits).day(.twoDigits).year(.twoDigits)) - .replacingOccurrences(of: "/", with: ".") ?? "—") - .font(.bighelp(.footnote).monospaced()) - .foregroundStyle(.white.opacity(0.75)) - Spacer() - Image(systemName: symbol) - .font(.bighelp(.title2)) - .foregroundStyle(.white.opacity(0.85)) - } - } - .padding(BighelpTokens.space16) - .frame(maxWidth: .infinity, minHeight: 150, alignment: .topLeading) - .background( - RoundedRectangle(cornerRadius: 24, style: .continuous) - .fill(LinearGradient(colors: colors, startPoint: .topLeading, endPoint: .bottomTrailing)) - ) - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityLabel(title == "SOUL" ? "Soul" : "Memory") - .accessibilityHint("Opens it to read.") - .accessibilityIdentifier(identifier) - } - - // MARK: Pieces - - private func sectionTitle(_ title: String) -> some View { - Text(title) - .font(.bighelp(.title3).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .padding(.top, BighelpTokens.space8) - .accessibilityAddTraits(.isHeader) - } - - private func emptyState(symbol: String, text: String) -> some View { - VStack(spacing: BighelpTokens.space8) { - Image(systemName: symbol) - .font(.bighelp(.title)) - .foregroundStyle(theme.tertiaryText) - Text(text) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - } - .frame(maxWidth: .infinity) - .padding(.vertical, BighelpTokens.space32) - } - - private func dayGroups(_ items: [T], date: KeyPath) -> [(title: String, items: [T])] { - var groups: [(title: String, items: [T])] = [] - let calendar = Calendar.current - for item in items { - let day = item[keyPath: date] - let title = calendar.isDateInToday(day) ? "Today" - : calendar.isDateInYesterday(day) ? "Yesterday" - : day.formatted(.dateTime.weekday(.wide).month(.abbreviated).day()) - if groups.last?.title == title { groups[groups.count - 1].items.append(item) } - else { groups.append((title, [item])) } - } - return groups - } - - @BighelpThemeReader private var theme -} - -private struct IdentityDocumentView: View { - let title: String - let document: AgentIdentityDocuments.Document - @Environment(\.dismiss) private var dismiss - - var body: some View { - NavigationStack { - ScrollView { - VStack(alignment: .leading, spacing: BighelpTokens.space12) { - if document.text.isEmpty { - Text("Nothing here yet.") - .foregroundStyle(theme.secondaryText) - } else { - Text(document.text) - .font(.bighelp(.body).monospaced()) - .foregroundStyle(theme.primaryText) - .textSelection(.enabled) - } - if document.truncated { - Label("Showing the first 64 KB.", systemImage: "scissors") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } - } - .padding(BighelpTokens.space20) - .frame(maxWidth: .infinity, alignment: .leading) - } - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle(title) - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("Done") { dismiss() } - #if targetEnvironment(macCatalyst) - .keyboardShortcut(.cancelAction) - #endif - } - } - } - } - - @BighelpThemeReader private var theme -} - -/// Tapping an agent's name: switch agents, open a group chat, or make a new agent. -struct AgentSwitcherSheet: View { - struct Group: Identifiable { - let id: String - let name: String - let memberCount: Int - } - - let agents: [AgentProfile] - let selectedID: String? - let imageURL: (AgentProfile) -> URL? - let groups: [Group] - let onSelect: (AgentProfile) -> Void - let onSelectGroup: (Group) -> Void - let onNewGroup: () -> Void - let onNewAgent: () -> Void - let onManageAgents: () -> Void - @Environment(\.dismiss) private var dismiss - - var body: some View { - NavigationStack { - List { - Section("Agents") { - ForEach(agents) { agent in - Button { - dismiss() - onSelect(agent) - } label: { - HStack(spacing: BighelpTokens.space12) { - AgentLiveAvatar(agentID: agent.id, displayName: agent.name, imageURL: imageURL(agent), size: 44) - VStack(alignment: .leading, spacing: 2) { - Text(agent.name).font(.bighelp(.headline)).foregroundStyle(theme.primaryText) - if !agent.role.isEmpty { - Text(agent.role).font(.bighelp(.subheadline)).foregroundStyle(theme.secondaryText) - } - } - Spacer() - if agent.id == selectedID { - Image(systemName: "checkmark").foregroundStyle(theme.action).fontWeight(.semibold) - } - } - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityAddTraits(agent.id == selectedID ? .isSelected : []) - .accessibilityIdentifier("agent.switcher.agent.\(agent.id)") - } - Button { - dismiss() - onNewAgent() - } label: { - Label("New agent", systemImage: "plus.circle") - } - .accessibilityIdentifier("agent.switcher.new-agent") - Button { - dismiss() - onManageAgents() - } label: { - Label("Manage agents", systemImage: "person.2") - } - .accessibilityIdentifier("agent.switcher.manage") - } - Section("Group chats") { - ForEach(groups) { group in - Button { - dismiss() - onSelectGroup(group) - } label: { - Label { - VStack(alignment: .leading, spacing: 2) { - Text(group.name).foregroundStyle(theme.primaryText) - Text("\(group.memberCount) agents").font(.bighelp(.footnote)).foregroundStyle(theme.secondaryText) - } - } icon: { - Image(systemName: "person.3.fill") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.action) - } - } - .accessibilityIdentifier("agent.switcher.group.\(group.id)") - } - Button { - dismiss() - onNewGroup() - } label: { - Label("New group chat", systemImage: "plus.bubble") - } - .accessibilityIdentifier("agent.switcher.new-group") - } - } - .scrollContentBackground(.hidden) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .navigationTitle("Switch") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("Done") { dismiss() } - #if targetEnvironment(macCatalyst) - .keyboardShortcut(.cancelAction) - #endif - } - } - } - .bighelpSheetSize(.standard) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("agent.switcher") - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Board/AgentToday.swift b/Bighelp/Board/AgentToday.swift index 26b061e9..fd7fc9f8 100644 --- a/Bighelp/Board/AgentToday.swift +++ b/Bighelp/Board/AgentToday.swift @@ -1,7 +1,7 @@ import Foundation import Observation -// An agent's background work of the last days, on its Dashboard (Bots mode) as Activities, by day: +// An agent's background work of the last days, on its Dashboard as Activities, by day: // the subagents, background commands and, when the person asks, the routines (scheduled task runs) // the plugin's `agents/today` reports (`native-agents-today-v1`), running ones first. Only what the // computer says; nothing here starts or stops work. diff --git a/Bighelp/Board/BoardDashboardViews.swift b/Bighelp/Board/BoardDashboardViews.swift index 1f33e218..d25d15fc 100644 --- a/Bighelp/Board/BoardDashboardViews.swift +++ b/Bighelp/Board/BoardDashboardViews.swift @@ -1,7 +1,7 @@ import SwiftUI import UIKit -// A bot's Dashboard (the first tab of its profile in Bots mode): Feed, Ideas and Goals as piles of +// A bot's Dashboard (the first tab of its page): Feed, Ideas and Goals as piles of // the boards' color blocks. Swipe the top card right to act on it, left to put it away; Undo shows // after each swipe. Touch and hold (right-click on the Mac) has the card's usual menu, and VoiceOver // has both swipes as actions, so swiping is never the only way. Rules: `BoardDashboard.swift`. @@ -410,8 +410,7 @@ struct BoardDashboardView: View { onAsk: { text in after { context.onAsk(text) } }, onSend: { text in after { context.onSend(text) } }, onBlueprint: { text in after { context.onBlueprint(text) } }, - onMenu: {}, onNewChat: { after { context.onNewChat() } }, onPickAgents: {}, - tools: [], onBack: { model.sheet = nil }) + onNewChat: { after { context.onNewChat() } }, onBack: { model.sheet = nil }) } } diff --git a/Bighelp/Board/IslandStage.swift b/Bighelp/Board/IslandStage.swift index 59c3e4f8..293dcc2e 100644 --- a/Bighelp/Board/IslandStage.swift +++ b/Bighelp/Board/IslandStage.swift @@ -6,7 +6,6 @@ import SwiftUI struct IslandStage: View { let activity: AgentIslandActivity @Environment(\.accessibilityReduceMotion) private var reduceMotion - @Environment(\.appAppearance) private var appearance static let avatarSize: CGFloat = 38 @@ -29,17 +28,10 @@ struct IslandStage: View { .accessibilityHidden(true) } - /// Bots mode draws each bot as its mark, here too. - @ViewBuilder + /// The bot's face as the home draws it (its mark when it has no character or picture). private var face: some View { - if appearance.simpleBots { - SimpleBotFace(agentID: activity.agentID, name: activity.name, imageURL: activity.imageURL, - size: Self.avatarSize) - } else { - AgentLiveAvatar(agentID: activity.agentID, displayName: activity.name, - imageURL: activity.imageURL, activity: activity.kind, - size: Self.avatarSize, showsBadge: false) - } + SimpleBotFace(agentID: activity.agentID, name: activity.name, imageURL: activity.imageURL, + size: Self.avatarSize) } } diff --git a/Bighelp/BotMode/BotModeCreateRoomView.swift b/Bighelp/BotMode/BotModeCreateRoomView.swift index 357af058..9fb7d7c2 100644 --- a/Bighelp/BotMode/BotModeCreateRoomView.swift +++ b/Bighelp/BotMode/BotModeCreateRoomView.swift @@ -1,6 +1,6 @@ import SwiftUI -/// Bots mode's New Group Chat: a section to put the new group chat in. +/// The Bots view's New Group Chat: a section to put the new group chat in. struct BotModeCreateSectionChoice { let sections: [FleetSection] /// Files the made group chat (its room ID) in the picked section. @@ -13,26 +13,22 @@ struct BotModeCreateRoomView: View { let agents: AgentDirectoryStore let seedProfileID: String? let onCreated: (String) -> Void - /// New chat mode: one agent starts a 1:1 chat, two or more a group. - let onStartDirect: ((String) -> Void)? - /// Bots mode: an optional Section row. + /// An optional Section row. let sectionChoice: BotModeCreateSectionChoice? @State private var presentationOwnerID: String init(rooms: BotModeRoomStore, agents: AgentDirectoryStore, seedProfileID: String?, sectionChoice: BotModeCreateSectionChoice? = nil, - onStartDirect: ((String) -> Void)? = nil, onCreated: @escaping (String) -> Void) { self.rooms = rooms self.agents = agents self.seedProfileID = seedProfileID self.sectionChoice = sectionChoice - self.onStartDirect = onStartDirect + self.onCreated = onCreated _presentationOwnerID = State(initialValue: rooms.nativePresentationOwnerID) } - private var startsDirectChat: Bool { onStartDirect != nil && selected.count == 1 } private var isGroupSelection: Bool { selected.count >= 2 } @Environment(\.bighelpUIV3Enabled) private var uiV3Enabled @@ -62,7 +58,7 @@ struct BotModeCreateRoomView: View { } } .background(theme.canvas) - .navigationTitle(onStartDirect == nil ? "New group chat" : "New chat") + .navigationTitle("New group chat") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction).bighelpToolbarText() } } .onAppear { @@ -135,8 +131,7 @@ struct BotModeCreateRoomView: View { private var nativeForm: some View { ScrollView { VStack(alignment: .leading, spacing: BighelpTokens.space24) { - if onStartDirect == nil || isGroupSelection { - TextField(onStartDirect == nil ? "Group name" : "Group name (optional)", text: $name) + TextField("Group name", text: $name) .textInputAutocapitalization(.words) .bighelpFont(.body) .foregroundStyle(theme.primaryText) @@ -149,7 +144,6 @@ struct BotModeCreateRoomView: View { } .disabled(isSubmitting || hasPendingCreation || ownerChanged) .accessibilityIdentifier("bot-mode.create.title") - } VStack(alignment: .leading, spacing: BighelpTokens.space12) { HStack(alignment: .firstTextBaseline) { @@ -174,16 +168,14 @@ struct BotModeCreateRoomView: View { } } } - Text(onStartDirect == nil - ? "Pick 2 to \(BotModeRoom.maximumMembers) agents. Members are fixed once the group is created." - : "Pick one agent to chat 1:1, or up to \(BotModeRoom.maximumMembers) for a group chat.") + Text("Pick 2 to \(BotModeRoom.maximumMembers) agents. Members are fixed once the group is created.") .bighelpFont(.metadata) .foregroundStyle(theme.secondaryText) .fixedSize(horizontal: false, vertical: true) } if offersRoomSettings { roomSettings } - if let sectionChoice, onStartDirect == nil { + if let sectionChoice { sectionPicker(sectionChoice) .padding(.horizontal, BighelpTokens.space16) .frame(minHeight: 52) @@ -194,7 +186,7 @@ struct BotModeCreateRoomView: View { } } - if !rooms.canCreateNativeRoom, onStartDirect == nil || isGroupSelection { + if !rooms.canCreateNativeRoom { Label("This host isn’t ready for group chats yet.", systemImage: "info.circle") .bighelpFont(.label) .foregroundStyle(theme.secondaryText) @@ -226,7 +218,7 @@ struct BotModeCreateRoomView: View { .accessibilityIdentifier("bot-mode.create.error") } - if onStartDirect == nil || isGroupSelection { advancedDisclosure } + advancedDisclosure } .padding(.horizontal, BighelpTokens.space20) .padding(.vertical, BighelpTokens.space16) @@ -246,7 +238,7 @@ struct BotModeCreateRoomView: View { Button { Task { await create() } } label: { - Text(hasPendingCreation ? "Check room" : createTitle) + Text(hasPendingCreation ? "Check room" : "Create") .bighelpFont(.body, weight: .semibold) .foregroundStyle(theme.actionForeground) .frame(maxWidth: .infinity, minHeight: 52) @@ -269,7 +261,7 @@ struct BotModeCreateRoomView: View { /// Hermes keeps a group's settings where it advertises `groups.context`; they're saved /// right after the room exists. private var offersRoomSettings: Bool { - rooms.nativeCapabilities?.supports("groups.context") == true && (onStartDirect == nil || isGroupSelection) + rooms.nativeCapabilities?.supports("groups.context") == true } private var selectedProfiles: [AgentProfile] { @@ -509,25 +501,17 @@ struct BotModeCreateRoomView: View { .accessibilityIdentifier("bot-mode.create.participant.\(profile.id)") } - private var createTitle: String { - guard onStartDirect != nil else { return "Create" } - return isGroupSelection ? "Start group chat" : "Start chat" - } - private var isCreateDisabled: Bool { - if startsDirectChat { return isSubmitting || ownerChanged } - return isSubmitting || ownerChanged || !rooms.canCreateNativeRoom + isSubmitting || ownerChanged || !rooms.canCreateNativeRoom || !(2...BotModeRoom.maximumMembers).contains(selected.count) || unseatableNote != nil - || (onStartDirect == nil && name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || name.count > 200 } - /// Hermes says which agents it can seat in a group (`seatable_profiles`). New group chat - /// lists only those; New chat keeps every agent for 1:1 chats and holds back a group - /// that includes one it can't seat. + /// Hermes says which agents it can seat in a group (`seatable_profiles`): only those are listed. private var pickableProfiles: [AgentProfile] { - guard onStartDirect == nil, let capabilities = rooms.nativeCapabilities else { return agents.profiles } + guard let capabilities = rooms.nativeCapabilities else { return agents.profiles } return agents.profiles.filter { capabilities.canSeat(profile: $0.id) } } @@ -541,14 +525,8 @@ struct BotModeCreateRoomView: View { : "\(ListFormatter.localizedString(byJoining: names)) can’t join group chats on this host." } - /// New-chat groups may skip the name. - private var groupName: String { - let typed = name.trimmingCharacters(in: .whitespacesAndNewlines) - guard typed.isEmpty else { return typed } - return Self.automaticName(agents.profiles.filter { selected.contains($0.id) }.map(\.name)) - } - - /// A group named after its agents: "Juno & Alfie", "Juno, Alfie & Nova". + /// A group named after its agents: "Juno & Alfie", "Juno, Alfie & Nova". New chat names the group + /// it makes this way. static func automaticName(_ names: [String]) -> String { guard let last = names.last else { return "Group chat" } let joined = names.count == 1 ? last : names.dropLast().joined(separator: ", ") + " & " + last @@ -567,11 +545,6 @@ struct BotModeCreateRoomView: View { private func create() async { guard !isSubmitting else { return } - if startsDirectChat, let agentID = selected.first, let onStartDirect { - dismiss() - onStartDirect(agentID) - return - } guard !ownerChanged else { errorMessage = "The selected host changed. Reopen this form before creating a room." return @@ -580,7 +553,7 @@ struct BotModeCreateRoomView: View { defer { isSubmitting = false } do { let room = try await rooms.createNativeRoom( - roomID: roomID, name: onStartDirect == nil ? name : groupName, + roomID: roomID, name: name, profiles: agents.profiles.filter { selected.contains($0.id) } ) guard !ownerChanged, !Task.isCancelled else { throw WorkspaceClientError.ownerChanged } diff --git a/Bighelp/BotMode/BotModeRoomStore+NativeCatalog.swift b/Bighelp/BotMode/BotModeRoomStore+NativeCatalog.swift index c6d2fe89..3ca122fb 100644 --- a/Bighelp/BotMode/BotModeRoomStore+NativeCatalog.swift +++ b/Bighelp/BotMode/BotModeRoomStore+NativeCatalog.swift @@ -83,6 +83,14 @@ extension BotModeRoomStore { return nativeCapabilities != nil ? nativeExecutionAvailable : groupChatsBeforeReconnect } + /// Whether this computer makes group chats, for a list that marks who can join one. Nil until its + /// Hermes has answered on this connection: not knowing yet is no reason to mark a bot as unable. + var makesGroupChats: Bool? { + guard nativeClient is any HermesBotModeCatalogClient else { return false } + if nativeCapabilities == nil, !groupChatsBeforeReconnect { return nil } + return offersNewGroupChat + } + func nativeRoomIsWorking(roomID: String) -> Bool { nativeDriverWorkingByRoom[roomID] == true || room(id: roomID)?.isRunning == true } diff --git a/Bighelp/Cards/BighelpCardObjectViews.swift b/Bighelp/Cards/BighelpCardObjectViews.swift index bc38d158..9140fe9d 100644 --- a/Bighelp/Cards/BighelpCardObjectViews.swift +++ b/Bighelp/Cards/BighelpCardObjectViews.swift @@ -30,7 +30,7 @@ struct BighelpCardObjectAction: Identifiable { // MARK: - Shared layout -/// Bots mode's row: a round or square picture, a title and one quiet line, +/// The Bots view's row: a round or square picture, a title and one quiet line, /// and round buttons at the end. When they don't fit on one line (a long /// name, five buttons, large text) the buttons go under the picture. private struct BighelpCardObjectRow: View { @@ -90,7 +90,7 @@ private struct BighelpCardObjectRow: View { } } -/// A round glass button with one symbol, like Bots mode's header buttons. +/// A round glass button with one symbol, like the Bots view's header buttons. private struct BighelpCardObjectButton: View { let action: BighelpCardObjectAction @BighelpThemeReader private var theme diff --git a/Bighelp/Cards/BighelpCardObjects.swift b/Bighelp/Cards/BighelpCardObjects.swift index 2d112699..29c51ea2 100644 --- a/Bighelp/Cards/BighelpCardObjects.swift +++ b/Bighelp/Cards/BighelpCardObjects.swift @@ -9,9 +9,10 @@ import Foundation /// The validator and the renderer read props through these same initializers, /// so a card that validates always draws. enum BighelpCardObjects { - /// Photo drafts (`contact_draft`, `event_draft`) and agents' apps (`html_app`) are objects too: - /// plain props, no children. - static let types: Set = Set(["contact", "place", "music", HTMLAppWire.type]).union(ImageDraftWire.types) + /// Photo drafts (`contact_draft`, `event_draft`), agents' apps (`html_app`) and space drafts + /// (`space_draft`) are objects too: plain props, no children. + static let types: Set = Set(["contact", "place", "music", HTMLAppWire.type, SpacesWire.type]) + .union(ImageDraftWire.types) /// What the speaker note says this app draws when the plugin knows about them. static let feature = "native-card-objects-v1" static let renders = ["contact", "place", "music"] @@ -23,6 +24,7 @@ enum BighelpCardObjects { case "music": _ = try BighelpCardMusic(props: props) case "contact_draft", "event_draft": _ = try ImageDraft(type: type, props: props) case HTMLAppWire.type: _ = try HTMLAppCard(props: props, title: "") + case SpacesWire.type: _ = try SpaceDraftCard(props: props, title: "") default: throw BighelpCardValidationError.invalid } } diff --git a/Bighelp/Cards/BighelpCardValidator.swift b/Bighelp/Cards/BighelpCardValidator.swift index ba8f5b1d..2f5ed949 100644 --- a/Bighelp/Cards/BighelpCardValidator.swift +++ b/Bighelp/Cards/BighelpCardValidator.swift @@ -12,7 +12,7 @@ enum BighelpCardValidator { static let supportedElementTypes: Set = [ "card", "vstack", "hstack", "grid", "text", "metric", "badge", "progress", "chart", "table", "list", "divider", "spacer", "image", - "contact", "place", "music", "contact_draft", "event_draft", HTMLAppWire.type, + "contact", "place", "music", "contact_draft", "event_draft", HTMLAppWire.type, SpacesWire.type, ] private static let supportedOperations: Set = [ "coalesce", "add", "subtract", "multiply", "divide", "percent_change", @@ -105,6 +105,7 @@ enum BighelpCardValidator { // A card holds one photo draft and nothing else to act on beside it (docs/IMAGE_DRAFTS.md). try ImageDraftCard.validateComposition(card.elements) try HTMLAppCard.validateComposition(card.elements) + try SpaceDraftCard.validateComposition(card.elements) return card } diff --git a/Bighelp/Cards/BighelpCardView.swift b/Bighelp/Cards/BighelpCardView.swift index 62b7d29a..5debac4d 100644 --- a/Bighelp/Cards/BighelpCardView.swift +++ b/Bighelp/Cards/BighelpCardView.swift @@ -41,6 +41,9 @@ struct BighelpCardView: View { } else if let app = HTMLAppCard.app(in: card) { // An agent's app: the card opens it; its page never draws in the chat. HTMLAppCardView(app: app, cardID: card.id) + } else if let draft = SpaceDraftCard.draft(in: card) { + // A bot's draft of a space: Add to Today puts it there; nothing runs before. + SpaceDraftCardView(draft: draft) } else { displayCard } @@ -119,11 +122,62 @@ private struct CardBackgroundInk: ViewModifier { } } +/// A column in a panel, which has a fixed height: rows from the top, each one whole. A row that +/// doesn't fit is asked for less room (a text then shows fewer whole lines, a column inside fewer +/// rows); one that still doesn't fit ends the column, so nothing is ever cut through. +struct BighelpCardWholeRows: Layout { + var spacing: CGFloat + + /// Each shown row's size, in order. With no height asked, every row at its own height. + private func rows(width: CGFloat?, height: CGFloat?, subviews: Subviews) -> [CGSize] { + var sizes: [CGSize] = [] + var used: CGFloat = 0 + for subview in subviews { + let top = sizes.isEmpty ? used : used + spacing + var size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil)) + if let height, top + size.height > height + 0.5 { + let left = height - top + guard left > 0 else { break } + size = subview.sizeThatFits(ProposedViewSize(width: width, height: left)) + guard size.height <= left + 0.5 else { break } + } + sizes.append(size) + used = top + size.height + } + return sizes + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let height = proposal.height.flatMap { $0.isFinite ? $0 : nil } + let sizes = rows(width: proposal.width, height: height, subviews: subviews) + let rowsHeight = sizes.reduce(0) { $0 + $1.height } + spacing * CGFloat(max(sizes.count - 1, 0)) + return CGSize(width: proposal.width ?? sizes.map(\.width).max() ?? 0, height: rowsHeight) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let sizes = rows(width: bounds.width, height: bounds.height, subviews: subviews) + var y = bounds.minY + for (index, subview) in subviews.enumerated() { + if index < sizes.count { + subview.place(at: CGPoint(x: bounds.minX, y: y), anchor: .topLeading, + proposal: ProposedViewSize(width: bounds.width, height: sizes[index].height)) + y += sizes[index].height + spacing + } else { + // A layout can't leave a row out: it goes far below, where the panel clips it. + subview.place(at: CGPoint(x: bounds.minX, y: bounds.maxY + 10_000), anchor: .topLeading, + proposal: ProposedViewSize(width: bounds.width, height: nil)) + } + } + } +} + struct BighelpCardRenderer: View { static let supportedTypes = BighelpCardValidator.supportedElementTypes let card: BighelpCardDocument let isValid: Bool + /// A space's panel draws less of its card (Spaces); nil in chats, where nothing changes. + @Environment(\.bighelpCardLimits) private var limits init(card: BighelpCardDocument) { self.card = card @@ -152,8 +206,10 @@ struct BighelpCardRenderer: View { switch type { case "card": - return AnyView(VStack(alignment: .leading, spacing: BighelpCardDesignTokens.spacing) { - if let title = text(props["title"], item: item, itemSourceID: itemSourceID) { + return AnyView(column(spacing: BighelpCardDesignTokens.spacing) { + // A panel's header names the space already. + if let title = text(props["title"], item: item, itemSourceID: itemSourceID), + !(limits?.omitsRootTitle == true && id == card.root) { Text(title).font(.bighelp(.headline)) } if let subtitle = text(props["subtitle"], item: item, itemSourceID: itemSourceID) { @@ -162,7 +218,7 @@ struct BighelpCardRenderer: View { renderChildren(children, item: item, itemSourceID: itemSourceID) }) case "vstack": - return AnyView(VStack(alignment: .leading, spacing: spacing(props["spacing"])) { + return AnyView(column(spacing: spacing(props["spacing"])) { renderChildren(children, item: item, itemSourceID: itemSourceID) }) case "hstack": @@ -183,7 +239,7 @@ struct BighelpCardRenderer: View { return AnyView(Text(value) .font(textFont(props["typography"]?.string)) .foregroundStyle(semanticColor(props["color"]?.string)) - .lineLimit(props["line_limit"]?.integer)) + .lineLimit(Self.lineLimit(props["line_limit"]?.integer, panel: limits?.maxTextLines))) case "metric": let label = text(props["label"], item: item, itemSourceID: itemSourceID) ?? "Value" let value = resolved(props["value"], item: item, itemSourceID: itemSourceID) @@ -224,7 +280,8 @@ struct BighelpCardRenderer: View { } return AnyView(BighelpCardMiniChart( values: values, - color: semanticColor(props["series"]?.array?.first?.object?["semantic"]?.string) + color: semanticColor(props["series"]?.array?.first?.object?["semantic"]?.string), + height: limits?.chartHeight ).accessibilityLabel(props["description"]?.string ?? "Chart")) case "table": return AnyView(renderTable(props: props, children: children, item: item, itemSourceID: itemSourceID)) @@ -255,6 +312,14 @@ struct BighelpCardRenderer: View { } } + /// A card's column. In a panel it shows whole rows only (`BighelpCardWholeRows`); in a chat it + /// is the plain stack it always was. + private func column(spacing: CGFloat, @ViewBuilder content: () -> some View) -> some View { + let layout = limits == nil ? AnyLayout(VStackLayout(alignment: .leading, spacing: spacing)) + : AnyLayout(BighelpCardWholeRows(spacing: spacing)) + return layout { content() } + } + private func renderChildren( _ children: [String], item: BighelpJSONValue?, @@ -271,8 +336,9 @@ struct BighelpCardRenderer: View { itemSourceID: String? ) -> some View { let bindingSource = props["items"]?.object?["source"]?.string - let items = Array((resolved(props["items"], item: nil, itemSourceID: itemSourceID)?.array ?? []).prefix(50)) - return VStack(alignment: .leading, spacing: BighelpCardDesignTokens.compactSpacing) { + let items = Array((resolved(props["items"], item: nil, itemSourceID: itemSourceID)?.array ?? []) + .prefix(limits?.maxListItems ?? 50)) + return column(spacing: BighelpCardDesignTokens.compactSpacing) { if items.isEmpty { Text(props["empty_text"]?.string ?? "No items available.") .foregroundStyle(.secondary) @@ -293,9 +359,9 @@ struct BighelpCardRenderer: View { item: BighelpJSONValue?, itemSourceID: String? ) -> some View { - let columns = Array((props["columns"]?.array ?? []).prefix(8)) - let rows = Array((props["rows"]?.array ?? []).prefix(50)) - return VStack(alignment: .leading, spacing: 6) { + let columns = Array((props["columns"]?.array ?? []).prefix(limits?.maxTableColumns ?? 8)) + let rows = Array((props["rows"]?.array ?? []).prefix(limits?.maxTableRows ?? 50)) + return column(spacing: 6) { HStack(alignment: .firstTextBaseline, spacing: 8) { ForEach(Array(columns.enumerated()), id: \.offset) { _, column in Text(column.object?["label"]?.string ?? "Column") @@ -376,6 +442,12 @@ struct BighelpCardRenderer: View { } } + /// The card's own line limit, but never more than a panel allows. + private static func lineLimit(_ asked: Int?, panel: Int?) -> Int? { + guard let panel else { return asked } + return min(asked ?? panel, panel) + } + private func spacing(_ value: BighelpJSONValue?) -> CGFloat { switch value?.string { case "none": 0 @@ -415,6 +487,8 @@ struct BighelpCardRenderer: View { private struct BighelpCardMiniChart: View { let values: [Double] let color: Color + /// A panel's fixed chart height; nil grows from 72 points as a chat card does. + var height: CGFloat? = nil var body: some View { GeometryReader { geometry in @@ -427,7 +501,7 @@ private struct BighelpCardMiniChart: View { } } } - .frame(minHeight: 72) + .frame(minHeight: height ?? 72, maxHeight: height) .accessibilityLabel("Chart with \(values.count) values") } } diff --git a/Bighelp/Chat/ChatAgentTalkRail.swift b/Bighelp/Chat/ChatAgentTalkRail.swift index 2e9a7752..0280e0fa 100644 --- a/Bighelp/Chat/ChatAgentTalkRail.swift +++ b/Bighelp/Chat/ChatAgentTalkRail.swift @@ -554,26 +554,17 @@ struct ChatAgentFaceStack: View { } } -/// One agent's face: its Bots mode mark while that mode is on, else the -/// face the rest of the app draws (character, pet or picture). +/// One agent's face, as the rest of the app draws it (character, pet, mark or picture). struct ChatAgentTalkFace: View { let agentID: String let name: String let imageURL: URL? let size: CGFloat - @Environment(\.appAppearance) private var appearance - var body: some View { - Group { - if appearance.simpleBots { - SimpleBotFace(agentID: agentID, name: name, imageURL: imageURL, size: size) - } else { - AgentLiveAvatar(agentID: agentID, displayName: name, imageURL: imageURL, size: size, showsBadge: false) - } - } - .frame(width: size, height: size) - .accessibilityHidden(true) + SimpleBotFace(agentID: agentID, name: name, imageURL: imageURL, size: size) + .frame(width: size, height: size) + .accessibilityHidden(true) } } diff --git a/Bighelp/Chat/ChatComposer.swift b/Bighelp/Chat/ChatComposer.swift index fc5b5710..87a879ca 100644 --- a/Bighelp/Chat/ChatComposer.swift +++ b/Bighelp/Chat/ChatComposer.swift @@ -15,6 +15,10 @@ final class ChatComposerActions { var dismissKeyboard: () -> Void = {} var willSend: () -> Void = {} var referenceSend: ((ReferenceFrozenDraft, MidSessionChatBehavior?) async -> Void)? + /// One home: a new chat's Send asks this first (`ChatNewChatSlot.sendOverride`), saying whether + /// the box holds references. True means the message was taken or can't go yet, and the box does + /// nothing more with it. + var sendOverride: (@MainActor (_ holdsReferences: Bool) -> Bool)? } /// The message box as the chat screen places it: takes the chat's closures on every draw, puts them @@ -39,6 +43,7 @@ struct ChatComposerHost: View { let referenceHub: ReferenceHubStore let referenceSkills: SkillsAndToolsStore? let onReferenceSend: ((ReferenceFrozenDraft, MidSessionChatBehavior?) async -> Void)? + var sendOverride: (@MainActor (_ holdsReferences: Bool) -> Bool)? = nil @State private var actions = ChatComposerActions() var body: some View { @@ -48,6 +53,7 @@ struct ChatComposerHost: View { actions.dismissKeyboard = onDismissKeyboard actions.willSend = onWillSend actions.referenceSend = onReferenceSend + actions.sendOverride = sendOverride return ChatComposer( model: model, agentName: agentName, sessionCatalog: sessionCatalog, actions: actions, offersAttachments: onAttachmentTap != nil, draftFocus: draftFocus, isDraftFocused: isDraftFocused, @@ -534,16 +540,14 @@ struct ChatComposer: View, Equatable { ) .overlay(alignment: .topLeading) { ComposerPlaceholder(model: model, color: theme.secondaryText, - text: homeChrome.isSimpleBots && !model.isBotMode - ? String(localized: "Ask \(placeholderName)") - : String(localized: "Message \(placeholderName)")) + text: String(localized: "Message \(placeholderName)")) } // The text view says what's typed itself; reading the draft here redrew the whole box // on every keystroke. .accessibilityLabel("Message") } - @Environment(\.agentHomeChrome) private var homeChrome + private var placeholderName: String { guard model.isBotMode else { return agentName } @@ -663,6 +667,10 @@ struct ChatComposer: View, Equatable { private func submit(behavior: MidSessionChatBehavior?, keepsFocus: Bool = false) { guard model.canSend else { return } if !keepsFocus { dismissComposerKeyboard() } + // One home: a new chat's message can belong to a group chat or a coding session. Asked + // before the references' own send, so nothing of it goes to this chat by another way. It is + // told of the references, which only this chat's own send can carry. + if let sendOverride = actions.sendOverride, sendOverride(!referenceHub.selected.isEmpty) { return } if !referenceHub.selected.isEmpty { // A reference send keeps its exact reviewed bytes, so a quote line can't ride along. guard model.replyDraft == nil else { diff --git a/Bighelp/Chat/ChatNativeMarkdownRendering.swift b/Bighelp/Chat/ChatNativeMarkdownRendering.swift index d06ea9f7..3f77bed2 100644 --- a/Bighelp/Chat/ChatNativeMarkdownRendering.swift +++ b/Bighelp/Chat/ChatNativeMarkdownRendering.swift @@ -13,7 +13,7 @@ struct ChatNativeMarkdownStyle { /// Interim agent messages render slightly smaller than the answer. var textScale: CGFloat = 1 var mentionIdentities: [ChatMentionIdentity] = [] - /// Markdown file paths become links that open the viewer (Code mode chats). + /// Markdown file paths become links that open the viewer (coding sessions). var linksMarkdownFiles = false var citationLinks: [Int: URL] = [:] } diff --git a/Bighelp/Chat/ChatNewChatSlot.swift b/Bighelp/Chat/ChatNewChatSlot.swift new file mode 100644 index 00000000..c1df4ce7 --- /dev/null +++ b/Bighelp/Chat/ChatNewChatSlot.swift @@ -0,0 +1,45 @@ +import SwiftUI + +/// One home: what the shell gives the one chat that is New chat's blank chat, so the ordinary chat +/// screen is also the New chat screen. The chat draws these only while nothing is sent in it: from +/// its first message on (staged, sending or sent) it is an ordinary chat, whatever is still passed. +/// +/// The shell decides which chat gets one from the chat's id (`NewChatSession.conversationID`), never +/// from its messages. The parts are the shell's own views (`NewChatToRow`, `NewChatPeopleList`, +/// `NewChatChoicesRow`), each with its own state: a change in one redraws that part, not the chat. +@MainActor +struct ChatNewChatSlot { + /// "To:" and the picked bots, the whole width under Back and ⋯, where the bot's name would be. + let toRow: AnyView + /// The bots to pick from, over the empty messages, between the To row and the message box. + var people: AnyView? = nil + /// The choices under the message box that can make the chat a coding session (one picked bot). + var choicesRow: AnyView? = nil + /// Send asks this first, saying whether the box holds references. True means the message went + /// elsewhere (a group chat, a coding session), which empties the box once it has the message, or + /// that it can't go yet, which leaves the box as it was and says why under the To row; false + /// sends in this chat as usual. It must not capture a view: the message box keeps it for as long + /// as the chat is open (`NewChatSendRelay`). + var sendOverride: (@MainActor (_ holdsReferences: Bool) -> Bool)? = nil + /// False takes + away: a message a group chat or a coding session takes goes as text only. + var offersAttachments = true + /// The To row holds exactly one bot and this chat is that bot's. False hides what acts on the + /// chat's own bot (voice, ⋯ › Bot page): with nobody picked, or two or more, that is another bot + /// than the To row shows. + var isOneBotsChat = true +} + +extension ChatModel { + /// Nothing is sent here and nothing failed: New chat's blank chat still draws its To row. A + /// first message (waiting, on its way or sent) makes it an ordinary chat. + var isBlankForNewChat: Bool { + transcriptEntries.isEmpty && stagedSends.isEmpty && bigFileSends.isEmpty && !isSending + && !hasPreviousHistory && failureMessage == nil + } + + /// The box holds more than text: attachments (also ones still being added, or that didn't + /// attach) or references. Only this chat's own send carries them; they can't move to another chat. + var holdsAttachmentsOrReferences: Bool { + hasDraftAttachmentActivity || !referenceSelections.isEmpty + } +} diff --git a/Bighelp/Chat/ChatView.swift b/Bighelp/Chat/ChatView.swift index 6b344939..a71b4eef 100644 --- a/Bighelp/Chat/ChatView.swift +++ b/Bighelp/Chat/ChatView.swift @@ -24,73 +24,6 @@ struct ChatHeaderLiveActivityPresentation: Equatable { } } -/// Owner-fenced dependencies for editing the profile that owns this chat. -/// -/// The presenting composition root supplies the exact profile and authority -/// check. `ChatView` owns only the sheet, so opening the editor never replaces -/// the retained chat route or its draft. -@MainActor -struct ChatAgentEditorPresentation { - let profileID: String - let store: AgentDirectoryStore - let runtimeDefaultsClient: (any AgentRuntimeDefaultsClient)? - let runtimeDefaultsReadOnlyReason: String? - private let isCurrent: @MainActor () -> Bool - fileprivate let onCompleted: @MainActor (AgentProfile) -> Void - - init( - profileID: String, - store: AgentDirectoryStore, - runtimeDefaultsClient: (any AgentRuntimeDefaultsClient)? = nil, - runtimeDefaultsReadOnlyReason: String? = nil, - isCurrent: @escaping @MainActor () -> Bool, - onCompleted: @escaping @MainActor (AgentProfile) -> Void = { _ in } - ) { - self.profileID = profileID - self.store = store - self.runtimeDefaultsClient = runtimeDefaultsClient - self.runtimeDefaultsReadOnlyReason = runtimeDefaultsReadOnlyReason - self.isCurrent = isCurrent - self.onCompleted = onCompleted - } - - var isAvailable: Bool { - isCurrent() && store.profiles.contains(where: { $0.id == profileID }) - } - - fileprivate func makeRoute() -> ChatAgentEditorRoute? { - guard isAvailable, - let profile = store.profiles.first(where: { $0.id == profileID }) else { - return nil - } - let expectedProfileID = profileID - let editor = AgentEditorModel.editing( - profile, - store: store, - processor: AvatarImageProcessor(), - isCurrent: { - isCurrent() - && store.profiles.contains(where: { $0.id == expectedProfileID }) - } - ) - return ChatAgentEditorRoute( - model: editor, - runtimeDefaultsClient: runtimeDefaultsClient, - runtimeDefaultsReadOnlyReason: runtimeDefaultsReadOnlyReason, - onCompleted: onCompleted - ) - } -} - -@MainActor -private struct ChatAgentEditorRoute: Identifiable { - let id = UUID() - let model: AgentEditorModel - let runtimeDefaultsClient: (any AgentRuntimeDefaultsClient)? - let runtimeDefaultsReadOnlyReason: String? - let onCompleted: @MainActor (AgentProfile) -> Void -} - struct ChatView: View { @Environment(\.dismiss) private var dismiss @Environment(\.bighelpScreen) private var screen @@ -127,7 +60,6 @@ struct ChatView: View { let agentStatus: String let identityParticipants: [ChatIdentityParticipant]? let agents: AgentDirectoryStore? - let agentEditorPresentation: ChatAgentEditorPresentation? let dashboardModel: DashboardModel? let directHermesClient: DirectHermesConversationClient? let directHermesClarifications: [DirectHermesPrompt] @@ -162,6 +94,8 @@ struct ChatView: View { let referenceHub: ReferenceHubStore? let referenceSkills: SkillsAndToolsStore? let onReferenceSend: ((ReferenceFrozenDraft, MidSessionChatBehavior?) async -> Void)? + /// One home: New chat's parts, given to its blank chat only. Read through `newChat`. + let newChatSlot: ChatNewChatSlot? @State private var fallbackReferenceHub = ReferenceHubStore(owner: nil, providers: []) @State private var isChatVisible = false /// Tells the app which chat this screen shows (`BighelpVisibleChats`, ...). @@ -182,7 +116,6 @@ struct ChatView: View { @State private var optionsButtonBottom: CGFloat = 0 @State private var canvasWidth: CGFloat = 0 #endif - @State private var agentEditorRoute: ChatAgentEditorRoute? @State private var sessionTitleDialog: SessionTitleDialog? @State private var sessionTitleDraft = "" @State private var sessionTitleErrorMessage = "" @@ -221,7 +154,6 @@ struct ChatView: View { agentStatus: String = "Hermes", identityParticipants: [ChatIdentityParticipant]? = nil, agents: AgentDirectoryStore? = nil, - agentEditorPresentation: ChatAgentEditorPresentation? = nil, dashboardModel: DashboardModel? = nil, directHermesClient: DirectHermesConversationClient? = nil, directHermesClarifications: [DirectHermesPrompt] = [], @@ -252,9 +184,11 @@ struct ChatView: View { workStyle: ChatWorkStyle = .card, showsHeader: Bool = true, sessionControlAccessory: ChatSessionControlAccessory? = nil, - onForceRefresh: (@MainActor () async throws -> Void)? = nil + onForceRefresh: (@MainActor () async throws -> Void)? = nil, + newChat: ChatNewChatSlot? = nil ) { self.model = model + self.newChatSlot = newChat self.onForceRefresh = onForceRefresh self.foldCompletedTurns = foldCompletedTurns self.workStyle = workStyle @@ -267,7 +201,6 @@ struct ChatView: View { self.agentStatus = agentStatus self.identityParticipants = identityParticipants self.agents = agents - self.agentEditorPresentation = agentEditorPresentation self.dashboardModel = dashboardModel self.directHermesClient = directHermesClient self.directHermesClarifications = directHermesClarifications @@ -305,6 +238,15 @@ struct ChatView: View { model.isBotMode ? .steps : reasoningPlacement } + /// One home: New chat's parts while nothing is sent here. A first message (waiting, on its way + /// or sent) or a failure to show makes this an ordinary chat, whatever the shell still passes. + /// They go with the pushed header, which holds the To row. A chat without the slot reads + /// nothing here, and with it only what the rows already read. + private var newChat: ChatNewChatSlot? { + guard let newChatSlot, homeChrome.isPushedChat, model.isBlankForNewChat else { return nil } + return newChatSlot + } + var body: some View { let _ = ChatPerformanceProbe.count("chat.body") let _ = model.botModeRoomStore?.rooms @@ -316,16 +258,6 @@ struct ChatView: View { .background { theme.canvas.ignoresSafeArea() } - .bighelpSheet(item: $agentEditorRoute) { route in - AgentEditorView( - model: route.model, - runtimeDefaultsClient: route.runtimeDefaultsClient, - runtimeDefaultsReadOnlyReason: route.runtimeDefaultsReadOnlyReason - ) { profile in - route.onCompleted(profile) - agentEditorRoute = nil - } - } .environment(\.bighelpUIV3Enabled, true) .environment(\.bighelpUIV2Enabled, true) .environment(\.chatActivityDisclosureStore, model.activityDisclosures) @@ -576,6 +508,8 @@ struct ChatView: View { // insets; overlay heights do not reserve a second SwiftUI scroll region. private var chatCanvas: some View { timeline + // One home: a new chat's people list stands where its empty messages would be. + .opacity(showsNewChatPeople ? 0 : 1) #if !os(visionOS) // Messages run on under the status bar and home indicator, so the blur under the // header reaches the top of the screen without a hard edge. UIKit adds those @@ -599,6 +533,7 @@ struct ChatView: View { .ignoresSafeArea() } #endif + .overlay { newChatPeople } .overlay(alignment: .bottom) { timelineStatusOverlay } .overlay(alignment: .top) { floatingHeader @@ -620,15 +555,7 @@ struct ChatView: View { .popover(isPresented: sessionControlsPresented(from: .composer)) { macSessionControls } #endif if laptopDeckHeight > 0, !isDraftFocused { Spacer(minLength: 0) } - // Chats keep the bottom bar under the composer. - if showsChatBar, !screen.usesSideBar, let selection = homeChrome.tabSelection { - FloatingTabBar(selection: selection, tabs: homeChrome.barTabs, - onNewChat: startNewChatFromBar, onPickAgents: pickAgentsFromBar, - newChatIdentifier: "chat.home.new-chat", - homeIndicatorSink: FloatingTabBar.homeIndicatorSink(forBottomInset: bottomSafeArea), - unread: homeChrome.unreadTabs, isInChat: true) - .transition(.move(edge: .bottom).combined(with: .opacity)) - } + newChatChoices } // The messages stop at the fold: the timeline keeps clear of all of this. .frame(minHeight: laptopDeckHeight) @@ -636,7 +563,7 @@ struct ChatView: View { // does. Offered an equal share, a long list showed about two rows. .layoutPriority((referenceHub ?? fallbackReferenceHub).isPresented && laptopDeckHeight == 0 ? 1 : 0) #if !os(visionOS) - // The same soft blur under the message box and the tab bar. + // The same soft blur under the message box and a new chat's choices. .background { ChatEdgeBlur(edge: .bottom) { [timelineController] in timelineController.scrollView } .ignoresSafeArea(edges: .bottom) @@ -646,25 +573,6 @@ struct ChatView: View { } } .toolbar(.hidden, for: .navigationBar) - // The iPhone Duo: the bar's places go down the side strip instead of under the message box. - .toolbar { - if showsChatBar, screen.usesSideBar, let selection = homeChrome.tabSelection { - BighelpStripTabs(selection: selection, tabs: homeChrome.barTabs, - unread: homeChrome.unreadTabs, isInChat: true, - selectedTint: theme.action, tint: theme.secondaryText) - } - } - #if os(visionOS) - // Chats keep Vision Pro's tab strip beside the window. - .ornament(visibility: homeChrome.isEnabled && homeChrome.showsTabBar && homeChrome.tabSelection != nil - ? .visible : .hidden, - attachmentAnchor: .scene(.leading), contentAlignment: .trailing) { - if let selection = homeChrome.tabSelection { - VisionTabOrnament(selection: selection, tabs: homeChrome.barTabs, unread: homeChrome.unreadTabs, - isInChat: true) - } - } - #endif .onGeometryChange(for: CGFloat.self) { proxy in proxy.size.height + proxy.safeAreaInsets.top + proxy.safeAreaInsets.bottom } action: { screenHeight = $0 } @@ -684,26 +592,47 @@ struct ChatView: View { return max(0, safeBottomInWindow - fold.maxY) } - /// Chats keep the bar, and it tucks away while you type. - private var showsChatBar: Bool { - homeChrome.isEnabled && homeChrome.showsTabBar && homeChrome.tabSelection != nil - && !isDraftFocused && !BighelpPlatform.usesTabOrnament + /// One home: the bots to pick from, over a new chat's empty messages until something is sent. + private var showsNewChatPeople: Bool { newChat?.people != nil } + + /// Between the header and the message box, so the list follows the keyboard and its rows never + /// run under either. An overlay of its own: it takes no part in the message box's layout. + @ViewBuilder + private var newChatPeople: some View { + if let people = newChat?.people { + people + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .contentShape(.rect) + .clipped() + .padding(.top, headerHeight) + .padding(.bottom, composerHeight) + } + } + + /// One home: a new chat's choices (project, where it runs, branch, mode) under the message box, + /// in the place the in-chat bar had. A sibling of the box, so a change in it never redraws the + /// box, and `composerHeight` measures both, so the messages keep clear of it. + @ViewBuilder + private var newChatChoices: some View { + if let choices = newChat?.choicesRow { + choices + // The box's lane, with the row's own side padding outside it. + .frame(maxWidth: horizontalSizeClass == .regular + ? ChatCanvasLayout.regularLaneMaximumWidth + 2 * BighelpTokens.space12 : .infinity) + // Its own height only: offered a share of the spare room, it would take it from the spacer. + .fixedSize(horizontal: false, vertical: true) + } } /// Each control samples the transcript, never an opaque toolbar slab. /// The table alone reserves the measured header and composer insets. private var floatingHeader: some View { - Group { - if homeChrome.isEnabled { - homeHeader - } else { - standardHeader - } - } + let toRow = newChat?.toRow + return pushedHeader(toRow: toRow) .background(alignment: .bottom) { sessionControlsAnchor } .foregroundStyle(theme.primaryText) - .modifier(ChatHeaderPlacement(isHome: homeChrome.isEnabled)) - .padding(.bottom, 8) + // The To row ends in its own line, and the people list starts right under it. + .padding(.bottom, toRow == nil ? 8 : 0) #if !os(visionOS) .background { // Messages scroll on beneath the header and blur near the top, so the @@ -714,7 +643,6 @@ struct ChatView: View { #endif } - /// Chat tab: the agent's live avatar leads, like a home screen. /// One-on-one chats only: group chats already show their title. private var shownSessionTitle: String? { guard showsSessionTitle, !model.isBotMode else { return nil } @@ -726,72 +654,14 @@ struct ChatView: View { resolvedIdentityParticipants.first?.stableID ?? model.memberIDs.first ?? agentName } - /// The bar's New chat: a new chat with this agent. A group chat has no one agent, so it opens the picker. - private func startNewChatFromBar() { - dismissKeyboard() - if model.isBotMode { homeChrome.onNewChat(nil) } else { homeChrome.onStartChat(homeAgentID) } - } - - /// Touch and hold New chat: the picker, with this chat's agent already picked. - private func pickAgentsFromBar() { - dismissKeyboard() - homeChrome.onNewChat(model.isBotMode ? nil : homeAgentID) - } - - private var homeHeader: some View { - let participant = resolvedIdentityParticipants.first - return AgentHomeChatHeader( - agentID: homeAgentID, - displayName: agentName, - imageURL: participant?.imageURL, - activity: model.liveActivityKind, - sessionTitle: shownSessionTitle, - groupIdentity: model.isBotMode ? AnyView(conversationHeader) : nil, - options: AnyView(chatOptionsMenu), - chrome: homeChrome, - screenHeight: screenHeight, - beforeAction: dismissKeyboard - ) - } - - private var standardHeader: some View { - HStack(alignment: .top, spacing: 8) { - HStack(spacing: 4) { - Button { - dismissKeyboard() - dismiss() - } label: { - Image(systemName: "chevron.left") - .font(.bighelp(.title3).weight(.semibold)) - .frame(width: 44, height: 44) - .contentShape(.circle) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - } - .buttonStyle(.plain) - .accessibilityLabel("Back") - .accessibilityIdentifier("chat.back") - } - .frame(width: 92, alignment: .leading) - conversationHeader.frame(maxWidth: .infinity) - HStack(spacing: 4) { - // Bots mode keeps each bot to one chat on its home; ⋯ still starts a new one. - if !homeChrome.isSimpleBots { - Button(action: onNewChatTap) { - Image(systemName: "square.and.pencil") - .font(.bighelp(.title3)) - .frame(width: 44, height: 44) - .contentShape(.circle) - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - } - .buttonStyle(.plain) - .accessibilityLabel("New chat") - .accessibilityIdentifier("chat.new-chat") - } - chatOptionsMenu - .bighelpNavigationGlass(in: Circle(), isInteractive: true) - } - .frame(width: 92, alignment: .trailing) - } + /// One home: Back, who the chat is with (a bot's pill opens its page) and ⋯; a new chat with + /// nothing sent has its To row instead. Back pops to wherever the chat was opened from. + private func pushedHeader(toRow: AnyView?) -> some View { + ChatPushedHeader(identity: AnyView(conversationHeader), toRow: toRow, options: AnyView(chatOptionsMenu), + onBack: { + dismissKeyboard() + dismiss() + }) } private var composer: some View { @@ -812,8 +682,11 @@ struct ChatView: View { companionIsAdventurous: companionStore?.isAdventurous == true, referenceHub: referenceHub ?? fallbackReferenceHub, referenceSkills: referenceSkills, - onReferenceSend: onReferenceSend + onReferenceSend: onReferenceSend, + sendOverride: newChat?.sendOverride ) + // One home: while New chat's To row isn't this chat's one bot, voice would be another bot's. + .modifier(ChatVoiceAvailability(isOffered: newChat?.isOneBotsChat != false)) .frame(maxWidth: .infinity, alignment: .center) } @@ -852,10 +725,8 @@ struct ChatView: View { groupConversationIdentityButton if let teamCallAction { TeamCallHeaderButton(action: teamCallAction) } } - } else if homeChrome.isSimpleBots { - simpleBotIdentityButton } else { - conversationIdentityButton + simpleBotIdentityButton } } .accessibilityElement(children: .contain) @@ -954,7 +825,7 @@ struct ChatView: View { } #endif - /// Bots mode: the bot's mark and name in one pill; it opens the bot's profile. + /// The bot's face and name in one pill; it opens the bot's page. private var simpleBotIdentityButton: some View { let participant = resolvedIdentityParticipants.first let agentID = model.memberIDs.first ?? participant?.stableID ?? agentName @@ -972,33 +843,6 @@ struct ChatView: View { .accessibilityIdentifier("chat.identity") } - private var conversationIdentityButton: some View { - Button { - dismissKeyboard() - // Bots mode: a bot's name opens its profile; a group's still opens its people. - if homeChrome.isSimpleBots, !model.isBotMode, let agentID = model.memberIDs.first { - homeChrome.onProfile(agentID) - } else { - onPeopleTap() - } - } label: { - ChatConversationIdentityLabel( - title: agentName, - subtitle: headerLiveActivityPresentation?.text, - participants: resolvedIdentityParticipants, - theme: theme, - subtitleShimmers: headerLiveActivityPresentation?.shimmers == true, - showsCaption: true, - liveState: headerLiveState - ) - } - .buttonStyle(.plain) - .accessibilityLabel("Chat with \(agentName)") - .accessibilityValue(headerLiveActivityPresentation?.text ?? headerLiveState.label) - .accessibilityHint("Opens agent and chat details") - .accessibilityIdentifier("chat.identity") - } - /// The header avatar is the agent's live status: working while a turn /// runs, replying once its answer is streaming into the transcript. private var headerLiveState: AgentLiveState { @@ -1088,9 +932,9 @@ struct ChatView: View { return device >= .xLarge || dynamicTypeSize.isAccessibilitySize } - /// One list: a Bot Chat's New Bot Chat (the home chat's Switch agent), then This chat (with File - /// changes), Model (Model & speed, Usage) and More (Edit agent, Advanced). Folded, This chat, Agent - /// and More hold all but Model & speed, so no level needs scrolling without reducing the font. + /// One list: a Bot Chat's New Bot Chat, then This chat (with File changes), Model (Model & speed, + /// Usage) and More (Bot page, Advanced). Folded, This chat, Agent and More hold all but Model & + /// speed, so no level needs scrolling without reducing the font. private var chatOptionsMenu: some View { Menu { if foldsChatOptions { @@ -1101,10 +945,10 @@ struct ChatView: View { Label("This chat", systemImage: "bubble.left") } .accessibilityIdentifier("chat.options.this-chat") - if onNewBotChat != nil || !model.isBotMode { + if onNewBotChat != nil || showsBotPageItem { Menu { newChatItems - editAgentItem + botPageItem } label: { Label("Agent", systemImage: "person.crop.circle") } @@ -1132,15 +976,15 @@ struct ChatView: View { usageMenu } Section { - editAgentItem + botPageItem advancedMenu } } } label: { Image(systemName: "ellipsis") #if targetEnvironment(macCatalyst) - // The same glyph as New chat beside it. - .font(.bighelp(.title3).weight(homeChrome.isEnabled ? .semibold : .regular)) + // The same weight as Back across the header. + .font(.bighelp(.title3).weight(.semibold)) #endif .frame(minWidth: BighelpTokens.hitTarget, minHeight: BighelpTokens.hitTarget) .contentShape(.rect) @@ -1238,7 +1082,7 @@ struct ChatView: View { } } - /// A Bot Chat's New Bot Chat and the home chat's Switch agent. + /// A Bot Chat's New Bot Chat. @ViewBuilder private var newChatItems: some View { if let onNewBotChat { @@ -1248,23 +1092,23 @@ struct ChatView: View { } .accessibilityIdentifier("chat.new-bot-chat") } - if homeChrome.isEnabled, !model.isBotMode { - Button("Switch agent", systemImage: "person.2") { - dismissKeyboard() - homeChrome.onSwitchAgent() - } - .accessibilityIdentifier("chat.switch-agent") - } } + /// A chat with one bot, in the shell: only there is a page to open. Not while New chat's To row + /// names nobody or several bots: the page would be the blank chat's bot's, not theirs. + private var showsBotPageItem: Bool { + !model.isBotMode && homeChrome.isPushedChat && newChat?.isOneBotsChat != false + } + + /// The bot's page, the same one its name in the header opens. @ViewBuilder - private var editAgentItem: some View { - if !model.isBotMode { - Button("Edit agent", systemImage: "person.crop.circle") { - presentCurrentAgentEditor() + private var botPageItem: some View { + if showsBotPageItem { + Button("Bot page", systemImage: "person.crop.circle") { + dismissKeyboard() + homeChrome.onProfile(homeAgentID) } - .disabled(!canEditCurrentAgent) - .accessibilityIdentifier("chat.edit-current-agent") + .accessibilityIdentifier("chat.bot-page") } } @@ -1511,19 +1355,6 @@ struct ChatView: View { ) } - private var canEditCurrentAgent: Bool { - guard let presentation = agentEditorPresentation, - presentation.profileID == model.memberIDs.first else { return false } - return presentation.isAvailable - } - - private func presentCurrentAgentEditor() { - guard canEditCurrentAgent, - let route = agentEditorPresentation?.makeRoute() else { return } - dismissKeyboard() - agentEditorRoute = route - } - private var resolvedIdentityParticipants: [ChatIdentityParticipant] { if let identityParticipants, !identityParticipants.isEmpty { return identityParticipants @@ -1585,7 +1416,8 @@ struct ChatView: View { private var attachmentAction: ((ChatActionMenuAction) -> Void)? { - guard let onAttachmentTap else { return nil } + // One home: a new chat's message that a group chat or a coding session takes is text only. + guard let onAttachmentTap, newChat?.offersAttachments != false else { return nil } return { action in dismissKeyboard() onAttachmentTap(action) @@ -1610,6 +1442,20 @@ struct ChatView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass } +/// Takes voice out of the message box's button where the chat's bot isn't who the person is +/// writing to. Read and set here, in a view of its own, so the box's other capabilities stay as +/// its screen gave them. +private struct ChatVoiceAvailability: ViewModifier { + let isOffered: Bool + @Environment(\.chatSurfaceCapabilities) private var capabilities + + func body(content: Content) -> some View { + var next = capabilities + if !isOffered { next.voice = false } + return content.environment(\.chatSurfaceCapabilities, next) + } +} + #Preview("Chat · canonical timeline") { ChatView( model: ChatModel( @@ -1639,20 +1485,3 @@ struct ChatView: View { ) ) } - -/// The home header's ☰ and buttons sit where a root screen's top bar puts them, the -/// same as on Feed, Ideas, Goals and Files. The plain header keeps its own margins -/// (Vision Pro's rounded window corner clipped ☰, so it stays clear). -private struct ChatHeaderPlacement: ViewModifier { - let isHome: Bool - - func body(content: Content) -> some View { - if isHome { - content.bighelpHeaderButtonsPlacement() - } else { - content - .padding(.horizontal, BighelpPlatform.usesTabOrnament ? 22 : 12) - .padding(.top, BighelpPlatform.usesTabOrnament ? 12 : 4) - } - } -} diff --git a/Bighelp/Chat/HermesWorkspaceViews.swift b/Bighelp/Chat/HermesWorkspaceViews.swift index aa601c79..d21bc67a 100644 --- a/Bighelp/Chat/HermesWorkspaceViews.swift +++ b/Bighelp/Chat/HermesWorkspaceViews.swift @@ -1,269 +1,5 @@ import SwiftUI -@MainActor -struct HermesWorkspacePickerView: View { - let store: HermesWorkspaceStore - let agentID: String - let sessionID: String? - let onSelected: (() -> Void)? - - @Environment(\.dismiss) private var dismiss - - init( - store: HermesWorkspaceStore, - agentID: String, - sessionID: String? = nil, - onSelected: (() -> Void)? = nil - ) { - self.store = store - self.agentID = agentID - self.sessionID = sessionID - self.onSelected = onSelected - } - - var body: some View { - NavigationStack { - ScrollView { - HermesWorkspaceManagerContent( - store: store, - agentID: agentID, - sessionID: sessionID - ) { - onSelected?() - dismiss() - } - .padding(.horizontal, BighelpTokens.space20) - .padding(.vertical, BighelpTokens.space16) - } - .scrollIndicators(.hidden) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .navigationTitle("Workspace") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .topBarTrailing) { - Button("Done") { dismiss() } - } - } - } - .task(id: "\(agentID)|\(sessionID ?? "none")") { - await store.load(agentID: agentID, sessionID: sessionID) - } - .accessibilityIdentifier("hermes-workspaces.screen") - } - - @BighelpThemeReader private var theme: BighelpTheme - -} - -@MainActor -struct HermesWorkspaceManagerContent: View { - let store: HermesWorkspaceStore - let agentID: String - let sessionID: String? - let onSelected: () -> Void - - @State private var isCreatePresented = false - @State private var workspacePendingArchive: HermesWorkspaceSummary? - - var body: some View { - VStack(alignment: .leading, spacing: BighelpTokens.space12) { - HStack(spacing: BighelpTokens.space8) { - Text("Manage Workspaces") - .bighelpFont(.sectionTitle) - .foregroundStyle(theme.primaryText) - Spacer(minLength: BighelpTokens.space8) - BighelpHeaderActionButton( - systemImage: "plus", - accessibilityLabel: "New Workspace" - ) { - isCreatePresented = true - } - .accessibilityIdentifier("hermes-workspaces.create") - } - - HermesWorkspaceRows( - store: store, - agentID: agentID, - sessionID: sessionID, - onSelected: onSelected, - onArchive: { workspacePendingArchive = $0 } - ) - } - .bighelpSheet(isPresented: $isCreatePresented) { - HermesWorkspaceCreateView(store: store, agentID: agentID) - } - .confirmationDialog( - workspacePendingArchive.map { "Archive \($0.name)?" } ?? "Archive Workspace?", - isPresented: Binding( - get: { workspacePendingArchive != nil }, - set: { if !$0 { workspacePendingArchive = nil } } - ), - titleVisibility: .visible, - presenting: workspacePendingArchive - ) { workspace in - Button("Archive Workspace", role: .destructive) { - workspacePendingArchive = nil - Task { await store.archive(id: workspace.id, agentID: agentID) } - } - Button("Cancel", role: .cancel) { - workspacePendingArchive = nil - } - } message: { _ in - Text("This archives the Workspace registration. Its remote folders and files are not deleted.") - } - } - - @BighelpThemeReader private var theme: BighelpTheme - -} - -@MainActor -struct HermesWorkspaceRows: View { - let store: HermesWorkspaceStore - let agentID: String - let sessionID: String? - let onSelected: () -> Void - let onArchive: (HermesWorkspaceSummary) -> Void - - var body: some View { - VStack(alignment: .leading, spacing: BighelpTokens.space8) { - if store.isLoading, store.catalog == nil { - BighelpThinkingOrb( - scenario: .searching, - visibleLabel: "Loading Workspaces" - ) - .frame(maxWidth: .infinity, minHeight: 160) - } else if let catalog = store.catalog, catalog.workspaces.isEmpty { - ContentUnavailableView( - "No Workspaces", - systemImage: "square.stack.3d.up", - description: Text("Create a Workspace on your Hermes host, then try again.") - ) - } else if let catalog = store.catalog { - ForEach(catalog.workspaces) { workspace in - let isSelected = HermesWorkspaceSelectionPresentation.isSelected( - workspace, - store: store, - sessionID: sessionID - ) - HStack(spacing: BighelpTokens.space4) { - Button { - Task { - if await store.select( - id: workspace.id, - agentID: agentID, - sessionID: sessionID - ) { - onSelected() - } - } - } label: { - workspaceRow(workspace) - } - .buttonStyle(.plain) - .disabled(store.selectingID != nil || store.archivingID != nil) - .accessibilityValue(isSelected ? "Selected" : "Not selected") - .accessibilityIdentifier("hermes-workspace.\(workspace.id)") - - Button { - onArchive(workspace) - } label: { - if store.archivingID == workspace.id { - BighelpThinkingOrb(scenario: .working, scale: .inline) - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - } else { - Image(systemName: "archivebox") - .font(.system(size: 16, weight: .semibold)) - .foregroundStyle(theme.secondaryText) - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - } - } - .buttonStyle(.plain) - .disabled(store.selectingID != nil || store.archivingID != nil || store.isCreating) - .accessibilityLabel("Archive \(workspace.name)") - .accessibilityIdentifier("hermes-workspace.archive.\(workspace.id)") - } - .padding(.trailing, BighelpTokens.space4) - .background(theme.surface, in: .rect(cornerRadius: BighelpTokens.radius16)) - .overlay { - RoundedRectangle(cornerRadius: BighelpTokens.radius16, style: .continuous) - .stroke( - isSelected ? theme.action : theme.border, - lineWidth: isSelected ? 1.5 : BighelpTokens.hairline - ) - } - } - } else { - ContentUnavailableView( - "Workspaces unavailable", - systemImage: "square.stack.3d.up", - description: Text(store.errorMessage ?? "Connect to the selected Hermes host and try again.") - ) - } - - if let message = store.errorMessage { - Text(message) - .bighelpFont(.metadata) - .foregroundStyle(theme.warning) - .fixedSize(horizontal: false, vertical: true) - Button("Try again") { - Task { - await store.load(agentID: agentID, sessionID: sessionID) - } - } - .bighelpActionStyle() - .tint(theme.action) - } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("hermes-workspaces.content") - } - - private func workspaceRow(_ workspace: HermesWorkspaceSummary) -> some View { - let isSelected = HermesWorkspaceSelectionPresentation.isSelected( - workspace, - store: store, - sessionID: sessionID - ) - return HStack(alignment: .top, spacing: BighelpTokens.space12) { - Image(systemName: isSelected - ? "square.stack.3d.up.fill" - : "square.stack.3d.up") - .font(.system(size: 20, weight: .semibold)) - .foregroundStyle(isSelected ? theme.action : theme.primaryText) - .frame(width: 36, height: 36) - .background(theme.raisedSurface, in: .rect(cornerRadius: 10)) - VStack(alignment: .leading, spacing: 3) { - Text(workspace.name) - .bighelpFont(.label, weight: .semibold) - .foregroundStyle(theme.primaryText) - if !workspace.description.isEmpty { - Text(workspace.description) - .bighelpFont(.body) - .foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - Text("\(workspace.folderCount) \(workspace.folderCount == 1 ? "folder" : "folders")") - .bighelpFont(.metadata) - .foregroundStyle(theme.tertiaryText) - } - Spacer(minLength: BighelpTokens.space8) - if store.selectingID == workspace.id { - BighelpThinkingOrb(scenario: .working, scale: .inline) - } else if isSelected { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(theme.action) - } - } - .padding(BighelpTokens.space12) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(.rect) - } - - @BighelpThemeReader private var theme: BighelpTheme - -} - @MainActor /// A new Hermes project: a name, a folder chats will work in and, from the /// Projects screen, a short description. diff --git a/Bighelp/Chat/SlashCommands.swift b/Bighelp/Chat/SlashCommands.swift index ef81344f..0275dcc6 100644 --- a/Bighelp/Chat/SlashCommands.swift +++ b/Bighelp/Chat/SlashCommands.swift @@ -158,7 +158,7 @@ struct SlashCommandIndex: Equatable, Sendable { @MainActor protocol SlashCommandCatalogClient: AnyObject { func catalog(sessionID: String, agentID: String) async throws -> [SlashCommandDescriptor] - /// The commands a new session would have, before it exists (Code mode's / list). + /// The commands a new session would have, before it exists (New chat's / list). func draftCatalog(agentID: String, folder: String?) async throws -> [SlashCommandDescriptor] } diff --git a/Bighelp/Code/CodeBatch.swift b/Bighelp/Code/CodeBatch.swift index 20ebf245..159689aa 100644 --- a/Bighelp/Code/CodeBatch.swift +++ b/Bighelp/Code/CodeBatch.swift @@ -1,6 +1,6 @@ import SwiftUI -/// A job staged in Code mode's message box, waiting for Send all. It keeps the +/// A job staged from New chat's choices row, waiting for Send all. It keeps the /// chips it was staged with (where it runs, branch, model, mode). struct CodeStagedJob: Codable, Identifiable, Equatable, Sendable { let id: UUID diff --git a/Bighelp/Code/CodeBranchName.swift b/Bighelp/Code/CodeBranchName.swift index 5910144c..33162471 100644 --- a/Bighelp/Code/CodeBranchName.swift +++ b/Bighelp/Code/CodeBranchName.swift @@ -1,6 +1,6 @@ import Foundation -/// Code mode names a new worktree's branch from the message that starts it: +/// A coding session names a new worktree's branch from the message that starts it: /// "Make the Kanban lanes scroll on iPad" → `code/make-kanban-lanes-scroll-ipad`. /// The worktree's folder takes the part after `code/`. enum CodeBranchName { diff --git a/Bighelp/Code/CodeHomeView.swift b/Bighelp/Code/CodeCards.swift similarity index 51% rename from Bighelp/Code/CodeHomeView.swift rename to Bighelp/Code/CodeCards.swift index cb6edecb..f9620502 100644 --- a/Bighelp/Code/CodeHomeView.swift +++ b/Bighelp/Code/CodeCards.swift @@ -1,229 +1,7 @@ import SwiftUI -/// What the Code home needs from the shell. -@MainActor -struct CodeHomeContext { - let store: CodeHomeStore - let status: any CodeSessionStatusReading - let agents: [AgentProfile] - var avatarURL: (AgentProfile) -> URL? = { _ in nil } - /// The person's sections, which the agent picker lists agents by. - var sections: [FleetSection] = [] - let onOpenSession: (CodeSessionRecord) -> Void - let onOpenChanges: (CodeSessionRecord) -> Void - var onOpenBatch: (CodeBatch) -> Void = { _ in } - let onPullRequests: () -> Void - let onWorktrees: () -> Void - /// Asks Hermes which sessions are running, for cards whose chat isn't open. - let onRefreshActivity: () async -> Void - /// Changes with each connection to the computer, so the home reloads once it's up. - let connectionKey: String? -} - -/// Code mode's home (the Launchpad): this project's coding sessions with their -/// live status, and the message box that starts a new one with each send. -struct CodeHomeView: View { - let context: CodeHomeContext - @State private var renaming: CodeBatch? - @State private var newTitle = "" - - var body: some View { - let store = context.store - ScrollView { - LazyVStack(alignment: .leading, spacing: BighelpTokens.space12) { - filterChips - if let message = store.errorMessage { - Label(message, systemImage: "exclamationmark.triangle") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .accessibilityIdentifier("code.error") - } - ForEach(store.projectLaunches) { launch in - CodeLaunchCard(launch: launch) { store.dismiss(launch) } - } - ForEach(visibleBatches) { batch in - batchCard(batch) - } - ForEach(visibleSessions) { session in - sessionCard(session) - } - if store.projectLaunches.isEmpty && store.projectSessions.isEmpty && store.projectBatches.isEmpty - && !store.isLoading { - empty - } - } - .padding(.horizontal, BighelpTokens.space16) - .padding(.top, BighelpTokens.space4) - .padding(.bottom, BighelpTokens.space16) - .frame(maxWidth: 720) - .frame(maxWidth: .infinity) - } - .scrollIndicators(.hidden) - .dismissesKeyboardOnScroll(true) - // A tap anywhere outside the message box puts the keyboard away, as in - // Messages. Simultaneous, so cards and chips still take their taps. - .simultaneousGesture(TapGesture().onEnded { BighelpKeyboard.dismiss() }) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .safeAreaInset(edge: .bottom, spacing: 0) { - CodeComposer(store: store, agents: context.agents, avatarURL: context.avatarURL, sections: context.sections, - onWorktrees: context.onWorktrees) - .frame(maxWidth: 720) - .frame(maxWidth: .infinity) - } - .toolbar { - #if targetEnvironment(macCatalyst) - ToolbarItem(placement: .topBarTrailing) { - Button("Refresh", systemImage: "arrow.clockwise") { Task { await reload() } } - .keyboardShortcut("r") - .accessibilityIdentifier("code.refresh") - } - #endif - ToolbarItem(placement: .topBarTrailing) { - Button(action: context.onPullRequests) { - Image(systemName: "arrow.triangle.pull").bighelpToolbarIcon() - } - .bighelpIconLabel(openPullRequests == 1 ? "1 open pull request" : "\(openPullRequests) open pull requests") - .accessibilityIdentifier("code.pull-requests") - } - } - .bighelpRefreshable { await reload() } - .task(id: context.connectionKey) { await reload() } - .alert("Rename batch", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) { - TextField("Name", text: $newTitle) - .accessibilityIdentifier("code.batch.rename") - Button("Save") { - if let renaming { context.store.rename(renaming, to: newTitle) } - } - Button("Cancel", role: .cancel) {} - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("code.screen") - } - - private func reload() async { - await context.store.load() - await context.onRefreshActivity() - } - - private var openPullRequests: Int { - context.store.git?.pullRequests.filter { $0.state == "open" }.count ?? 0 - } - - private var visibleSessions: [CodeSessionRecord] { - let store = context.store - guard store.filter != .all else { return store.projectSingleSessions } - return store.projectSingleSessions.filter { status(of: $0).filter == store.filter } - } - - /// A batch shows under a filter when any of its sessions matches it. - private var visibleBatches: [CodeBatch] { - let store = context.store - guard store.filter != .all else { return store.projectBatches } - return store.projectBatches.filter { batch in - batch.sessionIDs.contains { id in - store.sessions.first { $0.id == id }.map { status(of: $0).filter == store.filter } ?? false - } - } - } - - private func batchCard(_ batch: CodeBatch) -> some View { - let store = context.store - let members = CodeBatchMember.members(of: batch, sessions: store.sessions) - let pending = store.pendingLaunches(of: batch).reversed() - let lines = members.map { member in - CodeBatchCard.Line(id: member.id, title: member.title, color: member.color, - status: store.sessions.first { $0.id == member.id }.map(status(of:)) ?? .ready) - } + pending.enumerated().map { offset, launch in - CodeBatchCard.Line(id: launch.id.uuidString, title: launch.title, - color: CodeSessionColor.color(at: members.count + offset), - status: launch.step.isFailed ? .failed("Couldn't start") : .starting("Setting up")) - } - return Button { context.onOpenBatch(batch) } label: { - CodeBatchCard(batch: batch, lines: lines, startedCount: members.count) - } - .buttonStyle(.bighelpTilePress) - .contextMenu { - Button("Rename", systemImage: "pencil") { - renaming = batch - newTitle = batch.title - } - Button("Remove from list", systemImage: "eye.slash") { store.forget(batch) } - } - .accessibilityIdentifier("code.batch-card") - } - - private func status(of session: CodeSessionRecord) -> CodeSessionStatus { - context.store.status(of: session, reader: context.status) - } - - private var filterChips: some View { - let store = context.store - let counts = Dictionary(grouping: store.projectSessions.map { status(of: $0).filter }, by: { $0 }) - .mapValues(\.count) - return ScrollView(.horizontal) { - HStack(spacing: BighelpTokens.space8) { - ForEach(CodeSessionFilter.allCases) { filter in - let count = filter == .all ? store.projectSessions.count : counts[filter] ?? 0 - Button { store.filter = filter } label: { - HStack(spacing: BighelpTokens.space4) { - Text(filter.title) - Text("\(count)").foregroundStyle(store.filter == filter ? theme.canvas.opacity(0.7) : theme.secondaryText) - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(store.filter == filter ? theme.canvas : theme.primaryText) - .padding(.horizontal, BighelpTokens.space12) - .frame(minHeight: 34) - .background(store.filter == filter ? theme.primaryText : theme.surface, in: .capsule) - .contentShape(.capsule) - } - .bighelpPlainButtonStyle(.capsule) - .accessibilityAddTraits(store.filter == filter ? .isSelected : []) - .accessibilityIdentifier("code.filter.\(filter.rawValue)") - } - } - } - .scrollIndicators(.hidden) - } +// Work's cards for coding sessions: a batch, a session, a launch on its way, and their parts. - private func sessionCard(_ session: CodeSessionRecord) -> some View { - let pullRequest = session.branch.flatMap { branch in - context.store.git?.pullRequests.first { $0.branch == branch } - } - return Button { context.onOpenSession(session) } label: { - CodeSessionCard(session: session, status: status(of: session), pullRequest: pullRequest) - } - .buttonStyle(.bighelpTilePress) - .contextMenu { - Button("Changes", systemImage: "plus.forwardslash.minus") { context.onOpenChanges(session) } - Button("Remove from list", systemImage: "eye.slash") { context.store.forget(session) } - } - .accessibilityIdentifier("code.session.\(session.id)") - } - - private var empty: some View { - VStack(spacing: BighelpTokens.space12) { - Image(systemName: "chevron.left.forwardslash.chevron.right") - .font(.system(size: 36, weight: .semibold)) - .foregroundStyle(theme.action) - Text(context.store.projects.isEmpty ? "No projects yet" : "Describe a change") - .font(.bighelp(.title3).weight(.semibold)) - .foregroundStyle(theme.primaryText) - Text(context.store.projects.isEmpty - ? "Add a git folder from your computer as a project, then send what you want changed." - : "Each message you send starts its own session. Send another while the first one works.") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - } - .frame(maxWidth: .infinity) - .padding(.vertical, BighelpTokens.space32) - .accessibilityIdentifier("code.empty") - } - - @BighelpThemeReader private var theme -} - -/// One session: its status dot, name, where it works and what it's doing now. /// A batch sent with Send all: one card, one line per session with its live status. struct CodeBatchCard: View { struct Line: Identifiable { @@ -309,6 +87,7 @@ struct CodeBatchCard: View { @BighelpThemeReader private var theme } +/// One session: its status dot, name, where it works and what it's doing now. struct CodeSessionCard: View { let session: CodeSessionRecord let status: CodeSessionStatus diff --git a/Bighelp/Code/CodeChangesView.swift b/Bighelp/Code/CodeChangesView.swift index 58e3f10b..79382e53 100644 --- a/Bighelp/Code/CodeChangesView.swift +++ b/Bighelp/Code/CodeChangesView.swift @@ -1,6 +1,6 @@ import SwiftUI -/// A Code mode session's changes in its worktree (or the local folder), and +/// A coding session's changes in its worktree (or the local folder), and /// shipping them: commit, push and a pull request, with the host's own git. @MainActor @Observable diff --git a/Bighelp/Code/CodeComposer.swift b/Bighelp/Code/CodeComposer.swift deleted file mode 100644 index b033feb2..00000000 --- a/Bighelp/Code/CodeComposer.swift +++ /dev/null @@ -1,842 +0,0 @@ -import SwiftUI - -/// Code mode's message box: the text with Send beside it, then a line with the agent -/// (its chip opens the model, reasoning and fast mode for new sessions), the mode -/// (Default, Plan, YOLO) and Stage, each a full-size target. Under it, three chips choose -/// the project, where the session works (a new worktree or the local checkout) and its -/// branch; they stay set after each send, so the next message starts the next session -/// right away. Typing `/` first shows the new session's commands and skills. -/// Orchestration mode: Stage keeps the message (with the chips as they are) in a tray -/// above the box, and Send all starts every staged job as one batch. -struct CodeComposer: View { - @Bindable var store: CodeHomeStore - let agents: [AgentProfile] - var avatarURL: (AgentProfile) -> URL? = { _ in nil } - var sections: [FleetSection] = [] - let onWorktrees: () -> Void - @State private var message = "" - @State private var isPickingProject = false - @State private var isPickingBranch = false - @State private var isPickingRuntime = false - @FocusState private var isFocused: Bool - - var body: some View { - VStack(alignment: .leading, spacing: BighelpTokens.space8) { - if isTypingCommand { - slashList - .transition(.opacity) - } - if !store.projectStaged.isEmpty { - stagedTray - } - VStack(alignment: .leading, spacing: BighelpTokens.space8) { - HStack(alignment: .bottom, spacing: BighelpTokens.space8) { - TextField("Describe a change…", text: $message, axis: .vertical) - .font(.bighelp(.body)) - .foregroundStyle(theme.primaryText) - .lineLimit(1...6) - .focused($isFocused) - .padding(.vertical, BighelpTokens.space8) - .bighelpMacFieldArea() - .accessibilityIdentifier("code.composer.field") - if hasStaged { - sendAllButton - .fixedSize() - } else { - sendButton - .fixedSize() - } - } - HStack(spacing: BighelpTokens.space8) { - agentChip - .layoutPriority(-1) - modeMenu - .fixedSize() - Spacer(minLength: 0) - stageButton - .fixedSize() - } - } - .padding(.leading, BighelpTokens.space16) - .padding(.trailing, BighelpTokens.space12) - .padding(.vertical, BighelpTokens.space12) - .bighelpSurface(.composer) - ScrollView(.horizontal) { - HStack(spacing: BighelpTokens.space8) { - projectChip - placementMenu - branchChip - } - .padding(.horizontal, BighelpTokens.space4) - } - .scrollIndicators(.hidden) - } - .padding(.horizontal, BighelpTokens.space12) - .padding(.bottom, BighelpTokens.space8) - .bighelpSheet(isPresented: $isPickingProject) { - CodeProjectPicker(store: store) - .bighelpSheetSize(.standard) - } - .bighelpSheet(isPresented: $isPickingBranch) { - CodeBranchPicker(store: store, message: message) - .bighelpSheetSize(.standard) - } - .bighelpSheet(isPresented: $isPickingRuntime) { - CodeRuntimePicker(store: store, agents: agents, avatarURL: avatarURL, sections: sections) - .bighelpSheetSize(.standard) - } - .task(id: isTypingCommand) { - if isTypingCommand { await store.loadCommandsIfNeeded() } - } - } - - // MARK: The / list - - /// A `/` with no space after it yet: the list is open. - private var isTypingCommand: Bool { - message.hasPrefix("/") && !message.contains(where: \.isWhitespace) - } - - private var matchingCommands: [SlashCommandDescriptor] { - SlashCommandIndex(commands: store.commands).suggestions(for: message).sorted { lhs, rhs in - if (lhs.source == .skill) != (rhs.source == .skill) { return lhs.source == .skill } - return lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending - } - } - - private var slashList: some View { - let commands = matchingCommands - return BighelpSuggestionList( - suggestions: commands.map { command in - BighelpSuggestion(id: command.name, - icon: .symbol(command.source == .skill ? "wand.and.stars" : "command"), - sigil: "/", name: command.name, detail: command.description, - tag: command.source == .skill ? "Skill" : "Command") - }, - identifier: "code.slash", - emptyText: store.commandsError ?? (store.commands.isEmpty ? "Loading commands…" : "No matching commands."), - onPick: { picked in - guard let command = commands.first(where: { $0.name == picked.id }) else { return } - message = SlashCommandIndex(commands: [command]).draft(selecting: command) - isFocused = true - } - ) { - BighelpSuggestionHeader(systemImage: "command", title: "Commands and skills", - count: store.commands.isEmpty ? nil : commands.count, - isLoading: store.commands.isEmpty && store.commandsError == nil) - } - } - - // MARK: The mode button - - private var modeMenu: some View { - Menu { - Section("How should this session work?") { - ForEach(CodeSessionMode.allCases) { mode in - Button { - store.mode = mode - } label: { - Label(mode.title, systemImage: store.mode == mode ? "checkmark" : mode.systemImage) - Text(mode.detail) - } - .accessibilityIdentifier("code.mode.\(mode.rawValue)") - } - } - } label: { - HStack(spacing: BighelpTokens.space4) { - Image(systemName: store.mode.systemImage) - Text(store.mode.title).lineLimit(1) - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(modeTint) - .padding(.horizontal, BighelpTokens.space12) - .frame(minHeight: BighelpTokens.scaled(44)) - .background(store.mode == .standard ? theme.raisedSurface : modeTint.opacity(0.14), in: .capsule) - .contentShape(.capsule) - } - .accessibilityLabel("Mode: \(store.mode.title)") - .accessibilityIdentifier("code.composer.mode") - } - - private var modeTint: Color { - switch store.mode { - case .standard: theme.secondaryText - case .plan: theme.action - case .yolo: theme.warning - } - } - - /// The agent new sessions start with, by name; it opens the agent, model, reasoning and fast mode. - private var agentChip: some View { - let agent = agents.first { $0.id == store.agentID } - return Button { isPickingRuntime = true } label: { - HStack(spacing: BighelpTokens.space8) { - if let agent { - AgentLiveAvatar(agentID: agent.id, displayName: agent.name, imageURL: avatarURL(agent), - size: BighelpTokens.scaled(26), showsBadge: false) - } else { - Image(systemName: "person.crop.circle") - } - Text(agent?.name ?? "Agent") - .lineLimit(1) - .truncationMode(.tail) - Image(systemName: "chevron.right") - .font(.bighelp(.caption2).weight(.semibold)) - .foregroundStyle(theme.secondaryText) - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .padding(.leading, BighelpTokens.space8) - .padding(.trailing, BighelpTokens.space12) - .frame(minHeight: BighelpTokens.scaled(44)) - .background(theme.raisedSurface, in: .capsule) - .contentShape(.capsule) - } - .bighelpPlainButtonStyle(.capsule) - .accessibilityLabel("Agent: \(agent?.name ?? "none"), \(runtimeTitle)") - .accessibilityHint("Changes the agent, model, reasoning and fast mode for new sessions.") - .accessibilityIdentifier("code.composer.agent") - } - - private var runtimeTitle: String { - let runtime = store.runtime - var parts = [runtime.modelID.map { ModelNameCatalogStore.shared.displayName(for: $0) } ?? "Agent's model"] - if let reasoning = runtime.reasoning { parts.append(CodeRuntimeChoice.reasoningLabel(reasoning)) } - if runtime.fastMode == true { parts.append("Fast") } - return parts.joined(separator: " · ") - } - - private var canSend: Bool { - store.project != nil && !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - - // MARK: Orchestration mode - - private var hasStaged: Bool { !store.projectStaged.isEmpty } - - /// Staged jobs plus the one in the box, if any. - private var sendAllCount: Int { store.projectStaged.count + (canSend ? 1 : 0) } - - /// Keeps the message for Send all. With jobs staged it shrinks to its icon, so Send all fits. - private var stageButton: some View { - Button { - if store.stage(message) { message = "" } - } label: { - HStack(spacing: BighelpTokens.space4) { - Image(systemName: "rectangle.stack.badge.plus") - if !hasStaged { Text("Stage") } - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(canSend ? theme.primaryText : theme.secondaryText) - .padding(.horizontal, hasStaged ? 0 : BighelpTokens.space12) - .frame(minWidth: BighelpTokens.scaled(44), minHeight: BighelpTokens.scaled(44)) - .background(theme.raisedSurface, in: .capsule) - .contentShape(.capsule) - } - .bighelpPlainButtonStyle(.capsule) - .disabled(!canSend) - .keyboardShortcut(.return, modifiers: [.command, .shift]) - .bighelpIconLabel("Stage for Send all", shortcut: "⇧⌘↩") - .accessibilityIdentifier("code.composer.stage") - } - - private var sendAllButton: some View { - Button { - if store.sendAll(including: message) != nil { message = "" } - } label: { - HStack(spacing: BighelpTokens.space8) { - Text("Send all").lineLimit(1) - Text("\(sendAllCount)") - .font(.bighelp(.caption).weight(.bold)) - .padding(.horizontal, 6) - .frame(minWidth: 20, minHeight: 20) - .background(theme.actionForeground.opacity(0.25), in: .capsule) - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.actionForeground) - .padding(.leading, BighelpTokens.space16) - .padding(.trailing, BighelpTokens.space12) - .frame(minHeight: BighelpTokens.scaled(44)) - .background(theme.action, in: .capsule) - .contentShape(.capsule) - } - .bighelpPlainButtonStyle(.capsule) - .disabled(store.project == nil || sendAllCount == 0) - .keyboardShortcut(.return, modifiers: .command) - .accessibilityLabel("Send all \(sendAllCount)") - .accessibilityIdentifier("code.composer.send-all") - } - - /// The staged jobs, each with the chips it was staged with; a tap on × takes one out. - private var stagedTray: some View { - let jobs = store.projectStaged - return VStack(alignment: .leading, spacing: BighelpTokens.space8) { - HStack { - Text("Staged").font(.bighelp(.subheadline).weight(.semibold)) - + Text(jobs.count == 1 ? " · 1 job" : " · \(jobs.count) jobs") - .font(.bighelp(.subheadline)).foregroundStyle(theme.secondaryText) - Spacer(minLength: 0) - Button("Clear") { store.clearStaged() } - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .accessibilityIdentifier("code.staged.clear") - } - ScrollView { - VStack(spacing: BighelpTokens.space8) { - ForEach(Array(jobs.enumerated()), id: \.element.id) { index, job in - stagedRow(job, number: index + 1) - } - } - } - .frame(height: CGFloat(min(jobs.count, 3)) * BighelpTokens.scaled(56) - + CGFloat(min(jobs.count, 3) - 1) * BighelpTokens.space8) - .scrollIndicators(.hidden) - } - .padding(BighelpTokens.space12) - .background(theme.surface, in: .rect(cornerRadius: 20)) - .overlay { RoundedRectangle(cornerRadius: 20).stroke(theme.border, lineWidth: BighelpTokens.hairline) } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("code.staged") - } - - private func stagedRow(_ job: CodeStagedJob, number: Int) -> some View { - let color = CodeSessionColor.color(at: number - 1) - return HStack(spacing: BighelpTokens.space12) { - Text("\(number)") - .font(.bighelp(.caption).weight(.bold)) - .foregroundStyle(color) - .frame(width: BighelpTokens.scaled(22), height: BighelpTokens.scaled(22)) - .background(color.opacity(0.2), in: .circle) - VStack(alignment: .leading, spacing: 2) { - Text(job.title) - .font(.bighelp(.subheadline).weight(.medium)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - Label(stagedDetail(job), systemImage: job.placement.systemImage) - .font(.bighelp(.caption)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - } - .frame(maxWidth: .infinity, alignment: .leading) - Button("Remove", systemImage: "xmark") { store.unstage(job.id) } - .labelStyle(.iconOnly) - .font(.bighelp(.footnote).weight(.semibold)) - .foregroundStyle(theme.secondaryText) - .frame(width: 32, height: 32) - .contentShape(.rect) - .bighelpPlainButtonStyle() - .accessibilityIdentifier("code.staged.remove.\(number)") - } - .padding(.horizontal, BighelpTokens.space8) - .frame(minHeight: BighelpTokens.scaled(56)) - .background(theme.raisedSurface, in: .rect(cornerRadius: 14)) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("code.staged.job.\(number)") - } - - private func stagedDetail(_ job: CodeStagedJob) -> String { - let model = job.runtime.modelID.map { ModelNameCatalogStore.shared.displayName(for: $0) } ?? "Agent's model" - return [job.placement.title, job.branch, model, job.mode == .standard ? nil : job.mode.title] - .compactMap { $0 }.joined(separator: " · ") - } - - private var sendButton: some View { - Button { - if store.send(message) { message = "" } - } label: { - Image(systemName: "arrow.up") - .font(.bighelp(.body).weight(.bold)) - .foregroundStyle(canSend ? theme.actionForeground : theme.secondaryText) - .frame(width: BighelpTokens.scaled(44), height: BighelpTokens.scaled(44)) - .background(canSend ? theme.action : theme.raisedSurface, in: .circle) - .contentShape(.circle) - } - .bighelpPlainButtonStyle(.circle) - .disabled(!canSend) - .keyboardShortcut(.return, modifiers: .command) - .bighelpIconLabel("Start session", shortcut: "⌘↩") - .accessibilityIdentifier("code.composer.send") - } - - private var projectChip: some View { - Button { isPickingProject = true } label: { - CodeChipLabel(systemImage: "folder", text: store.project?.name ?? "Choose a project") - } - .bighelpPlainButtonStyle(.capsule) - .accessibilityLabel("Project: \(store.project?.name ?? "none")") - .accessibilityIdentifier("code.chip.project") - } - - private var placementMenu: some View { - Menu { - Section("Where should this session run?") { - ForEach(CodePlacement.allCases) { placement in - Button { - store.placement = placement - store.branch = nil - } label: { - Label(placement.title, systemImage: store.placement == placement ? "checkmark" : placement.systemImage) - Text(subtitle(for: placement)) - } - .accessibilityIdentifier("code.placement.\(placement.rawValue)") - } - } - Button("Manage worktrees", systemImage: "square.stack.3d.up", action: onWorktrees) - } label: { - CodeChipLabel(systemImage: store.placement.systemImage, text: store.placement.title) - } - .accessibilityLabel("Where it runs: \(store.placement.title)") - .accessibilityIdentifier("code.chip.placement") - } - - private func subtitle(for placement: CodePlacement) -> String { - let busy = store.sessionsInMainFolder - guard placement == .local, busy > 0 else { return placement.detail } - return busy == 1 ? "1 session is already working here." : "\(busy) sessions are already working here." - } - - private var branchChip: some View { - Button { isPickingBranch = true } label: { - CodeChipLabel(systemImage: "arrow.triangle.branch", text: store.branchTitle ?? "Branch", monospaced: true) - } - .bighelpPlainButtonStyle(.capsule) - .disabled(store.git == nil) - .accessibilityLabel("Branch: \(store.branchTitle ?? "default")") - .accessibilityIdentifier("code.chip.branch") - } - - @BighelpThemeReader private var theme -} - -struct CodeChipLabel: View { - let systemImage: String - let text: String - var monospaced = false - - var body: some View { - HStack(spacing: BighelpTokens.space4) { - Image(systemName: systemImage) - Text(text) - .font(monospaced ? .system(.subheadline, design: .monospaced).weight(.medium) - : .bighelp(.subheadline).weight(.medium)) - .lineLimit(1) - } - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.primaryText) - .padding(.horizontal, BighelpTokens.space12) - .frame(minHeight: BighelpTokens.scaled(34)) - .bighelpSurface(.capsuleControl, isInteractive: true) - .contentShape(.capsule) - } - - @BighelpThemeReader private var theme -} - -/// The project chip's sheet: Hermes projects, then git folders it found that can become one. -struct CodeProjectPicker: View { - @Bindable var store: CodeHomeStore - @Environment(\.dismiss) private var dismiss - @State private var search = "" - @State private var addingPath: String? - - var body: some View { - NavigationStack { - List { - BighelpSearchField(text: $search, accessibilityIdentifier: "code.projects.search") - .bighelpListSearchRow() - Section { - if store.projects.isEmpty { - if store.isLoading { - ProgressView().frame(maxWidth: .infinity) - } else { - Text(store.errorMessage ?? "No projects on this computer yet. Add a folder below.") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - } - } - ForEach(matching(store.projects)) { project in - Button { - Task { await store.selectProject(project.id) } - dismiss() - } label: { - HStack(spacing: BighelpTokens.space12) { - ProjectTile(id: project.id, icon: project.icon, color: project.color, size: 32) - VStack(alignment: .leading, spacing: 2) { - Text(project.name).font(.bighelp(.body)).foregroundStyle(theme.primaryText) - Text(project.folder) - .font(.system(.caption, design: .monospaced)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1).truncationMode(.head) - } - Spacer(minLength: 0) - if project.id == store.projectID { - Image(systemName: "checkmark").foregroundStyle(theme.action) - } - } - .contentShape(.rect) - } - .bighelpPlainButtonStyle() - .accessibilityIdentifier("code.project.\(project.id)") - } - } - .listRowBackground(theme.surface) - if !matching(store.found).isEmpty { - Section("Found on your computer") { - ForEach(matching(store.found)) { folder in - HStack(spacing: BighelpTokens.space12) { - Image(systemName: "folder").frame(width: 32).foregroundStyle(theme.secondaryText) - VStack(alignment: .leading, spacing: 2) { - Text(folder.name).font(.bighelp(.body)).foregroundStyle(theme.primaryText) - Text(folder.path) - .font(.system(.caption, design: .monospaced)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1).truncationMode(.head) - } - Spacer(minLength: 0) - if addingPath == folder.path { - ProgressView() - } else { - Button("Add") { - addingPath = folder.path - Task { - await store.addProject(folder) - addingPath = nil - if store.project?.folder == folder.path { dismiss() } - } - } - .font(.bighelp(.subheadline).weight(.semibold)) - .accessibilityIdentifier("code.found.add") - } - } - } - } - .listRowBackground(theme.surface) - } - } - .listStyle(.insetGrouped) - .scrollContentBackground(.hidden) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle("Project") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } - } - .bighelpRefreshable { await store.load() } - .task { if store.projects.isEmpty { await store.load() } } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("code.projects") - } - - private func matching(_ projects: [CodeProject]) -> [CodeProject] { - let term = search.trimmingCharacters(in: .whitespaces) - guard !term.isEmpty else { return projects } - return projects.filter { $0.name.localizedCaseInsensitiveContains(term) || $0.folder.localizedCaseInsensitiveContains(term) } - } - - private func matching(_ folders: [CodeFoundFolder]) -> [CodeFoundFolder] { - let term = search.trimmingCharacters(in: .whitespaces) - guard !term.isEmpty else { return folders } - return folders.filter { $0.name.localizedCaseInsensitiveContains(term) || $0.path.localizedCaseInsensitiveContains(term) } - } - - @BighelpThemeReader private var theme -} - -/// The branch chip's sheet. New worktree: the new branch's name (named from the -/// message unless changed) and the branch it starts from. Local: the branch to -/// check out in the project's folder. -struct CodeBranchPicker: View { - @Bindable var store: CodeHomeStore - let message: String - @Environment(\.dismiss) private var dismiss - @State private var search = "" - @State private var newBranch = "" - - var body: some View { - NavigationStack { - List { - if store.placement == .newWorktree { - Section { - TextField(suggested, text: $newBranch) - .font(.system(.body, design: .monospaced)) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - .accessibilityIdentifier("code.branch.new") - } header: { - Text("New branch") - } footer: { - Text("Named from your message unless you type a name.") - } - .listRowBackground(theme.surface) - } - BighelpSearchField(text: $search, prompt: "Search branches", accessibilityIdentifier: "code.branch.search") - .bighelpListSearchRow() - Section(store.placement == .newWorktree ? "Start from" : "Branch") { - ForEach(matching(localBranches)) { branch in - branchRow(branch) - } - } - .listRowBackground(theme.surface) - if store.placement == .local, !matching(remoteBranches).isEmpty { - Section("On GitHub") { - ForEach(matching(remoteBranches)) { branch in - Text(branch.name) - .font(.system(.body, design: .monospaced)) - .foregroundStyle(theme.secondaryText) - } - } - .listRowBackground(theme.surface) - } - } - .listStyle(.insetGrouped) - .scrollContentBackground(.hidden) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle(store.placement == .newWorktree ? "Start from" : "Branch") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .confirmationAction) { - Button("Done") { - let name = newBranch.trimmingCharacters(in: .whitespacesAndNewlines) - store.newBranchName = name.isEmpty ? nil : name - dismiss() - } - .accessibilityIdentifier("code.branch.done") - } - } - .onAppear { newBranch = store.newBranchName ?? "" } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("code.branches") - } - - private var suggested: String { - let taken = Set(store.git?.branches.map(\.name) ?? []) - return CodeBranchName.suggested(for: message.isEmpty ? "change" : message, taken: taken) - } - - /// Worktrees start from base branches; Local checks out a local branch. - private var localBranches: [StockGitBranch] { - guard let git = store.git else { return [] } - return store.placement == .newWorktree ? git.baseBranches : git.branches.filter { !$0.isRemote } - } - - private var remoteBranches: [StockGitBranch] { - store.git?.branches.filter(\.isRemote) ?? [] - } - - private func branchRow(_ branch: StockGitBranch) -> some View { - let selected = branch.name == store.branchTitle - // A branch checked out in another worktree can't be checked out here too. - let busyElsewhere = store.placement == .local && branch.worktreePath != nil - && branch.worktreePath != store.project?.folder - return Button { - store.branch = branch.name - dismiss() - } label: { - HStack(spacing: BighelpTokens.space12) { - Image(systemName: "arrow.triangle.branch").foregroundStyle(theme.secondaryText) - VStack(alignment: .leading, spacing: 2) { - Text(branch.name) - .font(.system(.body, design: .monospaced)) - .foregroundStyle(busyElsewhere ? theme.secondaryText : theme.primaryText) - if let note = note(for: branch) { - Text(note).font(.bighelp(.caption)).foregroundStyle(theme.secondaryText) - } - } - Spacer(minLength: 0) - if selected { Image(systemName: "checkmark").foregroundStyle(theme.action) } - } - .contentShape(.rect) - } - .bighelpPlainButtonStyle() - .disabled(busyElsewhere) - .accessibilityIdentifier("code.branch.\(branch.name)") - } - - private func note(for branch: StockGitBranch) -> String? { - if branch.isDefault { return "Default" } - guard let path = branch.worktreePath else { return nil } - return path == store.project?.folder ? "Checked out in the local folder" : "In a worktree" - } - - private func matching(_ branches: [StockGitBranch]) -> [StockGitBranch] { - let term = search.trimmingCharacters(in: .whitespaces) - guard !term.isEmpty else { return branches } - return branches.filter { $0.name.localizedCaseInsensitiveContains(term) } - } - - @BighelpThemeReader private var theme -} - -/// The agent chip's sheet: the agent new sessions run with (under their sections, then the rest), -/// then its model (or the agent's own), reasoning level and fast mode. Each session applies them -/// before its first message. -struct CodeRuntimePicker: View { - @Bindable var store: CodeHomeStore - var agents: [AgentProfile] = [] - var avatarURL: (AgentProfile) -> URL? = { _ in nil } - var sections: [FleetSection] = [] - @Environment(\.dismiss) private var dismiss - @State private var providers: [BighelpLinkModelProvider] = [] - @State private var isLoading = true - @State private var loadError: String? - @State private var search = "" - - var body: some View { - NavigationStack { - Form { - if agents.count > 1 { - let grouped = FleetSectioning.grouped(agents, sections: sections, placement: \.placement) - ForEach(Array(grouped.enumerated()), id: \.offset) { _, group in - Section(group.section?.name ?? (grouped.count > 1 ? String(localized: "Other agents") - : String(localized: "Agent"))) { - ForEach(group.items) { agent in agentRow(agent) } - } - .listRowBackground(theme.surface) - } - } - Section("Model") { - NavigationLink { - modelList - } label: { - LabeledContent("Model", value: modelTitle) - } - .accessibilityIdentifier("code.runtime.model") - } - .listRowBackground(theme.surface) - Section { - Picker("Reasoning", selection: $store.runtime.reasoning) { - Text("Agent's setting").tag(String?.none) - ForEach(CodeRuntimeChoice.reasoningLevels, id: \.value) { level in - Text(level.label).tag(Optional(level.value)) - } - } - .accessibilityIdentifier("code.runtime.reasoning") - Picker("Fast mode", selection: $store.runtime.fastMode) { - Text("Agent's setting").tag(Bool?.none) - Text("On").tag(Optional(true)) - Text("Off").tag(Optional(false)) - } - .disabled(fastModeUnavailable != nil) - .accessibilityIdentifier("code.runtime.fast") - } footer: { - Text(fastModeUnavailable ?? "Each new session checks these with Hermes before your message goes out.") - } - .listRowBackground(theme.surface) - } - .scrollContentBackground(.hidden) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle(agents.first { $0.id == store.agentID }?.name ?? "Agent") - .navigationBarTitleDisplayMode(.inline) - .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } - // Models are the agent's own: a new agent loads its list. - .task(id: store.agentID) { await load() } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("code.runtime") - } - - private func agentRow(_ agent: AgentProfile) -> some View { - Button { - Task { await store.selectAgent(agent.id) } - } label: { - HStack(spacing: BighelpTokens.space12) { - AgentLiveAvatar(agentID: agent.id, displayName: agent.name, imageURL: avatarURL(agent), - size: BighelpTokens.scaled(30), showsBadge: false) - Text(agent.name).foregroundStyle(theme.primaryText) - Spacer(minLength: 0) - if agent.id == store.agentID { - Image(systemName: "checkmark").foregroundStyle(theme.action) - } - } - .contentShape(.rect) - } - .bighelpPlainButtonStyle() - .accessibilityIdentifier("code.runtime.agent.\(agent.id)") - } - - private var modelTitle: String { - store.runtime.modelID.map { ModelNameCatalogStore.shared.displayName(for: $0) } ?? "Agent's model" - } - - /// Fast mode needs a chosen model that supports it. - private var fastModeUnavailable: String? { - guard let modelID = store.runtime.modelID else { return "Choose a model to use Fast Mode." } - return FastMode.unavailableReason(provider: providers.first { $0.id == store.runtime.providerID }, - model: modelID) - } - - private var modelList: some View { - List { - BighelpSearchField(text: $search, prompt: "Search models", accessibilityIdentifier: "code.runtime.search") - .bighelpListSearchRow() - Section { - modelRow(title: "Agent's model", providerID: nil, modelID: nil) - } - .listRowBackground(theme.surface) - if isLoading { - ProgressView().frame(maxWidth: .infinity) - } else if let loadError { - Text(loadError).font(.bighelp(.subheadline)).foregroundStyle(theme.secondaryText) - } - ForEach(providers.filter { !matching($0).isEmpty }) { provider in - Section(provider.name) { - ForEach(matching(provider), id: \.self) { model in - modelRow(title: ModelNameCatalogStore.shared.displayName(for: model), - providerID: provider.id, modelID: model) - } - } - .listRowBackground(theme.surface) - } - } - .listStyle(.insetGrouped) - .scrollContentBackground(.hidden) - .background(theme.canvas.ignoresSafeArea()) - .navigationTitle("Model") - .navigationBarTitleDisplayMode(.inline) - } - - private func modelRow(title: String, providerID: String?, modelID: String?) -> some View { - Button { - store.runtime.providerID = providerID - store.runtime.modelID = modelID - if fastModeUnavailable != nil { store.runtime.fastMode = nil } - } label: { - HStack { - Text(title).foregroundStyle(theme.primaryText) - Spacer(minLength: 0) - if store.runtime.providerID == providerID && store.runtime.modelID == modelID { - Image(systemName: "checkmark").foregroundStyle(theme.action) - } - } - .contentShape(.rect) - } - .bighelpPlainButtonStyle() - .accessibilityIdentifier(providerID.map { "code.runtime.model.\($0).\(modelID ?? "")" } ?? "code.runtime.model.agent") - } - - private func matching(_ provider: BighelpLinkModelProvider) -> [String] { - let term = search.trimmingCharacters(in: .whitespaces) - guard !term.isEmpty else { return provider.models } - return provider.models.filter { - $0.localizedCaseInsensitiveContains(term) - || ModelNameCatalogStore.shared.displayName(for: $0).localizedCaseInsensitiveContains(term) - || provider.name.localizedCaseInsensitiveContains(term) - } - } - - private func load() async { - isLoading = true - defer { isLoading = false } - do { - providers = try await store.modelProviders() - loadError = providers.isEmpty ? "No models found for this agent." : nil - } catch is CancellationError { - } catch { - loadError = "Models couldn't load. \(error.localizedDescription)" - } - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Code/CodeHomeStore.swift b/Bighelp/Code/CodeHomeStore.swift index 1234173b..fe01a44c 100644 --- a/Bighelp/Code/CodeHomeStore.swift +++ b/Bighelp/Code/CodeHomeStore.swift @@ -1,7 +1,7 @@ import Foundation import Observation -/// Code mode's home for one computer: what the three chips under the message box +/// Coding sessions for one computer: what the three chips under the message box /// hold (project, where it runs, branch), the agent that runs the sessions, and /// the sessions sent from here. Each Send starts its own session and returns at /// once, so several can be sent back to back. Orchestration mode stages jobs (each diff --git a/Bighelp/Code/CodeLauncher.swift b/Bighelp/Code/CodeLauncher.swift index 8c0705eb..4d234b91 100644 --- a/Bighelp/Code/CodeLauncher.swift +++ b/Bighelp/Code/CodeLauncher.swift @@ -11,7 +11,7 @@ protocol CodeSessionStarting { func send(_ message: String, toSession sessionID: String) async throws } -/// What one Send in Code mode asks for. +/// What one Send of a coding session asks for. struct CodeLaunchRequest: Equatable, Sendable { let message: String let agentID: String diff --git a/Bighelp/Code/CodeModels.swift b/Bighelp/Code/CodeModels.swift index 29368382..e838b57a 100644 --- a/Bighelp/Code/CodeModels.swift +++ b/Bighelp/Code/CodeModels.swift @@ -1,6 +1,6 @@ import Foundation -/// Where a Code mode session works. +/// Where a coding session works. enum CodePlacement: String, Codable, CaseIterable, Identifiable, Sendable { /// Its own copy of the project on a new branch, so sessions run side by side. case newWorktree @@ -31,7 +31,7 @@ enum CodePlacement: String, Codable, CaseIterable, Identifiable, Sendable { } } -/// How a new Code mode session works (the message box's mode button). Each is a +/// How a new coding session works (the choices row's mode chip). Each is a /// Hermes option: Plan sends the first message through `/plan`, which writes a /// Markdown plan and changes no code; YOLO turns on the session's own YOLO /// setting (no approval prompts) before the first message. @@ -73,7 +73,7 @@ enum CodeSessionMode: String, Codable, CaseIterable, Identifiable, Sendable { } } -/// A project Code mode can start sessions in: a Hermes project with one main folder. +/// A project a coding session can start in: a Hermes project with one main folder. struct CodeProject: Identifiable, Equatable, Sendable { let id: String let name: String @@ -90,7 +90,7 @@ struct CodeFoundFolder: Identifiable, Equatable, Sendable { var id: String { path } } -/// One session Code mode started, kept on this device per computer so its card +/// One coding session, kept on this device per computer so its card /// survives a relaunch. Its status always comes from the live chat. struct CodeSessionRecord: Codable, Identifiable, Equatable, Sendable { /// The app's session ID, which opens the chat. diff --git a/Bighelp/Code/CodePickers.swift b/Bighelp/Code/CodePickers.swift new file mode 100644 index 00000000..cca334b8 --- /dev/null +++ b/Bighelp/Code/CodePickers.swift @@ -0,0 +1,265 @@ +import SwiftUI + +// The chips a new chat's choices row uses for a coding session, and the pickers they open. + +struct CodeChipLabel: View { + let systemImage: String + let text: String + var monospaced = false + + var body: some View { + HStack(spacing: BighelpTokens.space4) { + Image(systemName: systemImage) + Text(text) + .font(monospaced ? .system(.subheadline, design: .monospaced).weight(.medium) + : .bighelp(.subheadline).weight(.medium)) + .lineLimit(1) + } + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.primaryText) + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: BighelpTokens.scaled(34)) + .bighelpSurface(.capsuleControl, isInteractive: true) + .contentShape(.capsule) + } + + @BighelpThemeReader private var theme +} + +/// The project chip's sheet: Hermes projects, then git folders it found that can become one. +struct CodeProjectPicker: View { + @Bindable var store: CodeHomeStore + @Environment(\.dismiss) private var dismiss + @State private var search = "" + @State private var addingPath: String? + + var body: some View { + NavigationStack { + List { + BighelpSearchField(text: $search, accessibilityIdentifier: "code.projects.search") + .bighelpListSearchRow() + Section { + if store.projects.isEmpty { + if store.isLoading { + ProgressView().frame(maxWidth: .infinity) + } else { + Text(store.errorMessage ?? String(localized: "No projects on this computer yet. Add a folder below.")) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + } + } + ForEach(matching(store.projects)) { project in + Button { + Task { await store.selectProject(project.id) } + dismiss() + } label: { + HStack(spacing: BighelpTokens.space12) { + ProjectTile(id: project.id, icon: project.icon, color: project.color, size: 32) + VStack(alignment: .leading, spacing: 2) { + Text(project.name).font(.bighelp(.body)).foregroundStyle(theme.primaryText) + Text(project.folder) + .font(.system(.caption, design: .monospaced)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1).truncationMode(.head) + } + Spacer(minLength: 0) + if project.id == store.projectID { + Image(systemName: "checkmark").foregroundStyle(theme.action) + } + } + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("code.project.\(project.id)") + } + } + .listRowBackground(theme.surface) + if !matching(store.found).isEmpty { + Section("Found on your computer") { + ForEach(matching(store.found)) { folder in + HStack(spacing: BighelpTokens.space12) { + Image(systemName: "folder").frame(width: 32).foregroundStyle(theme.secondaryText) + VStack(alignment: .leading, spacing: 2) { + Text(folder.name).font(.bighelp(.body)).foregroundStyle(theme.primaryText) + Text(folder.path) + .font(.system(.caption, design: .monospaced)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1).truncationMode(.head) + } + Spacer(minLength: 0) + if addingPath == folder.path { + ProgressView() + } else { + Button("Add") { + addingPath = folder.path + Task { + await store.addProject(folder) + addingPath = nil + if store.project?.folder == folder.path { dismiss() } + } + } + .font(.bighelp(.subheadline).weight(.semibold)) + .accessibilityIdentifier("code.found.add") + } + } + } + } + .listRowBackground(theme.surface) + } + } + .listStyle(.insetGrouped) + .scrollContentBackground(.hidden) + .background(theme.canvas.ignoresSafeArea()) + .navigationTitle("Project") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } + } + .bighelpRefreshable { await store.load() } + .task { if store.projects.isEmpty { await store.load() } } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("code.projects") + } + + private func matching(_ projects: [CodeProject]) -> [CodeProject] { + let term = search.trimmingCharacters(in: .whitespaces) + guard !term.isEmpty else { return projects } + return projects.filter { $0.name.localizedCaseInsensitiveContains(term) || $0.folder.localizedCaseInsensitiveContains(term) } + } + + private func matching(_ folders: [CodeFoundFolder]) -> [CodeFoundFolder] { + let term = search.trimmingCharacters(in: .whitespaces) + guard !term.isEmpty else { return folders } + return folders.filter { $0.name.localizedCaseInsensitiveContains(term) || $0.path.localizedCaseInsensitiveContains(term) } + } + + @BighelpThemeReader private var theme +} + +/// The branch chip's sheet. New worktree: the new branch's name (named from the +/// message unless changed) and the branch it starts from. Local: the branch to +/// check out in the project's folder. +struct CodeBranchPicker: View { + @Bindable var store: CodeHomeStore + let message: String + @Environment(\.dismiss) private var dismiss + @State private var search = "" + @State private var newBranch = "" + + var body: some View { + NavigationStack { + List { + if store.placement == .newWorktree { + Section { + TextField(suggested, text: $newBranch) + .font(.system(.body, design: .monospaced)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .accessibilityIdentifier("code.branch.new") + } header: { + Text("New branch") + } footer: { + Text("Named from your message unless you type a name.") + } + .listRowBackground(theme.surface) + } + BighelpSearchField(text: $search, prompt: String(localized: "Search branches"), accessibilityIdentifier: "code.branch.search") + .bighelpListSearchRow() + Section(store.placement == .newWorktree ? "Start from" : "Branch") { + ForEach(matching(localBranches)) { branch in + branchRow(branch) + } + } + .listRowBackground(theme.surface) + if store.placement == .local, !matching(remoteBranches).isEmpty { + Section("On GitHub") { + ForEach(matching(remoteBranches)) { branch in + Text(branch.name) + .font(.system(.body, design: .monospaced)) + .foregroundStyle(theme.secondaryText) + } + } + .listRowBackground(theme.surface) + } + } + .listStyle(.insetGrouped) + .scrollContentBackground(.hidden) + .background(theme.canvas.ignoresSafeArea()) + .navigationTitle(store.placement == .newWorktree ? "Start from" : "Branch") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { + let name = newBranch.trimmingCharacters(in: .whitespacesAndNewlines) + store.newBranchName = name.isEmpty ? nil : name + dismiss() + } + .accessibilityIdentifier("code.branch.done") + } + } + .onAppear { newBranch = store.newBranchName ?? "" } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("code.branches") + } + + private var suggested: String { + let taken = Set(store.git?.branches.map(\.name) ?? []) + return CodeBranchName.suggested(for: message.isEmpty ? "change" : message, taken: taken) + } + + /// Worktrees start from base branches; Local checks out a local branch. + private var localBranches: [StockGitBranch] { + guard let git = store.git else { return [] } + return store.placement == .newWorktree ? git.baseBranches : git.branches.filter { !$0.isRemote } + } + + private var remoteBranches: [StockGitBranch] { + store.git?.branches.filter(\.isRemote) ?? [] + } + + private func branchRow(_ branch: StockGitBranch) -> some View { + let selected = branch.name == store.branchTitle + // A branch checked out in another worktree can't be checked out here too. + let busyElsewhere = store.placement == .local && branch.worktreePath != nil + && branch.worktreePath != store.project?.folder + return Button { + store.branch = branch.name + dismiss() + } label: { + HStack(spacing: BighelpTokens.space12) { + Image(systemName: "arrow.triangle.branch").foregroundStyle(theme.secondaryText) + VStack(alignment: .leading, spacing: 2) { + Text(branch.name) + .font(.system(.body, design: .monospaced)) + .foregroundStyle(busyElsewhere ? theme.secondaryText : theme.primaryText) + if let note = note(for: branch) { + Text(note).font(.bighelp(.caption)).foregroundStyle(theme.secondaryText) + } + } + Spacer(minLength: 0) + if selected { Image(systemName: "checkmark").foregroundStyle(theme.action) } + } + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .disabled(busyElsewhere) + .accessibilityIdentifier("code.branch.\(branch.name)") + } + + private func note(for branch: StockGitBranch) -> String? { + if branch.isDefault { return String(localized: "Default") } + guard let path = branch.worktreePath else { return nil } + return path == store.project?.folder ? String(localized: "Checked out in the local folder") + : String(localized: "In a worktree") + } + + private func matching(_ branches: [StockGitBranch]) -> [StockGitBranch] { + let term = search.trimmingCharacters(in: .whitespaces) + guard !term.isEmpty else { return branches } + return branches.filter { $0.name.localizedCaseInsensitiveContains(term) } + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Code/CodeProjectSource.swift b/Bighelp/Code/CodeProjectSource.swift index 7cb5802a..bca0851e 100644 --- a/Bighelp/Code/CodeProjectSource.swift +++ b/Bighelp/Code/CodeProjectSource.swift @@ -1,6 +1,6 @@ import Foundation -/// The projects Code mode can start sessions in, for one agent (Hermes keeps +/// The projects a coding session can start in, for one agent (Hermes keeps /// projects per agent). @MainActor protocol CodeProjectSource: AnyObject { diff --git a/Bighelp/Code/CodePullRequestsSheet.swift b/Bighelp/Code/CodePullRequestsSheet.swift index 12f6bdef..2e0f3b29 100644 --- a/Bighelp/Code/CodePullRequestsSheet.swift +++ b/Bighelp/Code/CodePullRequestsSheet.swift @@ -1,6 +1,6 @@ import SwiftUI -/// ☰ › Pull requests in Code mode: the selected project's pull requests that +/// Pull requests (a project's ⋯ on Work): the selected project's pull requests that /// GitHub knows for its branches. Each opens on GitHub. struct CodePullRequestsSheet: View { let projectName: String @@ -52,7 +52,7 @@ struct CodePullRequestsSheet: View { @BighelpThemeReader private var theme } -/// ☰ › Worktrees in Code mode: the project's branches and worktrees, where +/// Worktrees (a project's ⋯ on Work, and New chat's choices row): the project's branches and worktrees, where /// finished ones are removed (Hermes keeps a worktree until someone does). struct CodeWorktreesSheet: View { @State var store: StockGitStore diff --git a/Bighelp/Code/CodeSessionStatusReader.swift b/Bighelp/Code/CodeSessionStatusReader.swift index f16c06a7..655d38f6 100644 --- a/Bighelp/Code/CodeSessionStatusReader.swift +++ b/Bighelp/Code/CodeSessionStatusReader.swift @@ -1,6 +1,6 @@ import Foundation -/// Reads a Code mode session's status from its live chat, where the app keeps one, +/// Reads a coding session's status from its live chat, where the app keeps one, /// and otherwise from the session list (which Hermes's active sessions refresh). @MainActor protocol CodeSessionStatusReading { @@ -15,7 +15,12 @@ struct CodeChatStatusReader: CodeSessionStatusReading { func status(of sessionID: String) -> CodeSessionStatus { let chat = features.preparedChatModel(id: sessionID) if let prompt = chat?.nativeConversationClient?.prompts.first { - return .needsYou(prompt.kind == .approval ? "Approve a command" : "Answer a question") + return .needsYou(prompt.kind == .approval ? Self.approveCommand : Self.answerQuestion) + } + // A chat that isn't open has no prompts here; the dashboard's list (what Today's Needs you + // reads) still says it waits. The chat is never opened or resumed to find out. + if let ask = Self.waitingAsk(for: sessionID, in: features.dashboardModel.snapshot?.attentionItems ?? []) { + return .needsYou(ask) } let record = catalog.session(id: sessionID) let isRunning = chat?.isSending == true @@ -27,4 +32,19 @@ struct CodeChatStatusReader: CodeSessionStatusReading { let title = last.title.trimmingCharacters(in: .whitespacesAndNewlines) return .running(title.isEmpty ? nil : title) } + + private static var approveCommand: String { String(localized: "Approve a command") } + private static var answerQuestion: String { String(localized: "Answer a question") } + + /// What the dashboard lists as waiting on the person in this session: an approval or a question. + static func waitingAsk(for sessionID: String, in items: [DashboardAttentionItem]) -> String? { + for item in items where item.sessionID == sessionID { + switch item.interaction { + case .approval: return approveCommand + case .clarification: return answerQuestion + case .none: continue + } + } + return nil + } } diff --git a/Bighelp/Code/CodeSessionSwitcher.swift b/Bighelp/Code/CodeSessionSwitcher.swift index ea87b737..2c455872 100644 --- a/Bighelp/Code/CodeSessionSwitcher.swift +++ b/Bighelp/Code/CodeSessionSwitcher.swift @@ -10,7 +10,7 @@ extension CodeHomeStore { return reader.status(of: session.id) } - /// Code mode's switcher beside a chat (`BighelpChatSwitcher`): this project's sessions, the + /// A coding session's switcher beside its chat (`BighelpChatSwitcher`): this project's sessions, the /// ones working or waiting on you first, then the newest. func switcherSessions(reader: any CodeSessionStatusReading) -> [(CodeSessionRecord, CodeSessionStatus)] { let sessions = projectSingleSessions.map { ($0, status(of: $0, reader: reader)) } diff --git a/Bighelp/Code/DemoCodeGit.swift b/Bighelp/Code/DemoCodeGit.swift index 393c06e6..cbf9d3e2 100644 --- a/Bighelp/Code/DemoCodeGit.swift +++ b/Bighelp/Code/DemoCodeGit.swift @@ -1,7 +1,7 @@ import Foundation /// Demo mode's git: each sample project's main folder on `main`, plus the worktrees -/// Code mode makes. A new worktree comes with three sample changed files (one is the +/// a coding session makes. A new worktree comes with three sample changed files (one is the /// plan `DemoHostTextFiles` serves), so Changes, its Markdown preview and Ship have /// something to show; commit, push and PR move them along. @MainActor diff --git a/Bighelp/Code/DevFactoryStore.swift b/Bighelp/Code/DevFactoryStore.swift index f4dd1794..e6210764 100644 --- a/Bighelp/Code/DevFactoryStore.swift +++ b/Bighelp/Code/DevFactoryStore.swift @@ -24,7 +24,7 @@ struct DevFactoryRecipeSetup: Equatable { } } -/// Dev Factory (☰ › Dev Factory in Code mode) for one computer: its coding recipes, +/// Dev Factory (a project's ⋯ on Work) for one computer: its coding recipes, /// their runs grouped by start (one run per project), and the templates new recipes /// come from. It's Workflows underneath (`native-workflows-code-v1`): the same client, /// runs and sign-offs. diff --git a/Bighelp/Code/DevFactoryViews.swift b/Bighelp/Code/DevFactoryViews.swift index 9e666c66..0ac3a3dd 100644 --- a/Bighelp/Code/DevFactoryViews.swift +++ b/Bighelp/Code/DevFactoryViews.swift @@ -14,7 +14,7 @@ struct DevFactoryContext { } /// Dev Factory's home (approved 4.1): what runs now, then your recipes, then the templates -/// new ones start from. ☰ › Dev Factory in Code mode. +/// new ones start from. Dev Factory (a project's ⋯ on Work). struct DevFactoryHomeView: View { let context: DevFactoryContext @State private var newFrom: WorkflowTemplate? diff --git a/Bighelp/Companion/AgentFace.swift b/Bighelp/Companion/AgentFace.swift index 871b4b12..4708947a 100644 --- a/Bighelp/Companion/AgentFace.swift +++ b/Bighelp/Companion/AgentFace.swift @@ -3,7 +3,7 @@ import SwiftUI /// What an agent's face is, from what this device and its computer know, in the order every /// surface draws them: a kit character, a petdex pet, a Hermes face or shape or a Bot Studio -/// avatar (both saved in Hermes' profile), a Bots mode mark, then its picture. One order, so the chat, Bots mode and its pet companion show the same face. +/// avatar (both saved in Hermes' profile), a mark, then its picture. One order, so the chat, the Bots view and its pet companion show the same face. enum AgentFace: Equatable { case character(CompanionAppearance) case pet(key: String) diff --git a/Bighelp/DesignSystem/BighelpBrand.swift b/Bighelp/DesignSystem/BighelpBrand.swift index 870571f4..a6c5a196 100644 --- a/Bighelp/DesignSystem/BighelpBrand.swift +++ b/Bighelp/DesignSystem/BighelpBrand.swift @@ -74,25 +74,6 @@ struct BighelpWordmark: View { } } -/// The brand bar as a leading toolbar item, without a glass capsule on iOS 26. -/// Touch and hold it to switch hosts. -struct BighelpBrandToolbarItem: ToolbarContent { - var demoHosts: DemoHosts? - - var body: some ToolbarContent { - #if compiler(>=6.2) && !os(visionOS) // visionOS toolbars have no shared glass. - if #available(iOS 26.0, *) { - ToolbarItem(placement: .topBarLeading) { BighelpHostSwitcherLockup(demoHosts: demoHosts) } - .sharedBackgroundVisibility(.hidden) - } else { - ToolbarItem(placement: .topBarLeading) { BighelpHostSwitcherLockup(demoHosts: demoHosts) } - } - #else - ToolbarItem(placement: .topBarLeading) { BighelpHostSwitcherLockup(demoHosts: demoHosts) } - #endif - } -} - #Preview("Noodle") { VStack(spacing: 24) { BighelpWordmark(height: 40) diff --git a/Bighelp/DesignSystem/BighelpChatSwitcher.swift b/Bighelp/DesignSystem/BighelpChatSwitcher.swift index efe8505a..dccbeb54 100644 --- a/Bighelp/DesignSystem/BighelpChatSwitcher.swift +++ b/Bighelp/DesignSystem/BighelpChatSwitcher.swift @@ -1,7 +1,7 @@ import SwiftUI -/// The switcher beside a chat: in Bots mode the faces of the bots on top of the home (then the -/// ones under them), in Code mode the running sessions. A tap goes to that chat; Back still goes +/// The switcher beside a chat: on the Bots view the faces of the bots on top of the home (then the +/// ones under them), in a coding session the running sessions. A tap goes to that chat; Back still goes /// home. It lives in the Duo's side column when folded (on unless turned off), and beside the /// chat on iPad and Mac in landscape once turned on (Settings › Modes › Chat switcher). enum BighelpChatSwitcher { diff --git a/Bighelp/DesignSystem/BighelpComponents.swift b/Bighelp/DesignSystem/BighelpComponents.swift index dcc9149d..738f4cef 100644 --- a/Bighelp/DesignSystem/BighelpComponents.swift +++ b/Bighelp/DesignSystem/BighelpComponents.swift @@ -174,103 +174,6 @@ extension BighelpHeaderActionPresentation { ) } -struct SpectrumActionHitTargetPresentation: Equatable, Sendable { - let visualSize: CGFloat - let minimumHeight: CGFloat - let expandsHorizontally: Bool -} - -struct SpectrumAction: View { - static let hitTargetPresentation = SpectrumActionHitTargetPresentation( - visualSize: BighelpTokens.primaryActionSize, - minimumHeight: BighelpTokens.primaryActionSize, - expandsHorizontally: true - ) - - let accessibilityLabel: String - let isAvailable: Bool - let action: () -> Void - - @Environment(\.accessibilityReduceTransparency) private var reduceTransparency - - init( - accessibilityLabel: String, - isAvailable: Bool = true, - action: @escaping () -> Void - ) { - self.accessibilityLabel = accessibilityLabel - self.isAvailable = isAvailable - self.action = action - } - - var body: some View { - let presentation = FloatingTabBar.newChatPresentation(for: theme.themeID) - let hitTarget = Self.hitTargetPresentation - Button(action: action) { - HStack(spacing: 0) { - Spacer(minLength: 0) - Image(systemName: "square.and.pencil") - .font(.system(size: 22, weight: .semibold)) - .symbolRenderingMode(.monochrome) - .foregroundStyle(presentation.foreground == .themeAccent - ? theme.action - : theme.primaryText) - .frame(width: hitTarget.visualSize, height: hitTarget.visualSize) - .modifier( - FloatingTabBarActionSurfaceModifier( - theme: theme, - reduceTransparency: reduceTransparency - ) - ) - .opacity(isAvailable ? 1 : 0.48) - Spacer(minLength: 0) - } - .frame( - maxWidth: hitTarget.expandsHorizontally ? .infinity : hitTarget.visualSize, - minHeight: hitTarget.minimumHeight - ) - .contentShape(.rect) - } - .buttonStyle(SpectrumPressStyle()) - .frame( - maxWidth: hitTarget.expandsHorizontally ? .infinity : hitTarget.visualSize, - minHeight: hitTarget.minimumHeight - ) - .contentShape(.rect) - .disabled(!isAvailable) - .bighelpIconLabel(accessibilityLabel) - .accessibilityValue(isAvailable ? "Available" : "Unavailable") - } - - @BighelpThemeReader private var theme -} - -struct FloatingTabBarActionSurfaceModifier: ViewModifier { - @Environment(\.bighelpUIV2Enabled) private var uiV2Enabled - let theme: BighelpTheme - let reduceTransparency: Bool - - @ViewBuilder - func body(content: Content) -> some View { - if uiV2Enabled { - content.bighelpSurface(.circularControl, isInteractive: true) - } else if reduceTransparency { - content.background(theme.raisedSurface, in: .circle) - } else { - #if os(visionOS) - content.glassBackgroundEffect(in: .circle) - #else - if #available(iOS 26, *) { - content - .glassEffect(.regular.interactive(), in: .circle) - } else { - content.background(.ultraThinMaterial, in: .circle) - } - #endif - } - } -} - private struct SpectrumPressStyle: ButtonStyle { @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -1017,7 +920,7 @@ struct BighelpIconTile: View { var body: some View { let color = tint ?? theme.action let solid = colorSchemeContrast == .increased - // Round, as Bots mode draws its rows: a soft wash of the person's color with the icon in it. + // Round, as the Bots view draws its rows: a soft wash of the person's color with the icon in it. // Increased Contrast keeps a solid circle with the color's own ink. BighelpSymbolImage(systemName: systemName) .frame(width: side * 0.62, height: side * 0.62) diff --git a/Bighelp/DesignSystem/BighelpNavigationGlass.swift b/Bighelp/DesignSystem/BighelpNavigationGlass.swift new file mode 100644 index 00000000..a28da826 --- /dev/null +++ b/Bighelp/DesignSystem/BighelpNavigationGlass.swift @@ -0,0 +1,153 @@ +import SwiftUI + +// The neutral glass the home's bar, headers and round buttons share, and the bar's row layout. + +/// What navigation glass draws as: liquid glass where the system has it, else a material, and a solid +/// surface when the person asked for less transparency. +enum NavigationGlassSurface: Equatable, Sendable { + case regularLiquidGlass + case regularMaterial + case thickMaterial + case opaque + + static func resolve(supportsLiquidGlass: Bool, reduceTransparency: Bool, + increasedContrast: Bool) -> NavigationGlassSurface { + if reduceTransparency { return .opaque } + if supportsLiquidGlass { return .regularLiquidGlass } + return increasedContrast ? .thickMaterial : .regularMaterial + } +} + +/// The labelled row reports its ideal width; the icon fallback respects its proposal. +/// Every destination gets the same measured width and height. +struct NavigationRowLayout: Layout { + var constrainsWidth = false + + static func fittingSize( + proposedWidth: CGFloat?, itemSizes: [CGSize], constrainsWidth: Bool = false + ) -> CGSize { + let requiredWidth = (itemSizes.map(\.width).max() ?? 44) * CGFloat(itemSizes.count) + let availableWidth = proposedWidth.flatMap { $0.isFinite ? $0 : nil } ?? requiredWidth + let width = constrainsWidth + ? max(44 * CGFloat(itemSizes.count), availableWidth) + : max(availableWidth, requiredWidth) + return CGSize(width: width, + height: itemSizes.map(\.height).max() ?? 44) + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let ideal = Self.fittingSize( + proposedWidth: proposal.width, + itemSizes: subviews.map { $0.sizeThatFits(.unspecified) }, + constrainsWidth: constrainsWidth + ) + guard constrainsWidth, !subviews.isEmpty else { return ideal } + let cellProposal = ProposedViewSize(width: ideal.width / CGFloat(subviews.count), height: nil) + return Self.fittingSize( + proposedWidth: ideal.width, + itemSizes: subviews.map { $0.sizeThatFits(cellProposal) }, + constrainsWidth: true + ) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + guard !subviews.isEmpty else { return } + let width = bounds.width / CGFloat(subviews.count) + for (index, subview) in subviews.enumerated() { + subview.place(at: CGPoint(x: bounds.minX + CGFloat(index) * width, y: bounds.minY), + anchor: .topLeading, + proposal: ProposedViewSize(width: width, height: bounds.height)) + } + } +} + +extension View { + /// Neutral native navigation glass with an optional interactive response. + /// No custom tint, glow or shadow; all consumers share its fallbacks. + func bighelpNavigationGlass(in shape: S, isInteractive: Bool = false) -> some View { + modifier(BighelpNavigationGlass(shape: shape, isInteractive: isInteractive)) + } +} + +private struct BighelpNavigationGlass: ViewModifier { + let shape: S + let isInteractive: Bool + + @Environment(\.accessibilityReduceTransparency) private var reduceTransparency + @Environment(\.colorSchemeContrast) private var colorSchemeContrast + + func body(content: Content) -> some View { + content.modifier(NavigationSurface( + shape: shape, + isInteractive: isInteractive, + surface: NavigationGlassSurface.resolve( + supportsLiquidGlass: supportsLiquidGlass, + reduceTransparency: reduceTransparency, + increasedContrast: colorSchemeContrast == .increased + ), + increasedContrast: colorSchemeContrast == .increased + )) + } + + private var supportsLiquidGlass: Bool { + #if compiler(>=6.2) && !os(visionOS) // visionOS has no glassEffect. + if #available(iOS 26.0, *) { return true } + #endif + return false + } +} + +private struct NavigationSurface: ViewModifier { + let shape: S + let isInteractive: Bool + let surface: NavigationGlassSurface + let increasedContrast: Bool + + func body(content: Content) -> some View { + surfaced(content) + .modifier(InteractiveGlassHover(shape: shape, isInteractive: isInteractive)) + .overlay { + if increasedContrast { + shape.strokeBorder(Color.primary.opacity(0.5), lineWidth: 1) + .allowsHitTesting(false) + .accessibilityHidden(true) + } + } + } + + @ViewBuilder + private func surfaced(_ content: Content) -> some View { + switch surface { + case .opaque: + content.background(Color(uiColor: .systemBackground), in: shape) + case .regularMaterial: + content.background(.regularMaterial, in: shape) + case .thickMaterial: + content.background(.thickMaterial, in: shape) + case .regularLiquidGlass: + #if compiler(>=6.2) && !os(visionOS) // visionOS has no glassEffect. + if #available(iOS 26.0, *) { + content.glassEffect(isInteractive ? .regular.interactive() : .regular, in: shape) + } else { + content.background(.regularMaterial, in: shape) + } + #else + content.background(.regularMaterial, in: shape) + #endif + } + } +} + +/// Mac: glass that's a button lights up under the pointer. +private struct InteractiveGlassHover: ViewModifier { + let shape: S + let isInteractive: Bool + + func body(content: Content) -> some View { + #if targetEnvironment(macCatalyst) + if isInteractive { content.bighelpHover(in: shape) } else { content } + #else + content + #endif + } +} diff --git a/Bighelp/DesignSystem/BighelpSideStrip.swift b/Bighelp/DesignSystem/BighelpSideStrip.swift index 043220de..a0a32972 100644 --- a/Bighelp/DesignSystem/BighelpSideStrip.swift +++ b/Bighelp/DesignSystem/BighelpSideStrip.swift @@ -1,8 +1,8 @@ import SwiftUI import UIKit -// The iPhone Duo's side strip, the column on the trailing edge under the camera and the status: -// the bar's places as toolbar items, and room for the chat switcher. +// The iPhone Duo's side strip, the column on the trailing edge under the camera and the status: room +// for the chat switcher. The home's places are toolbar items there (`HomeStripTabs`). extension View { /// Keeps a column free on the trailing edge and puts `column` in it, under the camera and the @@ -36,71 +36,3 @@ private struct BighelpSideColumnLayout: ViewModifier { } } } - -/// The bar's places handed to iOS as toolbar items. Built with the iOS 27.1 SDK, the Duo lays a -/// screen's toolbar out down its side strip, with the screen's own buttons (☰, the brand, a filter), -/// so the places line up with them there instead of a column of our own lying over them. -struct BighelpStripTabs: ToolbarContent { - @Binding var selection: AppTab - let tabs: [AppTab] - var unread: Set = [] - /// In a chat, Chat is the current tab whichever page the chat was opened from. - var isInChat = false - var onNewChat: (() -> Void)? - let selectedTint: Color - let tint: Color - - private var current: AppTab { isInChat ? .sessions : selection } - - var body: some ToolbarContent { - ToolbarItemGroup(placement: .bottomBar) { - ForEach(tabs) { tab in - place(tab) - } - if let onNewChat { - Button(action: onNewChat) { - Label(FloatingTabBar.newChatVisibleLabel, systemImage: "square.and.pencil") - } - .tint(selectedTint) - .accessibilityIdentifier(ConversationRootNavigationPresentation.composeAccessibilityIdentifier) - } - } - } - - private func place(_ tab: AppTab) -> some View { - let isSelected = current == tab - let isNew = unread.contains(tab) && !isSelected - return Button { - if isInChat, isSelected { return } - BighelpKeyboard.dismiss() - selection = tab - } label: { - Label { Text(tab.title) } icon: { icon(tab, selected: isSelected, isNew: isNew) } - .labelStyle(.iconOnly) - } - .tint(isSelected ? selectedTint : tint) - .accessibilityLabel(tab.title) - .accessibilityValue(isNew ? "New" : "") - .accessibilityAddTraits(isSelected ? .isSelected : []) - .accessibilityIdentifier(tab.accessibilityIdentifier) - } - - private func icon(_ tab: AppTab, selected: Bool, isNew: Bool) -> Image { - let base = tab.glyph?.image(selected: selected) ?? UIImage(systemName: tab.systemImage(selected: selected)) - guard let base else { return Image(systemName: tab.systemImage(selected: selected)) } - guard isNew else { return Image(uiImage: base).renderingMode(.template) } - // A toolbar button shows no badge, so Feed, Ideas or Goals with something new draws the - // bar's dot into its icon, colored here as the toolbar would have tinted it. - let diameter = max(6, base.size.width * 0.28) - // The dot gets its own corner, just outside the icon's art. - let inset = diameter * 0.5 - let size = CGSize(width: base.size.width + inset, height: base.size.height + inset) - let image = UIGraphicsImageRenderer(size: size).image { _ in - base.withTintColor(UIColor(tint), renderingMode: .alwaysOriginal).draw(at: CGPoint(x: 0, y: inset)) - UIColor(selectedTint).setFill() - UIBezierPath(ovalIn: CGRect(x: size.width - diameter, y: 0, width: diameter, height: diameter)).fill() - } - // On the image itself: the toolbar tints anything it's allowed to. - return Image(uiImage: image.withRenderingMode(.alwaysOriginal)) - } -} diff --git a/Bighelp/DesignSystem/BighelpTheme.swift b/Bighelp/DesignSystem/BighelpTheme.swift index ba46b2cb..ee4ee80e 100644 --- a/Bighelp/DesignSystem/BighelpTheme.swift +++ b/Bighelp/DesignSystem/BighelpTheme.swift @@ -752,8 +752,7 @@ struct BighelpAppearanceContext: Equatable, Sendable { } /// Vision Pro: 0 is a solid window, 1 shows the room through the glass. var windowTransparency = BighelpVisionGlass.defaultTransparency - /// Bots mode is on (Settings › Modes). It takes the same themes as the rest of the app. - var simpleBots = false + /// The Ink look, bighelp's default: black bubbles and buttons by day, ink after dark. Ink is /// `.graphite`; no saved choice is Ink too. func usesInk(dark: Bool) -> Bool { @@ -780,12 +779,10 @@ struct BighelpAppearanceContext: Equatable, Sendable { /// The same choices, shown in one mode (previews, widgets, exports). func forcing(_ scheme: ColorScheme) -> BighelpAppearanceContext { - var context = BighelpAppearanceContext( + BighelpAppearanceContext( appearance: scheme == .dark ? .dark : .light, lightBackground: lightBackground, darkBackground: darkBackground, bubbleColor: bubbleColor, customBubbleHex: customBubbleHex, bubbleFollowsTheme: bubbleFollowsTheme, windowTransparency: windowTransparency) - context.simpleBots = simpleBots - return context } } diff --git a/Bighelp/DesignSystem/BighelpV2Style.swift b/Bighelp/DesignSystem/BighelpV2Style.swift index 01a10208..0bdd9437 100644 --- a/Bighelp/DesignSystem/BighelpV2Style.swift +++ b/Bighelp/DesignSystem/BighelpV2Style.swift @@ -102,7 +102,7 @@ private struct BighelpFormSurfaceModifier: ViewModifier { } /// Ink tints with the page's ink, which is white after dark: a switch would be white on white. -/// Its switches are green, as on Bots mode's own Settings page. +/// Its switches are green. private struct InkSwitchStyle: ToggleStyle { func makeBody(configuration: Configuration) -> some View { Toggle(configuration).toggleStyle(BighelpFormSwitchStyle()).tint(SimpleBotColor.green.color) diff --git a/Bighelp/DesignSystem/FloatingTabBar.swift b/Bighelp/DesignSystem/FloatingTabBar.swift deleted file mode 100644 index 438460bd..00000000 --- a/Bighelp/DesignSystem/FloatingTabBar.swift +++ /dev/null @@ -1,540 +0,0 @@ -import SwiftUI - -// Still consumed by SpectrumAction outside primary navigation. -enum FloatingTabBarActionSurface: Equatable, Sendable { - case neutralGlass -} - -enum FloatingTabBarActionForeground: Equatable, Sendable { - case themeAccent -} - -struct FloatingTabBarActionPresentation: Equatable, Sendable { - let surface: FloatingTabBarActionSurface - let foreground: FloatingTabBarActionForeground - let usesGradient: Bool - let showsBorder: Bool - let usesGlow: Bool -} - -enum FloatingTabBarBackgroundSurface: Equatable, Sendable { - case regularLiquidGlass - case regularMaterial - case thickMaterial - case opaque -} - -struct FloatingTabBar: View { - static let newChatVisibleLabel = "New chat" - static let newChatAccessibilityLabel = String(localized: "New chat") - static let selectionShape = Capsule() - - static func newChatPresentation(for _: BighelpThemeID) -> FloatingTabBarActionPresentation { - FloatingTabBarActionPresentation(surface: .neutralGlass, foreground: .themeAccent, - usesGradient: false, showsBorder: false, usesGlow: false) - } - - static func backgroundSurface( - supportsLiquidGlass: Bool, - reduceTransparency: Bool, - increasedContrast: Bool - ) -> FloatingTabBarBackgroundSurface { - if reduceTransparency { return .opaque } - if supportsLiquidGlass { return .regularLiquidGlass } - return increasedContrast ? .thickMaterial : .regularMaterial - } - - /// The shell reserves navigation space only at the root, never over a pushed chat or keyboard. - static func isRootBarVisible(for path: [AppRoute]) -> Bool { - path.isEmpty - } - - @Binding var selection: AppTab - /// New chat, in the middle of the bar. Nil leaves it out (All agents has its own). - let onNewChat: (() -> Void)? - /// Touch and hold New chat: the picker, for another agent or a group. - var onPickAgents: (() -> Void)? - /// UI tests find the chat's New chat by its old header name. - var newChatIdentifier = ConversationRootNavigationPresentation.composeAccessibilityIdentifier - /// Points the bar drops into the home indicator's area. - let homeIndicatorSink: CGFloat - /// Feed, Ideas or Goals with something the person hasn't seen: a small dot. - let unread: Set - /// In a chat, Chat is the current tab whichever page the chat was opened from. - var isInChat = false - /// Chat, then what the person pinned (Settings › Appearance › App layout). - let tabs: [AppTab] - - @Environment(\.colorSchemeContrast) private var colorSchemeContrast - @Environment(\.accessibilityReduceMotion) private var reduceMotion - @Environment(\.verticalSizeClass) private var verticalSizeClass - @State private var tabChanges = 0 - /// The glyphs keep a 3-pt margin on their 24-pt grid, so 26 draws them about 20pt. - @ScaledMetric(relativeTo: .caption2) private var iconSize: CGFloat = 26 - - init(selection: Binding, tabs: [AppTab] = AppTab.allCases, onNewChat: (() -> Void)? = nil, - onPickAgents: (() -> Void)? = nil, - newChatIdentifier: String = ConversationRootNavigationPresentation.composeAccessibilityIdentifier, - homeIndicatorSink: CGFloat = 0, unread: Set = [], isInChat: Bool = false) { - self.tabs = tabs - self._selection = selection - self.onNewChat = onNewChat - self.onPickAgents = onPickAgents - self.newChatIdentifier = newChatIdentifier - self.homeIndicatorSink = homeIndicatorSink - self.unread = unread - self.isInChat = isInChat - } - - /// The highlighted tab: a chat pushed from Ideas is still a chat. - private var current: AppTab { isInChat ? .sessions : selection } - - /// Like the system tab bar, the bar sits low, just above the home - /// indicator, instead of a full safe-area inset above it. Clamped so a - /// keyboard's inset never pushes it off screen. - static func homeIndicatorSink(forBottomInset inset: CGFloat) -> CGFloat { - min(max(0, inset - 14), 20) - } - - /// What the bar's row holds: the tabs, with New chat in the middle. - enum Slot: Hashable { - case tab(AppTab) - case newChat - } - - /// Chat and three places either side of New chat: [Chat, Feed, New chat, Ideas, Goals]. - static func slots(tabs: [AppTab], hasNewChat: Bool) -> [Slot] { - var slots = tabs.map(Slot.tab) - if hasNewChat { slots.insert(.newChat, at: (slots.count + 1) / 2) } - return slots - } - - var body: some View { - // Each tab named under its icon, New chat in the middle. - navigationRow(constrainsWidth: true) { - ForEach(Self.slots(tabs: tabs, hasNewChat: onNewChat != nil), id: \.self) { slot in - switch slot { - case .tab(let tab): destination(tab) - case .newChat: newChatButton - } - } - } - .padding(6) - .bighelpNavigationGlass(in: Capsule()) - .sensoryFeedback(.selection, trigger: tabChanges) - .frame(maxWidth: BighelpTokens.scaled(620)) - .accessibilityElement(children: .contain) - .accessibilityLabel("Primary navigation") - .accessibilityIdentifier("primary-navigation") - .padding(.horizontal, 12) - .padding(.vertical, isVerticallyCompact ? 4 : 8) - .frame(maxWidth: .infinity) - // One place on every screen: nothing moves the bar (search lives at the top of each page). - .padding(.bottom, -homeIndicatorSink) - } - - private var isVerticallyCompact: Bool { verticalSizeClass == .compact } - - /// In the person's color (Appearance), like their bubbles. - @ViewBuilder - private var newChatButton: some View { - if let onNewChat { - RootComposeButton(identifier: newChatIdentifier, systemImage: "plus", - size: BighelpTokens.scaled(isVerticallyCompact ? 44 : 52), - onLongPress: onPickAgents, action: onNewChat) - .accessibilityShowsLargeContentViewer { - Label(Self.newChatVisibleLabel, systemImage: "plus") - } - .frame(maxWidth: .infinity) - } - } - - private func navigationRow( - constrainsWidth: Bool = false, @ViewBuilder content: () -> Content - ) -> some View { - let layout = NavigationRowLayout(constrainsWidth: constrainsWidth) - return layout { content() } - } - - - private func destination(_ tab: AppTab) -> some View { - let isSelected = current == tab - return Button { - // Chat in a chat is where you already are. - if isInChat, isSelected { return } - BighelpKeyboard.dismiss() - if selection != tab { tabChanges += 1 } - withAnimation(reduceMotion ? nil : .snappy(duration: BighelpTokens.transitionDuration)) { - selection = tab - } - } label: { - itemLabel(tab, selected: isSelected) - .overlay(alignment: .topTrailing) { - if unread.contains(tab), !isSelected { - Circle() - .fill(theme.action) - .frame(width: 8, height: 8) - .padding(.top, isVerticallyCompact ? 4 : 8) - .padding(.trailing, 10) - .accessibilityHidden(true) - } - } - } - .buttonStyle(.bighelpTilePress) - .bighelpHover(in: Self.selectionShape) - .bighelpHelp(tab.title, shortcut: tabs.firstIndex(of: tab).map { "⌘\($0 + 1)" }) - .accessibilityLabel(tab.title) - .accessibilityValue(unread.contains(tab) && !isSelected ? "New" : "") - .accessibilityShowsLargeContentViewer { - if let glyph = tab.glyph { - Label { Text(tab.title) } icon: { Image(uiImage: glyph.image(selected: isSelected)) } - } else { - Label(tab.title, systemImage: tab.systemImage(selected: isSelected)) - } - } - .accessibilityAddTraits(isSelected ? .isSelected : []) - .accessibilityIdentifier(tab.accessibilityIdentifier) - } - - // Destinations share the existing neutral surface and equal touch targets. - private func itemLabel(_ tab: AppTab, selected: Bool) -> some View { - let identifier = tab.accessibilityIdentifier - return VStack(spacing: 2) { - AppTabIcon(tab: tab, selected: selected) - .frame(width: BighelpTokens.scaled(min(iconSize, 32)), height: BighelpTokens.scaled(min(iconSize, 32))) - .accessibilityIdentifier(identifier + ".icon") - Text(tab.title) - .font(.bighelp(.caption2).weight(.semibold)) - .lineLimit(1) - .minimumScaleFactor(0.8) - .accessibilityIdentifier(identifier + ".label") - } - // The theme's ink, not `.secondary`: on glass that turns symbols vibrant - // but leaves the drawn glyphs a faint grey. The current tab is a pill in the person's color. - .foregroundStyle(selected ? theme.actionForeground : theme.secondaryText) - .padding(.horizontal, 4) - .padding(.vertical, isVerticallyCompact ? 3 : 6) - .frame(minWidth: BighelpTokens.hitTarget, maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) - .background { - if selected { - Self.selectionShape - .fill(theme.action) - .transition(reduceMotion ? .opacity : .scale(scale: 0.86).combined(with: .opacity)) - .accessibilityHidden(true) - } - } - .contentShape(.rect) - } - - @BighelpThemeReader private var theme -} - -/// The labelled row reports its ideal width; the icon fallback respects its proposal. -/// Every destination gets the same measured width and height. -struct NavigationRowLayout: Layout { - var constrainsWidth = false - - static func fittingSize( - proposedWidth: CGFloat?, itemSizes: [CGSize], constrainsWidth: Bool = false - ) -> CGSize { - let requiredWidth = (itemSizes.map(\.width).max() ?? 44) * CGFloat(itemSizes.count) - let availableWidth = proposedWidth.flatMap { $0.isFinite ? $0 : nil } ?? requiredWidth - let width = constrainsWidth - ? max(44 * CGFloat(itemSizes.count), availableWidth) - : max(availableWidth, requiredWidth) - return CGSize(width: width, - height: itemSizes.map(\.height).max() ?? 44) - } - - func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { - let ideal = Self.fittingSize( - proposedWidth: proposal.width, - itemSizes: subviews.map { $0.sizeThatFits(.unspecified) }, - constrainsWidth: constrainsWidth - ) - guard constrainsWidth, !subviews.isEmpty else { return ideal } - let cellProposal = ProposedViewSize(width: ideal.width / CGFloat(subviews.count), height: nil) - return Self.fittingSize( - proposedWidth: ideal.width, - itemSizes: subviews.map { $0.sizeThatFits(cellProposal) }, - constrainsWidth: true - ) - } - - func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { - guard !subviews.isEmpty else { return } - let width = bounds.width / CGFloat(subviews.count) - for (index, subview) in subviews.enumerated() { - subview.place(at: CGPoint(x: bounds.minX + CGFloat(index) * width, y: bounds.minY), - anchor: .topLeading, - proposal: ProposedViewSize(width: width, height: bounds.height)) - } - } -} - -extension View { - /// Neutral native navigation glass with an optional interactive response. - /// No custom tint, glow or shadow; all consumers share its fallbacks. - func bighelpNavigationGlass(in shape: S, isInteractive: Bool = false) -> some View { - modifier(BighelpNavigationGlass(shape: shape, isInteractive: isInteractive)) - } -} - -private struct BighelpNavigationGlass: ViewModifier { - let shape: S - let isInteractive: Bool - - @Environment(\.accessibilityReduceTransparency) private var reduceTransparency - @Environment(\.colorSchemeContrast) private var colorSchemeContrast - - func body(content: Content) -> some View { - content.modifier(NavigationSurface( - shape: shape, - isInteractive: isInteractive, - surface: FloatingTabBar.backgroundSurface( - supportsLiquidGlass: supportsLiquidGlass, - reduceTransparency: reduceTransparency, - increasedContrast: colorSchemeContrast == .increased - ), - increasedContrast: colorSchemeContrast == .increased - )) - } - - private var supportsLiquidGlass: Bool { - #if compiler(>=6.2) && !os(visionOS) // visionOS has no glassEffect. - if #available(iOS 26.0, *) { return true } - #endif - return false - } -} - -private struct NavigationSurface: ViewModifier { - let shape: S - let isInteractive: Bool - let surface: FloatingTabBarBackgroundSurface - let increasedContrast: Bool - - func body(content: Content) -> some View { - surfaced(content) - .modifier(InteractiveGlassHover(shape: shape, isInteractive: isInteractive)) - .overlay { - if increasedContrast { - shape.strokeBorder(Color.primary.opacity(0.5), lineWidth: 1) - .allowsHitTesting(false) - .accessibilityHidden(true) - } - } - } - - @ViewBuilder - private func surfaced(_ content: Content) -> some View { - switch surface { - case .opaque: - content.background(Color(uiColor: .systemBackground), in: shape) - case .regularMaterial: - content.background(.regularMaterial, in: shape) - case .thickMaterial: - content.background(.thickMaterial, in: shape) - case .regularLiquidGlass: - #if compiler(>=6.2) && !os(visionOS) // visionOS has no glassEffect. - if #available(iOS 26.0, *) { - content.glassEffect(isInteractive ? .regular.interactive() : .regular, in: shape) - } else { - content.background(.regularMaterial, in: shape) - } - #else - content.background(.regularMaterial, in: shape) - #endif - } - } -} - -/// Mac: glass that's a button lights up under the pointer. -private struct InteractiveGlassHover: ViewModifier { - let shape: S - let isInteractive: Bool - - func body(content: Content) -> some View { - #if targetEnvironment(macCatalyst) - if isInteractive { content.bighelpHover(in: shape) } else { content } - #else - content - #endif - } -} - -#if os(visionOS) -/// Vision Pro's tabs: a vertical glass strip beside the window, where visionOS -/// puts its own tab bars. Each target is 60pt and lights up where you look, -/// well away from the window's move and close controls under it. -struct VisionTabOrnament: View { - @Binding var selection: AppTab - var tabs: [AppTab] = AppTab.allCases - var unread: Set = [] - var onNewChat: (() -> Void)? - /// In a chat, Chat is the current tab. - var isInChat = false - - var body: some View { - VStack(spacing: BighelpTokens.space8) { - ForEach(tabs) { tab in - let isSelected = (isInChat ? .sessions : selection) == tab - Button { - if isInChat, isSelected { return } - selection = tab - } label: { - AppTabIcon(tab: tab, selected: isSelected) - .frame(width: 32, height: 32) - .frame(width: 60, height: 60) - .background { - if isSelected { Circle().fill(.white.opacity(0.22)) } - } - .overlay(alignment: .topTrailing) { - if unread.contains(tab), !isSelected { - Circle().fill(Color.accentColor).frame(width: 10, height: 10).padding(8) - } - } - } - .buttonStyle(.plain) - .buttonBorderShape(.circle) - .contentShape(.hoverEffect, Circle()) - .hoverEffect(.highlight) - .help(tab.title) - .accessibilityLabel(tab.title) - .accessibilityValue(unread.contains(tab) && !isSelected ? "New" : "") - .accessibilityAddTraits(isSelected ? .isSelected : []) - .accessibilityIdentifier(tab.accessibilityIdentifier) - } - if let onNewChat { - Divider().frame(width: 36) - Button(action: onNewChat) { - Image(systemName: "square.and.pencil") - .font(.bighelp(.title2).weight(.semibold)) - .frame(width: 60, height: 60) - } - .buttonStyle(.plain) - .buttonBorderShape(.circle) - .contentShape(.hoverEffect, Circle()) - .hoverEffect(.highlight) - .help(FloatingTabBar.newChatVisibleLabel) - .accessibilityLabel(FloatingTabBar.newChatAccessibilityLabel) - .accessibilityIdentifier("root.new-chat") - } - } - .padding(BighelpTokens.space12) - .glassBackgroundEffect(in: Capsule()) - .accessibilityElement(children: .contain) - .accessibilityLabel("Primary navigation") - .accessibilityIdentifier("primary-navigation") - } -} -#endif - -/// A bottom-bar tab's icon, filling its frame: bighelp's glyph for Chat, Feed, -/// Ideas and Goals, outlined until selected; Apps keeps its symbol. -struct AppTabIcon: View { - let tab: AppTab - let selected: Bool - - var body: some View { - if let glyph = tab.glyph { - BighelpTabGlyphShape(glyph: glyph, selected: selected) - } else { - // A symbol fills its frame; the glyphs keep a 3-pt margin on their 24-pt grid. - Image(systemName: tab.systemImage(selected: selected)) - .resizable() - .scaledToFit() - .fontWeight(.medium) // Close to the glyphs' 1.7-pt line. - .scaleEffect(0.78) - .contentTransition(.symbolEffect(.replace)) - } - } -} - -extension AppTab { - var glyph: BighelpTabGlyph? { - switch self { - case .sessions: .chat - case .feed: .feed - case .ideas: .ideas - case .goals: .goals - default: nil - } - } -} - -extension AppTab { - var title: String { - switch self { - case .home: String(localized: "Activity") - case .agents: String(localized: "Agents") - case .sessions: String(localized: "Chat") - case .inbox: String(localized: "Inbox") - case .profile: String(localized: "Settings") - case .scheduledTasks: String(localized: "Tasks") - case .feed: String(localized: "Feed") - case .ideas: String(localized: "Ideas") - case .goals: String(localized: "Goals") - case .apps: String(localized: "Files") - case .projects: String(localized: "Projects") - case .kanban: String(localized: "Kanban") - case .workflows: String(localized: "Workflows") - case .usage: String(localized: "Usage") - case .code: String(localized: "Code") - case .sessionList: String(localized: "Sessions") - } - } - - func systemImage(selected: Bool) -> String { - switch (self, selected) { - case (.home, true): "waveform.path" - case (.home, false): "waveform.path" - case (.agents, true): "person.2.fill" - case (.agents, false): "person.2" - case (.sessions, true): "bubble.left.fill" - case (.sessions, false): "bubble.left" - case (.inbox, true): "tray.full.fill" - case (.inbox, false): "tray" - case (.profile, true): "gearshape.fill" - case (.profile, false): "gearshape" - case (.scheduledTasks, _): "calendar.badge.clock" - case (.feed, true): "newspaper.fill" - case (.feed, false): "newspaper" - case (.ideas, true): "lightbulb.fill" - case (.ideas, false): "lightbulb" - case (.goals, true): "checkmark.square.fill" - case (.goals, false): "checkmark.square" - case (.apps, true): "square.on.circle.fill" - case (.apps, false): "square.on.circle" - case (.projects, true): "folder.fill" - case (.projects, false): "folder" - case (.kanban, _): "rectangle.split.3x1" - case (.workflows, _): "flowchart" - case (.usage, _): "gauge.with.dots.needle.50percent" - case (.code, _): "chevron.left.forwardslash.chevron.right" - case (.sessionList, true): "bubble.left.and.bubble.right.fill" - case (.sessionList, false): "bubble.left.and.bubble.right" - } - } - - var accessibilityIdentifier: String { - switch self { - case .home: "tab.home" - case .agents: "tab.agents" - case .sessions: "tab.sessions" - case .inbox: "tab.inbox" - case .profile: "tab.profile" - case .scheduledTasks: "tab.scheduled-tasks" - case .feed: "tab.feed" - case .ideas: "tab.ideas" - case .goals: "tab.goals" - case .apps: "tab.apps" - case .projects: "tab.projects" - case .kanban: "tab.kanban" - case .workflows: "tab.workflows" - case .usage: "tab.usage" - case .code: "tab.code" - case .sessionList: "tab.session-list" - } - } -} diff --git a/Bighelp/DesignSystem/LongTextEditor.swift b/Bighelp/DesignSystem/LongTextEditor.swift index ac567672..a6bf4221 100644 --- a/Bighelp/DesignSystem/LongTextEditor.swift +++ b/Bighelp/DesignSystem/LongTextEditor.swift @@ -2,7 +2,7 @@ import SwiftUI import UIKit /// The editor for long text people write and tune: an agent's instructions (its SOUL) and a -/// personality's, in the form's box, the full-screen editor and Bots mode's sheet. One UIKit +/// personality's, in the form's box, the full-screen editor and a bot page's sheet. One UIKit /// text view everywhere, because SwiftUI's `TextEditor` stuttered with thousands of /// characters (#727): the form measured all of its text on every keystroke to size the box, /// a drag down the box took the form's interactive keyboard dismissal, and nothing kept the diff --git a/Bighelp/DesignSystem/MacTileMenu.swift b/Bighelp/DesignSystem/MacTileMenu.swift new file mode 100644 index 00000000..9909d547 --- /dev/null +++ b/Bighelp/DesignSystem/MacTileMenu.swift @@ -0,0 +1,98 @@ +import SwiftUI +import UIKit + +#if targetEnvironment(macCatalyst) +/// A right-click menu for one tile of a grid that sits in a single List row +/// (pinned chats). SwiftUI's `.contextMenu` can't be used there: +/// the row shows its first tile's menu for every tile. Only right- and +/// Control-clicks land on this view; other clicks, hovers and scrolls pass +/// through to the tile. +struct MacTileMenu: UIViewRepresentable { + typealias Item = TileMenuItem + + /// Read when the menu opens, so it shows the tile's current choices. + let items: () -> [Item] + + func makeCoordinator() -> Coordinator { Coordinator(items: items) } + + func makeUIView(context: Context) -> SecondaryClickView { + let view = SecondaryClickView() + view.backgroundColor = .clear + view.addInteraction(UIContextMenuInteraction(delegate: context.coordinator)) + return view + } + + func updateUIView(_ view: SecondaryClickView, context: Context) { + context.coordinator.items = items + } + + final class SecondaryClickView: UIView { + override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { + guard let event, event.buttonMask.contains(.secondary) || event.modifierFlags.contains(.control) else { + return nil + } + return super.hitTest(point, with: event) + } + } + + final class Coordinator: NSObject, UIContextMenuInteractionDelegate { + var items: () -> [Item] + /// What the open menu shows; its actions run these. + private var shown: [Item] = [] + + init(items: @escaping () -> [Item]) { + self.items = items + } + + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configurationForMenuAtLocation location: CGPoint + ) -> UIContextMenuConfiguration? { + shown = items() + guard !shown.isEmpty else { return nil } + let menu = TileMenuItem.menu(shown) + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in menu } + } + } +} +#endif + +/// One choice in a pinned tile's right-click menu on the Mac. +struct TileMenuItem { + let title: String + let systemImage: String + var isDestructive = false + var isEnabled = true + /// Draws a separator above this item. + var startsGroup = false + /// A submenu's choices; nil for an action. + var children: [TileMenuItem]? = nil + var identifier: String? = nil + var perform: @MainActor () -> Void = {} + + #if os(iOS) + @MainActor + static func menu(_ items: [TileMenuItem], title: String = "", image: UIImage? = nil) -> UIMenu { + var groups: [[UIMenuElement]] = [[]] + for item in items { + if item.startsGroup, !(groups.last?.isEmpty ?? true) { groups.append([]) } + let image = UIImage(systemName: item.systemImage) + if let children = item.children { + groups[groups.count - 1].append(menu(children, title: item.title, image: image)) + continue + } + var attributes: UIMenuElement.Attributes = [] + if item.isDestructive { attributes.insert(.destructive) } + if !item.isEnabled { attributes.insert(.disabled) } + let perform = item.perform + let action = UIAction(title: item.title, image: image, attributes: attributes) { _ in perform() } + action.accessibilityIdentifier = item.identifier + groups[groups.count - 1].append(action) + } + let children: [UIMenuElement] = groups.count == 1 + ? groups[0] + : groups.map { UIMenu(options: .displayInline, children: $0) } + return UIMenu(title: title, image: image, children: children) + } + #endif +} diff --git a/Bighelp/DirectHermes/DirectHermesAuthentication.swift b/Bighelp/DirectHermes/DirectHermesAuthentication.swift index 1df9acaa..585b5826 100644 --- a/Bighelp/DirectHermes/DirectHermesAuthentication.swift +++ b/Bighelp/DirectHermes/DirectHermesAuthentication.swift @@ -213,6 +213,8 @@ final class DirectHermesHTTP { // A photo draft's picture, in the same ~3 MB pieces as attachments/fetch. "/api/plugins/loopdy/native/image-drafts/source": 4 * 1_024 * 1_024 + 65_536, "/api/plugins/loopdy/native/board/media": 12 * 1_024 * 1_024, + // Every bot's spaces with their cards: the plugin stops adding cards at 3.5 MiB. + "/api/plugins/loopdy/native/spaces/list": 4 * 1_024 * 1_024 + 65_536, "/api/plugins/loopdy/native/workspace-files/read": maximumMediaResponseBytes, ] diff --git a/Bighelp/DirectHermes/DirectHermesChatSpeakerNote.swift b/Bighelp/DirectHermes/DirectHermesChatSpeakerNote.swift index f0da8c03..0d70bc23 100644 --- a/Bighelp/DirectHermes/DirectHermesChatSpeakerNote.swift +++ b/Bighelp/DirectHermes/DirectHermesChatSpeakerNote.swift @@ -75,7 +75,9 @@ final class DirectHermesChatSpeakerNote: ChatSpeakerNoting { // Drafts only with the plugin that knows them: older ones refuse names they don't know. let drafts = pluginFeatures.contains(ImageDraftWire.feature) ? ImageDraftWire.renders : [] let apps = pluginFeatures.contains(HTMLAppWire.feature) ? HTMLAppWire.renders : [] - payload["renders"] = .array((BighelpCardObjects.renders + drafts + apps).map(BighelpJSONValue.string)) + let spaces = pluginFeatures.contains(SpacesWire.feature) ? SpacesWire.renders : [] + // Seven names; the plugin takes at most eight. + payload["renders"] = .array((BighelpCardObjects.renders + drafts + apps + spaces).map(BighelpJSONValue.string)) } return payload } diff --git a/Bighelp/DirectHermes/DirectHermesNativeContext.swift b/Bighelp/DirectHermes/DirectHermesNativeContext.swift index 3775e58c..894920c9 100644 --- a/Bighelp/DirectHermes/DirectHermesNativeContext.swift +++ b/Bighelp/DirectHermes/DirectHermesNativeContext.swift @@ -243,7 +243,7 @@ final class DirectHermesNativePluginClient { } guard (200...299).contains(response.http.statusCode) else { if [401, 403, 412, 428].contains(response.http.statusCode) { self.context = nil } - throw responseError(response, mutation: route.isMutation) + throw responseError(response, mutation: route.isMutation, knownOutcomeCodes: route.knownOutcomeCodes) } guard echoedID == requestGuard.requestIDHeader, DirectHermesNativeRequestGuard.contextTag(response.http.value(forHTTPHeaderField: "ETag")) == requestGuard.etag else { @@ -279,7 +279,8 @@ final class DirectHermesNativePluginClient { /// Features whose plugin routes refuse requests over 192 KB. private static let smallRequestFeatures: Set = ["native-card-templates-v1", workflowsFeature, workflowsEditFeature, workflowsTriggerFeature, - MyTemplatesWire.feature, ImageDraftWire.feature] + MyTemplatesWire.feature, ImageDraftWire.feature, + SpacesWire.feature] /// Workflows: stages run by agents on the host, with your sign-off. static let workflowsFeature = "native-workflows-v1" @@ -309,6 +310,9 @@ final class DirectHermesNativePluginClient { /// A route that takes file bytes; others keep the 1 MiB (or 192 KiB) request cap. /// `DirectHermesHTTP.requestBodyLimit` must allow the same. var maximumRequestBytes: Int? + /// 5xx codes this route's plugin sends only once it knows what happened, so they read as a + /// refusal (`.rejected`) rather than an unknown outcome. + var knownOutcomeCodes: Set = [] } private static func route(_ operation: WorkspaceOperation) throws -> Route { @@ -420,7 +424,7 @@ final class DirectHermesNativePluginClient { return Route(path: "agents/deliveries", feature: DirectHermesAgentTalkReader.deliveriesFeature, isMutation: false, maximumResponseBytes: 1_048_576, timeout: 10) case .agentsActivity: - // Read every few seconds while Bots mode's home or the Agents screen shows; at most 64 agents. + // Read every few seconds while the Bots view shows; at most 64 agents. return Route(path: "agents/activity", feature: DirectHermesBotChatActivityClient.feature, isMutation: false, maximumResponseBytes: 32_768, timeout: 10) case .computerScreenStatus, .computerScreenObserve: @@ -516,6 +520,26 @@ final class DirectHermesNativePluginClient { // Read every few seconds while a live app is open; at most 1 MiB of data. return Route(path: "html-apps/data", feature: HTMLAppWire.feature, isMutation: false, maximumResponseBytes: 2 * 1_024 * 1_024 + 131_072, timeout: 10) + case .spacesList: + // Every bot's live spaces; cards the phone has are left out, and the plugin keeps the rest + // under 3.5 MiB. + return Route(path: "spaces/list", feature: SpacesWire.feature, isMutation: false, + maximumResponseBytes: 4 * 1_024 * 1_024 + 65_536, timeout: 30) + case .spacesGet: + return Route(path: "spaces/get", feature: SpacesWire.feature, isMutation: false, + maximumResponseBytes: 524_288, timeout: 20) + case .spacesAdd, .spacesUpdate, .spacesDelete: + // spaces.add -> spaces/add. `schedules_unavailable` is known: nothing was scheduled for + // add, and for delete the space is off Today already (a retry with the same + // `operationId` finishes it; SpacesStore does). + return Route(path: operation.rawValue.replacingOccurrences(of: ".", with: "/"), + feature: SpacesWire.feature, isMutation: true, maximumResponseBytes: 524_288, timeout: 20, + knownOutcomeCodes: Self.spacesKnownOutcomeCodes) + case .spacesRefresh: + // A script runs inside the request, for up to 50 seconds. `routine_failed` (502) means it + // ran and failed: the outcome is known. + return Route(path: "spaces/refresh", feature: SpacesWire.feature, isMutation: true, + maximumResponseBytes: 524_288, timeout: 60, knownOutcomeCodes: Self.spacesKnownOutcomeCodes) case .peopleSpeaking: // Sent before each message; a slow host never holds a message for long. return Route(path: "people/speaking", feature: "native-people-v1", isMutation: true, @@ -592,16 +616,26 @@ final class DirectHermesNativePluginClient { /// Plugin codes for "this computer can't do that at all", sent before any work starts. static let refusedBeforeStartingCodes: Set = ["runner_unavailable", "workflows_unavailable", "store_unavailable", - "bot_chat_gateway_unavailable", + "bot_chat_gateway_unavailable", "spaces_unavailable", // A failed skill upload is rolled back before the answer. "skill_import_failed", "skill_import_unavailable"] + /// The spaces routes' 5xx answers with a known outcome: `routine_failed` (502, Update now ran and + /// failed) and `schedules_unavailable` (503; for delete, the space is off Today and not yet gone). + /// Not in `refusedBeforeStartingCodes`: Workflows' triggers send `schedules_unavailable` too. + private static let spacesKnownOutcomeCodes: Set = ["routine_failed", "schedules_unavailable"] + static func refusedBeforeStarting(_ response: DirectHermesHTTP.Response) -> Bool { - guard let code = (try? response.object())?["error"]?.object?["code"]?.string else { return false } + guard let code = errorCode(response) else { return false } return refusedBeforeStartingCodes.contains(code) } - private func responseError(_ response: DirectHermesHTTP.Response, mutation: Bool) -> WorkspaceClientError { + private static func errorCode(_ response: DirectHermesHTTP.Response) -> String? { + (try? response.object())?["error"]?.object?["code"]?.string + } + + private func responseError(_ response: DirectHermesHTTP.Response, mutation: Bool, + knownOutcomeCodes: Set = []) -> WorkspaceClientError { switch response.http.statusCode { case 401, 403: return .authenticationRequired case 412: return .conflict @@ -609,7 +643,10 @@ final class DirectHermesNativePluginClient { case 428: return .unavailable(.unsupportedOperation) case 503 where Self.refusedBeforeStarting(response): // The plugin says so before it does anything, so the outcome is known. - return .rejected(code: (try? response.object())?["error"]?.object?["code"]?.string ?? "") + return .rejected(code: Self.errorCode(response) ?? "") + case 500...599 where Self.errorCode(response).map({ knownOutcomeCodes.contains($0) }) == true: + // This route's plugin sends the code only once it knows what happened. + return .rejected(code: Self.errorCode(response)) case 500...599: return mutation ? .outcomeUnknown : .transportUnavailable default: break } diff --git a/Bighelp/DirectHermes/DirectHermesStockGitClient.swift b/Bighelp/DirectHermes/DirectHermesStockGitClient.swift index 9cf70dfd..bc98c027 100644 --- a/Bighelp/DirectHermes/DirectHermesStockGitClient.swift +++ b/Bighelp/DirectHermes/DirectHermesStockGitClient.swift @@ -234,7 +234,7 @@ final class DirectHermesStockGitClient: StockGitManaging, ProjectGitClient { private var preparedActions: [UUID: StockGitPreparedAction] = [:] /// Linked worktrees of each registered Project's primary folder, from Hermes's own /// worktree list for that folder. Besides the primary folder, these are the only - /// paths a target may name (Code mode's sessions each work in one). + /// paths a target may name (coding sessions each work in one). private var projectWorktrees: [String: (primary: StockGitProjectTarget, paths: Set)] = [:] init( diff --git a/Bighelp/DirectHermes/DirectHermesWorkspaceClient.swift b/Bighelp/DirectHermes/DirectHermesWorkspaceClient.swift index 531481ed..f6fa08ca 100644 --- a/Bighelp/DirectHermes/DirectHermesWorkspaceClient.swift +++ b/Bighelp/DirectHermes/DirectHermesWorkspaceClient.swift @@ -386,7 +386,7 @@ final class DirectHermesWorkspaceClient: WorkspaceOperationPerforming { } return .rpc(operation.rawValue, payload) } - // YOLO (Code mode's mode, the chat's toggle): one session's flag, never the agent's default. + // YOLO (a coding session's mode, the chat's toggle): one session's flag, never the agent's default. if payload["key"] == .string("yolo") { guard operation == .configSet, payload["profile"]?.string != nil, payload["session_id"]?.string != nil, payload["scope"] == .string("session"), diff --git a/Bighelp/Driving/DriveCatalog.swift b/Bighelp/Driving/DriveCatalog.swift index aab550cc..eeb63673 100644 --- a/Bighelp/Driving/DriveCatalog.swift +++ b/Bighelp/Driving/DriveCatalog.swift @@ -1,6 +1,6 @@ import Foundation -/// Every place an agent's drive can open, with its playbook per mode. It lists only places the +/// Every place an agent's drive can open, with the steps that reach it. It lists only places the /// navigator can reach for real: a route, a tab, a bot profile tab or sheet, or a Settings page. /// Places that open only from a view's own state join as they get a way in (#662). /// `navigation.places` searches it; the plugin never holds a copy, so new places ship with the app. @@ -8,16 +8,16 @@ enum DriveCatalog { static func place(_ id: String) -> DrivePlace? { byID[id] } /// The places that fit the person's words, best first. Every word must appear in the place's - /// title, description, keywords or trail. No words lists every place in `mode`. - static func search(_ query: String, mode: BighelpMode, nerdMode: Bool, limit: Int) -> [DrivePlace] { + /// title, description, keywords or trail. No words lists every place. + static func search(_ query: String, nerdMode: Bool, limit: Int) -> [DrivePlace] { let words = query.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).map(String.init) .filter { !stopWords.contains($0) } - let reachable = places.filter { $0.playbooks[mode] != nil && (nerdMode || !$0.needs.contains(.nerdMode)) } + let reachable = places.filter { nerdMode || !$0.needs.contains(.nerdMode) } guard !words.isEmpty else { return Array(reachable.prefix(limit)) } let scored = reachable.compactMap { place -> (DrivePlace, Int)? in let title = place.title.lowercased() let keywords = place.keywords.joined(separator: " ").lowercased() - let rest = (place.what + " " + (place.playbooks[mode] ?? []).map(\.label).joined(separator: " ")).lowercased() + let rest = (place.what + " " + place.steps.map(\.label).joined(separator: " ")).lowercased() var score = 0 for word in words { let stem = word.count > 3 && word.hasSuffix("s") ? String(word.dropLast()) : word @@ -41,7 +41,7 @@ enum DriveCatalog { static let places: [DrivePlace] = botPlaces + boardPlaces + workPlaces + settingsPlaces + hermesPlaces - // MARK: - Bots mode: a bot's profile + // MARK: - A bot's page private static let profile = DriveStep.go("{Bot}'s profile", .botProfile(BotProfileOpening())) @@ -68,127 +68,120 @@ enum DriveCatalog { private static let botPlaces: [DrivePlace] = [ DrivePlace("bot.profile", String(localized: "Bot profile"), String(localized: "A bot's own page: its look, Dashboard, settings, files and screen."), - keywords: ["profile", "about", "bot page"], needs: [.bot], playbooks: [.bots: [profile]]), + keywords: ["profile", "about", "bot page"], needs: [.bot], steps: [profile]), DrivePlace("bot.dashboard", String(localized: "Dashboard"), String(localized: "The bot's Feed, Ideas and Goals as piles you swipe, with Today on top."), keywords: ["dashboard", "piles", "cards", "feed", "ideas", "goals"], needs: [.bot], - playbooks: [.bots: profileTab(.dashboard, String(localized: "Dashboard"))]), + steps: profileTab(.dashboard, String(localized: "Dashboard"))), DrivePlace("bot.dashboard.today", String(localized: "Activities"), String(localized: "What the bot ran in the background, by day: subagents and commands."), keywords: ["activities", "today", "background", "running", "subagents", "processes", "commands", "activity"], - needs: [.bot], playbooks: [.bots: profileTab(.dashboard, String(localized: "Dashboard")) - + [.point(String(localized: "Activities"), at: "dashboard.today.toggle")]]), + needs: [.bot], steps: profileTab(.dashboard, String(localized: "Dashboard")) + + [.point(String(localized: "Activities"), at: "dashboard.today.toggle")]), DrivePlace("bot.dashboard.templates.feed", String(localized: "Feed templates"), String(localized: "Ready-made jobs the bot can do for your Feed. Swipe right to use one."), keywords: ["feed", "templates", "what can feed do", "starter", "ideas for feed", "blueprints"], - needs: [.bot], playbooks: [.bots: templates(.feed, String(localized: "Feed"))]), + needs: [.bot], steps: templates(.feed, String(localized: "Feed"))), DrivePlace("bot.dashboard.templates.ideas", String(localized: "Ideas templates"), String(localized: "Ready-made prompts that fill the bot's Ideas."), keywords: ["ideas", "templates", "starter", "suggestions", "blueprints"], - needs: [.bot], playbooks: [.bots: templates(.idea, String(localized: "Ideas"))]), + needs: [.bot], steps: templates(.idea, String(localized: "Ideas"))), DrivePlace("bot.dashboard.templates.goals", String(localized: "Goals templates"), String(localized: "Ready-made goals the bot can track for you."), keywords: ["goals", "templates", "habits", "starter", "blueprints"], - needs: [.bot], playbooks: [.bots: templates(.goal, String(localized: "Goals"))]), + needs: [.bot], steps: templates(.goal, String(localized: "Goals"))), DrivePlace("bot.info", String(localized: "Info"), String(localized: "The bot's look, instructions, model, voice and routines."), keywords: ["info", "bot settings", "settings for bot"], needs: [.bot], - playbooks: [.bots: profileTab(.info, String(localized: "Info"))]), + steps: profileTab(.info, String(localized: "Info"))), DrivePlace("bot.info.character", String(localized: "Character"), String(localized: "The bot's shape and color, or a character, pet or photo."), keywords: ["look", "avatar", "shape", "color", "picture", "face"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Character"), "simple-bots.profile.character")]), + steps: infoRow(String(localized: "Character"), "simple-bots.profile.character")), DrivePlace("bot.info.instructions", String(localized: "Instructions"), String(localized: "What the bot is told to be and do."), keywords: ["instructions", "personality", "soul", "prompt", "rules", "behave"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Instructions"), "simple-bots.profile.instructions")]), + steps: infoRow(String(localized: "Instructions"), "simple-bots.profile.instructions")), DrivePlace("bot.info.photo-actions", String(localized: "Photo actions"), String(localized: "Turn photos of business cards and posters into contacts and events."), keywords: ["photo", "business card", "poster", "contact", "event"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Photo actions"), "simple-bots.profile.photo-actions")]), + steps: infoRow(String(localized: "Photo actions"), "simple-bots.profile.photo-actions")), DrivePlace("bot.info.default-model", String(localized: "Default Model"), String(localized: "The AI model and reasoning the bot uses for its chats."), keywords: ["model", "ai model", "reasoning", "smarter", "faster"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Default Model"), "simple-bots.profile.default-model")]), + steps: infoRow(String(localized: "Default Model"), "simple-bots.profile.default-model")), DrivePlace("bot.info.default-voice", String(localized: "Default Voice"), String(localized: "How the bot sounds in voice chats."), keywords: ["voice", "speech", "talk", "sound"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Default Voice"), "simple-bots.profile.default-voice")]), + steps: infoRow(String(localized: "Default Voice"), "simple-bots.profile.default-voice")), DrivePlace("bot.info.advanced-options", String(localized: "Advanced Options"), String(localized: "Safety, memory, notices and what happens while the bot works."), keywords: ["advanced", "approvals", "memory", "safety", "permissions"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Advanced Options"), "simple-bots.profile.advanced-options")]), + steps: infoRow(String(localized: "Advanced Options"), "simple-bots.profile.advanced-options")), DrivePlace("bot.info.routines", String(localized: "Routines"), String(localized: "Jobs the bot does on a schedule. Add one here."), keywords: ["routines", "schedule", "scheduled", "every day", "reminder", "recurring"], needs: [.bot], - playbooks: [.bots: infoRow(String(localized: "Add routine"), "simple-bots.profile.add-routine")]), + steps: infoRow(String(localized: "Add routine"), "simple-bots.profile.add-routine")), DrivePlace("bot.computer", String(localized: "Computer"), String(localized: "The bot's own screen: watch it work or take control."), keywords: ["computer", "screen", "browser", "desktop", "watch"], needs: [.bot], - playbooks: [.bots: profileTab(.computer, String(localized: "Computer"))]), + steps: profileTab(.computer, String(localized: "Computer"))), DrivePlace("bot.files", String(localized: "Files"), String(localized: "The bot's folder on your computer."), keywords: ["files", "folder", "documents", "downloads"], needs: [.bot], - playbooks: [.bots: profileTab(.files, String(localized: "Files"))]), + steps: profileTab(.files, String(localized: "Files"))), DrivePlace("bot.media", String(localized: "Media"), String(localized: "Photos and videos from your chats with the bot."), keywords: ["media", "photos", "videos", "pictures"], needs: [.bot], - playbooks: [.bots: profileTab(.media, String(localized: "Media"))]), + steps: profileTab(.media, String(localized: "Media"))), ] - // MARK: - Chat and Code: the agent's boards and work pages, pushed over the chat - - private static func both(_ steps: [DriveStep]) -> [BighelpMode: [DriveStep]] { [.chat: steps, .code: steps] } + // MARK: - The boards and work pages, pushed over the chat private static func page(_ id: String, _ title: String, _ what: String, keywords: [String], - needs: Set = [], _ route: AppRoute, - modes: [BighelpMode] = [.chat, .code]) -> DrivePlace { - let steps = [DriveStep.go(title, .push(route))] - return DrivePlace(id, title, what, keywords: keywords, needs: needs, - playbooks: Dictionary(uniqueKeysWithValues: modes.map { ($0, steps) })) + needs: Set = [], _ route: AppRoute) -> DrivePlace { + DrivePlace(id, title, what, keywords: keywords, needs: needs, steps: [.go(title, .push(route))]) } private static let boardPlaces: [DrivePlace] = [ page("boards.feed", String(localized: "Feed"), String(localized: "Posts and updates from your agent."), keywords: ["feed", "posts", "updates", "news"], .board(.feed)), page("boards.ideas", String(localized: "Ideas"), String(localized: "Things your agent offers to do for you."), - keywords: ["ideas", "suggestions"], .board(.ideas)), + keywords: ["ideas", "suggestions"], .board(.idea)), page("boards.goals", String(localized: "Goals"), String(localized: "Goals your agent tracks for you."), - keywords: ["goals", "habits", "progress"], .board(.goals)), - page("boards.files", String(localized: "Files"), String(localized: "Files, pages, pictures and videos your agent made."), - keywords: ["files", "artifacts", "media", "apps"], .board(.apps)), + keywords: ["goals", "habits", "progress"], .board(.goal)), ] private static let workPlaces: [DrivePlace] = [ DrivePlace("agents", String(localized: "Agents"), String(localized: "Every agent and group chat on this computer."), keywords: ["agents", "bots", "group chats", "team"], - playbooks: [.chat: [.go(String(localized: "Agents"), .tab(.agents))]]), + steps: [.go(String(localized: "Bots"), .tab(.conversations, view: .bots))]), DrivePlace("sessions", String(localized: "Sessions"), String(localized: "Every chat on this computer, to search and reopen."), keywords: ["sessions", "chats", "history", "conversations", "old chats"], - playbooks: [.chat: [.go(String(localized: "Sessions"), .tab(.sessionList))]]), + steps: [.go(String(localized: "Chats"), .tab(.conversations, view: .chats))]), page("projects", String(localized: "Projects"), String(localized: "Related chats and folders together."), keywords: ["projects", "folders", "workspaces"], .projects), page("kanban", String(localized: "Kanban"), String(localized: "Your agents' task board, from Later to Done."), keywords: ["kanban", "board", "tasks", "cards", "todo"], .kanban), page("workflows", String(localized: "Workflows"), String(localized: "Multi-step jobs agents run, with your sign-off."), - keywords: ["workflows", "automation", "pipelines", "runs"], .workflows, modes: [.chat]), + keywords: ["workflows", "automation", "pipelines", "runs"], .workflows), page("scheduled-tasks", String(localized: "Scheduled tasks"), String(localized: "Work your agents do on a schedule."), - keywords: ["scheduled", "tasks", "routines", "cron", "every day", "reminders"], .scheduledTasks, modes: [.chat]), + keywords: ["scheduled", "tasks", "routines", "cron", "every day", "reminders"], .scheduledTasks), page("usage", String(localized: "Usage"), String(localized: "Your plans, limits, and how much each agent used."), - keywords: ["usage", "limits", "plan", "cost", "tokens", "quota"], .usage, modes: [.bots, .chat, .code]), + keywords: ["usage", "limits", "plan", "cost", "tokens", "quota"], .usage), page("skills", String(localized: "Skills & tools"), String(localized: "The skills and tools your agent can use."), - keywords: ["skills", "tools", "abilities", "plugins"], .skillsAndTools, modes: [.chat]), + keywords: ["skills", "tools", "abilities", "plugins"], .skillsAndTools), page("models", String(localized: "Default model"), String(localized: "The AI model new chats start with."), keywords: ["model", "default model", "ai model", "llm"], .workspaceManagement(.models)), page("ai-providers", String(localized: "AI providers"), String(localized: "Sign in to AI providers or add their keys."), keywords: ["providers", "api key", "keys", "sign in", "accounts"], .workspaceManagement(.keys)), page("dev-factory", String(localized: "Dev Factory"), String(localized: "Coding recipes that run across projects, and their runs."), - keywords: ["dev factory", "recipes", "automation"], .devFactory, modes: [.code]), + keywords: ["dev factory", "recipes", "automation"], .devFactory), ] // MARK: - Settings - /// Settings opens from your circle in Bots mode and from ☰ in Chat and Code: the same pages in each. + /// Settings opens from your circle on every root. private static func settings(_ id: String, _ title: String, _ what: String, keywords: [String], needs: Set = [], full pages: [(String, SettingsDestination, String?)], point: (String, String)? = nil) -> DrivePlace { @@ -202,9 +195,7 @@ enum DriveCatalog { if let point { built.append(.point(point.0, at: point.1)) } return built } - let path = steps(pages, start: []) - return DrivePlace(id, title, what, keywords: keywords, needs: needs, - playbooks: [.bots: path, .chat: path, .code: path]) + return DrivePlace(id, title, what, keywords: keywords, needs: needs, steps: steps(pages, start: [])) } private static func section(_ section: SettingsMenuSection) -> (String, SettingsDestination, String?) { @@ -231,10 +222,6 @@ enum DriveCatalog { String(localized: "Avatar size, names, message text size and spacing in chats."), keywords: ["chat layout", "message size", "spacing", "avatar size", "font"], full: [section(.appearance), (String(localized: "Chat layout"), .chatLayout, "settings.appearance.chat-layout")]), - settings("settings.appearance.app-layout", String(localized: "App layout"), - String(localized: "What the bottom bar holds and the order of the menu."), - keywords: ["app layout", "bottom bar", "tab bar", "tabs", "menu order", "pin"], - full: [section(.appearance), (String(localized: "App layout"), .appLayout, "settings.appearance.app-layout")]), settings("settings.appearance.thinking", String(localized: "Thinking"), String(localized: "The look of the Thinking control that sets how hard an agent thinks."), keywords: ["thinking", "reasoning", "thinking slider", "effort", "slider look"], @@ -283,10 +270,6 @@ enum DriveCatalog { settings("settings.you", String(localized: "You"), String(localized: "Your name and photo on your messages."), keywords: ["my name", "my photo", "profile", "me"], full: [(String(localized: "You"), .you, "settings.you")]), - settings("settings.modes", String(localized: "Modes"), - String(localized: "Bots mode, Code mode and the switch between them at the top of each home."), - keywords: ["modes", "bots mode", "code mode", "mode switch", "unified mode toggle", "experience"], - full: [section(.modes)]), settings("settings.system", String(localized: "Your computers"), String(localized: "Your computers, Hermes updates and restarts."), keywords: ["system", "computers", "hosts", "update hermes", "plugin", "restart"], diff --git a/Bighelp/Driving/DriveNavigator.swift b/Bighelp/Driving/DriveNavigator.swift index 0661d4ce..03835370 100644 --- a/Bighelp/Driving/DriveNavigator.swift +++ b/Bighelp/Driving/DriveNavigator.swift @@ -17,7 +17,9 @@ enum DriveScroll { /// Where the person was before a drive, for Return to chat. struct DriveSnapshot: Equatable { - var tab: AppTab + var tab: HomeTab + /// The first tab's view (Bots or Chats). + var view: HomeConversationsView var path: [AppRoute] } @@ -310,11 +312,14 @@ final class AppDriveRouter: DriveRouting { init(appState: AppState) { self.appState = appState } - func snapshot() -> DriveSnapshot { DriveSnapshot(tab: appState.selectedTab, path: appState.path) } + func snapshot() -> DriveSnapshot { + DriveSnapshot(tab: appState.selectedTab, view: appState.home.view, path: appState.path) + } func restore(_ snapshot: DriveSnapshot) async { await closeSettings() appState.selectedTab = snapshot.tab + appState.home.view = snapshot.view appState.path = snapshot.path } @@ -325,8 +330,9 @@ final class AppDriveRouter: DriveRouting { case .push(let route): await closeSettings() if appState.path.last != route { appState.open(route) } - case .tab(let tab): + case .tab(let tab, let view): await closeSettings() + if let view { appState.home.view = view } appState.select(tab) case .botProfile(let opening): guard let bot else { return } diff --git a/Bighelp/Driving/DrivePlace.swift b/Bighelp/Driving/DrivePlace.swift index 6e568633..3774c678 100644 --- a/Bighelp/Driving/DrivePlace.swift +++ b/Bighelp/Driving/DrivePlace.swift @@ -1,7 +1,7 @@ import Foundation /// One place in bighelp an agent can take the person to (issue #662): a page, a sheet or a control, -/// with the steps that reach it in each mode. `DriveCatalog` lists them; `DriveNavigator` plays one. +/// with the steps that reach it. `DriveCatalog` lists them; `DriveNavigator` plays one. struct DrivePlace: Identifiable, Sendable { let id: String let title: String @@ -10,13 +10,14 @@ struct DrivePlace: Identifiable, Sendable { /// Words a person might use for it, beside its title and `what`. let keywords: [String] let needs: Set - /// The steps in each mode. A mode without steps can't reach the place. - let playbooks: [BighelpMode: [DriveStep]] + /// The steps that reach it: a bot's page for a place inside a bot, else the page's own push or its + /// Settings pages. Every place has them. + let steps: [DriveStep] init(_ id: String, _ title: String, _ what: String, keywords: [String] = [], needs: Set = [], - playbooks: [BighelpMode: [DriveStep]]) { + steps: [DriveStep]) { self.id = id; self.title = title; self.what = what; self.keywords = keywords - self.needs = needs; self.playbooks = playbooks + self.needs = needs; self.steps = steps } } @@ -66,8 +67,8 @@ struct DriveStep: Equatable, Sendable { enum DriveMove: Equatable, Sendable { /// Pushes a page over where the person is (the chat stays under it for Return to chat). case push(AppRoute) - /// A root place without a route (Agents, the chat list). - case tab(AppTab) + /// One of the home's three places; `view` picks Bots or Chats on the first. + case tab(HomeTab, view: HomeConversationsView? = nil) /// The bot's profile, on a tab and with a sheet. A profile already open takes the change live. case botProfile(BotProfileOpening) /// The Settings sheet, on these pages. diff --git a/Bighelp/Driving/DriveShellHooks.swift b/Bighelp/Driving/DriveShellHooks.swift index fa3324db..14d9d0fd 100644 --- a/Bighelp/Driving/DriveShellHooks.swift +++ b/Bighelp/Driving/DriveShellHooks.swift @@ -6,7 +6,6 @@ struct DriveShellHooks: ViewModifier { let appState: AppState let featureStore: ShellFeatureStore let agents: AgentDirectoryStore - let settings: SettingsStore let usesDemoFixtures: Bool var navigator: DriveNavigator = .shared @@ -30,10 +29,10 @@ struct DriveShellHooks: ViewModifier { #if DEBUG .onAppear { guard usesDemoFixtures, ProcessInfo.processInfo.arguments.contains(DriveFixture.launchArgument) else { return } - let state = appState, features = featureStore, settings = settings + let state = appState, features = featureStore // Not a `.task`: the root's tasks stop once a chat covers it (AGENTS.md › Root `.task(id:)`). Task { - await DriveFixture.play(arguments: ProcessInfo.processInfo.arguments, mode: { settings.currentMode }, + await DriveFixture.play(arguments: ProcessInfo.processInfo.arguments, chat: { state.chatOnScreen.flatMap { features.preparedChatModel(id: $0) } }) } } @@ -53,7 +52,7 @@ enum DriveFixture { /// Waits up to 20 seconds for a chat to be on screen (a test taps one, or the demo opens it), then /// plays the drive a moment later, once. - static func play(arguments: [String], mode: () -> BighelpMode, chat: () -> ChatModel?) async { + static func play(arguments: [String], chat: () -> ChatModel?) async { guard !played, let place = value(after: launchArgument, in: arguments).flatMap(DriveCatalog.place) else { return } var open: ChatModel? for _ in 0..<80 { @@ -61,12 +60,12 @@ enum DriveFixture { if open != nil { break } try? await Task.sleep(for: .milliseconds(250)) } - guard let agentID = open?.memberIDs.first, let steps = place.playbooks[mode()] else { return } + guard let agentID = open?.memberIDs.first, !place.steps.isEmpty else { return } try? await Task.sleep(for: .milliseconds(1500)) guard !played else { return } played = true let bot = place.needs.contains(.bot) ? DriveNavigator.shared.agent(agentID).map { (id: $0.id, name: $0.name) } : nil - DriveNavigator.shared.open(place, steps: steps, bot: bot, + DriveNavigator.shared.open(place, steps: place.steps, bot: bot, note: value(after: noteArgument, in: arguments) ?? place.what, agentID: agentID) } diff --git a/Bighelp/Fixtures/ConversationFixtures.swift b/Bighelp/Fixtures/ConversationFixtures.swift index 5b366386..3070334c 100644 --- a/Bighelp/Fixtures/ConversationFixtures.swift +++ b/Bighelp/Fixtures/ConversationFixtures.swift @@ -33,7 +33,7 @@ class ConversationFixtureClient: AttachmentConversationClient, CompactingConvers func send(message: String, conversationID: String) async throws -> ConversationResponse { guard !shouldFail else { throw ConversationFixtureError.unavailable } - // Code mode's Plan mode: the demo "writes" the plan `DemoHostTextFiles` serves. + // A coding session's Plan mode: the demo "writes" the plan `DemoHostTextFiles` serves. if message.hasPrefix("/plan") { return ConversationResponse(items: [ assistantItem( diff --git a/Bighelp/Fleet/FleetFixtureReader.swift b/Bighelp/Fleet/FleetFixtureReader.swift index 7423395c..890213c2 100644 --- a/Bighelp/Fleet/FleetFixtureReader.swift +++ b/Bighelp/Fleet/FleetFixtureReader.swift @@ -91,17 +91,7 @@ final class FleetFixtureReader: FleetHostReading { memberNames: ["Rio Tanaka", "Sage Ortiz"], updatedAt: now.addingTimeInterval(-50 * 60), isWorking: false, canRename: false, canDelete: false, memberIDs: ["research", "reviewer"]), ], - refreshedAt: now, - otherAppChats: [ - FleetOtherAppChat(hostID: id, item: HermesForeignSessionItem( - id: String(repeating: "e", count: 64), source: "codex", sourceLabel: "Codex CLI", - title: "Speed up the test suite", cwd: "~/Projects/site", modifiedAt: now.addingTimeInterval(-40 * 60), - turnCount: 9, excerpt: "Run the slow tests in parallel")), - FleetOtherAppChat(hostID: id, item: HermesForeignSessionItem( - id: String(repeating: "f", count: 64), source: "claude", sourceLabel: "Claude Code", - title: "Draft the launch post", cwd: "~/Projects/blog", modifiedAt: now.addingTimeInterval(-5 * 60 * 60), - turnCount: 5, excerpt: "Three short paragraphs")), - ] + refreshedAt: now ) } diff --git a/Bighelp/Fleet/FleetListOrganizing.swift b/Bighelp/Fleet/FleetListOrganizing.swift deleted file mode 100644 index 1d62ee3c..00000000 --- a/Bighelp/Fleet/FleetListOrganizing.swift +++ /dev/null @@ -1,214 +0,0 @@ -import SwiftUI - -/// A group chat in the all-hosts list: its name, host and who's in it. -struct FleetGroupRow: View { - let group: FleetGroup - let fleet: FleetStore - - var body: some View { - HStack(spacing: BighelpTokens.space12) { - Image(systemName: "person.3.fill") - .font(.system(size: 18, weight: .semibold)) - .foregroundStyle(theme.action) - .frame(width: SessionRow.avatarSize, height: SessionRow.avatarSize) - .background(theme.action.opacity(0.14), in: .circle) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space8) { - Text(group.name) - .font(.bighelp(.callout).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - if fleet.showsHostNames { FleetHostTag(name: fleet.hostName(group.hostID)) } - Spacer(minLength: BighelpTokens.space4) - Text(SessionRow.compactTimestamp(group.updatedAt)) - .font(.bighelp(.footnote)) - .monospacedDigit() - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - .layoutPriority(1) - } - Text(group.isWorking ? "Agents are working" : "Group chat") - .font(.bighelp(.footnote).weight(.medium)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - Text(ListFormatter.localizedString(byJoining: group.memberNames)) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - } - } - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) - .contentShape(.rect) - .accessibilityElement(children: .combine) - } - - @BighelpThemeReader private var theme -} - -/// A section's name over its rows, with its own Rename and Delete. -struct FleetSectionHeader: View { - let title: String - let count: Int - var onRename: (() -> Void)? = nil - var onDelete: (() -> Void)? = nil - var onMoveUp: (() -> Void)? = nil - var onMoveDown: (() -> Void)? = nil - - var body: some View { - HStack(spacing: BighelpTokens.space8) { - Image(systemName: "folder") - .foregroundStyle(theme.secondaryText) - .accessibilityHidden(true) - Text(title) - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - Text("\(count)") - .font(.bighelp(.footnote)) - .monospacedDigit() - .foregroundStyle(theme.secondaryText) - Spacer(minLength: BighelpTokens.space8) - if let onRename, let onDelete { - Menu { - Button("Rename section", systemImage: "pencil", action: onRename) - .accessibilityIdentifier("fleet.section.rename") - if let onMoveUp { Button("Move up", systemImage: "arrow.up", action: onMoveUp) } - if let onMoveDown { Button("Move down", systemImage: "arrow.down", action: onMoveDown) } - Button("Delete section", systemImage: "trash", role: .destructive, action: onDelete) - .accessibilityIdentifier("fleet.section.delete") - } label: { - Image(systemName: "ellipsis") - .frame(width: BighelpTokens.hitTarget, height: 32) - .contentShape(.rect) - } - .foregroundStyle(theme.secondaryText) - .accessibilityLabel("\(title) options") - .accessibilityIdentifier("fleet.section.menu.\(title)") - } - } - .textCase(nil) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("fleet.section.\(title)") - } - - @BighelpThemeReader private var theme -} - -/// What a name prompt in the all-hosts list is for. -enum FleetNamePrompt: Equatable { - /// A new section, optionally with an item to file into it. - case newSection(filing: FleetListItem?) - case renameSection(FleetSection) - case renameGroup(FleetGroup) - - var title: String { - switch self { - case .newSection: "New section" - case .renameSection: "Rename section" - case .renameGroup: "Rename group" - } - } - - var confirmTitle: String { - switch self { - case .newSection: "Create" - case .renameSection, .renameGroup: "Rename" - } - } -} - -/// The all-hosts list's prompts: names, deleting a group, a save that -/// didn't work, and Undo after deleting a section. -struct FleetListPrompts: ViewModifier { - let fleet: FleetStore - @Binding var namePrompt: FleetNamePrompt? - @Binding var deletingGroup: FleetGroup? - @Binding var deletedSection: FleetSectionDeletion? - let onGroupAction: ((FleetGroup, FleetGroupAction) -> Void)? - @State private var name = "" - - func body(content: Content) -> some View { - content - .onChange(of: namePrompt) { _, prompt in - switch prompt { - case .renameSection(let section)?: name = section.name - case .renameGroup(let group)?: name = group.name - default: name = "" - } - } - .alert(namePrompt?.title ?? "", isPresented: Binding( - get: { namePrompt != nil }, set: { if !$0 { namePrompt = nil } })) { - TextField("Name", text: $name) - .accessibilityIdentifier("fleet.name-prompt.field") - Button("Cancel", role: .cancel) { namePrompt = nil } - Button(namePrompt?.confirmTitle ?? "OK") { submit() } - .disabled(FleetSection.cleanName(name) == nil) - .accessibilityIdentifier("fleet.name-prompt.confirm") - } - .confirmationDialog("Delete this group?", isPresented: Binding( - get: { deletingGroup != nil }, set: { if !$0 { deletingGroup = nil } }), titleVisibility: .visible) { - Button("Delete group", role: .destructive) { - if let group = deletingGroup { onGroupAction?(group, .delete) } - deletingGroup = nil - } - .accessibilityIdentifier("fleet.group.delete.confirm") - } message: { Text("This permanently deletes the group on Hermes and stops its active work.") } - .alert("Couldn't save", isPresented: Binding( - get: { fleet.placementError != nil }, set: { if !$0 { fleet.placementError = nil } })) { - Button("OK", role: .cancel) { fleet.placementError = nil } - } message: { Text(fleet.placementError ?? "") } - .overlay(alignment: .bottom) { undoBanner } - .task(id: deletedSection?.section.id) { - guard deletedSection != nil else { return } - try? await Task.sleep(for: .seconds(8)) - deletedSection = nil - } - } - - @ViewBuilder - private var undoBanner: some View { - if let deletion = deletedSection { - HStack(spacing: BighelpTokens.space12) { - Text("Deleted “\(deletion.section.name)”. Its agents are still here.") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.primaryText) - .frame(maxWidth: .infinity, alignment: .leading) - Button("Undo") { - fleet.undoDeleteSection(deletion) - deletedSection = nil - } - .font(.bighelp(.subheadline).weight(.semibold)) - .accessibilityIdentifier("fleet.section.undo") - } - .padding(.horizontal, BighelpTokens.space16) - .padding(.vertical, BighelpTokens.space12) - .background(theme.surface, in: .rect(cornerRadius: 16)) - .shadow(color: .black.opacity(0.12), radius: 12, y: 4) - .padding(.horizontal, BighelpTokens.space16) - .padding(.bottom, 96) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("fleet.section.undo-banner") - } - } - - private func submit() { - guard let prompt = namePrompt, let clean = FleetSection.cleanName(name) else { return } - namePrompt = nil - switch prompt { - case .newSection(let filing): - guard let section = fleet.createSection(named: clean) else { return } - switch filing { - case .agent(let agent)?: Task { try? await fleet.file(agent, in: section.id) } - case .group(let group)?: fleet.file(group, in: section.id) - case nil: break - } - case .renameSection(let section): - Task { await fleet.renameSection(section.id, to: clean) } - case .renameGroup(let group): - onGroupAction?(group, .rename(clean)) - } - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Fleet/FleetModels.swift b/Bighelp/Fleet/FleetModels.swift index 3fa819c4..8aa93936 100644 --- a/Bighelp/Fleet/FleetModels.swift +++ b/Bighelp/Fleet/FleetModels.swift @@ -17,18 +17,6 @@ struct FleetSnapshot: Codable, Equatable, Sendable { /// Group chats; nil in snapshots saved before groups were listed. var groups: [FleetGroup]? = nil var refreshedAt: Date - /// The newest chats in Codex and Claude Code on that computer, not yet brought - /// into Hermes; nil when its Hermes can't list them (or before they were read). - var otherAppChats: [FleetOtherAppChat]? = nil -} - -/// A chat in Codex or Claude Code on one computer (Hermes' `session.foreign.list`). -/// Opening one goes to that computer's own Sessions screen, which brings it in. -struct FleetOtherAppChat: Codable, Equatable, Sendable, Identifiable { - let hostID: UUID - let item: HermesForeignSessionItem - - var id: String { FleetID.make(hostID, item.id) } } /// Agent IDs are only unique within one host. @@ -123,6 +111,9 @@ struct FleetChat: Codable, Equatable, Sendable, Identifiable { var isActive: Bool /// Hermes' `source` for the chat (where it started); see `SessionOrigin`. var origin: String? = nil + /// Pinned on its computer, as of the last time that computer was the one in use (only its live + /// record says); nil when it was never read live. + var isPinned: Bool? = nil var id: String { FleetID.make(hostID, storedSessionID) } } @@ -133,19 +124,6 @@ enum FleetChatChange: Equatable, Sendable { case archive } -/// All sessions' filters while every computer shows. A computer is picked with its chip. -struct FleetChatsFilter: Equatable { - /// One agent, by its `FleetAgent.id` (its computer and profile). - var agentID: String? - /// Where the chats started, by `SessionOrigin` label. - var origin: String? - /// Hermes, Codex or Claude Code, from the choice above the list. Kept apart from - /// the menu's filters: it stays when a computer is picked. - var app: SessionAppFilter = .all - - var isActive: Bool { agentID != nil || origin != nil } -} - struct FleetTask: Codable, Equatable, Sendable, Identifiable { let hostID: UUID let jobID: String @@ -174,36 +152,15 @@ enum FleetOpen: Equatable, Sendable { case task(jobID: String, profileID: String) case newChat(profileID: String) case group(roomID: String) - /// A group chat's settings (Bots mode's Group Settings). + /// A group chat's settings (the Bots view's Group Settings). case groupSettings(roomID: String) /// A new group chat with these agents, from New chat's Group chat. `peers` /// are agents on other computers; this host is the group's home. case newGroup(profileIDs: [String], peers: [HermesBotModePeerCandidate] = []) /// The agent's routines (its scheduled tasks). case routines(profileID: String) - /// Bots mode's bot profile. + /// A bot's page. case botProfile(profileID: String) - case destination(FleetDestination) -} - -/// Screens that belong to one host. With several hosts, the all-hosts view -/// asks which one first. -enum FleetDestination: String, Equatable, Sendable, Identifiable { - case settings, agents, newAgent, projects, kanban, workflows, folder - - var id: Self { self } - - var title: String { - switch self { - case .settings: "Settings" - case .agents: "Agents" - case .newAgent: "New agent" - case .projects: "Projects" - case .kanban: "Kanban" - case .workflows: "Workflows" - case .folder: "Folder" - } - } } /// A tap that has to wait for its host to become the selected one. @@ -218,14 +175,7 @@ struct FleetPendingOpen: Equatable, Sendable { switch open { case .agent(let id), .newChat(let id), .routines(let id), .botProfile(let id): id case .chat(let id, _, _), .task(_, let id): id - case .group, .groupSettings, .newGroup, .destination: nil + case .group, .groupSettings, .newGroup: nil } } } - -/// What a group chat's row can do from the all-hosts list. -enum FleetGroupAction: Equatable, Sendable { - case open - case rename(String) - case delete -} diff --git a/Bighelp/Fleet/FleetSections.swift b/Bighelp/Fleet/FleetSections.swift index 939a1d1e..e76b46d5 100644 --- a/Bighelp/Fleet/FleetSections.swift +++ b/Bighelp/Fleet/FleetSections.swift @@ -54,7 +54,7 @@ struct FleetSectionDeletion: Equatable { } /// An agent a section change files or takes out, and how its placement is saved on its own -/// computer: through the all-hosts copy here, through the live list in Bots mode. +/// computer: through the all-hosts copy here, through the live list on the Bots view. struct FleetSectionMember { let id: String let placement: AgentListPlacement? @@ -289,7 +289,7 @@ extension FleetStore { for id in ids where retiringSectionIDs[id] == token { retiringSectionIDs[id] = nil } } - /// Waits until a deleted section's members are out of it (Bots mode's sheets, tests). + /// Waits until a deleted section's members are out of it (the Bots view's sheets, tests). func waitForSectionUnfiling(_ id: String) async { await sectionUnfiling[id]?.value } @@ -349,7 +349,7 @@ extension FleetStore { file(groupKey: group.id, in: sectionID) } - /// By its list ID (`FleetGroup.id`), for group chats Bots mode shows from the gateway in use. + /// By its list ID (`FleetGroup.id`), for group chats the Bots view shows from the gateway in use. func file(groupKey: String, in sectionID: String?) { let section = section(id: sectionID)?.id guard groupSectionIDs[groupKey] != section else { return } @@ -357,7 +357,7 @@ extension FleetStore { saveSections() } - /// Pinning a group chat puts it on top of Bots mode's home; unpinning takes it off. + /// Pinning a group chat puts it on top of the Bots view; unpinning takes it off. func setPinned(groupKey: String, _ pinned: Bool) { guard pinnedGroupIDs.contains(groupKey) != pinned else { return } if pinned { pinnedGroupIDs.append(groupKey) } else { pinnedGroupIDs.removeAll { $0 == groupKey } } @@ -365,7 +365,7 @@ extension FleetStore { saveSections() } - /// Hiding only changes Bots mode's home: the group chat keeps working, and search's filter shows it. + /// Hiding only changes the Bots view: the group chat keeps working, and search's filter shows it. func setHidden(groupKey: String, _ hidden: Bool) { guard hiddenGroupIDs.contains(groupKey) != hidden else { return } if hidden { hiddenGroupIDs.append(groupKey) } else { hiddenGroupIDs.removeAll { $0 == groupKey } } @@ -435,7 +435,7 @@ extension FleetStore { } /// Rebuilds sections other devices made from what their members carry: every host's copies, - /// and `live` (the gateway in use's own agents, which Bots mode reads without these copies). + /// and `live` (the gateway in use's own agents, which the Bots view reads without these copies). func adoptSections(adding live: [AgentListPlacement] = []) { let placements = hosts.flatMap { snapshots[$0.id]?.agents ?? [] }.compactMap(\.placement) + live let adopted = FleetSectioning.adopt(sections, placements: placements, @@ -450,7 +450,7 @@ extension FleetStore { struct SavedSections: Codable { var sections: [FleetSection] var groups: [String: String] - /// Nil in files saved before Bots mode pinned and hid group chats. + /// Nil in files saved before the Bots view pinned and hid group chats. var pinnedGroups: [String]? = nil var hiddenGroups: [String]? = nil } diff --git a/Bighelp/Fleet/FleetSettingsView.swift b/Bighelp/Fleet/FleetSettingsView.swift index c66b2c4b..65035485 100644 --- a/Bighelp/Fleet/FleetSettingsView.swift +++ b/Bighelp/Fleet/FleetSettingsView.swift @@ -2,12 +2,9 @@ import SwiftUI /// Settings › Your computers › Update every computer, with every computer shown: update Hermes, /// update the bighelp plugin and restart messaging everywhere at once, or on one computer from its -/// own row, each with its own live status. From the all-hosts view, this app's Appearance and Chat -/// are here too. +/// own row, each with its own live status. struct FleetSettingsView: View { let store: FleetMaintenanceStore - /// This app's own pages (Appearance, Chat), the same ones Settings opens. - var appPage: ((SettingsMenuSection) -> AnyView)? @State private var confirmation: Confirmation? private enum Confirmation: Identifiable { @@ -35,7 +32,7 @@ struct FleetSettingsView: View { hermesSection pluginSection gatewaySection - if let appPage { appSection(appPage) } + } .listStyle(.insetGrouped) .bighelpFormSurface() @@ -58,31 +55,6 @@ struct FleetSettingsView: View { // MARK: Sections - /// Appearance and Chat apply to bighelp on every host, so they're here too. - private func appSection(_ page: @escaping (SettingsMenuSection) -> AnyView) -> some View { - Section { - ForEach([SettingsMenuSection.appearance, .chat]) { section in - NavigationLink { page(section) } label: { - HStack(spacing: BighelpTokens.space12) { - BighelpIconTile(systemName: section == .appearance ? "paintpalette.fill" : "bubble.left.and.bubble.right.fill") - VStack(alignment: .leading, spacing: 2) { - Text(section.title) - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(theme.primaryText) - Text(section.detail) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } - } - .frame(minHeight: BighelpTokens.hitTarget) - } - .accessibilityIdentifier("fleet.settings.app.\(section.rawValue)") - } - } header: { - Text("This app") - } - } - private var hermesSection: some View { Section { let count = store.hermesCandidates.count diff --git a/Bighelp/Fleet/FleetStore.swift b/Bighelp/Fleet/FleetStore.swift index 3f44d470..35e8d255 100644 --- a/Bighelp/Fleet/FleetStore.swift +++ b/Bighelp/Fleet/FleetStore.swift @@ -95,7 +95,7 @@ final class FleetStore { var sections: [FleetSection] = [] /// Which section each group chat is in, by its list ID. Kept on this device. var groupSectionIDs: [String: String] = [:] - /// Group chats pinned on Bots mode's home, and ones hidden from it, by list ID. Hermes keeps + /// Group chats pinned on the Bots view, and ones hidden from it, by list ID. Hermes keeps /// neither for group chats, so the app does (and the computers, `bots.layout`). var pinnedGroupIDs: [String] = [] var hiddenGroupIDs: [String] = [] @@ -319,41 +319,6 @@ final class FleetStore { .sorted { $0.updatedAt > $1.updatedAt } } - /// The chats whose title or preview has the search text. An empty search keeps them all. - func chats(on hostID: UUID? = nil, matching query: String) -> [FleetChat] { - let query = query.trimmingCharacters(in: .whitespacesAndNewlines) - guard !query.isEmpty else { return chats(on: hostID) } - return chats(on: hostID).filter { - $0.title.localizedCaseInsensitiveContains(query) || $0.preview.localizedCaseInsensitiveContains(query) - } - } - - /// All sessions' list: the search and filters on top of one computer or all of them. - func chats(on hostID: UUID? = nil, matching query: String, filter: FleetChatsFilter) -> [FleetChat] { - chats(on: hostID, matching: query).filter { chat in - (filter.agentID.map { $0 == FleetID.make(chat.hostID, chat.profileID) } ?? true) - && (filter.origin.map { $0 == SessionOrigin.label(chat.origin) } ?? true) - && filter.app.includes(source: chat.origin) - } - } - - /// Chats still in Codex or Claude Code on the computers read, newest first. - /// The selected computer's come from its live connection instead (Sessions). - func otherAppChats(on hostID: UUID? = nil, matching query: String = "", - app: SessionAppFilter = .all) -> [FleetOtherAppChat] { - let query = query.trimmingCharacters(in: .whitespacesAndNewlines) - return hosts.filter { (hostID == nil || $0.id == hostID) && $0.id != selectedHostID } - .flatMap { snapshots[$0.id]?.otherAppChats ?? [] } - .filter { app.showsOtherAppChats && app.includes(source: $0.item.source) } - .filter { query.isEmpty || $0.item.title.localizedCaseInsensitiveContains(query) } - .sorted { ($0.item.modifiedAt ?? .distantPast) > ($1.item.modifiedAt ?? .distantPast) } - } - - /// Where the listed chats started, by name, for All sessions' Started in filter. - func origins(on hostID: UUID? = nil) -> [String] { - Array(Set(chats(on: hostID).compactMap { SessionOrigin.label($0.origin) })).sorted() - } - /// Every scheduled task, the next to run first. func tasks(on hostID: UUID? = nil, query: String = "") -> [FleetTask] { let query = query.trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/Bighelp/Fleet/FleetViews.swift b/Bighelp/Fleet/FleetViews.swift index 4e81ff59..b841747e 100644 --- a/Bighelp/Fleet/FleetViews.swift +++ b/Bighelp/Fleet/FleetViews.swift @@ -18,796 +18,6 @@ struct FleetHostTag: View { @BighelpThemeReader private var theme } -extension FleetActivity { - var liveState: AgentLiveState { - switch self { - case .working: .thinking - case .waiting: .nudge - } - } -} - -/// Filter chips: all hosts, or one. A host that couldn't be read says so. -struct FleetHostFilter: View { - let fleet: FleetStore - @Binding var selection: UUID? - - var body: some View { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: BighelpTokens.space8) { - chip("All hosts", isOn: selection == nil, id: "fleet.filter.all") { selection = nil } - ForEach(fleet.hosts) { host in - chip(host.name, isOn: selection == host.id, - status: HostConnectionStatus(fleet: fleet.statuses[host.id], hostName: host.name), - id: "fleet.filter.\(host.name)") { selection = host.id } - } - } - .padding(.horizontal, BighelpTokens.space16) - } - } - - /// A host out of reach shows it; one that's loading or reachable stays plain. - private func chip(_ title: String, isOn: Bool, status: HostConnectionStatus? = nil, id: String, - action: @escaping () -> Void) -> some View { - Button(action: action) { - HStack(spacing: 5) { - if let status, status.phase == .disconnected { - BighelpConnectionIndicator(phase: status.phase, tint: isOn ? theme.actionForeground : nil) - } - Text(title).lineLimit(1) - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(isOn ? theme.actionForeground : theme.primaryText) - .padding(.horizontal, BighelpTokens.space12) - .frame(minHeight: 34) - .background(isOn ? theme.action : theme.surface, in: .capsule) - .contentShape(.capsule) - } - .buttonStyle(.plain) - .accessibilityAddTraits(isOn ? .isSelected : []) - .accessibilityIdentifier(id) - } - - @BighelpThemeReader private var theme -} - -/// One agent: its picture (with what it's doing), name, host, and its latest chat. -struct FleetAgentRow: View { - let agent: FleetAgent - let fleet: FleetStore - - var body: some View { - let latest = fleet.latestChat(for: agent) - HStack(spacing: BighelpTokens.space12) { - AvatarView(stableID: agent.profileID, displayName: agent.name, - imageURL: fleet.avatars.url(for: agent.avatarFile), size: SessionRow.avatarSize, - state: agent.activity?.liveState) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space8) { - Text(agent.name) - .font(.bighelp(.callout).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - if fleet.showsHostNames { FleetHostTag(name: fleet.hostName(agent.hostID)) } - Spacer(minLength: BighelpTokens.space4) - if let latest { - Text(SessionRow.compactTimestamp(latest.updatedAt)) - .font(.bighelp(.footnote)) - .monospacedDigit() - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - .layoutPriority(1) - } - } - if !agent.role.isEmpty { - Text(agent.role) - .font(.bighelp(.footnote).weight(.medium)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - } - Text(subtitle(latest)) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - } - } - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) - .contentShape(.rect) - .accessibilityElement(children: .combine) - } - - private func subtitle(_ latest: FleetChat?) -> String { - if let activity = agent.activity { return activity.liveState.label } - if let latest { - let preview = SessionPreviewText.plain(latest.preview) - return preview.isEmpty ? latest.title : preview - } - return "Start a chat" - } - - @BighelpThemeReader private var theme -} - -/// All agents on all hosts: pick one and start working with it. -struct FleetHomeView: View { - let fleet: FleetStore - let onOpen: (FleetAgent) -> Void - /// None while the selected host is still connecting. - var onNewChat: (() -> Void)? = nil - /// Pins or unpins an agent on its own host. - var onSetPinned: ((FleetAgent, Bool) -> Void)? = nil - /// Opens, renames or deletes a group chat. None hides group chats' actions. - var onGroupAction: ((FleetGroup, FleetGroupAction) -> Void)? = nil - /// The agent's routines: add, pause, resume or delete them there. - var onOpenRoutines: ((FleetAgent) -> Void)? = nil - /// New agent: asks which computer first. - var onNewAgent: (() -> Void)? = nil - /// Opens one of the chats running now, on its computer. None hides Active Sessions. - var onOpenChat: ((FleetChat) -> Void)? = nil - /// The computer every all-hosts list is narrowed to; nil shows every computer. - @Binding var hostFilter: UUID? - /// Hidden agents show, dimmed, so they can be shown again. For this visit only. - @State private var showsHidden = false - @State private var namePrompt: FleetNamePrompt? - @State private var deletingGroup: FleetGroup? - @State private var deletedSection: FleetSectionDeletion? - /// A pinned agent held and let go, where its menu can't open (visionOS, - /// iOS before 17.4): its actions. - @State private var managing: FleetAgent? - @State private var search = "" - @State private var isArrangingPinned = false - - var body: some View { - let pinned = pinnedAgents - let listed = listedAgents(excluding: Set(pinned.map(\.id))) - List { - BighelpSearchField(text: $search, prompt: "Search agents", accessibilityLabel: "Search agents", - accessibilityIdentifier: "fleet.search") - .bighelpListSearchRow() - if !pinned.isEmpty { - Section { - pinnedRow(pinned) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - } - if fleet.showsHostNames { - Section { - FleetHostFilter(fleet: fleet, selection: $hostFilter) - .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 4, trailing: 0)) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - } - // As one computer's Chat list has them: the chats running now, on every computer shown. - let active = activeChats - if let onOpenChat, !active.isEmpty { - Section { - ForEach(active) { chat in - Button { onOpenChat(chat) } label: { FleetChatRow(chat: chat, fleet: fleet) } - .buttonStyle(.plain) - .listRowBackground(Color.clear) - .accessibilityIdentifier("fleet.active.\(chat.title)") - } - } header: { - FleetActiveSessionsHeader() - } - } - ForEach(blocks(listed)) { block in - Section { - ForEach(block.items) { item in itemRow(item) } - } header: { - blockHeader(block) - } - } - Section { - FleetHostNotes(fleet: fleet, hostFilter: hostFilter) - } - } - .listStyle(.plain) - .scrollContentBackground(.hidden) - .scrollDisabled(isArrangingPinned) - // The one main action, where a thumb rests, on the right. - .overlay(alignment: .bottomTrailing) { - if let onNewChat { - RootComposeButton(identifier: "fleet.new-chat", size: 72, action: onNewChat) - .padding(.trailing, BighelpTokens.space20) - .padding(.bottom, BighelpTokens.space12) - } - } - .toolbar { - // Top right, in place of the one-host switch (☰ has that): new agent, sections, hidden agents. - if onGroupAction != nil { - ToolbarItem(placement: .topBarTrailing) { organizeMenu } - } - } - .bighelpRefreshable { - fleet.refresh(force: true) - await fleet.waitForReads() - } - .overlay { - if fleet.agents().isEmpty, fleet.groups().isEmpty, !fleet.hosts.contains(where: { fleet.isReading($0.id) }) { - ContentUnavailableView("No agents yet", systemImage: "person.2", - description: Text("The agents on your hosts show up here.")) - } - } - .task { fleet.refresh() } - .confirmationDialog(managing?.name ?? "", isPresented: Binding( - get: { managing != nil }, set: { if !$0 { managing = nil } }), titleVisibility: .visible) { - if let agent = managing { - Button("Open chat") { onOpen(agent) } - if let onSetPinned { - Button("Unpin") { onSetPinned(agent, false) } - .accessibilityIdentifier("fleet.pinned.unpin") - } - Button("Cancel", role: .cancel) {} - } - } - .modifier(FleetListPrompts(fleet: fleet, namePrompt: $namePrompt, deletingGroup: $deletingGroup, - deletedSection: $deletedSection, onGroupAction: onGroupAction)) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("fleet.home") - } - - /// The chats running now, newest first; a search narrows them like the agents. - private var activeChats: [FleetChat] { - fleet.chats(on: hostFilter, matching: search).filter(\.isActive) - } - - /// Pinned agents up top, like favorites, when nothing is filtered. - private var pinnedAgents: [FleetAgent] { - guard search.isEmpty, hostFilter == nil else { return [] } - return fleet.pinnedAgents().filter { showsHidden || !$0.isHidden } - } - - private func listedAgents(excluding pinned: Set) -> [FleetListItem] { - let query = search.trimmingCharacters(in: .whitespaces) - let agents = fleet.agents(on: hostFilter).filter { agent in - guard !pinned.contains(agent.id), showsHidden || !agent.isHidden else { return false } - guard !query.isEmpty else { return true } - return agent.name.localizedCaseInsensitiveContains(query) - || agent.role.localizedCaseInsensitiveContains(query) - || fleet.hostName(agent.hostID).localizedCaseInsensitiveContains(query) - } - guard onGroupAction != nil else { return agents.map(FleetListItem.agent) } - let groups = fleet.groups(on: hostFilter).filter { group in - query.isEmpty || group.name.localizedCaseInsensitiveContains(query) - || group.memberNames.contains { $0.localizedCaseInsensitiveContains(query) } - || fleet.hostName(group.hostID).localizedCaseInsensitiveContains(query) - } - return agents.map(FleetListItem.agent) + groups.map(FleetListItem.group) - } - - /// Sections in the person's order, then everything not in one. While - /// searching, empty sections step aside. - private func blocks(_ items: [FleetListItem]) -> [FleetSectionBlock] { - let all = FleetSectioning.blocks(items, sections: fleet.sections, groupSections: fleet.groupSectionIDs) - guard search.isEmpty else { return all.filter { !$0.items.isEmpty } } - return all - } - - @ViewBuilder - private func blockHeader(_ block: FleetSectionBlock) -> some View { - if let section = block.section { - let index = fleet.sections.firstIndex(of: section) ?? 0 - FleetSectionHeader(title: section.name, count: block.items.count, - onRename: { namePrompt = .renameSection(section) }, - onDelete: { deletedSection = fleet.deleteSection(section.id) }, - onMoveUp: index > 0 ? { fleet.moveSection(section.id, by: -1) } : nil, - onMoveDown: index < fleet.sections.count - 1 ? { fleet.moveSection(section.id, by: 1) } : nil) - } else if !fleet.sections.isEmpty, !block.items.isEmpty { - FleetSectionHeader(title: "Not in a section", count: block.items.count) - } - } - - /// New agent, new section, and showing hidden agents. New group chat is in New chat. - private var organizeMenu: some View { - Menu { - if let onNewAgent { - Button("New agent", systemImage: "person.badge.plus", action: onNewAgent) - .accessibilityIdentifier("fleet.organize.new-agent") - } - Button("New section", systemImage: "folder.badge.plus") { namePrompt = .newSection(filing: nil) } - .accessibilityIdentifier("fleet.organize.new-section") - let hidden = fleet.hiddenAgentCount - if hidden > 0 || showsHidden { - Toggle(isOn: $showsHidden) { - Label("Show hidden agents (\(hidden))", systemImage: "eye") - } - .accessibilityIdentifier("fleet.organize.show-hidden") - } - } label: { - // Plus: it adds (an agent, a section), and it isn't New chat's compose button. - Image(systemName: "plus").bighelpToolbarIcon() - } - .bighelpIconLabel("Add") - .accessibilityHint("New agent, new section, hidden agents.") - .accessibilityIdentifier("fleet.organize") - } - - @ViewBuilder - private func itemRow(_ item: FleetListItem) -> some View { - switch item { - case .agent(let agent): agentRow(agent) - case .group(let group): groupRow(group) - } - } - - private func agentRow(_ agent: FleetAgent) -> some View { - Button { onOpen(agent) } label: { - FleetAgentRow(agent: agent, fleet: fleet) - .opacity(agent.isHidden ? 0.45 : 1) - } - .buttonStyle(.plain) - .listRowBackground(Color.clear) - .contextMenu { TileMenuContent(items: agentMenu(agent)) } - .accessibilityValue(agent.isHidden ? "Hidden" : "") - .accessibilityIdentifier("fleet.agent.\(agent.name)") - } - - /// An agent's long-press menu, the same for its row and its pinned tile. - private func agentMenu(_ agent: FleetAgent) -> [TileMenuItem] { - var items: [TileMenuItem] = [] - if let onSetPinned { - items.append(TileMenuItem(title: agent.isPinned ? "Unpin" : "Pin", - systemImage: agent.isPinned ? "pin.slash" : "pin", - identifier: "fleet.agent.\(agent.isPinned ? "unpin" : "pin")") { - onSetPinned(agent, !agent.isPinned) - }) - } - if let onOpenRoutines { - let count = fleet.tasks(on: agent.hostID).filter { $0.profileID == agent.profileID }.count - items.append(TileMenuItem(title: count == 0 ? "Routines" : "Routines (\(count))", - systemImage: "clock.arrow.circlepath", identifier: "fleet.agent.routines") { - onOpenRoutines(agent) - }) - } - if onGroupAction != nil { - items.append(sectionMenu(current: fleet.section(of: agent), item: .agent(agent)) { id in - Task { try? await fleet.file(agent, in: id) } - }) - items.append(TileMenuItem(title: agent.isHidden ? "Show in list" : "Hide from list", - systemImage: agent.isHidden ? "eye" : "eye.slash", - identifier: "fleet.agent.\(agent.isHidden ? "unhide" : "hide")") { - Task { try? await fleet.setHidden(agent, !agent.isHidden) } - }) - } - return items - } - - private func groupRow(_ group: FleetGroup) -> some View { - Button { onGroupAction?(group, .open) } label: { FleetGroupRow(group: group, fleet: fleet) } - .buttonStyle(.plain) - .listRowBackground(Color.clear) - .contextMenu { - Button("Open chat", systemImage: "bubble.left.and.bubble.right") { onGroupAction?(group, .open) } - TileMenuContent(items: [sectionMenu(current: fleet.section(of: group), item: .group(group)) { - fleet.file(group, in: $0) - }]) - if group.hostID == fleet.selectedHostID { - Button("Rename", systemImage: "pencil") { namePrompt = .renameGroup(group) } - .disabled(!group.canRename) - .accessibilityIdentifier("fleet.group.rename") - Button("Delete", systemImage: "trash", role: .destructive) { deletingGroup = group } - .disabled(!group.canDelete) - .accessibilityIdentifier("fleet.group.delete") - } - } - .accessibilityIdentifier("fleet.group.\(group.name)") - } - - /// Move to a section, a new one, or out of the one it's in. - private func sectionMenu(current: FleetSection?, item: FleetListItem, - file: @escaping (String?) -> Void) -> TileMenuItem { - var choices = fleet.sections.map { section in - TileMenuItem(title: section.name, systemImage: section.id == current?.id ? "checkmark" : "folder", - isEnabled: section.id != current?.id) { file(section.id) } - } - choices.append(TileMenuItem(title: "New section", systemImage: "folder.badge.plus", - identifier: "fleet.move.new-section") { namePrompt = .newSection(filing: item) }) - if current != nil { - choices.append(TileMenuItem(title: "Remove from section", systemImage: "folder.badge.minus", - identifier: "fleet.move.remove") { file(nil) }) - } - return TileMenuItem(title: "Move to section", systemImage: "folder", children: choices, identifier: "fleet.move") - } - - /// Big pictures with the name and role, simple like a contact grid. Touch - /// and hold one to drag it into a new place. - private func pinnedRow(_ agents: [FleetAgent]) -> some View { - PinnedArrangeGrid( - items: agents, - columns: PinnedAgentsLayout.columns, - canReorder: true, space: "fleet.pinned", open: onOpen, manage: { managing = $0 }, - menu: { agentMenu($0) }, reorder: { fleet.reorderPinned($0) }, isArranging: $isArrangingPinned, - identifier: { "fleet.pinned.\($0.name)" }, - tile: { agent, lifted in pinnedTile(agent, lifted: lifted) }, - trailing: { EmptyView() } - ) - .padding(.horizontal, BighelpTokens.space16) - .padding(.vertical, BighelpTokens.space8) - } - - private func pinnedTile(_ agent: FleetAgent, lifted: Bool) -> some View { - PinnedAgentTileLabel(name: agent.name, isLifted: lifted) { - AvatarView(stableID: agent.profileID, displayName: agent.name, - imageURL: fleet.avatars.url(for: agent.avatarFile), size: PinnedAgentsLayout.avatarSize, - state: agent.activity?.liveState) - } detail: { - if let role = AgentFeaturedTile.roleLine(agent.role) { Text(role) } - } - .accessibilityElement(children: .combine) - // Once, with its computer like the rows say ("on Desk Hermes"); the picture also named it. - .accessibilityLabel(pinnedLabel(agent)) - } - - private func pinnedLabel(_ agent: FleetAgent) -> String { - let parts = [agent.name, AgentFeaturedTile.roleLine(agent.role), - fleet.showsHostNames ? "on \(fleet.hostName(agent.hostID))" : nil] - return parts.compactMap { $0 }.joined(separator: ", ") - } - - @BighelpThemeReader private var theme -} - -/// The list stays up while a tapped agent's host connects, with a note. -struct FleetConnectingView: View { - let fleet: FleetStore - @Binding var hostFilter: UUID? - let onOpen: (FleetAgent) -> Void - /// False once connecting stopped without a connection. - let isConnecting: Bool - let retry: () -> Void - /// Failure shows only after an attempt; a switch starts connecting a moment later. - @State private var hasTried = false - - var body: some View { - let requiresAuthentication = registry?.selectedWorkspace?.requiresAuthentication == true - let status = requiresAuthentication ? HostConnectionStatus(.disconnected, "Sign in again") - : HostConnectionStatus(fleetSwitchTo: fleet.selectedHostID.map(fleet.hostName) ?? "your host", - isConnecting: isConnecting, hasTried: hasTried) - FleetHomeView(fleet: fleet, onOpen: onOpen, hostFilter: $hostFilter) - .onChange(of: isConnecting, initial: true) { _, connecting in if connecting { hasTried = true } } - .onChange(of: fleet.selectedHostID) { _, _ in hasTried = isConnecting } - .safeAreaInset(edge: .top, spacing: 0) { - // The list shows what each host had last time; only a failure says anything. - if status.phase == .disconnected { - HStack(spacing: BighelpTokens.space8) { - BighelpConnectionIndicator(phase: status.phase) - Text(status.label) - .contentTransition(.opacity) - if requiresAuthentication, let host = registry?.selectedHost { - Button("Sign in again") { registry?.beginAuthentication(for: host) } - .buttonStyle(.borderless) - .accessibilityIdentifier("fleet.sign-in-again") - } else { - Button("Try again", action: retry) - .buttonStyle(.borderless) - } - } - .font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .frame(maxWidth: .infinity, minHeight: 44) - .background(theme.surface) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("fleet.connecting") - } - } - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .toolbar { BighelpHostsToolbarLink(registry: registry) } - } - - @Environment(\.bighelpHostRegistry) private var registry - @BighelpThemeReader private var theme -} - -/// Hosts still loading or out of reach, at the bottom of a list. -struct FleetHostNotes: View { - let fleet: FleetStore - let hostFilter: UUID? - - var body: some View { - ForEach(fleet.hosts.filter { hostFilter == nil || $0.id == hostFilter }) { host in - if let status = HostConnectionStatus(fleet: fleet.statuses[host.id], hostName: host.name) { - switch status.phase { - case .disconnected: - HStack(spacing: BighelpTokens.space8) { - BighelpConnectionIndicator(phase: status.phase) - VStack(alignment: .leading, spacing: 2) { - Text(status.label).font(.bighelp(.subheadline).weight(.semibold)) - .foregroundStyle(theme.primaryText) - if let reason = status.detailText { - Text(fleet.snapshots[host.id] == nil ? reason : "\(reason) Showing what it had last time.") - .font(.bighelp(.footnote)).foregroundStyle(theme.secondaryText) - } - } - Spacer(minLength: BighelpTokens.space8) - Button("Try again") { fleet.refresh(force: true) } - .font(.bighelp(.subheadline).weight(.semibold)) - .buttonStyle(.borderless) - } - .listRowBackground(Color.clear) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("fleet.host-note.\(host.name)") - case .connecting where fleet.snapshots[host.id] == nil: - HStack(spacing: BighelpTokens.space8) { - BighelpConnectionIndicator(phase: status.phase) - Text(status.label).font(.bighelp(.subheadline)).foregroundStyle(theme.secondaryText) - } - .listRowBackground(Color.clear) - default: - EmptyView() - } - } - } - } - - @BighelpThemeReader private var theme -} - -/// Every chat on every host, newest first, each tagged with its host and where it started. -/// A computer's chip works on that computer the way one-computer mode does: its own Sessions -/// screen (projects, folders, pins), without leaving all hosts. -struct FleetChatsView: View { - let fleet: FleetStore - @Binding var hostFilter: UUID? - @Binding var filter: FleetChatsFilter - let onOpen: (FleetChat) -> Void - /// The picked computer's own Sessions screen once it's the working computer; nil until then. - var hostSessions: ((UUID) -> AnyView?)? = nil - /// Codex and Claude Code chats on the working computer, through its live connection. - var otherApps: (source: any OtherAppChatsSource, id: String)? = nil - /// Opens a chat still in Codex or Claude Code: on its computer's own Sessions screen. - var onOpenOtherApp: ((FleetOtherAppChat) -> Void)? = nil - /// A chat's long-press Rename and Archive, on whichever computer it's on. - var onChange: ((FleetChat, FleetChatChange) -> Void)? = nil - @State private var search = "" - @State private var renaming: FleetChat? - @State private var renameDraft = "" - @State private var liveOtherApps: OtherAppChatsStore? - @State private var liveOtherAppsID: String? - - var body: some View { - if let hostFilter, let sessions = hostSessions?(hostFilter) { - sessions - .safeAreaInset(edge: .top, spacing: 0) { - if fleet.showsHostNames { - FleetHostFilter(fleet: fleet, selection: $hostFilter) - .padding(.vertical, BighelpTokens.space4) - .background(BighelpThemeCanvas(theme: theme)) - } - } - } else { - mergedList - } - } - - private var mergedList: some View { - let chats = visibleChats - let otherAppChats = visibleOtherAppChats - return List { - BighelpSearchField(text: $search, prompt: "Search sessions", accessibilityLabel: "Search sessions", - accessibilityIdentifier: "fleet.sessions.search") - .bighelpListSearchRow() - if fleet.showsHostNames { - FleetHostFilter(fleet: fleet, selection: $hostFilter) - .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 4, trailing: 0)) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - SessionAppFilterBar(selection: $filter.app) - .listRowInsets(EdgeInsets(top: 4, leading: BighelpTokens.space16, bottom: 8, trailing: BighelpTokens.space16)) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - // As on one gateway's list: chats running now on any computer first, under Active Sessions. - let active = chats.filter(\.isActive) - if active.isEmpty { - chatRows(chats) - } else { - Section { - chatRows(active) - } header: { - FleetActiveSessionsHeader() - } - let recent = chats.filter { !$0.isActive } - if !recent.isEmpty { - Section { - chatRows(recent) - } header: { - FleetSectionCaption(title: "Recent") - .accessibilityIdentifier("fleet.sessions.section.recent") - } - } - } - if !otherAppChats.isEmpty { - Section { - ForEach(otherAppChats) { chat in - Button { onOpenOtherApp?(chat) } label: { - OtherAppChatRow(item: chat.item, - hostName: fleet.showsHostNames ? fleet.hostName(chat.hostID) : nil) - } - .buttonStyle(.plain) - .disabled(onOpenOtherApp == nil) - .listRowBackground(Color.clear) - .accessibilityIdentifier("fleet.other-app.\(chat.item.title)") - } - } header: { - Text(otherAppsTitle) - .font(.bighelp(.caption).weight(.semibold)) - .foregroundStyle(theme.secondaryText) - .textCase(nil) - .accessibilityIdentifier("fleet.other-apps") - } - } - FleetHostNotes(fleet: fleet, hostFilter: hostFilter) - } - .listStyle(.plain) - .scrollContentBackground(.hidden) - .dismissesKeyboardOnScroll(true, immediately: true) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .toolbar { ToolbarItem(placement: .topBarTrailing) { filterMenu } } - .bighelpRefreshable { - fleet.refresh(force: true) - await fleet.waitForReads() - } - .overlay { - Group { - if chats.isEmpty, otherAppChats.isEmpty { - if !search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - ContentUnavailableView.search(text: search) - } else if filter.isActive || filter.app != .all { - ContentUnavailableView(filter.app.emptyTitle, systemImage: "line.3.horizontal.decrease.circle", - description: Text("Try a different agent, place or app.")) - } else { - ContentUnavailableView("No sessions yet", systemImage: "bubble.left.and.bubble.right") - } - } - } - // A message, not a control: the search field at the top stays usable through it. - .allowsHitTesting(false) - } - .task { fleet.refresh() } - .task(id: LiveOtherAppsKey(id: otherApps?.id, app: filter.app)) { await loadLiveOtherApps() } - .alert("Rename chat", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } }), - presenting: renaming) { chat in - TextField("Session name", text: $renameDraft) - .accessibilityIdentifier("fleet.chat.rename-field") - Button("Cancel", role: .cancel) {} - Button("Save") { onChange?(chat, .rename(renameDraft)) } - .accessibilityIdentifier("fleet.chat.rename-save") - } message: { chat in - Text(chat.title == "Bot Chat" - ? "Renamed, this becomes a regular chat, and tapping the agent starts a new Bot Chat." - : "Enter a name up to \(SessionTitleRules.maximumLength) characters.") - } - .navigationTitle("All sessions") - .accessibilityIdentifier("fleet.chats") - } - - private var visibleChats: [FleetChat] { fleet.chats(on: hostFilter, matching: search, filter: filter) } - - private func chatRows(_ chats: [FleetChat]) -> some View { - ForEach(chats) { chat in - Button { onOpen(chat) } label: { FleetChatRow(chat: chat, fleet: fleet) } - .buttonStyle(.plain) - .contextMenu { chatActions(chat) } - .listRowBackground(Color.clear) - .accessibilityIdentifier("fleet.chat.\(chat.title)") - } - } - - @ViewBuilder - private func chatActions(_ chat: FleetChat) -> some View { - if let onChange { - Button("Rename", systemImage: "pencil") { - renameDraft = chat.title - renaming = chat - } - .accessibilityIdentifier("fleet.chat.rename") - Button("Archive", systemImage: "archivebox") { onChange(chat, .archive) } - .accessibilityIdentifier("fleet.chat.archive") - } - } - - /// Chats still in Codex or Claude Code: the working computer's live, the others' as last read. - private var visibleOtherAppChats: [FleetOtherAppChat] { - guard filter.app.showsOtherAppChats, filter.agentID == nil, filter.origin == nil else { return [] } - let query = search.trimmingCharacters(in: .whitespacesAndNewlines) - var live: [FleetOtherAppChat] = [] - if let selected = fleet.selectedHostID, hostFilter == nil || hostFilter == selected, let store = liveOtherApps { - live = store.items - .filter { filter.app.includes(source: $0.source) } - .filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) } - .map { FleetOtherAppChat(hostID: selected, item: $0) } - } - return (live + fleet.otherAppChats(on: hostFilter, matching: query, app: filter.app)) - .sorted { ($0.item.modifiedAt ?? .distantPast) > ($1.item.modifiedAt ?? .distantPast) } - } - - private var otherAppsTitle: String { - switch filter.app { - case .codex: "In Codex" - case .claudeCode: "In Claude Code" - case .all, .hermes: "In Codex and Claude Code" - } - } - - private func loadLiveOtherApps() async { - guard let otherApps else { - liveOtherApps = nil - liveOtherAppsID = nil - return - } - let store: OtherAppChatsStore - if let current = liveOtherApps, liveOtherAppsID == otherApps.id { - store = current - } else { - store = OtherAppChatsStore(source: otherApps.source) - liveOtherApps = store - liveOtherAppsID = otherApps.id - } - guard filter.app.showsOtherAppChats else { return } - await store.load(app: filter.app.foreignSource) - } - - /// The same filters as one computer's Sessions, for what every computer reports. - /// Projects belong to one computer: pick its chip to group or filter by project. - private var filterMenu: some View { - let agents = fleet.agents(on: hostFilter).sorted { - $0.name.localizedStandardCompare($1.name) == .orderedAscending - } - let origins = fleet.origins(on: hostFilter) - // Each filter is its own labeled submenu that shows its current choice. - return Menu { - Section("Filter by") { - Picker(selection: $filter.agentID) { - Text("All agents").tag(String?.none) - ForEach(agents) { agent in - Text(fleet.showsHostNames && hostFilter == nil ? "\(agent.name) · \(fleet.hostName(agent.hostID))" : agent.name) - .tag(Optional(agent.id)) - } - } label: { - Label("Agent", systemImage: "person.crop.circle") - Text(filter.agentID.flatMap { id in agents.first { $0.id == id }?.name } ?? "All agents") - } - .pickerStyle(.menu) - .accessibilityIdentifier("fleet.chats.filter.agent") - if !origins.isEmpty { - Picker(selection: $filter.origin) { - Text("Everywhere").tag(String?.none) - ForEach(origins, id: \.self) { Text($0).tag(Optional($0)) } - } label: { - Label("Started in", systemImage: "arrow.down.app") - Text(filter.origin ?? "Everywhere") - } - .pickerStyle(.menu) - .accessibilityIdentifier("fleet.chats.filter.origin") - } - } - if filter.isActive { - Section { - Button("Clear Filters", systemImage: "arrow.counterclockwise") { - filter = FleetChatsFilter(app: filter.app) - } - .accessibilityIdentifier("fleet.chats.filters.clear") - } - } - } label: { - Image(systemName: filter.isActive - ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle") - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .accessibilityLabel("Filter chats") - .accessibilityIdentifier("fleet.chats.filters") - } - - @BighelpThemeReader private var theme -} - -/// A chat in the all-hosts lists: who it's with, its host, title and when. /// A section caption as the Sessions list draws them: small, bold, spaced capitals. struct FleetSectionCaption: View { let title: LocalizedStringKey @@ -823,371 +33,3 @@ struct FleetSectionCaption: View { .accessibilityAddTraits(.isHeader) } } - -/// "Active Sessions" with the working loader, as on one computer's Sessions list. -struct FleetActiveSessionsHeader: View { - @BighelpThemeReader private var theme - - var body: some View { - HStack(spacing: BighelpTokens.space8) { - FleetSectionCaption(title: "Active Sessions") - BighelpThinkingOrb(scenario: .working, scale: .inline, tint: theme.action) - .accessibilityHidden(true) - } - .accessibilityElement(children: .combine) - .accessibilityIdentifier("fleet.sessions.section.active") - } -} - -struct FleetChatRow: View { - let chat: FleetChat - let fleet: FleetStore - var compact = false - - var body: some View { - let agent = fleet.agent(hostID: chat.hostID, profileID: chat.profileID) - HStack(spacing: BighelpTokens.space12) { - AvatarView(stableID: chat.profileID, displayName: agent?.name ?? "Agent", - imageURL: fleet.avatars.url(for: agent?.avatarFile), size: compact ? 30 : SessionRow.avatarSize, - state: chat.isActive ? .thinking : nil) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space8) { - Text(chat.title.isEmpty ? "New chat" : chat.title) - .font(compact ? .body : .callout.weight(.semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - Spacer(minLength: BighelpTokens.space4) - Text(SessionRow.compactTimestamp(chat.updatedAt)) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - .layoutPriority(1) - } - HStack(spacing: 6) { - Text(agent?.name ?? "Agent") - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .lineLimit(1) - if fleet.showsHostNames { FleetHostTag(name: fleet.hostName(chat.hostID)) } - if !compact { SessionOriginTag(source: chat.origin, size: 11) } - } - } - } - .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) - .contentShape(.rect) - .accessibilityElement(children: .combine) - } - - @BighelpThemeReader private var theme -} - -/// Scheduled tasks on every host, each tagged with its host. -struct FleetTasksView: View { - let fleet: FleetStore - @Binding var hostFilter: UUID? - let onOpen: (FleetTask) -> Void - @State private var searchQuery = "" - - private var shownTasks: [FleetTask] { fleet.tasks(on: hostFilter, query: searchQuery) } - - var body: some View { - List { - BighelpSearchField(text: $searchQuery, prompt: "Search tasks", accessibilityLabel: "Search tasks", - accessibilityIdentifier: "scheduled-tasks.search") - .bighelpListSearchRow() - if fleet.showsHostNames { - FleetHostFilter(fleet: fleet, selection: $hostFilter) - .listRowInsets(EdgeInsets(top: 4, leading: 0, bottom: 4, trailing: 0)) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - ForEach(shownTasks) { task in - Button { onOpen(task) } label: { row(task) } - .buttonStyle(.plain) - .listRowBackground(Color.clear) - .accessibilityIdentifier("fleet.task.\(task.name)") - } - FleetHostNotes(fleet: fleet, hostFilter: hostFilter) - if shownTasks.isEmpty { - ContentUnavailableView(searchQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - ? "No scheduled tasks" : "No matching tasks", - systemImage: "calendar.badge.clock", - description: Text(searchQuery.isEmpty - ? "Ask an agent to check in or remind you, and it shows up here." - : "Try another search or computer.")) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - } - .listStyle(.plain) - .scrollContentBackground(.hidden) - .bighelpRefreshable { - fleet.refresh(force: true) - await fleet.waitForReads() - } - .task { fleet.refresh() } - .accessibilityIdentifier("fleet.tasks") - } - - private func row(_ task: FleetTask) -> some View { - let agent = fleet.agent(hostID: task.hostID, profileID: task.profileID) - return HStack(spacing: BighelpTokens.space12) { - AvatarView(stableID: task.profileID, displayName: agent?.name ?? "Agent", - imageURL: fleet.avatars.url(for: agent?.avatarFile), size: 44, - state: task.status == .failed ? .nudge : nil) - .accessibilityHidden(true) - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: BighelpTokens.space8) { - Text(task.name) - .font(.bighelp(.callout).weight(.semibold)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - if fleet.showsHostNames { FleetHostTag(name: fleet.hostName(task.hostID)) } - } - Text([agent?.name, task.schedule].compactMap { $0 }.joined(separator: " · ")) - .font(.bighelp(.subheadline)) - .foregroundStyle(theme.secondaryText) - .lineLimit(2) - Text(ScheduledTaskCopy.shortNextRun(status: task.status, nextRun: task.nextRun)) - .font(.bighelp(.footnote)) - .foregroundStyle(task.status == .failed ? theme.danger : theme.tertiaryText) - .lineLimit(1) - } - .frame(maxWidth: .infinity, alignment: .leading) - } - .padding(.vertical, BighelpTokens.space4) - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - .accessibilityElement(children: .combine) - } - - @BighelpThemeReader private var theme -} - -/// Asks which host a host-only screen (Settings, Projects…) should open for. -struct FleetHostPicker: View { - let fleet: FleetStore - let destination: FleetDestination - var appPage: ((SettingsMenuSection) -> AnyView)? - let onPick: (UUID) -> Void - @Environment(\.dismiss) private var dismiss - @State private var detent: PresentationDetent = .medium - - var body: some View { - NavigationStack { - List { - if destination == .settings, let maintenance = fleet.maintenance() { - Section { - NavigationLink { - FleetSettingsView(store: maintenance, appPage: appPage) - .onAppear { detent = .large } - } label: { - HStack(spacing: BighelpTokens.space12) { - BighelpIconTile(systemName: "square.stack.3d.up.fill") - VStack(alignment: .leading, spacing: 2) { - Text("Update every computer") - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(theme.primaryText) - Text("Together or one by one") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } - } - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .accessibilityIdentifier("fleet.gate.fleet-settings") - } - } - Section { - ForEach(fleet.hosts) { host in - Button { onPick(host.id) } label: { - HStack(spacing: BighelpTokens.space12) { - BighelpIconTile(systemName: "desktopcomputer") - VStack(alignment: .leading, spacing: 2) { - Text(host.name) - .font(.bighelp(.body).weight(.semibold)) - .foregroundStyle(theme.primaryText) - Text(detail(host)) - .font(.bighelp(.footnote)) - .foregroundStyle(theme.secondaryText) - } - Spacer(minLength: BighelpTokens.space8) - Image(systemName: "chevron.right") - .font(.bighelp(.footnote).weight(.semibold)) - .foregroundStyle(theme.tertiaryText) - } - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityIdentifier("fleet.gate.host.\(host.name)") - } - } footer: { - Text("\(destination.title) belongs to one host. Pick which one.") - } - } - .navigationTitle(destination.title) - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { dismiss() } - .keyboardShortcut(.cancelAction) - .accessibilityIdentifier("fleet.gate.cancel") - .bighelpToolbarText() - } - } - } - .presentationDetents([.medium, .large], selection: $detent) - .presentationDragIndicator(.visible) - .bighelpSheetSize(.standard) - .accessibilityIdentifier("fleet.gate") - } - - private func detail(_ host: FleetHost) -> String { - let agents = fleet.snapshots[host.id]?.agents.count - let count = agents.map { $0 == 1 ? "1 agent" : "\($0) agents" } - var unreachable: String? - if case .unreachable = fleet.statuses[host.id] { unreachable = "Couldn't reach it just now" } - return [host.isSelected ? "Open now" : nil, count, unreachable].compactMap { $0 }.joined(separator: " · ") - } - - @BighelpThemeReader private var theme -} - -/// New chat in the all-hosts view: pick any agent on any host. Group chat -/// turns it into picking several agents, from any hosts. -struct FleetAgentPicker: View { - let fleet: FleetStore - let onPick: (FleetAgent) -> Void - /// Starts a group chat with the picked agents. None hides Group chat. - var onPickGroup: (([FleetAgent]) -> Void)? = nil - @State private var search = "" - @State private var isPickingGroup = false - /// Picked agents, in the order they were tapped. - @State private var picked: [FleetAgent] = [] - @Environment(\.dismiss) private var dismiss - - var body: some View { - NavigationStack { - List { - Section { - ForEach(agents) { agent in row(agent) } - } header: { - if isPickingGroup { groupHeader } - } - } - .searchable(text: $search, prompt: "Search agents") - .navigationTitle(isPickingGroup ? "New group chat" : "New chat with…") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { dismiss() } - .keyboardShortcut(.cancelAction) - .accessibilityIdentifier("fleet.new-chat.cancel") - .bighelpToolbarText() - } - if let onPickGroup { - ToolbarItem(placement: .confirmationAction) { - if isPickingGroup { - Button("Create chat") { onPickGroup(picked) } - .fontWeight(.semibold) - .disabled(!(2...BotModeRoom.maximumMembers).contains(picked.count)) - .bighelpDefaultAction() - .accessibilityIdentifier("fleet.new-chat.create-group") - .bighelpToolbarText() - } else { - Button("Group chat") { withAnimation(.snappy(duration: 0.2)) { isPickingGroup = true } } - .accessibilityHint("Pick several agents for one chat.") - .accessibilityIdentifier("fleet.new-chat.group") - .bighelpToolbarText() - } - } - } - } - } - .presentationDragIndicator(.visible) - .bighelpSheetSize(.standard) - } - - private func row(_ agent: FleetAgent) -> some View { - let isPicked = picked.contains { $0.id == agent.id } - let isAvailable = !isPickingGroup || isPicked || canAdd(agent) - return Button { tap(agent) } label: { - HStack(spacing: BighelpTokens.space12) { - AvatarView(stableID: agent.profileID, displayName: agent.name, - imageURL: fleet.avatars.url(for: agent.avatarFile), size: 40) - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: BighelpTokens.space8) { - Text(agent.name).font(.bighelp(.body).weight(.semibold)).foregroundStyle(theme.primaryText) - if fleet.showsHostNames { FleetHostTag(name: fleet.hostName(agent.hostID)) } - } - if !agent.role.isEmpty { - Text(agent.role).font(.bighelp(.footnote)).foregroundStyle(theme.secondaryText).lineLimit(1) - } - } - Spacer(minLength: 0) - if isPickingGroup { - Image(systemName: isPicked ? "checkmark.circle.fill" : "circle") - .font(.bighelp(.title3)) - .foregroundStyle(isPicked ? theme.action : theme.tertiaryText) - .accessibilityHidden(true) - } - } - .frame(minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - .opacity(isAvailable ? 1 : 0.4) - } - .bighelpPlainButtonStyle() - .disabled(!isAvailable) - .accessibilityValue(isPickingGroup ? (isPicked ? "Selected" : "Not selected") : "") - .accessibilityAddTraits(isPicked ? .isSelected : []) - .accessibilityIdentifier("fleet.new-chat.\(agent.name)") - } - - /// How many are picked, and which computer the group lives on. - private var groupHeader: some View { - VStack(alignment: .leading, spacing: 2) { - Text(picked.count < 2 ? "Pick 2 to \(BotModeRoom.maximumMembers) agents" - : "\(picked.count) of \(BotModeRoom.maximumMembers) picked") - .monospacedDigit() - if fleet.showsHostNames { - Text(picked.first.map { "The group lives on \(fleet.hostName($0.hostID)). Agents on other hosts join it there." } - ?? "Agents can come from any of your hosts.") - } - } - .font(.bighelp(.footnote)) - .textCase(nil) - .foregroundStyle(theme.secondaryText) - .accessibilityElement(children: .combine) - .accessibilityIdentifier("fleet.new-chat.group-note") - } - - /// A group chat holds a few agents at most, from any hosts. - private func canAdd(_ agent: FleetAgent) -> Bool { - picked.count < BotModeRoom.maximumMembers - } - - private func tap(_ agent: FleetAgent) { - guard isPickingGroup else { return onPick(agent) } - if let index = picked.firstIndex(where: { $0.id == agent.id }) { - picked.remove(at: index) - } else if canAdd(agent) { - picked.append(agent) - } - } - - private var agents: [FleetAgent] { - let query = search.trimmingCharacters(in: .whitespaces) - return fleet.agents().filter { query.isEmpty || $0.name.localizedCaseInsensitiveContains(query) } - } - - @BighelpThemeReader private var theme -} - -/// What the working computer's Codex and Claude Code list reads, and the app chosen. -private struct LiveOtherAppsKey: Equatable { - let id: String? - let app: SessionAppFilter -} diff --git a/Bighelp/Fleet/RegistryFleetReader.swift b/Bighelp/Fleet/RegistryFleetReader.swift index 92c08567..27a8411e 100644 --- a/Bighelp/Fleet/RegistryFleetReader.swift +++ b/Bighelp/Fleet/RegistryFleetReader.swift @@ -29,7 +29,7 @@ final class RegistryFleetReader: FleetHostReading { } func canOpen(_ hostID: UUID) -> Bool { registry.hosts.contains { $0.id == hostID } } - /// Saved where that host's Agents screen keeps its pins (its own settings suite). + /// Saved where that host's Bots view keeps its pins (its own settings suite). func setPinned(_ pinned: Bool, hostID: UUID, profileID: String) -> Bool { guard let host = registry.hosts.first(where: { $0.id == hostID }), let scope = registry.workspace(for: host).savedConnection?.workspaceAuthority?.cacheScopeID, @@ -253,21 +253,13 @@ final class RegistryFleetReader: FleetHostReading { isDefault: profile.isDefault, activity: activity[profile.id], placement: profile.placement, botChat: botChats[profile.id].map(FleetBotChat.init), look: profile.look) } - // Codex and Claude Code chats on that computer; an older Hermes can't list them. - let defaultProfile = profiles.first(where: \.isDefault)?.id ?? profiles.first?.id ?? "default" - let otherApps = try? await DirectHermesSessionMaintenanceClient( - rpc: client, http: client, owner: owner, currentOwner: current, - resolveClosableRuntime: { _ in throw HermesSessionMaintenanceError.invalidRequest }, - reconcileClosedRuntime: { _ in throw HermesSessionMaintenanceError.invalidRequest } - ).foreignSessions(profileID: defaultProfile, source: nil, offset: 0, limit: 10) return FleetSnapshot(agents: agents, chats: chats, tasks: tasks.map { FleetTask(hostID: hostID, scheduledTask: $0) }, groups: await groups(hostID, workspace: workspace, owner: owner, profiles: profiles), - refreshedAt: Date(), - otherAppChats: otherApps.map { $0.sessions.map { FleetOtherAppChat(hostID: hostID, item: $0) } }) + refreshedAt: Date()) } - /// Its group chats, for Bots mode's Multi-gateway: the first page, to list and open. A host + /// Its group chats, for Show every computer: the first page, to list and open. A host /// that can't list them has none here. private static func groups(_ hostID: UUID, workspace: DirectHermesWorkspaceClient, owner: WorkspaceOwner, profiles: [AgentProfile]) async -> [FleetGroup] { diff --git a/Bighelp/HTMLApps/DemoHTMLAppsClient.swift b/Bighelp/HTMLApps/DemoHTMLAppsClient.swift index d428a5d8..1ab3afae 100644 --- a/Bighelp/HTMLApps/DemoHTMLAppsClient.swift +++ b/Bighelp/HTMLApps/DemoHTMLAppsClient.swift @@ -1,6 +1,6 @@ import Foundation -/// Demo mode's computer: two sample apps, answering the way the plugin does (docs/HTML_APPS.md › +/// Demo mode's computer: two sample apps and the demo spaces' pages, answering the way the plugin does (docs/HTML_APPS.md › /// Routes), so UI tests and the demo need no host. Made-up numbers only. @MainActor final class DemoHTMLAppsClient: HTMLAppsClient { @@ -25,6 +25,20 @@ final class DemoHTMLAppsClient: HTMLAppsClient { gardenWatchID: App(title: "Garden watch", description: "Soil, temperature and the last watering, from the sensors.", sendsAnswers: false, html: DemoHTMLApps.gardenWatch, data: DemoHTMLApps.gardenData), + // The demo spaces' pages (`DemoSpacesClient`): a panel on Today opens one. + DemoSpacesClient.commutePageID: App(title: "Commute", description: "Drive time to work, from live traffic.", + sendsAnswers: false, html: DemoSpacePages.commute, + data: DemoSpacePages.commuteData), + DemoSpacesClient.gardenPageID: App(title: "Garden", description: "Soil, temperature and the last watering.", + sendsAnswers: false, html: DemoSpacePages.garden, + data: DemoSpacePages.gardenData), + DemoSpacesClient.workoutsPageID: App(title: "Workouts", + description: "This week's training, read from the log each evening.", + sendsAnswers: false, html: DemoSpacePages.workouts, + data: DemoSpacePages.workoutsData), + DemoSpacesClient.spendingPageID: App(title: "Spending", description: "This month's spending against the budget.", + sendsAnswers: false, html: DemoSpacePages.spending, + data: DemoSpacePages.spendingData), ] /// Small, so demo mode and its UI tests load every page in several pieces, as a big page does. var pieceBytes = 1_024 diff --git a/Bighelp/HTMLApps/HTMLAppCardView.swift b/Bighelp/HTMLApps/HTMLAppCardView.swift index d0694afb..8b053f85 100644 --- a/Bighelp/HTMLApps/HTMLAppCardView.swift +++ b/Bighelp/HTMLApps/HTMLAppCardView.swift @@ -80,9 +80,9 @@ struct HTMLAppCardView: View { .onAppear(perform: readAnswered) .bighelpFullScreenCover(isPresented: $isOpen, onDismiss: readAnswered) { if let interactions, let identity { - HTMLAppScreen(app: app, agentID: interactions.scope.profileID) { message in + HTMLAppScreen(app: app, agentID: interactions.scope.profileID, send: { message in try interactions.reply(message, for: identity) - } + }) } } } diff --git a/Bighelp/HTMLApps/HTMLAppNavigationPolicy.swift b/Bighelp/HTMLApps/HTMLAppNavigationPolicy.swift new file mode 100644 index 00000000..d726e620 --- /dev/null +++ b/Bighelp/HTMLApps/HTMLAppNavigationPolicy.swift @@ -0,0 +1,38 @@ +import Foundation +import WebKit + +/// Where a navigation in an agent's app page may go. The page is untrusted (a routine can rewrite +/// a space's page with nobody watching), so the app is strict: a page leaves for the outside only as +/// a web link the person tapped. It never reaches bighelp's own links (`loopdy:`, +/// `app.loopdy.mobile:`), another app's scheme (`tel:`, `sms:`, `shortcuts:`), a file or another +/// page's `bighelp-app://` origin. +enum HTMLAppNavigationPolicy { + enum Decision: Equatable { + /// The page loads it. + case allowInPage + /// The person's tap on a web link: iOS opens it outside bighelp. + case openOutside + /// Nothing happens. + case drop + } + + /// The scheme every app page loads from (`HTMLAppWebView.scheme`). + static let appScheme = "bighelp-app" + + /// `isMainFrame` is false for a frame inside the page. A `window.open` or `target="_blank"` link + /// asks as a main-frame navigation. WebKit gives no public "user-initiated" flag, so + /// `.linkActivated` (a tap on a link) is what counts as the person's tap; a script's own + /// `location` or `window.open` is `.other` and goes nowhere. + static func decide(url: URL, appID: String, isMainFrame: Bool, navigationType: WKNavigationType) -> Decision { + guard let scheme = url.scheme?.lowercased() else { return .drop } + if scheme == appScheme { + return url.host() == appID ? .allowInPage : .drop + } + let isWeb = scheme == "http" || scheme == "https" + if isMainFrame { + return isWeb && navigationType == .linkActivated ? .openOutside : .drop + } + // Frames inside the page, and blank documents, load as the page asks. + return isWeb || scheme == "about" || scheme == "data" || scheme == "blob" ? .allowInPage : .drop + } +} diff --git a/Bighelp/HTMLApps/HTMLAppScreen.swift b/Bighelp/HTMLApps/HTMLAppScreen.swift index ee9b0f64..12dd416a 100644 --- a/Bighelp/HTMLApps/HTMLAppScreen.swift +++ b/Bighelp/HTMLApps/HTMLAppScreen.swift @@ -15,9 +15,13 @@ struct HTMLAppScreen: View { @Environment(\.scenePhase) private var scenePhase @BighelpThemeReader private var theme - init(app: HTMLAppCard, agentID: String, send: @escaping @MainActor (String) throws -> Void) { + /// `connection` is the computer the app is on: the one in use for a chat's card, the space's own + /// computer for a space's page (`TodaySpacesModel.pageConnection`). + init(app: HTMLAppCard, agentID: String, + connection: @escaping @MainActor () -> (scope: String, api: HTMLAppsAPI)? = HTMLAppHost.connection, + send: @escaping @MainActor (String) throws -> Void) { self.send = send - _model = State(initialValue: HTMLAppScreenModel(app: app, agentID: agentID)) + _model = State(initialValue: HTMLAppScreenModel(app: app, agentID: agentID, connection: connection)) } /// Data is read only while the page shows and bighelp is in front. diff --git a/Bighelp/HTMLApps/HTMLAppScreenModel.swift b/Bighelp/HTMLApps/HTMLAppScreenModel.swift index 51ff6c68..d2d0f027 100644 --- a/Bighelp/HTMLApps/HTMLAppScreenModel.swift +++ b/Bighelp/HTMLApps/HTMLAppScreenModel.swift @@ -98,7 +98,8 @@ final class HTMLAppScreenModel { var title: String { info?.title ?? app.title } var isLive: Bool { info?.isLive ?? app.isLive } - var sendsAnswers: Bool { info?.sendsAnswers ?? app.sendsAnswers } + /// A card that says no is final (a space's never sends): the plugin's `info` can only narrow a yes. + var sendsAnswers: Bool { app.sendsAnswers && (info?.sendsAnswers ?? true) } func open() async { guard let connection = connection() else { diff --git a/Bighelp/HTMLApps/HTMLAppWebView.swift b/Bighelp/HTMLApps/HTMLAppWebView.swift index 2a1449f2..d3e5c493 100644 --- a/Bighelp/HTMLApps/HTMLAppWebView.swift +++ b/Bighelp/HTMLApps/HTMLAppWebView.swift @@ -8,7 +8,7 @@ import WebKit /// safe: links and new windows open outside, the page can't move itself elsewhere, the camera and /// microphone are refused, and `window.bighelp` is the page's one way to reach the app. struct HTMLAppWebView: UIViewRepresentable { - static let scheme = "bighelp-app" + static let scheme = HTMLAppNavigationPolicy.appScheme /// Every app's storage (each origin keeps its own), apart from the rest of bighelp's web views. static let dataStoreID = UUID(uuidString: "6B1F3C2A-8D4E-4F5A-9B6C-2E7D8A9F0B1C")! @@ -113,17 +113,19 @@ struct HTMLAppWebView: UIViewRepresentable { func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction) async -> WKNavigationActionPolicy { guard let url = action.request.url else { return .cancel } - if url.scheme == HTMLAppWebView.scheme { - return url.host() == appID ? .allow : .cancel - } - // Frames inside the page, and blank documents, load as the page asks. - if action.targetFrame?.isMainFrame == false || url.scheme == "about" || url.scheme == "data" - || url.scheme == "blob" { + let decision = HTMLAppNavigationPolicy.decide( + url: url, appID: appID, isMainFrame: action.targetFrame?.isMainFrame != false, + navigationType: action.navigationType) + switch decision { + case .allowInPage: return .allow + case .openOutside: + // The page stays the app: a web link the person tapped opens outside bighelp. + openURL?(url) + return .cancel + case .drop: + return .cancel } - // The page stays the app: anything that would replace it opens outside bighelp. - openURL?(url) - return .cancel } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { @@ -141,7 +143,11 @@ struct HTMLAppWebView: UIViewRepresentable { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { - if let url = action.request.url { openURL?(url) } + if let url = action.request.url, + HTMLAppNavigationPolicy.decide(url: url, appID: appID, isMainFrame: true, + navigationType: action.navigationType) == .openOutside { + openURL?(url) + } return nil } diff --git a/Bighelp/Hermes/DirectHermesSessionCatalogClient.swift b/Bighelp/Hermes/DirectHermesSessionCatalogClient.swift index b57a239d..14d030bd 100644 --- a/Bighelp/Hermes/DirectHermesSessionCatalogClient.swift +++ b/Bighelp/Hermes/DirectHermesSessionCatalogClient.swift @@ -658,7 +658,7 @@ final class DirectHermesSessionCatalogClient: SessionCatalogClient { try await createOrdinarySession(profileID: profileID, folder: nil, title: nil, runtime: .init()) } - /// Code mode: a new chat in exactly `folder` (a project's worktree or checkout), + /// A coding session: a new chat in exactly `folder` (a project's worktree or checkout), /// named `title`. Unlike a chat in the selected project, it never falls back to /// another folder: work meant for a worktree must not land somewhere else. func createSession(agentID: String, folder: String, title: String, diff --git a/Bighelp/Home/Chats/ChatsInboxFixture.swift b/Bighelp/Home/Chats/ChatsInboxFixture.swift new file mode 100644 index 00000000..4441b4d6 --- /dev/null +++ b/Bighelp/Home/Chats/ChatsInboxFixture.swift @@ -0,0 +1,50 @@ +#if DEBUG +import SwiftUI + +/// The Chats view alone on made-up data, before the shell holds it: the demo's chats and bots on +/// "Home Hermes", Studio Mac's chats from the all-hosts demo, and Office Linux, which doesn't answer. +/// The first demo chat carries the Code tag. Long-press changes only print. +@MainActor +enum ChatsInboxFixture { + /// Suggested: `-use-demo-fixtures -test-chats-inbox` shows `ChatsInboxFixture.view()` as the root. + static let launchArgument = "-test-chats-inbox" + + static func view(header: AnyView = AnyView(sampleHeader)) -> some View { + ChatsInboxView(context: context(header: header)) + } + + /// The first tab's header at Chats, as the shell draws it over the list. Never an empty view: + /// the list's top inset then takes the whole screen, and only the search row shows, at the bottom. + private static var sampleHeader: some View { + HomeHeaderBar(context: HomeHeaderContext( + personName: "Sam Rivera", personImageURL: nil, onOpenSettings: {}, + viewSwitch: HomeViewSwitch(current: .chats, select: { _ in }), + newItems: SimpleBotsNewItem.allCases)) + } + + static func context(header: AnyView = AnyView(sampleHeader)) -> ChatsInboxContext { + let defaults = UserDefaults(suiteName: "bighelp.chats-inbox-fixture") ?? .standard + let records = DemoSessionCatalogClient.fixtureRecords + let catalog = SessionCatalogStore(client: DemoSessionCatalogClient(records: records), records: records, + repository: nil, loadsRepositoryOnInit: false, defaults: defaults) + let agents = AgentDirectoryStore(client: UnavailableAppCatalogClient(), defaults: defaults, + profiles: DemoAgentDirectoryClient.fixtureProfiles) + let fleet = FleetStore(reader: FleetFixtureReader(), directory: FileManager.default.temporaryDirectory + .appending(path: "bighelp-chats-inbox-\(ProcessInfo.processInfo.processIdentifier)")) + return ChatsInboxContext( + catalog: catalog, + agents: agents, + fleet: fleet, + showsEveryComputer: true, + codeSessionIDs: Set(records.prefix(1).map(\.id)), + header: header, + onOpen: { print("ChatsInboxFixture open", $0) }, + onChange: { row, change in print("ChatsInboxFixture change", row.id, change) }, + onRefresh: { try? await Task.sleep(for: .milliseconds(300)) }, + onNewChat: { print("ChatsInboxFixture new chat") }, + onOpenArchived: { print("ChatsInboxFixture archived") }, + onOpenThisComputer: { print("ChatsInboxFixture this computer") } + ) + } +} +#endif diff --git a/Bighelp/Home/Chats/ChatsInboxProjection.swift b/Bighelp/Home/Chats/ChatsInboxProjection.swift new file mode 100644 index 00000000..a5c62779 --- /dev/null +++ b/Bighelp/Home/Chats/ChatsInboxProjection.swift @@ -0,0 +1,116 @@ +import Foundation + +/// Another computer as the Chats view lists it: its chats and group chats from its all-hosts copy. +struct ChatsInboxComputer: Identifiable, Equatable { + let id: UUID + let name: String + let chats: [FleetChat] + let groups: [FleetGroup] +} + +/// Everything the Chats list is made from. +struct ChatsInboxInput: Equatable { + /// The computer in use's chats (`SessionCatalogStore.recentSummaries`). + var sessions: [SessionSummary] = [] + /// The computer in use's group chats, with or without messages: one with none yet isn't in the catalog. + var rooms: [HermesBotModeRoomSummary] = [] + /// Coding sessions started from Work on the computer in use, by app session ID. + var codeSessionIDs: Set = [] + var selectedHostID: UUID? = nil + /// Every computer's all-hosts copy; the one in use's is dropped, since its catalog is live. + var computers: [ChatsInboxComputer] = [] + /// Two or more computers show: chats on another computer carry its name. + var showsComputerTags = false +} + +/// The chip row's one choice: every chat, one computer's, or the unread ones. +enum ChatsInboxFilter: Hashable { + case all + case computer(UUID) + case unread +} + +/// A run of rows under one header: Pinned, then by day. +struct ChatsInboxSection: Identifiable, Equatable { + enum Kind: String, Equatable { + case pinned, today, yesterday, earlier + } + + let kind: Kind + let rows: [ChatsInboxRow] + + var id: Kind { kind } +} + +/// The Chats list as a pure function of what the stores hold: merged, the computer in use's copies +/// dropped, Pinned first, then newest first. The view keeps the result until an input changes +/// (`ChatsInboxCache`), so nothing here runs for each event a computer sends. +enum ChatsInboxProjection { + static func rows(_ input: ChatsInboxInput) -> [ChatsInboxRow] { + var rows: [ChatsInboxRow] = [] + var listedRooms = Set() + var listedIDs = Set() + for session in input.sessions where listedIDs.insert(session.id).inserted { + if let roomID = session.hostedRoomID { listedRooms.insert(roomID) } + rows.append(ChatsInboxRow(session: session, hostID: input.selectedHostID, + isCode: input.codeSessionIDs.contains(session.id))) + } + // A group chat with no message yet: Hermes' rooms list it, named as its catalog row will be. + for room in input.rooms where !room.isDisbanded && listedRooms.insert(room.roomID).inserted { + let summary = HostedRoomSessionProjection.summary(for: room) + guard listedIDs.insert(summary.id).inserted else { continue } + rows.append(ChatsInboxRow(session: summary, hostID: input.selectedHostID, isCode: false)) + } + for computer in input.computers where computer.id != input.selectedHostID { + let tag = input.showsComputerTags ? computer.name : nil + rows += computer.chats.map { ChatsInboxRow(fleetChat: $0, computerTag: tag) } + rows += computer.groups.map { ChatsInboxRow(fleetGroup: $0, computerTag: tag) } + } + return rows.sorted(by: inOrder) + } + + /// Pinned first, then the newest; the ID keeps equal times in one order. + static func inOrder(_ lhs: ChatsInboxRow, _ rhs: ChatsInboxRow) -> Bool { + if lhs.isPinned != rhs.isPinned { return lhs.isPinned } + if lhs.updatedAt != rhs.updatedAt { return lhs.updatedAt > rhs.updatedAt } + return lhs.id < rhs.id + } + + /// The chip and the search text on top of the merged rows. Search looks at titles and previews. + static func filter(_ rows: [ChatsInboxRow], by filter: ChatsInboxFilter, matching query: String) -> [ChatsInboxRow] { + let query = query.trimmingCharacters(in: .whitespacesAndNewlines) + return rows.filter { row in + switch filter { + case .all: break + case .computer(let id): guard row.hostID == id else { return false } + case .unread: guard row.isUnread else { return false } + } + return query.isEmpty + || row.title.localizedCaseInsensitiveContains(query) + || row.preview.localizedCaseInsensitiveContains(query) + } + } + + /// Pinned on top, then Today, Yesterday and Earlier, each keeping the rows' order. + static func sections(_ rows: [ChatsInboxRow], now: Date, calendar: Calendar = .current) -> [ChatsInboxSection] { + let startOfToday = calendar.startOfDay(for: now) + let startOfYesterday = calendar.date(byAdding: .day, value: -1, to: startOfToday) ?? startOfToday + var byKind: [ChatsInboxSection.Kind: [ChatsInboxRow]] = [:] + for row in rows { + let kind: ChatsInboxSection.Kind = if row.isPinned { + .pinned + } else if row.updatedAt >= startOfToday { + // A clock a little ahead on the computer still reads as today. + .today + } else if row.updatedAt >= startOfYesterday { + .yesterday + } else { + .earlier + } + byKind[kind, default: []].append(row) + } + return [ChatsInboxSection.Kind.pinned, .today, .yesterday, .earlier].compactMap { kind in + byKind[kind].map { ChatsInboxSection(kind: kind, rows: $0) } + } + } +} diff --git a/Bighelp/Home/Chats/ChatsInboxRow.swift b/Bighelp/Home/Chats/ChatsInboxRow.swift new file mode 100644 index 00000000..af87feb2 --- /dev/null +++ b/Bighelp/Home/Chats/ChatsInboxRow.swift @@ -0,0 +1,308 @@ +import Foundation +import SwiftUI + +/// One chat in the Chats view: a chat on the computer in use (live, from its catalog), or one on +/// another computer as its all-hosts copy last read it. One-to-one chats, group chats and coding +/// sessions are all rows of the same list. +struct ChatsInboxRow: Identifiable, Equatable { + enum Source: Equatable { + /// The computer in use: a catalog row, or a group chat with no message yet. + case session(SessionSummary) + /// Another computer's chat, from its all-hosts copy. + case fleetChat(FleetChat) + /// Another computer's group chat, from its all-hosts copy. + case fleetGroup(FleetGroup) + } + + let id: String + let source: Source + /// The computer it lives on; nil when no computer list is kept (one computer). + let hostID: UUID? + let isOnComputerInUse: Bool + let title: String + /// Hermes' preview as it came (Markdown and all); the row makes it plain as it draws. + let preview: String + let updatedAt: Date + /// Only the computer in use keeps pins and read state the list can see (`FleetChat` has neither). + let isPinned: Bool + let isUnread: Bool + let tracksUnread: Bool + let hasDraft: Bool + let isActive: Bool + let isGroup: Bool + /// A coding session started from Work. Only known for the computer in use. + let isCode: Bool + /// Who it's with, by profile ID on its own computer. + let memberIDs: [String] + let origin: String? + /// The computer's name for the row's tag; nil when the tag doesn't show. + let computerTag: String? + /// Its bot's Bot Chat state in `BotChatActivityStore`; nil for any other chat, whose state the + /// store doesn't know. + let activityKey: String? + + /// Pin, Mark read and Rename work through the computer in use's catalog; group chats are + /// managed in their own settings, as on the Sessions list. + private var isManagedHere: Bool { + if case .session(let summary) = source { return summary.hostedRoomID == nil } + return false + } + + private var isFleetChat: Bool { + if case .fleetChat = source { return true } + return false + } + + var canPin: Bool { isManagedHere } + var canMarkUnread: Bool { isManagedHere && tracksUnread } + /// Another computer's chat goes through the fleet's update call, which renames and archives. + var canRename: Bool { isManagedHere || isFleetChat } + var canArchive: Bool { isManagedHere || isFleetChat } + var isBotChat: Bool { !isGroup && title == "Bot Chat" } + + var target: ChatsInboxTarget { + switch source { + case .session(let summary): .session(summary) + case .fleetChat(let chat): .fleetChat(chat) + case .fleetGroup(let group): .group(group) + } + } +} + +extension ChatsInboxRow { + init(session: SessionSummary, hostID: UUID?, isCode: Bool) { + let isGroup = session.kind == .botMode || session.hostedRoomID != nil + let isBotChat = !isGroup && session.isBotChat + self.init( + id: "here/" + session.id, source: .session(session), hostID: hostID, isOnComputerInUse: true, + title: session.title, preview: session.preview, updatedAt: session.updatedAt, + isPinned: session.isPinned, isUnread: session.isUnread, tracksUnread: session.tracksUnread, + hasDraft: session.hasDraft, isActive: session.isActive, isGroup: isGroup, isCode: isCode, + memberIDs: session.agentIDs, origin: session.origin, computerTag: nil, + activityKey: isBotChat ? session.agentIDs.first.map(BotChatActivityStore.liveKey) : nil + ) + } + + init(fleetChat chat: FleetChat, computerTag: String?) { + self.init( + id: chat.id, source: .fleetChat(chat), hostID: chat.hostID, isOnComputerInUse: false, + title: chat.title.isEmpty ? String(localized: "New chat") : chat.title, preview: chat.preview, + updatedAt: chat.updatedAt, isPinned: chat.isPinned ?? false, isUnread: false, tracksUnread: false, hasDraft: false, + isActive: chat.isActive, isGroup: false, isCode: false, memberIDs: [chat.profileID], origin: chat.origin, + computerTag: computerTag, + activityKey: chat.title == "Bot Chat" ? FleetID.make(chat.hostID, chat.profileID) : nil + ) + } + + init(fleetGroup group: FleetGroup, computerTag: String?) { + self.init( + id: group.id, source: .fleetGroup(group), hostID: group.hostID, isOnComputerInUse: false, + title: group.name, preview: group.memberNames.joined(separator: ", "), updatedAt: group.updatedAt, + isPinned: false, isUnread: false, tracksUnread: false, hasDraft: false, isActive: group.isWorking, + isGroup: true, isCode: false, memberIDs: group.memberIDs ?? [], origin: nil, computerTag: computerTag, + activityKey: nil + ) + } +} + +/// What a tap on a row opens. The shell routes each the way it already does: a session through +/// `SessionSelectionRouting` (a group chat by its room), another computer's through `openFleet`. +enum ChatsInboxTarget: Equatable { + case session(SessionSummary) + case fleetChat(FleetChat) + case group(FleetGroup) +} + +/// A row's long-press actions. The shell makes them: the catalog for the computer in use, +/// `FleetStore.updateChat` (rename, archive) for another computer. +enum ChatsInboxChange: Equatable, Sendable { + case pin(Bool) + case unread(Bool) + case rename(String) + case archive +} + +/// A Chats row: the face (a group's faces together), the title with its tags, the time and the +/// unread dot; under them the draft mark and the preview. While a Bot Chat works or needs you, +/// that takes the preview's line, as on the Bots view. +struct ChatsInboxRowLabel: View { + let row: ChatsInboxRow + let face: AnyView + let activity: BotChatActivityStore? + @Environment(\.dynamicTypeSize) private var typeSize + @BighelpThemeReader private var theme + + static let faceSize: CGFloat = 56 + + /// Read here, so only this row redraws when its bot's state changes. + private var busy: BotChatActivity? { + guard let key = row.activityKey, let value = activity?.activity(key), value.isBusy else { return nil } + return value + } + + var body: some View { + HStack(spacing: BighelpTokens.space16) { + face.frame(width: Self.faceSize, height: Self.faceSize) + VStack(alignment: .leading, spacing: 3) { + if typeSize.isAccessibilitySize { + // The largest text sizes: each part on a line of its own, so none is cut off. + HStack(spacing: BighelpTokens.space8) { + titleText.lineLimit(3) + pin + Spacer(minLength: BighelpTokens.space8) + unreadDot + } + tags + dateText + } else { + HStack(spacing: BighelpTokens.space8) { + titleText + .lineLimit(1) + .layoutPriority(1) + pin + tags + Spacer(minLength: BighelpTokens.space8) + // The title is cut, never the time. + dateText.fixedSize() + unreadDot + } + } + secondLine + } + } + .padding(.vertical, BighelpTokens.space8) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .contentShape(.rect) + .accessibilityElement(children: .combine) + } + + private var titleText: some View { + Text(row.title) + .font(.bighelp(.title3, weight: row.isUnread ? .semibold : .medium)) + .foregroundStyle(theme.primaryText) + } + + @ViewBuilder + private var tags: some View { + if row.isCode || row.computerTag != nil { + HStack(spacing: 4) { + if row.isCode { ChatsInboxCodeTag() } + if let name = row.computerTag { FleetHostTag(name: name) } + } + .fixedSize() + } + } + + @ViewBuilder + private var secondLine: some View { + if let busy, let line = busy.line { + Text(line) + .font(.bighelp(.body, weight: .medium)) + .foregroundStyle(lineColor(busy)) + .lineLimit(1) + } else { + HStack(spacing: 6) { + if row.isActive { + Circle() + .fill(AgentLiveState.thinking.dotColor) + .frame(width: 8, height: 8) + .accessibilityLabel("Working") + } + SessionOriginTag(source: row.origin, size: 12) + if row.hasDraft { + HStack(spacing: 2) { + Image(systemName: "pencil").accessibilityHidden(true) + Text("Draft") + } + .font(.bighelp(.footnote, weight: .semibold)) + .foregroundStyle(theme.secondaryText) + } + let preview = SessionPreviewText.plain(row.preview) + if !preview.isEmpty { + Text(preview) + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + .lineLimit(typeSize.isAccessibilitySize ? 2 : 1) + .truncationMode(.tail) + } + } + } + } + + /// Needing you in ember, a turn in the action color, work in the background in plain ink. + private func lineColor(_ activity: BotChatActivity) -> Color { + switch activity { + case .waiting: BighelpBrand.ember + case .background: theme.primaryText + case .idle, .working: theme.action + } + } + + @ViewBuilder + private var pin: some View { + if row.isPinned { + Image(systemName: "pin.fill") + .font(.bighelp(.caption2)) + .foregroundStyle(theme.tertiaryText) + .accessibilityLabel("Pinned") + } + } + + private var dateText: some View { + Text(SessionRow.compactTimestamp(row.updatedAt)) + .font(.bighelp(.subheadline)) + .monospacedDigit() + .foregroundStyle(theme.tertiaryText) + .lineLimit(1) + } + + @ViewBuilder + private var unreadDot: some View { + if row.isUnread { + Circle().fill(theme.information).frame(width: 9, height: 9).accessibilityLabel("Unread") + } + } +} + +/// "Code" on a coding session's row, drawn as the computer tag is. +struct ChatsInboxCodeTag: View { + @BighelpThemeReader private var theme + + var body: some View { + Text("Code") + .font(.bighelp(.caption2).weight(.semibold)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1) + .padding(.horizontal, 7) + .padding(.vertical, 2) + .background(theme.secondaryText.opacity(0.12), in: .capsule) + .accessibilityLabel("Coding session") + } +} + +/// A still stand-in for a row while the first chats load: no pulse, which would repaint every frame. +struct ChatsInboxPlaceholderRow: View { + let index: Int + @BighelpThemeReader private var theme + + var body: some View { + HStack(spacing: BighelpTokens.space16) { + Circle() + .fill(theme.incomingMessageBackground) + .frame(width: ChatsInboxRowLabel.faceSize, height: ChatsInboxRowLabel.faceSize) + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + bar(width: index.isMultiple(of: 2) ? 140 : 100, height: 14) + bar(width: index.isMultiple(of: 3) ? 160 : 220, height: 12) + } + Spacer(minLength: 0) + } + .padding(.vertical, BighelpTokens.space8) + .accessibilityHidden(true) + } + + private func bar(width: CGFloat, height: CGFloat) -> some View { + RoundedRectangle(cornerRadius: height / 2, style: .continuous) + .fill(theme.incomingMessageBackground) + .frame(width: width, height: height) + } +} diff --git a/Bighelp/Home/Chats/ChatsInboxView.swift b/Bighelp/Home/Chats/ChatsInboxView.swift new file mode 100644 index 00000000..b6f318fc --- /dev/null +++ b/Bighelp/Home/Chats/ChatsInboxView.swift @@ -0,0 +1,506 @@ +import SwiftUI + +/// What the Chats view needs from the shell. It reads its stores only through this. +@MainActor +struct ChatsInboxContext { + /// The computer in use: live rows, pins, read state, drafts. + let catalog: SessionCatalogStore + let agents: AgentDirectoryStore + /// Every computer's all-hosts copies; nil leaves only the computer in use. + var fleet: FleetStore? = nil + /// Settings' Show every computer: the other computers' chats join the list. + var showsEveryComputer = false + /// The computer in use's group chats (`BotModeRoomStore.catalogRooms`): one with no message yet + /// shows from here. + var rooms: [HermesBotModeRoomSummary] = [] + /// `CodeHomeStore.sessions` IDs, for the Code tag. + var codeSessionIDs: Set = [] + /// Which Bot Chats are working or need you, kept current while the list shows. + var activity: BotChatActivityStore? = nil + var activitySource: BotChatActivitySource? = nil + /// Whether a chat's message box holds something unsent, from the draft journal without + /// observing it (`SessionsModel.unsentDraft`); nil keeps the catalog's own mark. + var unsentDraft: ((String) -> Bool?)? = nil + /// The computer in use answers; while it doesn't, its last chats show under a note. + var isConnected = true + /// `HomeHeaderBar`, drawn on top. + let header: AnyView + let onOpen: (ChatsInboxTarget) -> Void + /// Makes a long-press change; the shell reports a failure. Nil leaves the actions out. + var onChange: ((ChatsInboxRow, ChatsInboxChange) -> Void)? = nil + /// Pull to refresh for the computer in use; the other computers are read again here. + var onRefresh: (@MainActor @Sendable () async -> Void)? = nil + /// The empty list's one action. + var onNewChat: (() -> Void)? = nil + var onOpenArchived: (() -> Void)? = nil + /// The computer in use's own Sessions page: projects, imports from other apps. + var onOpenThisComputer: (() -> Void)? = nil +} + +/// The first tab's Chats view: every chat on every computer in one list, Pinned on top, then the +/// newest. Search and one row of chips (All, each computer, Unread) sit over it. +struct ChatsInboxView: View { + let context: ChatsInboxContext + + @State private var search = "" + @State private var filter: ChatsInboxFilter = .all + @State private var renaming: ChatsInboxRow? + @State private var renameDraft = "" + @State private var cache = ChatsInboxCache() + @Environment(\.scenePhase) private var scenePhase + @BighelpThemeReader private var theme + + var body: some View { + let list = listState + List { + BighelpSearchField(text: $search, prompt: String(localized: "Search chats"), + accessibilityLabel: String(localized: "Search chats"), + accessibilityIdentifier: "chats.search") + .bighelpListSearchRow() + ChatsInboxChips(computers: list.chipComputers, statuses: context.fleet?.statuses ?? [:], + selection: $filter) + .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: BighelpTokens.space4, trailing: 0)) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + ForEach(list.offline, id: \.self) { name in + ChatsInboxOfflineNote(name: name) + } + content(list) + moreSection + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .dismissesKeyboardOnScroll(true, immediately: true) + .frame(maxWidth: ChatCanvasLayout.regularLaneMaximumWidth) + .frame(maxWidth: .infinity) + .safeAreaInset(edge: .top, spacing: 0) { context.header } + .background(theme.canvas.ignoresSafeArea()) + .bighelpRefreshable { [onRefresh = context.onRefresh, fleet = shownFleet] in + if let fleet { fleet.refresh(force: true) } + await onRefresh?() + if let fleet { await fleet.waitForReads() } + } + // The other computers are read again as the list shows (at most once a minute). + .task(id: shownFleet != nil) { shownFleet?.refresh() } + .botChatActivityUpdates(context.activity, source: context.activitySource, isActive: scenePhase == .active) + .alert("Rename chat", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } }), + presenting: renaming) { row in + TextField("Chat name", text: $renameDraft) + .accessibilityIdentifier("chats.rename.field") + Button("Cancel", role: .cancel) {} + Button("Save") { context.onChange?(row, .rename(renameDraft)) } + .accessibilityIdentifier("chats.rename.save") + } message: { row in + Text(row.isBotChat + ? "Renamed, this becomes a regular chat, and tapping the bot starts a new Bot Chat." + : "Enter a name up to \(SessionTitleRules.maximumLength) characters.") + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("chats.inbox") + } + + // MARK: State + + private var shownFleet: FleetStore? { context.showsEveryComputer ? context.fleet : nil } + + /// What one drawing shows, worked out from the cache. + private struct ListState { + let all: [ChatsInboxRow] + let sections: [ChatsInboxSection] + /// The computers to pick by chip; empty with one computer, so only All and Unread show. + let chipComputers: [FleetHost] + /// Computers that don't answer, among those shown: their last chats stay, under a note. + let offline: [String] + let filter: ChatsInboxFilter + } + + private var listState: ListState { + // Read every time, also on a cache hit: this is what draws the list again when chats change. + _ = context.catalog.presentedRecords + let fleet = shownFleet + let hosts = fleet?.hosts ?? [] + let showsComputers = hosts.count > 1 + let selectedHostID = fleet?.selectedHostID + let computers: [ChatsInboxComputer] = hosts.compactMap { host in + guard host.id != selectedHostID, let snapshot = fleet?.snapshots[host.id] else { return nil } + return ChatsInboxComputer(id: host.id, name: host.name, chats: snapshot.chats, groups: snapshot.groups ?? []) + } + // Read on every draw: the catalog's revision doesn't move for what only an open chat's + // message box holds (files are never saved), so the Draft mark went stale. Two lookups a chat. + var unsentDrafts: [String: Bool] = [:] + if let unsentDraft = context.unsentDraft { + for record in context.catalog.presentedRecords { + if let unsent = unsentDraft(record.id) { unsentDrafts[record.id] = unsent } + } + } + let key = ChatsInboxCache.Key( + catalog: ObjectIdentifier(context.catalog), + revision: context.catalog.presentedRevision, rooms: context.rooms, codeSessionIDs: context.codeSessionIDs, + selectedHostID: selectedHostID, computers: computers, showsComputerTags: showsComputers, + unsentDrafts: unsentDrafts + ) + let all = cache.rows(for: key) { [context] in + let summaries = context.catalog.recentSummaries(includeCronSessions: false).map { summary in + var summary = summary + if let unsent = unsentDrafts[summary.id] { summary.hasDraft = unsent } + return summary + } + return ChatsInboxProjection.rows(ChatsInboxInput( + sessions: summaries, rooms: context.rooms, codeSessionIDs: context.codeSessionIDs, + selectedHostID: selectedHostID, computers: computers, showsComputerTags: showsComputers)) + } + // A computer chip whose computer went (or that no longer shows) falls back to All. + let effective: ChatsInboxFilter = switch filter { + case .computer(let id) where !showsComputers || !hosts.contains(where: { $0.id == id }): .all + default: filter + } + let sections = cache.sections(effective, query: search, now: .now) + var offline: [String] = [] + if let fleet { + for host in hosts { + if case .computer(let id) = effective, id != host.id { continue } + if host.id == selectedHostID ? !context.isConnected : fleet.statuses[host.id].isUnreachable { + offline.append(host.name) + } + } + } else if !context.isConnected { + offline.append(String(localized: "This computer")) + } + return ListState(all: all, sections: sections, chipComputers: showsComputers ? hosts : [], + offline: offline, filter: effective) + } + + // MARK: Rows + + @ViewBuilder + private func content(_ list: ListState) -> some View { + if list.all.isEmpty, !context.catalog.hasLoadedState, context.isConnected { + ForEach(0..<4, id: \.self) { index in + ChatsInboxPlaceholderRow(index: index) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } + } else if list.sections.isEmpty { + emptyState(list) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } else { + let faces = ChatsInboxFaces(agents: context.agents, fleet: context.fleet) + ForEach(list.sections) { section in + Section { + ForEach(section.rows) { row in rowButton(row, faces: faces) } + } header: { + sectionHeader(section.kind) + } + } + } + } + + private func rowButton(_ row: ChatsInboxRow, faces: ChatsInboxFaces) -> some View { + Button { context.onOpen(row.target) } label: { + ChatsInboxRowLabel(row: row, face: faces.face(for: row, activity: context.activity), + activity: context.activity) + } + .buttonStyle(.plain) + // One menu for each row of the list, so a hold always acts on the row held. Right-click on the Mac. + .contextMenu { actions(row) } + .listRowBackground(Color.clear) + .listRowInsets(EdgeInsets(top: 0, leading: BighelpTokens.space16, bottom: 0, trailing: BighelpTokens.space16)) + .accessibilityIdentifier("chats.row.\(row.id)") + } + + @ViewBuilder + private func actions(_ row: ChatsInboxRow) -> some View { + if let onChange = context.onChange { + if row.canPin { + Button(row.isPinned ? "Unpin" : "Pin", systemImage: row.isPinned ? "pin.slash" : "pin") { + onChange(row, .pin(!row.isPinned)) + } + .accessibilityIdentifier("chats.action.pin.\(row.id)") + } + if row.canMarkUnread { + Button(row.isUnread ? "Mark read" : "Mark unread", + systemImage: row.isUnread ? "message" : "message.badge") { + onChange(row, .unread(!row.isUnread)) + } + .accessibilityIdentifier("chats.action.unread.\(row.id)") + } + if row.canRename { + Button("Rename", systemImage: "pencil") { + renameDraft = row.title + renaming = row + } + .accessibilityIdentifier("chats.action.rename.\(row.id)") + } + if row.canArchive { + Button("Archive", systemImage: "archivebox") { onChange(row, .archive) } + .accessibilityIdentifier("chats.action.archive.\(row.id)") + } + } + } + + private func sectionHeader(_ kind: ChatsInboxSection.Kind) -> some View { + let title: LocalizedStringKey = switch kind { + case .pinned: "Pinned" + case .today: "Today" + case .yesterday: "Yesterday" + case .earlier: "Earlier" + } + return FleetSectionCaption(title: title) + .accessibilityIdentifier("chats.section.\(kind.rawValue)") + } + + // MARK: Empty and more + + @ViewBuilder + private func emptyState(_ list: ListState) -> some View { + Group { + if !search.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + ContentUnavailableView.search(text: search) + } else if list.filter == .unread { + ContentUnavailableView("No unread chats", systemImage: "checkmark.message") + } else if case .computer(let id) = list.filter, let fleet = context.fleet, !list.all.isEmpty { + ContentUnavailableView("No chats on \(fleet.hostName(id))", systemImage: "desktopcomputer") + } else { + ContentUnavailableView { + Label("No chats yet", systemImage: "bubble.left.and.bubble.right") + } description: { + Text("Start one with New chat.") + } actions: { + if let onNewChat = context.onNewChat { + Button("New chat", action: onNewChat) + .bighelpProminentButtonStyle() + .buttonBorderShape(.capsule) + .tint(theme.action) + .accessibilityIdentifier("chats.empty.new-chat") + } + } + } + } + .frame(maxWidth: .infinity) + .padding(.top, BighelpTokens.space32) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("chats.empty") + } + + @ViewBuilder + private var moreSection: some View { + if context.onOpenArchived != nil || context.onOpenThisComputer != nil { + Section { + if let open = context.onOpenThisComputer { + moreRow("This computer", value: thisComputerName, systemImage: "desktopcomputer", + id: "chats.more.this-computer", action: open) + } + if let open = context.onOpenArchived { + moreRow("Archived", value: nil, systemImage: "archivebox", id: "chats.more.archived", action: open) + } + } header: { + FleetSectionCaption(title: "More") + } + } + } + + /// The computer in use's name, only where computers are named at all. + private var thisComputerName: String? { + guard let fleet = shownFleet, fleet.showsHostNames, let id = fleet.selectedHostID else { return nil } + return fleet.hostName(id) + } + + private func moreRow(_ title: LocalizedStringKey, value: String?, systemImage: String, id: String, + action: @escaping () -> Void) -> some View { + Button(action: action) { + HStack(spacing: BighelpTokens.space12) { + Image(systemName: systemImage) + .foregroundStyle(theme.secondaryText) + .frame(width: 28) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.bighelp(.body)).foregroundStyle(theme.primaryText) + if let value { + Text(value).font(.bighelp(.subheadline)).foregroundStyle(theme.secondaryText) + } + } + Spacer(minLength: BighelpTokens.space8) + Image(systemName: "chevron.right") + .font(.bighelp(.footnote, weight: .semibold)) + .foregroundStyle(theme.tertiaryText) + .accessibilityHidden(true) + } + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .contentShape(.rect) + } + .buttonStyle(.plain) + .listRowBackground(Color.clear) + .accessibilityIdentifier(id) + } +} + +/// Keeps the merged rows until the catalog's revision or a computer's copy changes, and the +/// sections until the chip, the search or the day changes, so a redraw for each streamed piece +/// of an answer doesn't sort the list again. Not observed: writing it from `body` draws nothing. +@MainActor +final class ChatsInboxCache { + struct Key: Equatable { + /// Whose chats these are. Every computer has its own catalog, each counting its revisions + /// from zero, and the list stays on screen through a switch: without this, two computers at + /// the same revision showed the first one's chats. + let catalog: ObjectIdentifier + let revision: Int + let rooms: [HermesBotModeRoomSummary] + let codeSessionIDs: Set + let selectedHostID: UUID? + let computers: [ChatsInboxComputer] + let showsComputerTags: Bool + /// The Draft marks that aren't the catalog's own: what open chats' message boxes hold, by + /// chat. The revision doesn't move for these. + var unsentDrafts: [String: Bool] = [:] + } + + private struct SectionsKey: Equatable { + let generation: Int + let filter: ChatsInboxFilter + let query: String + let day: Date + } + + private var key: Key? + private var rows: [ChatsInboxRow] = [] + private var generation = 0 + private var sectionsKey: SectionsKey? + private var sections: [ChatsInboxSection] = [] + + func rows(for key: Key, build: () -> [ChatsInboxRow]) -> [ChatsInboxRow] { + if key == self.key { return rows } + rows = build() + self.key = key + generation &+= 1 + return rows + } + + /// The last `rows(for:build:)` result, filtered and put under its headers. + func sections(_ filter: ChatsInboxFilter, query: String, now: Date, + calendar: Calendar = .current) -> [ChatsInboxSection] { + let key = SectionsKey(generation: generation, filter: filter, query: query, day: calendar.startOfDay(for: now)) + if key == sectionsKey { return sections } + sections = ChatsInboxProjection.sections(ChatsInboxProjection.filter(rows, by: filter, matching: query), + now: now, calendar: calendar) + sectionsKey = key + return sections + } +} + +/// The faces for rows: bots on the computer in use from its live profiles, others from their +/// all-hosts copies. Made once for each drawing of the list, not once for each row. +@MainActor +struct ChatsInboxFaces { + let agents: AgentDirectoryStore + let fleet: FleetStore? + private let profiles: [String: AgentProfile] + + init(agents: AgentDirectoryStore, fleet: FleetStore?) { + self.agents = agents + self.fleet = fleet + profiles = Dictionary(agents.profiles.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + } + + func face(for row: ChatsInboxRow, activity: BotChatActivityStore?) -> AnyView { + let size = ChatsInboxRowLabel.faceSize + let bots = members(of: row) + if row.isGroup { + return AnyView(SimpleBotsGroupFace(members: bots, size: size)) + } + let bot = bots.first ?? SimpleBotsBot(id: row.id, profileID: row.memberIDs.first ?? row.id, + hostID: row.hostID, name: row.title, role: "") + // Only a Bot Chat's face moves with its bot's state; the store knows nothing of other chats. + return AnyView(SimpleBotLiveFace(bot: bot, size: size, activity: row.activityKey == nil ? nil : activity) + .accessibilityHidden(true)) + } + + private func members(of row: ChatsInboxRow) -> [SimpleBotsBot] { + if row.isOnComputerInUse { + return row.memberIDs.compactMap { id in + profiles[id].map { SimpleBotsBot($0, imageURL: agents.avatarURL(for: $0)) } + } + } + guard let fleet, let hostID = row.hostID else { return [] } + return row.memberIDs.compactMap { id in + fleet.agent(hostID: hostID, profileID: id).map { + SimpleBotsBot($0, imageURL: fleet.avatars.url(for: $0.avatarFile)) + } + } + } +} + +/// The chip row: All, then each computer (with two or more), then Unread. One row that scrolls +/// sideways. Drawn as `FleetHostFilter`'s chips are, which can't hold the Unread chip. +struct ChatsInboxChips: View { + let computers: [FleetHost] + let statuses: [UUID: FleetHostStatus] + @Binding var selection: ChatsInboxFilter + @BighelpThemeReader private var theme + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: BighelpTokens.space8) { + chip(Text("All"), isOn: selection == .all, id: "chats.filter.all") { selection = .all } + ForEach(computers) { host in + chip(Text(verbatim: host.name), isOn: selection == .computer(host.id), + isOffline: statuses[host.id].isUnreachable, + id: "chats.filter.computer.\(host.name)") { selection = .computer(host.id) } + } + chip(Text("Unread"), isOn: selection == .unread, id: "chats.filter.unread") { selection = .unread } + } + .padding(.horizontal, BighelpTokens.space16) + } + .accessibilityElement(children: .contain) + } + + private func chip(_ title: Text, isOn: Bool, isOffline: Bool = false, + id: String, action: @escaping () -> Void) -> some View { + Button(action: action) { + HStack(spacing: 5) { + if isOffline { + BighelpConnectionIndicator(phase: .disconnected, tint: isOn ? theme.actionForeground : nil) + } + title.lineLimit(1) + } + .font(.bighelp(.subheadline).weight(.semibold)) + .foregroundStyle(isOn ? theme.actionForeground : theme.primaryText) + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: 34) + .background(isOn ? theme.action : theme.surface, in: .capsule) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .buttonStyle(.plain) + .accessibilityAddTraits(isOn ? .isSelected : []) + .accessibilityIdentifier(id) + } +} + +/// One quiet line over the list for a computer that doesn't answer; its last chats stay below. +struct ChatsInboxOfflineNote: View { + let name: String + @BighelpThemeReader private var theme + + var body: some View { + HStack(spacing: BighelpTokens.space8) { + BighelpConnectionIndicator(phase: .disconnected) + Text("\(name) isn't connected. Showing its last chats.") + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + } + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("chats.note.\(name)") + } +} + +private extension Optional where Wrapped == FleetHostStatus { + var isUnreachable: Bool { + if case .unreachable = self { return true } + return false + } +} diff --git a/Bighelp/Home/HomeChromeFixture.swift b/Bighelp/Home/HomeChromeFixture.swift new file mode 100644 index 00000000..7bd45bab --- /dev/null +++ b/Bighelp/Home/HomeChromeFixture.swift @@ -0,0 +1,144 @@ +#if DEBUG +import SwiftUI + +/// The home's chrome on made-up data, alone: every header variant, the bar and the sidebar. +/// For screenshots and review before the shell uses them (suggested launch argument `-test-home-chrome`). +struct HomeChromeFixture: View { + enum Part: String, CaseIterable, Identifiable { + case headers, bar, sidebar + var id: String { rawValue } + } + + @State private var part = Part.headers + @State private var view = HomeConversationsView.bots + @State private var tab = HomeTab.conversations + @State private var search = "" + @State private var computerID = "home" + @BighelpThemeReader private var theme + + var body: some View { + VStack(spacing: 0) { + Picker(selection: $part) { + ForEach(Part.allCases) { part in Text(verbatim: part.rawValue.capitalized).tag(part) } + } label: { + Text(verbatim: "Part") + } + .pickerStyle(.segmented) + .padding(BighelpTokens.space16) + .accessibilityIdentifier("home.fixture.part") + switch part { + case .headers: headers + case .bar: bar + case .sidebar: HomeSidebar(context: sidebarContext) + } + } + .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) + } + + // MARK: Headers + + private var headers: some View { + ScrollView { + VStack(alignment: .leading, spacing: BighelpTokens.space24) { + sample("First tab") { + HomeHeaderBar(context: header( + viewSwitch: HomeViewSwitch(current: view, select: { view = $0 }), + search: .button(label: "Search", action: {}), + newItems: SimpleBotsNewItem.allCases)) + } + sample("First tab, search field") { + HomeHeaderBar(context: header( + viewSwitch: HomeViewSwitch(current: view, select: { view = $0 }), + search: .field($search, prompt: "Search chats"), + newItems: [.groupChat])) + } + sample("Today") { + HomeHeaderBar(context: header(title: "Today", trailing: AnyView(editChip))) + } + sample("Work, two computers") { + HomeHeaderBar(context: header(title: "Work", search: .button(label: "Search", action: {}), + computer: computer)) + } + sample("With the sidebar button") { + HomeHeaderBar(context: header(title: "Today", onToggleSidebar: {})) + } + } + .padding(.bottom, BighelpTokens.space24) + } + } + + private func header(title: String? = nil, viewSwitch: HomeViewSwitch? = nil, search: HomeHeaderSearch? = nil, + newItems: [SimpleBotsNewItem] = [], trailing: AnyView? = nil, + computer: HomeHeaderComputer? = nil, + onToggleSidebar: (() -> Void)? = nil) -> HomeHeaderContext { + HomeHeaderContext(personName: "Sam Rivera", personImageURL: nil, onOpenSettings: {}, title: title, + viewSwitch: viewSwitch, search: search, newItems: newItems, trailing: trailing, + computer: computer, onToggleSidebar: onToggleSidebar) + } + + private var computer: HomeHeaderComputer { + let hosts = [("home", "Home Mac"), ("studio", "Studio Mac")].map { + BighelpMenuHosts.Host(id: $0.0, name: $0.1, isSelected: $0.0 == computerID) + } + return HomeHeaderComputer(name: hosts.first(where: \.isSelected)?.name ?? "", hosts: hosts, + select: { computerID = $0 }) + } + + private var editChip: some View { + Button {} label: { + Text(verbatim: "Edit") + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .padding(.horizontal, BighelpTokens.space16) + .frame(height: BighelpTokens.hitTarget) + .bighelpNavigationGlass(in: Capsule(), isInteractive: true) + } + .buttonStyle(.plain) + } + + private func sample(_ name: String, @ViewBuilder content: () -> Content) -> some View { + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + Text(verbatim: name) + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + .padding(.horizontal, BighelpTokens.space16) + content() + } + } + + // MARK: Bar + + private var bar: some View { + VStack { + Spacer() + Text(verbatim: "Selected: \(tab.rawValue)") + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + Spacer() + HomeTabBar(selection: $tab, items: HomeTabItem.standard(view: view, todayHasNew: true), onNewChat: {}) + } + } + + // MARK: Sidebar + + private var sidebarContext: HomeSidebarContext { + let chats: [(String, String, String, Bool)] = [ + ("trip", "Lisbon trip", "Mina", true), + ("budget", "Family budget", "Group chat", false), + ("garden", "Garden plan", "Jordan", false), + ] + let recent = chats.enumerated().map { index, chat in + HomeSidebarChat(id: chat.0, title: chat.1, subtitle: chat.2, + face: AnyView(AvatarView(stableID: chat.0, displayName: chat.2, size: 30)), + isUnread: chat.3, updatedAt: Date(timeIntervalSinceNow: -Double(index + 1) * 900), + open: {}) + } + return HomeSidebarContext( + items: HomeTabItem.standard(view: view, todayHasNew: true), selection: tab, onSelect: { tab = $0 }, + recent: recent, onSeeAll: {}, + more: [HomeSidebarLink(id: "shared", title: "Shared with bighelp", symbol: "tray.and.arrow.down", + detail: "2", showsDot: true, action: {})], + onNewChat: {}, onOpenSettings: {}) + } +} +#endif diff --git a/Bighelp/Home/HomeContracts.swift b/Bighelp/Home/HomeContracts.swift new file mode 100644 index 00000000..3b5b523b --- /dev/null +++ b/Bighelp/Home/HomeContracts.swift @@ -0,0 +1,33 @@ +import Foundation + +/// The two views of the first tab: one row per bot and group chat, or every chat, newest first. +/// The person picks which one the app opens on; the header's switch changes it for this run. +enum HomeConversationsView: String, CaseIterable, Sendable { + case bots, chats + + var title: String { + switch self { + case .bots: String(localized: "Bots") + case .chats: String(localized: "Chats") + } + } +} + +/// Where the app opens (Settings › Chat › Opens on). Bots and Chats open the first tab on that view. +enum HomeLanding: String, CaseIterable, Sendable { + case bots, chats, today, work + + var title: String { + switch self { + case .bots: String(localized: "Bots") + case .chats: String(localized: "Chats") + case .today: String(localized: "Today") + case .work: String(localized: "Work") + } + } +} + +/// The three places of the one home. The first takes the name of the person's default view. +enum HomeTab: String, CaseIterable, Sendable { + case conversations, today, work +} diff --git a/Bighelp/Home/HomeHeaderBar.swift b/Bighelp/Home/HomeHeaderBar.swift new file mode 100644 index 00000000..851eb03a --- /dev/null +++ b/Bighelp/Home/HomeHeaderBar.swift @@ -0,0 +1,344 @@ +import SwiftUI + +/// The first tab's Bots | Chats switch: which view of the conversations shows. It changes this run only; +/// Settings › Chat › Opens on picks the one the app opens on. +struct HomeViewSwitch { + let current: HomeConversationsView + let select: @MainActor (HomeConversationsView) -> Void +} + +/// Search in the header: a round button that opens a search page, or a field on the row under the buttons. +enum HomeHeaderSearch { + case button(label: LocalizedStringKey, identifier: String = "home.search", action: () -> Void) + case field(Binding, prompt: String, identifier: String = "home.search") +} + +/// The computer that Today and Work show, and the others to switch to. Only drawn with two or more. +struct HomeHeaderComputer { + let name: String + let hosts: [BighelpMenuHosts.Host] + let select: (String) -> Void + + var isShown: Bool { hosts.count >= 2 } +} + +/// What a home root's header draws. Each root hides the navigation bar and draws this on top. +@MainActor +struct HomeHeaderContext { + let personName: String + let personImageURL: URL? + let onOpenSettings: () -> Void + /// Today and Work. + var title: String? = nil + /// The first tab only. Wins over `title`. + var viewSwitch: HomeViewSwitch? = nil + var search: HomeHeaderSearch? = nil + /// The + menu, in this order; empty leaves + out. + var newItems: [SimpleBotsNewItem] = [] + var onNew: (SimpleBotsNewItem) -> Void = { _ in } + /// Today's Edit, for example. Sits before +. + var trailing: AnyView? = nil + /// Today and Work with two or more computers. + var computer: HomeHeaderComputer? = nil + /// iPad at regular width, Mac and Vision Pro: opens or closes the sidebar. + var onToggleSidebar: (() -> Void)? = nil + + /// What sits beside the person's circle. + enum Center: Equatable { + case viewSwitch(HomeConversationsView) + case title(String) + case empty + } + + var center: Center { + if let viewSwitch { return .viewSwitch(viewSwitch.current) } + if let title, !title.isEmpty { return .title(title) } + return .empty + } + + /// The computer menu, only when there's another computer to pick. + var shownComputer: HomeHeaderComputer? { + computer.flatMap { $0.isShown ? $0 : nil } + } +} + +/// The header every home root draws: the person's circle (Settings), the switch or the title, then +/// search, the computer, the root's own control and +. When the switch or the title doesn't fit beside +/// the buttons (large text), it moves to a row of its own instead of being cut. +struct HomeHeaderBar: View { + let context: HomeHeaderContext + + @BighelpThemeReader private var theme + + var body: some View { + VStack(spacing: BighelpTokens.space12) { + ViewThatFits(in: .horizontal) { + oneRow + twoRows + } + if case .field(let text, let prompt, let identifier) = context.search { + BighelpSearchField(text: text, prompt: prompt, accessibilityLabel: prompt, + accessibilityIdentifier: identifier) + } + } + // The slop each glass button would carry, so the placement puts the glass where the top bar does. + .padding(HeaderButtonMetrics.slop) + .bighelpHeaderButtonsPlacement() + .padding(.bottom, BighelpTokens.space8) + .background { HomeHeaderBackground() } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("home.header") + } + + // MARK: Layouts + + /// The switch centered between the two button groups, or the title after the circle. + @ViewBuilder + private var oneRow: some View { + switch context.center { + case .viewSwitch: + HomeHeaderRowLayout(spacing: BighelpTokens.space8) { + leadingButtons + centerView(wraps: false) + trailingButtons + } + case .title: + HStack(spacing: BighelpTokens.space8) { + leadingButtons + centerView(wraps: false) + Spacer(minLength: BighelpTokens.space8) + trailingButtons + } + case .empty: + HStack(spacing: BighelpTokens.space8) { + leadingButtons + Spacer(minLength: BighelpTokens.space8) + trailingButtons + } + } + } + + /// Large text: the buttons on top, the switch or the title whole under them. + private var twoRows: some View { + VStack(alignment: context.viewSwitch == nil ? .leading : .center, spacing: BighelpTokens.space8) { + HStack(spacing: BighelpTokens.space8) { + leadingButtons + Spacer(minLength: BighelpTokens.space8) + trailingButtons + } + if context.center != .empty { + centerView(wraps: true) + } + } + } + + @ViewBuilder + private func centerView(wraps: Bool) -> some View { + if let viewSwitch = context.viewSwitch { + HomeViewSwitchPill(viewSwitch: viewSwitch) + } else if let title = context.title, !title.isEmpty { + Text(title) + .font(.bighelp(.title2, weight: .bold)) + .foregroundStyle(theme.primaryText) + .lineLimit(wraps ? nil : 1) + .fixedSize(horizontal: !wraps, vertical: true) + .padding(.leading, wraps ? 0 : BighelpTokens.space4) + .accessibilityAddTraits(.isHeader) + .accessibilityIdentifier("home.title") + } + } + + // MARK: Buttons + + private var leadingButtons: some View { + HStack(spacing: BighelpTokens.space8) { + if let onToggleSidebar = context.onToggleSidebar { + SimpleBotsCircleButton(systemImage: "sidebar.leading", label: "Sidebar", + identifier: "home.sidebar-toggle", action: onToggleSidebar) + } + SimpleBotsPersonButton(name: context.personName, imageURL: context.personImageURL, + action: context.onOpenSettings) + } + .fixedSize() + } + + private var trailingButtons: some View { + HStack(spacing: BighelpTokens.space8) { + if let computer = context.shownComputer { + HomeHeaderComputerMenu(computer: computer) + } + if case .button(let label, let identifier, let action) = context.search { + SimpleBotsCircleButton(systemImage: "magnifyingglass", label: label, identifier: identifier, + action: action) + } + if let trailing = context.trailing { + trailing + } + if !context.newItems.isEmpty { + newMenu + } + } + .fixedSize() + } + + /// + : New bot, New group chat, New section, each only where it can work (the caller decides). + private var newMenu: some View { + Menu { + ForEach(context.newItems) { item in + Button(item.title, systemImage: item.systemImage) { context.onNew(item) } + .accessibilityIdentifier("home.new.\(item.rawValue)") + } + } label: { + Image(systemName: "plus") + .font(.bighelp(.title3, weight: .medium)) + .foregroundStyle(.primary) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(.circle) + .bighelpNavigationGlass(in: Circle(), isInteractive: true) + } + .menuOrder(.fixed) + .buttonStyle(.plain) + .accessibilityLabel("Add") + .accessibilityIdentifier("home.new") + } +} + +/// Behind a home root's header: the page color under the whole header, so a title is never drawn +/// over the rows scrolling by, then a short fade below it where they scroll away. +struct HomeHeaderBackground: View { + @BighelpThemeReader private var theme + + private static let fade: CGFloat = 16 + + var body: some View { + theme.canvas + .ignoresSafeArea(edges: .top) + .overlay(alignment: .bottom) { + LinearGradient(colors: [theme.canvas, theme.canvas.opacity(0)], startPoint: .top, endPoint: .bottom) + .frame(height: Self.fade) + .offset(y: Self.fade) + } + .allowsHitTesting(false) + } +} + +/// Bots | Chats, as tall as the header's glass buttons. The view showing sits in a lighter capsule. +struct HomeViewSwitchPill: View { + let viewSwitch: HomeViewSwitch + + @BighelpThemeReader private var theme + + private static let inset: CGFloat = 3 + + var body: some View { + HStack(spacing: 0) { + ForEach(HomeConversationsView.allCases, id: \.self) { view in + segment(view) + } + } + .padding(Self.inset) + .bighelpNavigationGlass(in: Capsule()) + .fixedSize() + .accessibilityElement(children: .contain) + .accessibilityLabel("View") + .accessibilityIdentifier("home.switch") + } + + private func segment(_ view: HomeConversationsView) -> some View { + let isOn = view == viewSwitch.current + return Button { + if !isOn { viewSwitch.select(view) } + } label: { + Text(view.title) + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(isOn ? theme.primaryText : theme.primaryText.opacity(0.75)) + .lineLimit(1) + .padding(.horizontal, BighelpTokens.scaled(13)) + .frame(minHeight: HeaderButtonMetrics.glass - Self.inset * 2) + .background { + if isOn { + Capsule() + .fill(selectedFill) + .shadow(color: .black.opacity(theme.isDarkPalette ? 0 : 0.12), radius: 2, y: 1) + } + } + .contentShape(Capsule()) + } + .bighelpPlainButtonStyle(.capsule) + .accessibilityAddTraits(isOn ? .isSelected : []) + .accessibilityIdentifier("home.switch.\(view.rawValue)") + } + + /// Dark: nearly black, sunk into the glass. Light: a white page on the gray track. + private var selectedFill: Color { + theme.isDarkPalette ? Color.black.opacity(0.6) : theme.canvas + } +} + +/// The computer in use, as a capsule; the others one tap away. +private struct HomeHeaderComputerMenu: View { + let computer: HomeHeaderComputer + + @BighelpThemeReader private var theme + + var body: some View { + Menu { + ForEach(computer.hosts) { host in + Button { computer.select(host.id) } label: { + if host.isSelected { Label(host.name, systemImage: "checkmark") } else { Text(host.name) } + } + .accessibilityIdentifier("home.computer.\(host.id)") + } + } label: { + HStack(spacing: BighelpTokens.space4) { + Text(computer.name) + .lineLimit(1) + Image(systemName: "chevron.up.chevron.down") + .font(.bighelp(.caption2, weight: .semibold)) + .accessibilityHidden(true) + } + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .padding(.horizontal, BighelpTokens.space12) + .frame(maxWidth: BighelpTokens.scaled(160)) + .frame(height: BighelpTokens.hitTarget) + .contentShape(Capsule()) + .bighelpNavigationGlass(in: Capsule(), isInteractive: true) + } + .menuOrder(.fixed) + .buttonStyle(.plain) + .accessibilityLabel("Computer") + .accessibilityValue(computer.name) + .accessibilityIdentifier("home.computer") + } +} + +/// One header row: the leading group at the start, the trailing group at the end, and the middle +/// view centered on the row. Its ideal width keeps the middle clear of both groups, so a +/// `ViewThatFits` falls back to two rows instead of letting them overlap. +struct HomeHeaderRowLayout: Layout { + var spacing: CGFloat + + /// The narrowest row that keeps the middle centered and clear of both sides. + static func requiredWidth(leading: CGFloat, middle: CGFloat, trailing: CGFloat, spacing: CGFloat) -> CGFloat { + 2 * max(leading, trailing) + middle + 2 * spacing + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let sizes = subviews.map { $0.sizeThatFits(.unspecified) } + guard sizes.count == 3 else { + return CGSize(width: sizes.map(\.width).reduce(0, +), height: sizes.map(\.height).max() ?? 0) + } + let required = Self.requiredWidth(leading: sizes[0].width, middle: sizes[1].width, + trailing: sizes[2].width, spacing: spacing) + let width = proposal.width.flatMap { $0.isFinite ? max($0, required) : nil } ?? required + return CGSize(width: width, height: sizes.map(\.height).max() ?? 0) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + guard subviews.count == 3 else { return } + subviews[0].place(at: CGPoint(x: bounds.minX, y: bounds.midY), anchor: .leading, proposal: .unspecified) + subviews[1].place(at: CGPoint(x: bounds.midX, y: bounds.midY), anchor: .center, proposal: .unspecified) + subviews[2].place(at: CGPoint(x: bounds.maxX, y: bounds.midY), anchor: .trailing, proposal: .unspecified) + } +} diff --git a/Bighelp/Home/HomeMenuPresentation.swift b/Bighelp/Home/HomeMenuPresentation.swift new file mode 100644 index 00000000..f9797b2d --- /dev/null +++ b/Bighelp/Home/HomeMenuPresentation.swift @@ -0,0 +1,103 @@ +import SwiftUI + + + +/// Presents the sidebar on iPad: it slides in from the leading edge over a dimmed screen, and a tap +/// outside closes it. iPhone has no sidebar: its bar holds the places. +/// The panel is a see-through full-screen cover so it sits above the title bar. +struct HomeMenuPresentation: ViewModifier { + @Binding var isPresented: Bool + let onDismiss: () -> Void + /// A new host/runtime supplies new stores and actions, not just new values. + var contentID: ObjectIdentifier? = nil + @ViewBuilder let menu: () -> Menu + + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.bighelpSideMenu) private var sideMenu + @State private var isCoverPresented = false + @State private var isPanelVisible = false + + static var panelWidth: CGFloat { 380 } + + func body(content: Content) -> some View { + if let sideMenu { + // Vision Pro and Mac: a column beside the app, which narrows to make + // room. The Mac's stays open while you pick chats and pages. + content.onChange(of: isPresented, initial: true) { _, presented in + if presented { showSideMenu(sideMenu) } else { sideMenu.hide() } + } + .onChange(of: contentID) { + if isPresented { showSideMenu(sideMenu) } + } + } else if horizontalSizeClass == .regular { + content + .bighelpFullScreenCover(isPresented: $isCoverPresented, onDismiss: onDismiss) { + panel.presentationBackground(.clear) + } + .onChange(of: isPresented, initial: true) { _, presented in + presented ? open() : close() + } + } else { + // Compact width has no sidebar. One left open (an iPad window made narrow) closes. + content.onChange(of: isPresented, initial: true) { _, presented in + if presented { isPresented = false } + } + } + } + + private func showSideMenu(_ sideMenu: BighelpSideMenu) { + // Build inside a SwiftUI update, not the presentation callback, so + // readiness keeps updating. contentID also replaces captured stores. + let panel = BighelpDeferredSection { menu() } + sideMenu.show(AnyView(panel)) { + isPresented = false + onDismiss() + } + } + + private var slide: Animation? { reduceMotion ? nil : .snappy(duration: 0.28) } + + private func open() { + guard !isCoverPresented else { return } + // The cover itself appears instantly; the panel does the sliding. + var instant = Transaction() + instant.disablesAnimations = true + withTransaction(instant) { isCoverPresented = true } + } + + private func close() { + guard isCoverPresented else { return } + withAnimation(slide) { + isPanelVisible = false + } completion: { + var instant = Transaction() + instant.disablesAnimations = true + withTransaction(instant) { isCoverPresented = false } + } + } + + private var panel: some View { + ZStack(alignment: .leading) { + if isPanelVisible { + Color.black.opacity(0.24) + .ignoresSafeArea() + .contentShape(.rect) + .onTapGesture { isPresented = false } + .accessibilityHidden(true) + .transition(.opacity) + menu() + .frame(width: Self.panelWidth) + .frame(maxHeight: .infinity) + .clipShape(.rect(topLeadingRadius: 0, bottomLeadingRadius: 0, + bottomTrailingRadius: 28, topTrailingRadius: 28)) + .shadow(color: .black.opacity(0.18), radius: 24, x: 6) + .ignoresSafeArea(.container, edges: .vertical) + .accessibilityAction(.escape) { isPresented = false } + .transition(.move(edge: .leading)) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + .onAppear { withAnimation(slide) { isPanelVisible = true } } + } +} diff --git a/Bighelp/Home/HomeSelection.swift b/Bighelp/Home/HomeSelection.swift new file mode 100644 index 00000000..92ac49de --- /dev/null +++ b/Bighelp/Home/HomeSelection.swift @@ -0,0 +1,41 @@ +import Foundation +import Observation + +/// Where the one home is and what it holds above any one computer: the bar's tab, the first tab's +/// view (Bots or Chats), New chat's picks, and Today's panels and boards. Every computer has its own +/// `AppState`, stores and chats (`NativeWorkspaceRuntime`); these stay when the computer in use +/// changes, so a bot picked on another computer keeps the tab, the view and the To row. +@MainActor +@Observable +final class HomeSelection { + /// The app's own. Tests and previews make one of their own (`AppState()`). + static let shared = HomeSelection() + + var tab: HomeTab = .conversations + /// The first tab's view. The header's switch changes it for this run; a launch starts on + /// `SettingsStore.homeView`. + var view: HomeConversationsView = .chats + + /// New chat's text and To row on their way to another computer with a pick (`handOffNewChat`, + /// `takeNewChatHandoff(after:)`). + @ObservationIgnored var newChatHandoff: NewChatHandoff? + /// An alert that names no chat asked for Needs you (`AppState.openNeedsYou`). Here, not in an + /// `AppState`: every computer has its own, and the one that got the tap isn't always the one + /// the shell on screen reads. + var isNeedsYouRequested = false + + @ObservationIgnored private(set) lazy var newChat = NewChatSession() + @ObservationIgnored private(set) lazy var todayLayout = TodayPanelLayoutStore() + @ObservationIgnored private(set) lazy var todayBoards = TodayBoardsStore() + + /// Where the app opens (Settings › Chat › Opens on), applied once as the app starts: Bots and + /// Chats are the first tab's views. No chat opens by itself. + func land(on landing: HomeLanding, view defaultView: HomeConversationsView) { + switch landing { + case .bots: (tab, view) = (.conversations, .bots) + case .chats: (tab, view) = (.conversations, .chats) + case .today: (tab, view) = (.today, defaultView) + case .work: (tab, view) = (.work, defaultView) + } + } +} diff --git a/Bighelp/Home/HomeSidebar.swift b/Bighelp/Home/HomeSidebar.swift new file mode 100644 index 00000000..b902f12e --- /dev/null +++ b/Bighelp/Home/HomeSidebar.swift @@ -0,0 +1,229 @@ +import SwiftUI + +/// A recent chat in the sidebar, as the shell reads it from the chat lists. +struct HomeSidebarChat: Identifiable { + let id: String + let title: String + /// Who it's with (a bot, or the group's name). + let subtitle: String + /// The bot's face, or the group's. + let face: AnyView + var isUnread = false + var updatedAt: Date? + let open: () -> Void +} + +/// A row in the sidebar's More group (Shared with bighelp, for example). +struct HomeSidebarLink: Identifiable { + let id: String + let title: String + let symbol: String + var detail: String? + var showsDot = false + let action: () -> Void +} + +/// What the sidebar shows: the three places, recent chats, then More. +@MainActor +struct HomeSidebarContext { + let items: [HomeTabItem] + /// The place showing; nil while a chat is open over it. + let selection: HomeTab? + let onSelect: (HomeTab) -> Void + var recent: [HomeSidebarChat] = [] + /// All chats; nil leaves See all out. + var onSeeAll: (() -> Void)? = nil + var more: [HomeSidebarLink] = [] + let onNewChat: () -> Void + let onOpenSettings: () -> Void + /// Runs before every choice: closes the iPad's slide-in panel; nothing for a sidebar that stays. + var close: () -> Void = {} +} + +/// The sidebar on iPad (slide-in), Mac and Vision Pro (`BighelpSideMenu` hosts it): the home's three +/// places, recent chats and More. iPhone has no sidebar; its bar holds the places. +struct HomeSidebar: View { + let context: HomeSidebarContext + + @BighelpThemeReader private var theme + + var body: some View { + List { + placesSection + recentSection + if !context.more.isEmpty { moreSection } + } + .listStyle(.insetGrouped) + .listSectionSpacing(16) + .environment(\.defaultMinListRowHeight, BighelpTokens.hitTarget) + .scrollContentBackground(.hidden) + .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) + .tint(theme.action) + .accessibilityIdentifier("home.sidebar") + } + + // MARK: Places + + private var placesSection: some View { + Section { + ForEach(context.items) { item in + let isSelected = context.selection == item.id + row(item.title, symbol: item.symbol(selected: isSelected), + id: "home.sidebar.place.\(item.id.rawValue)", + trailing: item.showsDot(selected: isSelected) ? .new : .none, + isSelected: isSelected) { context.onSelect(item.id) } + } + row(String(localized: "Settings"), symbol: "gearshape", id: "home.sidebar.settings", + action: context.onOpenSettings) + } header: { + HStack { + Spacer(minLength: 0) + newChatButton + } + .padding(.bottom, BighelpTokens.space4) + } + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } + + private var newChatButton: some View { + Button { choose(context.onNewChat) } label: { + Image(systemName: "square.and.pencil") + .font(.bighelp(.body).weight(.semibold)) + .foregroundStyle(theme.actionForeground) + .frame(width: BighelpTokens.scaled(40), height: BighelpTokens.scaled(40)) + .background(theme.action, in: Circle()) + // The circle stays its size; a touch counts over a full target around it. + .frame(minWidth: BighelpTokens.hitTarget, minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle(.circle) + .textCase(nil) + .bighelpHelp(HomeTabBar.newChatAccessibilityLabel, shortcut: "⌘N") + .accessibilityLabel(HomeTabBar.newChatAccessibilityLabel) + .accessibilityIdentifier("home.sidebar.new-chat") + } + + // MARK: Recent + + private var recentSection: some View { + Section { + if context.recent.isEmpty { + Text("Your chats show up here.") + .bighelpFont(.metadata) + .foregroundStyle(theme.secondaryText) + } else { + ForEach(context.recent) { chat in + Button { choose(chat.open) } label: { + HomeSidebarChatLabel(chat: chat) + .padding(.horizontal, BighelpMenuRowLayout.labelInset) + } + .bighelpPlainButtonStyle(BighelpMenuRowLayout.outline, + padding: BighelpMenuRowLayout.highlightPadding) + .listRowInsets(BighelpMenuRowLayout.insets) + .bighelpMenuRowSeparator() + .accessibilityIdentifier("home.sidebar.chat.\(chat.id)") + } + } + } header: { + HStack { + Text("Recent chats") + Spacer() + if let onSeeAll = context.onSeeAll { + Button("See all") { choose(onSeeAll) } + .font(.bighelp(.subheadline).weight(.semibold)) + .textCase(nil) + #if targetEnvironment(macCatalyst) + .bighelpPlainButtonStyle(padding: BighelpTokens.space4) + #endif + .accessibilityLabel("See all chats") + .accessibilityIdentifier("home.sidebar.see-all") + } + } + } + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } + + // MARK: More + + private var moreSection: some View { + Section("More") { + ForEach(context.more) { link in + row(link.title, detail: link.detail, symbol: link.symbol, id: "home.sidebar.more.\(link.id)", + trailing: link.showsDot ? .new : .none, action: link.action) + } + } + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } + + // MARK: Rows + + private func row(_ title: String, detail: String? = nil, symbol: String, id: String, + trailing: BighelpMenuRowLabel.Trailing = .none, isSelected: Bool = false, + action: @escaping () -> Void) -> some View { + Button { choose(action) } label: { + BighelpMenuRowLabel(title: title, detail: detail, symbol: symbol, trailing: trailing) + .padding(.horizontal, BighelpMenuRowLayout.labelInset) + .background { + if isSelected { + RoundedRectangle(cornerRadius: BighelpTokens.radius12, style: .continuous) + .fill(theme.surface) + .padding(-BighelpMenuRowLayout.highlightPadding) + .accessibilityHidden(true) + } + } + } + .bighelpPlainButtonStyle(BighelpMenuRowLayout.outline, padding: BighelpMenuRowLayout.highlightPadding) + .listRowInsets(BighelpMenuRowLayout.insets) + .bighelpMenuRowSeparator() + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier(id) + } + + private func choose(_ action: () -> Void) { + context.close() + action() + } +} + +/// A recent chat's row: its face, title and who it's with, unread, and when it last moved. The same +/// look as the old menu's `BighelpMenuChatRow`, from values the shell hands over, so chats on any +/// computer draw alike. +private struct HomeSidebarChatLabel: View { + let chat: HomeSidebarChat + + @BighelpThemeReader private var theme + + var body: some View { + HStack(spacing: BighelpTokens.space12) { + chat.face + .frame(width: 30, height: 30) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(chat.title.isEmpty ? String(localized: "New chat") : chat.title) + .bighelpFont(.body) + .foregroundStyle(theme.primaryText) + .lineLimit(1) + Text(chat.subtitle) + .bighelpFont(.metadata) + .foregroundStyle(theme.secondaryText) + .lineLimit(1) + } + Spacer(minLength: BighelpTokens.space8) + if chat.isUnread { + Circle().fill(theme.action).frame(width: 8, height: 8) + .accessibilityLabel("Unread") + } + if let updatedAt = chat.updatedAt { + Text(updatedAt, format: .relative(presentation: .named, unitsStyle: .narrow)) + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + } + } + .frame(minHeight: 44) + .contentShape(.rect) + .accessibilityElement(children: .combine) + } +} diff --git a/Bighelp/Home/HomeStripTabs.swift b/Bighelp/Home/HomeStripTabs.swift new file mode 100644 index 00000000..ab7f08a1 --- /dev/null +++ b/Bighelp/Home/HomeStripTabs.swift @@ -0,0 +1,63 @@ +import SwiftUI +import UIKit + +/// The home's places handed to iOS as toolbar items, for the iPhone Duo's side strip. Built with the +/// iOS 27.1 SDK, the Duo lays a screen's toolbar out down the strip, so the places line up with the +/// screen's own buttons there instead of a column of our own lying over them. +struct HomeStripTabs: ToolbarContent { + @Binding var selection: HomeTab + let items: [HomeTabItem] + var onNewChat: (() -> Void)? + let selectedTint: Color + let tint: Color + + var body: some ToolbarContent { + ToolbarItemGroup(placement: .bottomBar) { + ForEach(items) { item in + place(item) + } + if let onNewChat { + Button(action: onNewChat) { + Label(HomeTabBar.newChatVisibleLabel, systemImage: "square.and.pencil") + } + .tint(selectedTint) + .accessibilityIdentifier(HomeTabBar.newChatIdentifier) + } + } + } + + private func place(_ item: HomeTabItem) -> some View { + let isSelected = selection == item.id + let isNew = item.showsDot(selected: isSelected) + return Button { + BighelpKeyboard.dismiss() + selection = item.id + } label: { + Label { Text(item.title) } icon: { icon(item, selected: isSelected, isNew: isNew) } + .labelStyle(.iconOnly) + } + .tint(isSelected ? selectedTint : tint) + .accessibilityLabel(item.title) + .accessibilityValue(isNew ? String(localized: "New") : "") + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier(item.accessibilityIdentifier) + } + + private func icon(_ item: HomeTabItem, selected: Bool, isNew: Bool) -> Image { + let name = item.symbol(selected: selected) + guard isNew, let base = UIImage(systemName: name) else { return Image(systemName: name) } + // A toolbar button shows no badge, so Today with something new draws the bar's dot into its + // icon, colored here as the toolbar would have tinted it. + let diameter = max(6, base.size.width * 0.28) + // The dot gets its own corner, just outside the icon's art. + let inset = diameter * 0.5 + let size = CGSize(width: base.size.width + inset, height: base.size.height + inset) + let image = UIGraphicsImageRenderer(size: size).image { _ in + base.withTintColor(UIColor(tint), renderingMode: .alwaysOriginal).draw(at: CGPoint(x: 0, y: inset)) + UIColor(selectedTint).setFill() + UIBezierPath(ovalIn: CGRect(x: size.width - diameter, y: 0, width: diameter, height: diameter)).fill() + } + // On the image itself: the toolbar tints anything it's allowed to. + return Image(uiImage: image.withRenderingMode(.alwaysOriginal)) + } +} diff --git a/Bighelp/Home/HomeTabBar.swift b/Bighelp/Home/HomeTabBar.swift new file mode 100644 index 00000000..15d4e4b3 --- /dev/null +++ b/Bighelp/Home/HomeTabBar.swift @@ -0,0 +1,152 @@ +import SwiftUI + +/// One of the home's three places as the bar, the ornament, the Duo's strip and the sidebar show it. +struct HomeTabItem: Identifiable, Equatable { + let id: HomeTab + let title: String + let systemImage: String + let selectedSystemImage: String + /// Something there the person hasn't seen (Today). + var showsDot = false + + var accessibilityIdentifier: String { "home.tab.\(id.rawValue)" } + + func symbol(selected: Bool) -> String { selected ? selectedSystemImage : systemImage } + + /// The dot shows only on a place you're not on. + func showsDot(selected: Bool) -> Bool { showsDot && !selected } + + /// The three places in order. The first is named after the view the app opens on. + static func standard(view: HomeConversationsView, todayHasNew: Bool = false) -> [HomeTabItem] { + [ + view == .bots + ? HomeTabItem(id: .conversations, title: view.title, systemImage: "bubble.left.and.bubble.right", + selectedSystemImage: "bubble.left.and.bubble.right.fill") + : HomeTabItem(id: .conversations, title: view.title, systemImage: "bubble.left", + selectedSystemImage: "bubble.left.fill"), + HomeTabItem(id: .today, title: String(localized: "Today"), systemImage: "sun.max", + selectedSystemImage: "sun.max.fill", showsDot: todayHasNew), + HomeTabItem(id: .work, title: String(localized: "Work"), systemImage: "hammer", + selectedSystemImage: "hammer.fill"), + ] + } +} + +/// The home's bottom bar on iPhone and iPad: the three places in a glass capsule, and the round +/// New chat button beside it. Shown at the roots only; a pushed chat has Back instead. +struct HomeTabBar: View { + @Binding var selection: HomeTab + let items: [HomeTabItem] + let onNewChat: () -> Void + /// Points the bar drops into the home indicator's area (`homeIndicatorSink(forBottomInset:)`). + var homeIndicatorSink: CGFloat = 0 + + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.verticalSizeClass) private var verticalSizeClass + @State private var tabChanges = 0 + @ScaledMetric(relativeTo: .caption2) private var iconSize: CGFloat = 22 + @BighelpThemeReader private var theme + + static let newChatIdentifier = "home.new-chat" + static let newChatVisibleLabel = String(localized: "New chat") + static let newChatAccessibilityLabel = String(localized: "New chat") + + /// Like the system tab bar, the bar sits low, just above the home indicator, instead of a full + /// safe-area inset above it. Clamped so a keyboard's inset never pushes it off screen. + static func homeIndicatorSink(forBottomInset inset: CGFloat) -> CGFloat { + min(max(0, inset - 14), 20) + } + + private var isVerticallyCompact: Bool { verticalSizeClass == .compact } + + var body: some View { + HStack(alignment: .center, spacing: BighelpTokens.space12) { + NavigationRowLayout(constrainsWidth: true) { + ForEach(items) { item in place(item) } + } + .padding(6) + .bighelpNavigationGlass(in: Capsule()) + .sensoryFeedback(.selection, trigger: tabChanges) + .frame(maxWidth: BighelpTokens.scaled(380)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Primary navigation") + .accessibilityIdentifier("primary-navigation") + Spacer(minLength: 0) + RootComposeButton(identifier: Self.newChatIdentifier, systemImage: "square.and.pencil", + size: BighelpTokens.scaled(isVerticallyCompact ? 44 : 56), action: onNewChat) + .accessibilityShowsLargeContentViewer { + Label(Self.newChatVisibleLabel, systemImage: "square.and.pencil") + } + } + .padding(.horizontal, BighelpTokens.space12) + .padding(.vertical, isVerticallyCompact ? 4 : 8) + .frame(maxWidth: BighelpTokens.scaled(620)) + .frame(maxWidth: .infinity) + // One place on every root: nothing moves the bar. + .padding(.bottom, -homeIndicatorSink) + } + + private func place(_ item: HomeTabItem) -> some View { + let isSelected = selection == item.id + let showsDot = item.showsDot(selected: isSelected) + return Button { + BighelpKeyboard.dismiss() + guard selection != item.id else { return } + tabChanges += 1 + withAnimation(reduceMotion ? nil : .snappy(duration: BighelpTokens.transitionDuration)) { + selection = item.id + } + } label: { + label(item, selected: isSelected) + .overlay(alignment: .topTrailing) { + if showsDot { + Circle() + .fill(theme.action) + .frame(width: 8, height: 8) + .padding(.top, isVerticallyCompact ? 4 : 8) + .padding(.trailing, 10) + .accessibilityHidden(true) + } + } + } + .buttonStyle(.bighelpTilePress) + .bighelpHover(in: Capsule()) + .bighelpHelp(item.title, shortcut: items.firstIndex(of: item).map { "⌘\($0 + 1)" }) + .accessibilityLabel(item.title) + .accessibilityValue(showsDot ? String(localized: "New") : "") + .accessibilityShowsLargeContentViewer { + Label(item.title, systemImage: item.symbol(selected: isSelected)) + } + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier(item.accessibilityIdentifier) + } + + private func label(_ item: HomeTabItem, selected: Bool) -> some View { + VStack(spacing: 2) { + Image(systemName: item.symbol(selected: selected)) + .resizable() + .scaledToFit() + .fontWeight(.medium) + .frame(width: BighelpTokens.scaled(min(iconSize, 28)), height: BighelpTokens.scaled(min(iconSize, 28))) + .accessibilityHidden(true) + Text(item.title) + .font(.bighelp(.caption2).weight(.semibold)) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + // The theme's ink, not `.secondary`, which goes vibrant on glass. The current place is a pill. + .foregroundStyle(selected ? theme.actionForeground : theme.secondaryText) + .padding(.horizontal, 4) + .padding(.vertical, isVerticallyCompact ? 3 : 6) + .frame(minWidth: BighelpTokens.hitTarget, maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) + .background { + if selected { + Capsule() + .fill(theme.action) + .transition(reduceMotion ? .opacity : .scale(scale: 0.86).combined(with: .opacity)) + .accessibilityHidden(true) + } + } + .contentShape(.rect) + } +} diff --git a/Bighelp/Home/HomeTabOrnament.swift b/Bighelp/Home/HomeTabOrnament.swift new file mode 100644 index 00000000..47e00f3e --- /dev/null +++ b/Bighelp/Home/HomeTabOrnament.swift @@ -0,0 +1,70 @@ +import SwiftUI + +#if os(visionOS) +/// Vision Pro's places: a vertical glass strip beside the window, where visionOS puts its own tab +/// bars, with New chat under them. Each target is 60pt and lights up where you look. Shown at the +/// roots only; a pushed chat has Back. +struct HomeTabOrnament: View { + @Binding var selection: HomeTab + let items: [HomeTabItem] + var onNewChat: (() -> Void)? + + var body: some View { + VStack(spacing: BighelpTokens.space8) { + ForEach(items) { item in place(item) } + if let onNewChat { + Divider().frame(width: 36) + Button(action: onNewChat) { + Image(systemName: "square.and.pencil") + .font(.bighelp(.title2).weight(.semibold)) + .frame(width: 60, height: 60) + } + .buttonStyle(.plain) + .buttonBorderShape(.circle) + .contentShape(.hoverEffect, Circle()) + .hoverEffect(.highlight) + .help(HomeTabBar.newChatVisibleLabel) + .accessibilityLabel(HomeTabBar.newChatAccessibilityLabel) + .accessibilityIdentifier(HomeTabBar.newChatIdentifier) + } + } + .padding(BighelpTokens.space12) + .glassBackgroundEffect(in: Capsule()) + .accessibilityElement(children: .contain) + .accessibilityLabel("Primary navigation") + .accessibilityIdentifier("primary-navigation") + } + + private func place(_ item: HomeTabItem) -> some View { + let isSelected = selection == item.id + let showsDot = item.showsDot(selected: isSelected) + return Button { + selection = item.id + } label: { + Image(systemName: item.symbol(selected: isSelected)) + .resizable() + .scaledToFit() + .fontWeight(.medium) + .frame(width: 28, height: 28) + .frame(width: 60, height: 60) + .background { + if isSelected { Circle().fill(.white.opacity(0.22)) } + } + .overlay(alignment: .topTrailing) { + if showsDot { + Circle().fill(Color.accentColor).frame(width: 10, height: 10).padding(8) + } + } + } + .buttonStyle(.plain) + .buttonBorderShape(.circle) + .contentShape(.hoverEffect, Circle()) + .hoverEffect(.highlight) + .help(item.title) + .accessibilityLabel(item.title) + .accessibilityValue(showsDot ? String(localized: "New") : "") + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier(item.accessibilityIdentifier) + } +} +#endif diff --git a/Bighelp/Home/NewChat/NewChatChoicesRow.swift b/Bighelp/Home/NewChat/NewChatChoicesRow.swift new file mode 100644 index 00000000..b448fff4 --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatChoicesRow.swift @@ -0,0 +1,347 @@ +import SwiftUI + +/// What the choices row under New chat's message box needs. The shell gives one only for exactly one +/// picked bot on a computer with a `CodeHomeStore`; without it there's no row. +@MainActor +struct NewChatChoicesContext { + let session: NewChatSession + let store: CodeHomeStore + /// The picked bot's profile on the store's computer. Projects are each bot's own. + let agentID: String + /// The message box holds text (from `ChatModel.draftShape`): Stage needs it, Send all counts it. + let hasText: Bool + /// The box's text, read only when a chip needs it: Stage, and the branch name the picker suggests. + let draft: @MainActor () -> String + /// Empties the box once Stage has taken its text. + let clearDraft: @MainActor () -> Void + let onWorktrees: @MainActor () -> Void + /// Starts the staged jobs and the box's text as one batch (`CodeHomeStore.sendAll(including:)`). + let onSendAll: @MainActor () -> Void +} + +/// New chat's choices for one bot, in one row that scrolls sideways and never wraps: Project (none is +/// an ordinary chat), then, once a project is picked, where it runs (a new worktree or local), the +/// branch, the mode (Hermes' Plan and YOLO) and Stage. It reads and writes `CodeHomeStore` as Code +/// mode's message box does. Staged jobs show in a tray above it, with Send all. Equatable, so the +/// chat's redraws leave it alone: a chip change redraws only the row, through Observation. +struct NewChatChoicesRow: View, Equatable { + let context: NewChatChoicesContext + @State private var isPickingProject = false + @State private var isPickingBranch = false + /// The box's text when the branch picker opened, for the name it suggests. + @State private var branchMessage = "" + /// The store's project when its picker opened: a pick there becomes the chat's project. + @State private var projectBeforePicker: String? + @BighelpThemeReader private var theme + + /// What `==` compares, kept apart from the context's closures, which it never reads. + private let session: NewChatSession + private let store: CodeHomeStore + private let agentID: String + private let hasText: Bool + + init(context: NewChatChoicesContext) { + self.context = context + session = context.session + store = context.store + agentID = context.agentID + hasText = context.hasText + } + + nonisolated static func == (lhs: NewChatChoicesRow, rhs: NewChatChoicesRow) -> Bool { + lhs.session === rhs.session && lhs.store === rhs.store + && lhs.agentID == rhs.agentID && lhs.hasText == rhs.hasText + } + + var body: some View { + if session.recipients.count == 1 { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + if session.project != nil, !store.projectStaged.isEmpty { + NewChatStagedTray(store: store, hasText: hasText, onSendAll: context.onSendAll) + } + ScrollView(.horizontal) { + HStack(spacing: BighelpTokens.space8) { + projectChip + if session.project != nil { + placementMenu + branchChip + modeMenu + stageChip + } + } + .padding(.horizontal, BighelpTokens.space4) + } + .scrollIndicators(.hidden) + } + .padding(.horizontal, BighelpTokens.space12) + .padding(.bottom, BighelpTokens.space8) + .bighelpSheet(isPresented: $isPickingProject, onDismiss: adoptPickedProject) { + CodeProjectPicker(store: store) + .bighelpSheetSize(.standard) + } + .bighelpSheet(isPresented: $isPickingBranch) { + CodeBranchPicker(store: store, message: branchMessage) + .bighelpSheetSize(.standard) + } + // Work or another chat changed the store's project: this chat's follows while it has one. + .onChange(of: store.projectID) { _, _ in + if session.project != nil, let project = store.project { session.project = project } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("new-chat.choices") + } + } + + // MARK: Project + + /// The store's projects are its bot's: until it's on this one, the chip opens the picker after + /// switching it, so nothing changes until the person taps. + @ViewBuilder + private var projectChip: some View { + let label = CodeChipLabel(systemImage: "folder", text: session.project?.name ?? String(localized: "Project")) + if store.agentID == agentID { + Menu { + Button { session.project = nil } label: { + Label("No project", systemImage: session.project == nil ? "checkmark" : "bubble.left") + } + .accessibilityIdentifier("new-chat.project.none") + if !store.projects.isEmpty { + Section("Projects") { + ForEach(store.projects) { project in + Button { pick(project) } label: { + Label(project.name, systemImage: session.project?.id == project.id ? "checkmark" : "folder") + } + .accessibilityIdentifier("new-chat.project.\(project.id)") + } + } + } + Button("More projects…", systemImage: "ellipsis.circle") { openProjectPicker() } + .accessibilityIdentifier("new-chat.project.more") + } label: { + label + } + .accessibilityLabel(projectLabel) + .accessibilityIdentifier("new-chat.chip.project") + .task(id: agentID) { if store.projects.isEmpty { await store.load() } } + } else { + Button { + Task { + await store.selectAgent(agentID) + openProjectPicker() + } + } label: { + label + } + .bighelpPlainButtonStyle(.capsule) + .accessibilityLabel(projectLabel) + .accessibilityIdentifier("new-chat.chip.project") + } + } + + private var projectLabel: String { + session.project.map { String(localized: "Project: \($0.name)") } ?? String(localized: "Project: none") + } + + private func pick(_ project: CodeProject) { + session.project = project + Task { await store.selectProject(project.id) } + } + + private func openProjectPicker() { + projectBeforePicker = store.projectID + isPickingProject = true + } + + /// The picker selects in the store; a project picked there (or added) becomes this chat's. + private func adoptPickedProject() { + guard store.projectID != projectBeforePicker, let project = store.project else { return } + session.project = project + } + + // MARK: Where it runs, branch, mode + + private var placementMenu: some View { + Menu { + Section("Where should this chat run?") { + ForEach(CodePlacement.allCases) { placement in + Button { + store.placement = placement + store.branch = nil + } label: { + Label(placement.title, + systemImage: store.placement == placement ? "checkmark" : placement.systemImage) + Text(detail(for: placement)) + } + .accessibilityIdentifier("new-chat.placement.\(placement.rawValue)") + } + } + Button("Manage worktrees", systemImage: "square.stack.3d.up") { context.onWorktrees() } + } label: { + CodeChipLabel(systemImage: store.placement.systemImage, text: store.placement.title) + } + .accessibilityLabel(String(localized: "Where it runs: \(store.placement.title)")) + .accessibilityIdentifier("new-chat.chip.placement") + } + + /// Local warns about the chats already working in the project's folder. + private func detail(for placement: CodePlacement) -> String { + let busy = store.sessionsInMainFolder + guard placement == .local, busy > 0 else { return placement.detail } + return busy == 1 ? String(localized: "1 chat is already working here.") + : String(localized: "\(busy) chats are already working here.") + } + + private var branchChip: some View { + Button { + branchMessage = context.draft() + isPickingBranch = true + } label: { + CodeChipLabel(systemImage: "arrow.triangle.branch", + text: store.branchTitle ?? String(localized: "Branch"), monospaced: true) + } + .bighelpPlainButtonStyle(.capsule) + .disabled(store.git == nil) + .accessibilityLabel(String(localized: "Branch: \(store.branchTitle ?? String(localized: "default"))")) + .accessibilityIdentifier("new-chat.chip.branch") + } + + private var modeMenu: some View { + Menu { + Section("How should this chat work?") { + ForEach(CodeSessionMode.allCases) { mode in + Button { + store.mode = mode + } label: { + Label(mode.title, systemImage: store.mode == mode ? "checkmark" : mode.systemImage) + Text(mode.detail) + } + .accessibilityIdentifier("new-chat.mode.\(mode.rawValue)") + } + } + } label: { + CodeChipLabel(systemImage: store.mode.systemImage, text: store.mode.title) + } + .accessibilityLabel(String(localized: "Mode: \(store.mode.title)")) + .accessibilityIdentifier("new-chat.chip.mode") + } + + /// Keeps the box's text, with the chips as they are, for Send all. + private var stageChip: some View { + Button { + if store.stage(context.draft()) { context.clearDraft() } + } label: { + CodeChipLabel(systemImage: "rectangle.stack.badge.plus", text: String(localized: "Stage")) + } + .bighelpPlainButtonStyle(.capsule) + .disabled(!hasText || store.project == nil) + .accessibilityIdentifier("new-chat.chip.stage") + } +} + +/// The project's staged jobs over the choices row, each with the chips it was staged with, and Send +/// all. Send all is in this tray: New chat's own Send +/// button never changes for it. +private struct NewChatStagedTray: View { + let store: CodeHomeStore + let hasText: Bool + let onSendAll: @MainActor () -> Void + @BighelpThemeReader private var theme + + var body: some View { + let jobs = store.projectStaged + let count = jobs.count + (hasText ? 1 : 0) + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + HStack(spacing: BighelpTokens.space8) { + Text("Staged").font(.bighelp(.subheadline).weight(.semibold)) + + Text(jobs.count == 1 ? " · 1 job" : " · \(jobs.count) jobs") + .font(.bighelp(.subheadline)).foregroundStyle(theme.secondaryText) + Spacer(minLength: 0) + Button("Clear") { store.clearStaged() } + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .bighelpPlainButtonStyle() + .accessibilityIdentifier("new-chat.staged.clear") + sendAll(count) + } + ScrollView { + VStack(spacing: BighelpTokens.space8) { + ForEach(Array(jobs.enumerated()), id: \.element.id) { index, job in + row(job, number: index + 1) + } + } + } + .frame(height: CGFloat(min(jobs.count, 3)) * BighelpTokens.scaled(56) + + CGFloat(max(min(jobs.count, 3) - 1, 0)) * BighelpTokens.space8) + .scrollIndicators(.hidden) + } + .padding(BighelpTokens.space12) + .background(theme.surface, in: .rect(cornerRadius: 20)) + .overlay { RoundedRectangle(cornerRadius: 20).stroke(theme.border, lineWidth: BighelpTokens.hairline) } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("new-chat.staged") + } + + private func sendAll(_ count: Int) -> some View { + Button(action: onSendAll) { + Text("Send all \(count)") + .font(.bighelp(.subheadline).weight(.semibold)) + .foregroundStyle(theme.actionForeground) + .lineLimit(1) + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: BighelpTokens.scaled(34)) + .background(theme.action, in: .capsule) + // The capsule stays its size; a touch counts over a full target's height. + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle(.capsule) + .disabled(store.project == nil || count == 0) + .accessibilityIdentifier("new-chat.staged.send-all") + } + + private func row(_ job: CodeStagedJob, number: Int) -> some View { + let color = CodeSessionColor.color(at: number - 1) + return HStack(spacing: BighelpTokens.space12) { + Text("\(number)") + .font(.bighelp(.caption).weight(.bold)) + .foregroundStyle(color) + .frame(width: BighelpTokens.scaled(22), height: BighelpTokens.scaled(22)) + .background(color.opacity(0.2), in: .circle) + VStack(alignment: .leading, spacing: 2) { + Text(job.title) + .font(.bighelp(.subheadline).weight(.medium)) + .foregroundStyle(theme.primaryText) + .lineLimit(1) + Label(detail(job), systemImage: job.placement.systemImage) + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Button { store.unstage(job.id) } label: { + Image(systemName: "xmark") + .font(.bighelp(.footnote).weight(.semibold)) + .foregroundStyle(theme.secondaryText) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + // The mark stays about where it was: the full target reaches into the row's edge padding. + .padding(.trailing, -min(BighelpTokens.space8, (BighelpTokens.hitTarget - 32) / 2)) + .accessibilityLabel("Remove") + .accessibilityIdentifier("new-chat.staged.remove.\(number)") + } + .padding(.horizontal, BighelpTokens.space8) + .frame(minHeight: BighelpTokens.scaled(56)) + .background(theme.raisedSurface, in: .rect(cornerRadius: 14)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("new-chat.staged.job.\(number)") + } + + private func detail(_ job: CodeStagedJob) -> String { + let model = job.runtime.modelID.map { ModelNameCatalogStore.shared.displayName(for: $0) } + ?? String(localized: "Bot's model") + return [job.placement.title, job.branch, model, job.mode == .standard ? nil : job.mode.title] + .compactMap { $0 }.joined(separator: " · ") + } +} diff --git a/Bighelp/Home/NewChat/NewChatFixture.swift b/Bighelp/Home/NewChat/NewChatFixture.swift new file mode 100644 index 00000000..a310f001 --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatFixture.swift @@ -0,0 +1,103 @@ +#if DEBUG +import SwiftUI + +/// New chat's parts alone on made-up data, before the shell hosts them in a chat: the To row and +/// people list (two computers, a group chat), and the choices row under a stand-in message box +/// with demo projects. Nothing here sends; Send all and Manage worktrees do nothing. +@MainActor +enum NewChatFixture { + /// The launch argument the integrator can show it behind. + static let launchArgument = "-test-new-chat" + + static func makeView() -> some View { NewChatFixtureScreen() } + + static let homeComputer = FleetHost(id: UUID(uuidString: "6F1A2B3C-0000-4000-8000-000000000001")!, + name: "Home computer", isSelected: true) + static let studioComputer = FleetHost(id: UUID(uuidString: "6F1A2B3C-0000-4000-8000-000000000002")!, + name: "Studio computer", isSelected: false) + + static let bots: [SimpleBotsBot] = [ + bot("avery", "Avery", "Money and plans", on: homeComputer), + bot("mina", "Mina", "Travel", on: homeComputer), + bot("jordan", "Jordan", "Home", on: homeComputer), + bot("juno", "Juno", "Code", on: studioComputer), + ] + + static var groups: [SimpleBotsGroup] { + let group = FleetGroup(hostID: homeComputer.id, roomID: "room-family-budget", name: "Family budget", + memberNames: ["Avery", "Jordan"], updatedAt: Date(timeIntervalSince1970: 1_790_000_000), + isWorking: false, canRename: true, canDelete: true, memberIDs: ["avery", "jordan"]) + return [SimpleBotsGroup(group, members: bots.filter { ["avery", "jordan"].contains($0.profileID) })] + } + + static let rules = NewChatGroupRules(hostInUse: homeComputer.id, canMakeGroups: true) + + private static func bot(_ id: String, _ name: String, _ role: String, on host: FleetHost) -> SimpleBotsBot { + SimpleBotsBot(id: FleetID.make(host.id, id), profileID: id, hostID: host.id, name: name, role: role) + } + + /// Demo projects and git, saved in a suite of their own so the real Code home's choices stay put. + static func makeStore() -> CodeHomeStore { + let git = DemoCodeGit() + return CodeHomeStore(scopeID: "new-chat-fixture", agentID: "avery", source: DemoCodeProjectSource(), + git: { git }, starter: NewChatFixtureStarter(), + defaults: UserDefaults(suiteName: "bighelp.new-chat-fixture") ?? .standard) + } +} + +private struct NewChatFixtureScreen: View { + @State private var session = NewChatSession() + @State private var store = NewChatFixture.makeStore() + @State private var draft = "" + @BighelpThemeReader private var theme + + var body: some View { + VStack(spacing: 0) { + NewChatView(context: NewChatContext( + session: session, bots: NewChatFixture.bots, + hosts: [NewChatFixture.homeComputer, NewChatFixture.studioComputer], + groups: NewChatFixture.groups, rules: NewChatFixture.rules, + onRecipientsChanged: { _ in }, onOpenGroup: { _ in })) + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + if let line = NewChatSend.contextLine(session, stagedJobs: store.projectStaged.count, + hasText: !draft.isEmpty) { + Text(verbatim: line) + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .padding(.horizontal, BighelpTokens.space20) + } + // A stand-in for the chat's message box, which the chat screen draws. + TextField("", text: $draft, prompt: Text(verbatim: "Message"), axis: .vertical) + .padding(BighelpTokens.space12) + .bighelpSurface(.composer) + .padding(.horizontal, BighelpTokens.space12) + if let bot = session.recipients.first { + let text = draft + NewChatChoicesRow(context: NewChatChoicesContext( + session: session, store: store, agentID: bot.profileID, hasText: !text.isEmpty, + draft: { text }, clearDraft: { draft = "" }, onWorktrees: {}, onSendAll: {})) + .equatable() + } + } + .padding(.vertical, BighelpTokens.space8) + } + .background(theme.canvas.ignoresSafeArea()) + .onAppear { + if session.recipients.isEmpty { session.start(with: [NewChatFixture.bots[0]]) } + } + } +} + +/// The fixture never starts a session. +private struct NewChatFixtureStarter: CodeSessionStarting { + func startSession(agentID: String, folder: String, title: String, runtime: CodeRuntimeChoice) async throws -> String { + throw CancellationError() + } + + func apply(_ mode: CodeSessionMode, toSession sessionID: String, agentID: String) async throws {} + + func send(_ message: String, toSession sessionID: String) async throws { + throw CancellationError() + } +} +#endif diff --git a/Bighelp/Home/NewChat/NewChatHandoff.swift b/Bighelp/Home/NewChat/NewChatHandoff.swift new file mode 100644 index 00000000..c3c8e86b --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatHandoff.swift @@ -0,0 +1,59 @@ +import Foundation + +/// New chat's text and To row on their way to another computer with a pick: the blank chat or the +/// group chat made there takes them (`RootShellView.performFleetOpen`). The box they came from +/// keeps its text until then, so a switch that fails loses nothing. +@MainActor +struct NewChatHandoff { + /// The box's text; nil when it held none. + let text: String? + /// The chat about to start on the other computer is New chat's own blank chat (its To row). + let followsPick: Bool + /// The blank chat the text came from. + private(set) weak var source: ChatModel? + + init(text: String?, followsPick: Bool, source: ChatModel?) { + self.text = text + self.followsPick = followsPick + self.source = source + } + + /// The other computer has the text: the box it came from lets it go, unless the person has + /// changed it since. + func delivered() { + guard let source, let text, !text.isEmpty, source.draft == text else { return } + source.draft = "" + } +} + +/// How a tap that needed another computer ended (`RootShellView.openFleet`). +enum FleetOpenEnd: Equatable, Sendable { + /// That computer is the one in use and what was tapped opens. + case opened + /// It can't be switched to (the demo's sample computers). + case refused + /// The person cancelled the wait. + case cancelled + /// It didn't answer, and the computer the tap came from is in use again. + case unanswered +} + +extension HomeSelection { + /// A New chat pick on another computer: what goes there with the switch. + func handOffNewChat(_ handoff: NewChatHandoff) { + newChatHandoff = handoff + } + + /// The switch ended: only one that opened gets New chat's text and To row. Every other end + /// drops them (the box still has the text), so a later New chat on that computer never starts + /// with an old message and To row. A group chat that was on its way counts as ended. + func takeNewChatHandoff(after end: FleetOpenEnd) -> NewChatHandoff? { + guard let handoff = newChatHandoff else { return nil } + newChatHandoff = nil + guard end == .opened else { + newChat.groupEnded() + return nil + } + return handoff + } +} diff --git a/Bighelp/Home/NewChat/NewChatRecipients.swift b/Bighelp/Home/NewChat/NewChatRecipients.swift new file mode 100644 index 00000000..593b800a --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatRecipients.swift @@ -0,0 +1,155 @@ +import Foundation + +/// What the computer in use says about group chats. Only it is asked: a group whose first bot is on +/// another computer is checked there when the shell makes it (`startFleetGroupChat`). +struct NewChatGroupRules: Equatable, Sendable { + /// The computer in use. A bot without a `hostID` is on it. + var hostInUse: UUID? + /// `BotModeRoomStore.makesGroupChats` on the computer in use: nil until its Hermes has said. A bot + /// is refused only on a no: until the answer comes, a second pick is taken, and making the group + /// says so if the computer can't. + var canMakeGroups: Bool? + /// `HermesBotModeCapabilities.seatableProfiles` on the computer in use. Hermes' older path + /// doesn't list them and seats any bot: nil. + var seatableProfiles: [String]? = nil + + func canSeat(_ profileID: String) -> Bool { + seatableProfiles?.contains(profileID) ?? true + } +} + +/// New chat's To row, as rules: one bot is a chat, two to `BotModeRoom.maximumMembers` a group chat. +/// A group lives on its first bot's computer (as the all-hosts New chat made them); bots on other +/// computers join it through their own computers' RoomLink, as `createGroupChat(with:peers:)` does. +enum NewChatRecipients { + enum Kind: Equatable, Sendable { + case nobody, chat, group + } + + /// Why a pick can't join the bots already in the To row: one plain line under it. + enum Refusal: Equatable, Sendable { + case full + case noGroups + case cannotSeat(names: [String]) + + var message: String { + switch self { + case .full: + String(localized: "A group chat holds up to \(BotModeRoom.maximumMembers) bots.") + case .noGroups: + String(localized: "Group chats need a newer Hermes on this computer.") + case .cannotSeat(let names) where names.count == 1: + String(localized: "\(names[0]) can’t join group chats on this computer.") + case .cannotSeat(let names): + String(localized: "\(ListFormatter.localizedString(byJoining: names)) can’t join group chats on this computer.") + } + } + } + + static func kind(of picked: [SimpleBotsBot]) -> Kind { + switch picked.count { + case 0: .nobody + case 1: .chat + default: .group + } + } + + /// The computer a bot is on. + static func computer(of bot: SimpleBotsBot, rules: NewChatGroupRules) -> UUID? { + bot.hostID ?? rules.hostInUse + } + + /// Why `bot` can't be added to `picked`; nil when it can (a first pick always can, for a chat). + static func refusal(adding bot: SimpleBotsBot, to picked: [SimpleBotsBot], + rules: NewChatGroupRules) -> Refusal? { + guard let first = picked.first, !picked.contains(where: { $0.id == bot.id }) else { return nil } + guard picked.count < BotModeRoom.maximumMembers else { return .full } + let home = computer(of: first, rules: rules) + guard home == rules.hostInUse else { return nil } + guard rules.canMakeGroups != false else { return .noGroups } + // Hermes seats only its own bots; the others join as peers. + let unseated = (picked + [bot]) + .filter { computer(of: $0, rules: rules) == home && !rules.canSeat($0.profileID) } + .map(\.name) + return unseated.isEmpty ? nil : .cannotSeat(names: unseated) + } + + /// A tap on a bot in the people list: picked bots go, others join unless refused. + static func toggling(_ bot: SimpleBotsBot, in picked: [SimpleBotsBot], + rules: NewChatGroupRules) -> (picked: [SimpleBotsBot], refusal: Refusal?) { + if picked.contains(where: { $0.id == bot.id }) { return (removing(bot, from: picked), nil) } + if let refusal = refusal(adding: bot, to: picked, rules: rules) { return (picked, refusal) } + return (picked + [bot], nil) + } + + static func removing(_ bot: SimpleBotsBot, from picked: [SimpleBotsBot]) -> [SimpleBotsBot] { + picked.filter { $0.id != bot.id } + } + + /// Whether a row shows as one that can join; a picked bot always can (a tap takes it out). + static func canJoin(_ bot: SimpleBotsBot, picked: [SimpleBotsBot], rules: NewChatGroupRules) -> Bool { + refusal(adding: bot, to: picked, rules: rules) == nil + } + + /// A group's bots on its own computer, and those that join from other computers. + static func split(_ picked: [SimpleBotsBot], + rules: NewChatGroupRules) -> (home: [SimpleBotsBot], peers: [SimpleBotsBot]) { + guard let first = picked.first else { return ([], []) } + let home = computer(of: first, rules: rules) + return (picked.filter { computer(of: $0, rules: rules) == home }, + picked.filter { computer(of: $0, rules: rules) != home }) + } + + /// The bots on other computers, as `createGroupChat(with:peers:)` takes them. + static func peerCandidates(_ picked: [SimpleBotsBot], rules: NewChatGroupRules, + hostName: (UUID) -> String) -> [HermesBotModePeerCandidate] { + split(picked, rules: rules).peers.compactMap { bot in + computer(of: bot, rules: rules).map { + HermesBotModePeerCandidate(hostID: $0.uuidString, hostName: hostName($0), + profileID: bot.profileID, name: bot.name) + } + } + } + + // MARK: The people list + + /// One computer's bots in the people list. `host` is nil for bots on no listed computer. + struct Section: Identifiable, Equatable { + let host: FleetHost? + let bots: [SimpleBotsBot] + + var id: String { host?.id.uuidString ?? "other" } + } + + /// The bots by computer, in `hosts`' order; bots on a computer that isn't listed come last. + /// The list shows a header for each only when there are two or more. + static func sections(_ bots: [SimpleBotsBot], hosts: [FleetHost], rules: NewChatGroupRules) -> [Section] { + let listed = Set(hosts.map(\.id)) + var byHost: [UUID: [SimpleBotsBot]] = [:] + var other: [SimpleBotsBot] = [] + for bot in bots { + if let host = computer(of: bot, rules: rules), listed.contains(host) { + byHost[host, default: []].append(bot) + } else { + other.append(bot) + } + } + var result = hosts.compactMap { host in byHost[host.id].map { Section(host: host, bots: $0) } } + if !other.isEmpty { result.append(Section(host: nil, bots: other)) } + return result + } + + /// The To row's field filters by name or role. + static func matches(_ bot: SimpleBotsBot, query: String) -> Bool { + let term = query.trimmingCharacters(in: .whitespacesAndNewlines) + return term.isEmpty || bot.name.localizedCaseInsensitiveContains(term) + || bot.role.localizedCaseInsensitiveContains(term) + } + + /// Group chats match by their name or a member's. + static func matches(_ group: SimpleBotsGroup, query: String) -> Bool { + let term = query.trimmingCharacters(in: .whitespacesAndNewlines) + return term.isEmpty || group.title.localizedCaseInsensitiveContains(term) + || group.members.contains { $0.name.localizedCaseInsensitiveContains(term) } + } +} diff --git a/Bighelp/Home/NewChat/NewChatSend.swift b/Bighelp/Home/NewChat/NewChatSend.swift new file mode 100644 index 00000000..cf54260a --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatSend.swift @@ -0,0 +1,117 @@ +import Foundation + +/// What New chat's Send does, and the line beside it that says so. `NewChatSendRelay` runs it: a +/// chat is the blank chat's own send, a group is left for the shell (`createGroupChat(with:peers:)`), +/// a coding session goes through `CodeHomeStore.send`, and staged jobs through +/// `CodeHomeStore.sendAll(including:)`. +enum NewChatSend: Equatable, Sendable { + case chat + case group + case coding + /// Jobs are staged for the project: Send starts them all, with the box's text as the last one. + case staged + + /// Nil while nobody is picked (Send says so and sends nothing) or past a group's size. + static func decide(recipients: Int, hasProject: Bool, stagedJobs: Int) -> NewChatSend? { + switch recipients { + case 1 where hasProject: stagedJobs > 0 ? NewChatSend.staged : NewChatSend.coding + case 1: .chat + case 2...BotModeRoom.maximumMembers: .group + default: nil + } + } + + /// `stagedJobs` is the project's in `CodeHomeStore.projectStaged`, read there, never copied. + @MainActor + static func decide(_ session: NewChatSession, stagedJobs: Int) -> NewChatSend? { + decide(recipients: session.recipients.count, hasProject: session.project != nil, stagedJobs: stagedJobs) + } + + /// The line by Send: "New chat with Mina", "Group chat · 3 bots", "Coding session in bighelp". + /// `jobs` counts what Send all starts: the staged jobs and the box's text, if any. + static func contextLine(_ send: NewChatSend, names: [String], projectName: String?, jobs: Int = 1) -> String { + switch send { + case .chat: + return String(localized: "New chat with \(names.first ?? "")") + case .group: + return String(localized: "Group chat · \(names.count) bots") + case .coding, .staged: + let project = projectName ?? "" + return send == .coding || jobs <= 1 + ? String(localized: "Coding session in \(project)") + : String(localized: "\(jobs) coding sessions in \(project)") + } + } + + @MainActor + static func contextLine(_ session: NewChatSession, stagedJobs: Int, hasText: Bool) -> String? { + guard let send = decide(session, stagedJobs: stagedJobs) else { return nil } + return contextLine(send, names: session.recipients.map(\.name), projectName: session.project?.name, + jobs: stagedJobs + (hasText ? 1 : 0)) + } + + // MARK: What Send does with the box as it stands + + /// Why Send sent nothing, or what it waits for: one short line under the To row + /// (`NewChatSession.note`). The box stays as it was. + enum Note: Equatable, Sendable { + /// Nobody is in the To row. + case nobody + /// A group chat's first message goes as text, and the box holds attachments or references. + case groupTextOnly + /// The same for a coding session's first message. + case codingTextOnly + /// Another bot was picked while the box holds attachments or references. They belong to the + /// chat they were added in, so the pick waits until they're out of the box. + case pickKeepsAttachments + /// The chat or the group chat for this pick is being made. + case starting + /// The computer in use can't start the coding session now: its project is gone or it isn't + /// connected. + case codingUnavailable + + var message: String { + switch self { + case .nobody: String(localized: "Pick who gets this") + case .groupTextOnly: String(localized: "Group chats start with text only") + case .codingTextOnly: String(localized: "Coding sessions start with text only") + case .pickKeepsAttachments: String(localized: "Remove attachments to pick another bot") + case .starting: String(localized: "Starting the chat…") + case .codingUnavailable: String(localized: "Coding sessions can’t start right now") + } + } + } + + /// One press of Send. It sends everything in the box, or nothing: a step that can't carry what + /// the box holds is refused with a note, never run without it. + enum Step: Equatable, Sendable { + /// The chat's own send: the blank chat is the picked bot's. + case sendHere + /// The blank chat isn't the picked bot's yet: it becomes so, and the text goes with it. + case followPick + case startGroup + case startCoding + case startStaged + case refuse(Note) + } + + /// `isPickedBotsChat`: the blank chat under the To row is the one picked bot's, on the computer + /// in use. `holdsAttachments`: the box holds attachments or references, which only that chat's + /// own send can carry. `isStartingGroup`: an earlier Send's group chat is still being made. + static func step(_ send: NewChatSend?, isPickedBotsChat: Bool, holdsAttachments: Bool, + isStartingGroup: Bool) -> Step { + guard let send else { return .refuse(.nobody) } + switch send { + case .chat: + if isPickedBotsChat { return .sendHere } + return holdsAttachments ? .refuse(.pickKeepsAttachments) : .followPick + case .group: + if isStartingGroup { return .refuse(.starting) } + return holdsAttachments ? .refuse(.groupTextOnly) : .startGroup + case .coding: + return holdsAttachments ? .refuse(.codingTextOnly) : .startCoding + case .staged: + return holdsAttachments ? .refuse(.codingTextOnly) : .startStaged + } + } +} diff --git a/Bighelp/Home/NewChat/NewChatSendRelay.swift b/Bighelp/Home/NewChat/NewChatSendRelay.swift new file mode 100644 index 00000000..278bf238 --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatSendRelay.swift @@ -0,0 +1,113 @@ +import Foundation + +/// What New chat's Send leaves for the shell on screen: the steps that need the shell's stores +/// (`NewChatSession.ask`, handed over by `NewChatToRow`). +enum NewChatRequest: Equatable, Sendable { + /// The blank chat isn't the picked bot's yet: make it so. The box's text goes with it. + case followPick + /// Make the group chat and send it the box's text. + case startGroup +} + +/// New chat's Send, outside any view. The message box keeps `ChatNewChatSlot.sendOverride` for as +/// long as the chat is open, so it must hold no view: this holds the To row's session, the chat and +/// the computer's coding store, and closures over stores only. It decides (`NewChatSend.step`), +/// does what those can do by themselves (a coding session, a note under the To row), and asks the +/// shell for the rest. The box keeps its text until whoever takes the message has it. +@MainActor +struct NewChatSendRelay { + let session: NewChatSession + /// New chat's blank chat, whose message box this Send belongs to. + let model: ChatModel + /// The computer in use's coding store, where it has one. + let store: CodeHomeStore? + /// The computer in use while every computer's bots can be picked; a bot that names another + /// computer isn't this chat's. + let hostInUse: @MainActor () -> UUID? + /// A coding session started: its project's page on Work. + let showProject: @MainActor (_ projectID: String) -> Void + + /// True when the message went elsewhere or can't go yet; false sends it in this chat, as any + /// chat does. `holdsReferences`: the box's own answer, which the chat's copy can trail by a key. + func send(holdsReferences: Bool) -> Bool { + let kind = NewChatSend.decide(session, stagedJobs: store?.projectStaged.count ?? 0) + let isPickedBotsChat = session.recipients.first.map { bot in + (bot.hostID == nil || bot.hostID == hostInUse()) && model.memberIDs == [bot.profileID] + } ?? false + switch NewChatSend.step(kind, isPickedBotsChat: isPickedBotsChat, + holdsAttachments: holdsReferences || model.holdsAttachmentsOrReferences, + isStartingGroup: session.isStartingGroup) { + case .sendHere: + session.show(nil) + return false + case .followPick: + session.ask(.followPick) + case .startGroup: + session.ask(.startGroup) + case .startCoding: + guard let store, let project = session.project, store.send(model.draft) else { + session.show(.codingUnavailable) + return true + } + finishCoding(project) + case .startStaged: + guard let store, let project = session.project, store.sendAll(including: model.draft) != nil else { + session.show(.codingUnavailable) + return true + } + finishCoding(project) + case .refuse(.nobody): + session.askWho() + case .refuse(let note): + session.show(note) + } + return true + } + + /// The store has the message: only now does the box let it go. + private func finishCoding(_ project: CodeProject) { + model.draft = "" + session.show(nil) + showProject(project.id) + } +} + +/// What a change of the To row asks of the blank chat under it. The To row and that chat must +/// agree: one picked bot means the chat is that bot's. +enum NewChatPick: Equatable, Sendable { + /// Not exactly one bot, or the blank chat is that bot's already. + case keep + /// The bot is on the computer in use: its chat takes the blank chat's place. + case start(profileID: String) + /// The bot is on another computer, which becomes the one in use first. + case switchComputer(UUID, profileID: String) + + /// `blankMembers`: who the blank chat is with now, nil when there is none. `hasFleet`: other + /// computers can be switched to; without it every bot is on the computer in use. + static func decide(recipients: [SimpleBotsBot], blankMembers: [String]?, hasFleet: Bool, + hostInUse: UUID?) -> NewChatPick { + guard recipients.count == 1, let bot = recipients.first else { return .keep } + if hasFleet, let hostID = bot.hostID, hostID != hostInUse { + return .switchComputer(hostID, profileID: bot.profileID) + } + return blankMembers == [bot.profileID] ? .keep : .start(profileID: bot.profileID) + } +} + +/// One chat starts at a time (`RootShellView.runNewChatStart`). A pick made while one starts used to +/// be dropped, which left the To row on one bot and the chat under it another's. It waits here +/// instead: when the start ends the To row is read again, so the latest pick gets the chat. +struct NewChatPickGate: Equatable, Sendable { + private(set) var isWaiting = false + + /// A pick came while a chat was starting. + mutating func hold() { + isWaiting = true + } + + /// The start ended. True when a pick waited: read the To row again now. + mutating func release() -> Bool { + defer { isWaiting = false } + return isWaiting + } +} diff --git a/Bighelp/Home/NewChat/NewChatSession.swift b/Bighelp/Home/NewChat/NewChatSession.swift new file mode 100644 index 00000000..60806a73 --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatSession.swift @@ -0,0 +1,110 @@ +import Foundation +import Observation + +/// What New chat holds while nothing is sent: who it's to, the blank chat the message box belongs +/// to, and the project a coding session would start in. The shell keeps one above every computer's +/// objects, so a pick on another computer (which switches the computer in use) keeps it. +@MainActor +@Observable +final class NewChatSession { + /// In the order they were picked; the first one's computer is a group's home. Keyed by + /// `SimpleBotsBot.id`, which is a `FleetID` while every computer's bots show. + private(set) var recipients: [SimpleBotsBot] = [] + /// The blank chat the message box belongs to (`ChatModel.conversationID`). + var conversationID: String? + /// The project a coding session starts in; nil is an ordinary chat. Only with exactly one bot. + var project: CodeProject? + /// The To row's field, which filters the people list. + var query = "" + /// Why the last pick was refused, until the next change. + private(set) var refusal: NewChatRecipients.Refusal? + /// Why Send sent nothing, or what it waits for, until the next change (`NewChatSend.Note`). + private(set) var note: NewChatSend.Note? + /// Goes up each time a note is said, the same one too, so VoiceOver hears every press of Send. + private(set) var noteCount = 0 + /// Goes up when Send needs someone in the To row: its field takes the cursor. + private(set) var fieldFocusRequests = 0 + /// What Send left for the shell on screen to do (`NewChatSendRelay`); `NewChatToRow` hands it + /// over. Send itself holds no view, so it can only ask. + private(set) var pendingRequest: NewChatRequest? + private(set) var requestCount = 0 + /// A group chat is being made from this New chat. Send waits for it: a second press would + /// make a second group chat. + private(set) var isStartingGroup = false + + var kind: NewChatRecipients.Kind { NewChatRecipients.kind(of: recipients) } + + /// A tap in the people list. True when the recipients changed. + @discardableResult + func toggle(_ bot: SimpleBotsBot, rules: NewChatGroupRules) -> Bool { + let change = NewChatRecipients.toggling(bot, in: recipients, rules: rules) + refusal = change.refusal + note = nil + guard change.picked != recipients else { return false } + setRecipients(change.picked) + query = "" + return true + } + + /// A chip's ×. + func remove(_ bot: SimpleBotsBot) { + refusal = nil + note = nil + setRecipients(NewChatRecipients.removing(bot, from: recipients)) + } + + /// Starts over with `bots`, as New chat from a bot's page does with that bot. + func start(with bots: [SimpleBotsBot] = [], conversationID: String? = nil) { + recipients = Array(bots.prefix(BotModeRoom.maximumMembers)) + self.conversationID = conversationID + project = nil + query = "" + refusal = nil + note = nil + pendingRequest = nil + isStartingGroup = false + } + + // MARK: Send + + /// Says why Send sent nothing; nil takes the line away. + func show(_ note: NewChatSend.Note?) { + self.note = note + if note != nil { noteCount += 1 } + } + + /// Send with nobody picked: it says so, and the To row's field takes the cursor. + func askWho() { + show(.nobody) + fieldFocusRequests += 1 + } + + /// Leaves `request` for the shell on screen. A group chat counts as starting from here on, so a + /// second Send before the shell has taken the request waits too. + func ask(_ request: NewChatRequest) { + if request == .startGroup { + isStartingGroup = true + show(.starting) + } + pendingRequest = request + requestCount += 1 + } + + func takeRequest() -> NewChatRequest? { + defer { pendingRequest = nil } + return pendingRequest + } + + /// The group chat opened, or making it failed: Send is free again. Every way it can end calls this. + func groupEnded() { + isStartingGroup = false + if note == .starting { note = nil } + } + + /// A project belongs to one bot's coding session: another bot, or a second one, drops it. + private func setRecipients(_ picked: [SimpleBotsBot]) { + let sameBot = recipients.count == 1 && picked.count == 1 && picked[0].id == recipients[0].id + if !sameBot { project = nil } + recipients = picked + } +} diff --git a/Bighelp/Home/NewChat/NewChatView.swift b/Bighelp/Home/NewChat/NewChatView.swift new file mode 100644 index 00000000..48fcc082 --- /dev/null +++ b/Bighelp/Home/NewChat/NewChatView.swift @@ -0,0 +1,307 @@ +import SwiftUI +import UIKit + +/// What New chat's To row and people list need from the shell. The chat screen draws them over a new +/// chat that has nothing sent yet: the To row in place of the chat's name, the list over the empty +/// messages. One bot is a chat; two to six a group chat. +@MainActor +struct NewChatContext { + let session: NewChatSession + /// Every bot that can be picked: the computer in use's, and other computers' while they show. + let bots: [SimpleBotsBot] + /// The computers the bots are on, in order, for the list's headers (shown with two or more). + let hosts: [FleetHost] + /// Group chats the person has, at the bottom of the list. + let groups: [SimpleBotsGroup] + let rules: NewChatGroupRules + /// Which bots are working or need you; nil leaves the state lines out. + var activity: BotChatActivityStore? = nil + var activitySource: BotChatActivitySource? = nil + /// This computer's bots aren't read yet: a still placeholder instead of the empty line. + var isLoading = false + /// The recipients changed (a pick, a chip's ×): the shell starts the blank chat for one bot. + let onRecipientsChanged: ([SimpleBotsBot]) -> Void + let onOpenGroup: (SimpleBotsGroup) -> Void + /// Send left this for the shell (`NewChatSession.ask`): the To row hands it over. + var onSendRequest: (NewChatRequest) -> Void = { _ in } + /// The empty list's one action; nil when this computer can't make bots. + var onNewBot: (() -> Void)? = nil +} + +/// The To row and the people list stacked, as the chat screen places them over a new chat. +struct NewChatView: View { + let context: NewChatContext + + var body: some View { + VStack(spacing: 0) { + NewChatToRow(context: context) + NewChatPeopleList(context: context) + } + } +} + +// MARK: The To row + +/// "To:", a chip for each picked bot (its × takes it out), then a field that filters the people list. +/// A refused pick, or a Send that sent nothing, says why in one line under it. +struct NewChatToRow: View { + let context: NewChatContext + @FocusState private var isFocused: Bool + @BighelpThemeReader private var theme + + var body: some View { + @Bindable var session = context.session + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + ScrollViewReader { proxy in + ScrollView(.horizontal) { + HStack(spacing: BighelpTokens.space8) { + Text("To:") + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + ForEach(session.recipients) { bot in + chip(bot) + } + TextField("Add a bot", text: $session.query) + .font(.bighelp(.body)) + .foregroundStyle(theme.primaryText) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.done) + .focused($isFocused) + .frame(minWidth: BighelpTokens.scaled(120)) + .bighelpMacFieldArea() + .onSubmit(pickOnlyMatch) + .accessibilityIdentifier("new-chat.to.field") + .id("field") + } + .padding(.horizontal, BighelpTokens.space16) + .frame(minHeight: BighelpTokens.hitTarget) + } + .scrollIndicators(.hidden) + // The field stays in view as chips are added. + .onChange(of: session.recipients.count) { _, _ in proxy.scrollTo("field", anchor: .trailing) } + } + if let refusal = session.refusal { + line(refusal.message, id: "new-chat.to.refusal") + } else if let note = session.note { + line(note.message, id: "new-chat.to.note") + } + Rectangle().fill(theme.separator).frame(height: BighelpTokens.hairline) + } + // Send with nobody picked: the cursor goes where the pick is made. + .onChange(of: session.fieldFocusRequests) { _, _ in isFocused = true } + // The line is new on screen and may be far from VoiceOver's cursor (it is on Send). + .onChange(of: session.noteCount) { _, _ in + if let note = session.note { UIAccessibility.post(notification: .announcement, argument: note.message) } + } + // Send holds no view, so what needs the shell comes through here. + .onChange(of: session.requestCount, initial: true) { _, _ in + if let request = session.takeRequest() { context.onSendRequest(request) } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("new-chat.to") + } + + private func line(_ text: String, id: String) -> some View { + Text(text) + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, BighelpTokens.space16) + .accessibilityIdentifier(id) + } + + private func chip(_ bot: SimpleBotsBot) -> some View { + Button { + context.session.remove(bot) + context.onRecipientsChanged(context.session.recipients) + } label: { + HStack(spacing: BighelpTokens.space4) { + SimpleBotFace(agentID: bot.profileID, name: bot.name, imageURL: bot.imageURL, + size: BighelpTokens.scaled(24)) + .companionScope(bot.faceScope) + Text(bot.name) + .font(.bighelp(.subheadline).weight(.medium)) + .foregroundStyle(theme.primaryText) + .lineLimit(1) + Image(systemName: "xmark") + .font(.bighelp(.caption2).weight(.bold)) + .foregroundStyle(theme.secondaryText) + } + .padding(.leading, BighelpTokens.space4) + .padding(.trailing, BighelpTokens.space8) + .frame(minHeight: BighelpTokens.scaled(34)) + .bighelpSurface(.capsuleControl, isInteractive: true) + // The capsule stays its size; a touch counts over the row's whole height. + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle(.capsule) + .accessibilityLabel(bot.name) + .accessibilityHint("Takes this bot out of the chat.") + .accessibilityIdentifier("new-chat.to.chip.\(bot.id)") + } + + /// Return picks the one bot the field matches, as Messages does. + private func pickOnlyMatch() { + let session = context.session + let matches = context.bots.filter { bot in + NewChatRecipients.matches(bot, query: session.query) && !session.recipients.contains { $0.id == bot.id } + } + guard !session.query.isEmpty, matches.count == 1 else { return } + if session.toggle(matches[0], rules: context.rules) { context.onRecipientsChanged(session.recipients) } + isFocused = true + } +} + +// MARK: The people list + +/// The bots, by computer when two or more show, then the group chats. Picked bots carry a check; +/// a bot that can't join the pick shows dimmed, and a tap on it says why. The field filters both. +struct NewChatPeopleList: View { + let context: NewChatContext + @Environment(\.scenePhase) private var scenePhase + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + @BighelpThemeReader private var theme + + var body: some View { + let session = context.session + let query = session.query + let sections = NewChatRecipients.sections(context.bots.filter { NewChatRecipients.matches($0, query: query) }, + hosts: context.hosts, rules: context.rules) + let groups = context.groups.filter { NewChatRecipients.matches($0, query: query) } + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + if context.bots.isEmpty { + if context.isLoading { placeholder } else { empty } + } else if sections.isEmpty && groups.isEmpty { + note("No bots or group chats match.") + } + ForEach(sections) { section in + if sections.count > 1 { header(section.host?.name ?? String(localized: "Other bots")) } + ForEach(section.bots) { bot in + NewChatBotRow(bot: bot, isPicked: session.recipients.contains { $0.id == bot.id }, + canJoin: NewChatRecipients.canJoin(bot, picked: session.recipients, + rules: context.rules), + activity: context.activity) { + if session.toggle(bot, rules: context.rules) { + context.onRecipientsChanged(session.recipients) + } + } + } + } + if !groups.isEmpty { + header(String(localized: "Group chats")) + ForEach(groups) { group in groupRow(group) } + } + } + .padding(.vertical, BighelpTokens.space8) + .frame(maxWidth: horizontalSizeClass == .regular ? ChatCanvasLayout.regularLaneMaximumWidth : .infinity) + .frame(maxWidth: .infinity) + } + .dismissesKeyboardOnScroll(true) + .botChatActivityUpdates(context.activity, source: context.activitySource, isActive: scenePhase == .active) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("new-chat.people") + } + + private func header(_ title: String) -> some View { + Text(title) + .font(.bighelp(.subheadline).weight(.semibold)) + .foregroundStyle(theme.secondaryText) + .padding(.horizontal, BighelpTokens.space20) + .padding(.top, BighelpTokens.space16) + .padding(.bottom, BighelpTokens.space4) + .accessibilityAddTraits(.isHeader) + } + + private func groupRow(_ group: SimpleBotsGroup) -> some View { + Button { context.onOpenGroup(group) } label: { + SimpleBotsRowLabel(face: AnyView(SimpleBotsGroupFace(members: group.members, size: 56)), + title: group.title, + preview: group.members.isEmpty ? nil + : ListFormatter.localizedString(byJoining: group.members.map(\.name)), + date: group.updatedAt, isUnread: false, isPinned: false) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("new-chat.group.\(group.id)") + } + + private var empty: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space12) { + note("No bots on this computer yet.") + if let onNewBot = context.onNewBot { + Button("New bot", systemImage: "plus", action: onNewBot) + .font(.bighelp(.body).weight(.semibold)) + .foregroundStyle(theme.action) + .frame(minHeight: BighelpTokens.hitTarget) + .padding(.horizontal, BighelpTokens.space20) + .bighelpPlainButtonStyle() + .accessibilityIdentifier("new-chat.new-bot") + } + } + } + + private func note(_ text: LocalizedStringKey) -> some View { + Text(text) + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, BighelpTokens.space20) + .padding(.vertical, BighelpTokens.space12) + } + + /// Still rows while this computer's bots load: nothing moves. + private var placeholder: some View { + VStack(alignment: .leading, spacing: 0) { + ForEach(0..<3, id: \.self) { _ in + HStack(spacing: BighelpTokens.space16) { + Circle().fill(theme.separator.opacity(0.6)).frame(width: 56, height: 56) + Capsule().fill(theme.separator.opacity(0.6)).frame(width: 140, height: 14) + } + .padding(.horizontal, BighelpTokens.space20) + .padding(.vertical, BighelpTokens.space12) + } + } + .accessibilityHidden(true) + } +} + +/// A bot in the people list: the Bots view's row (face, name, its state line or role), with a check +/// when picked. Its state is read here, so only this row redraws when it changes. +private struct NewChatBotRow: View { + let bot: SimpleBotsBot + let isPicked: Bool + let canJoin: Bool + let activity: BotChatActivityStore? + let onTap: () -> Void + @BighelpThemeReader private var theme + + var body: some View { + Button(action: onTap) { + HStack(spacing: 0) { + SimpleBotsRowLabel(face: AnyView(SimpleBotLiveFace(bot: bot, size: 56, activity: activity)), + title: bot.name, preview: bot.role.isEmpty ? nil : bot.role, + date: nil, isUnread: false, isPinned: false, + activityKey: bot.activityKey, activity: activity) + Image(systemName: isPicked ? "checkmark.circle.fill" : "circle") + .font(.bighelp(.title3)) + .foregroundStyle(isPicked ? theme.action : theme.tertiaryText) + .padding(.trailing, BighelpTokens.space20) + .accessibilityHidden(true) + } + .opacity(isPicked || canJoin ? 1 : 0.4) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .accessibilityValue(value) + .accessibilityAddTraits(isPicked ? .isSelected : []) + .accessibilityIdentifier("new-chat.bot.\(bot.id)") + } + + private var value: String { + let state = activity?.activity(bot.activityKey)?.accessibilityLabel + let picked = isPicked ? String(localized: "Selected") : String(localized: "Not selected") + return [picked, state].compactMap { $0 }.joined(separator: ", ") + } +} diff --git a/Bighelp/Hosts/BighelpHostRegistry.swift b/Bighelp/Hosts/BighelpHostRegistry.swift index 8130ad91..b20729ca 100644 --- a/Bighelp/Hosts/BighelpHostRegistry.swift +++ b/Bighelp/Hosts/BighelpHostRegistry.swift @@ -401,6 +401,8 @@ final class BighelpHostRegistry { guard host.accountScope == accountScope, hosts.contains(where: { $0.id == host.id }) else { throw DirectHermesError.secureStorageChanged } + // Its saved sign-in names the scope its Spaces are kept by; read it before the vault goes. + let spacesScope = workspace(for: host).savedConnection?.workspaceAuthority?.cacheScopeID // Stop local activity before deletion; never mutate or delete host sessions. generation = UUID() workspaces[host.id]?.suspendForPresentationExit() @@ -423,6 +425,9 @@ final class BighelpHostRegistry { // Agents' apps: their pages kept on the phone and what each page stored for itself. HTMLAppCache().eraseAll() Task { await HTMLAppWebView.eraseStorage() } + // Its Spaces: the panels leave Today and the phone's copy of them is erased, with their + // waiting changes. Other computers keep theirs. + TodaySpacesModel.shared.forget(hostKey: host.id.uuidString, scope: spacesScope) vault.invalidate(); draftStores[host.id]?.invalidate() hosts = remaining; selectedHostID = selection selectedWorkspace = selectedHost.map { workspace(for: $0) } diff --git a/Bighelp/Hosts/FirstRunOnboardingSteps.swift b/Bighelp/Hosts/FirstRunOnboardingSteps.swift index 26b37095..a75f54ef 100644 --- a/Bighelp/Hosts/FirstRunOnboardingSteps.swift +++ b/Bighelp/Hosts/FirstRunOnboardingSteps.swift @@ -1,7 +1,7 @@ import SwiftUI -/// The first-run steps after Connect: the optional plugin, notifications (once the plugin is in), and the -/// mode bighelp opens in. Plain words throughout: these screens are for everyone, not only the technical. +/// The first-run steps after Connect: the optional plugin, notifications (once the plugin is in), and how +/// the home opens. Plain words throughout: these screens are for everyone, not only the technical. enum FirstRunOnboarding { /// Connected, with the steps after Connect still to go. Keeps onboarding on screen past the host /// setup's own finish, which clears `onboardingHostID`. @@ -15,6 +15,7 @@ private struct FirstRunStepLayout: View { let systemImage: String let title: LocalizedStringKey let subtitle: LocalizedStringKey + var subtitleIdentifier: String? let primaryTitle: String let primaryIdentifier: String var isWorking = false @@ -44,6 +45,7 @@ private struct FirstRunStepLayout: View { .foregroundStyle(theme.secondaryText) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier(subtitleIdentifier ?? "") } content } @@ -305,245 +307,162 @@ private struct FirstRunAlertPreview: View { } } -// MARK: Mode +// MARK: How to start -/// The three ways to use bighelp, offered once at the end of setup. -enum FirstRunMode: String, CaseIterable, Identifiable { - case bots, sessions, code +/// How the home opens, asked once at the end of setup: one ongoing chat with each bot, or many chats. +/// Either way it's the same home; the answer picks Opens on, which Settings › Chat changes later. +enum FirstRunHome: String, CaseIterable, Identifiable { + case bots, chats var id: Self { self } var title: String { switch self { - case .bots: String(localized: "Bots") - case .sessions: String(localized: "Chat") - case .code: String(localized: "Code") + case .bots: String(localized: "With a bot") + case .chats: String(localized: "Across chats") } } var detail: String { switch self { - case .bots: String(localized: "Simple chats with your bots, like texting friends.") - case .sessions: String(localized: "Every chat, tool and setting in the full bighelp app.") - case .code: String(localized: "Start coding tasks on your projects and review the changes.") + case .bots: String(localized: "One ongoing chat with each bot.") + case .chats: String(localized: "Many chats, newest first.") } } - var systemImage: String { + var landing: HomeLanding { switch self { - case .bots: "bubble.left.and.bubble.right.fill" - case .sessions: "square.grid.2x2.fill" - case .code: "chevron.left.forwardslash.chevron.right" + case .bots: .bots + case .chats: .chats } } - /// The preview: a screenshot of the mode, in light and dark. - var previewImage: String { - switch self { - case .bots: "OnboardingModeBots" - case .sessions: "OnboardingModeSessions" - case .code: "OnboardingModeCode" - } - } - - /// Bots is Bots mode; Sessions the app as it comes; Code opens in Code mode. + /// Opens on, which also sets the first tab's view. @MainActor func apply(to settings: SettingsStore) { - switch self { - case .bots: - settings.codeModeEnabled = false - settings.simpleBotsEnabled = true - case .sessions: - settings.simpleBotsEnabled = false - settings.codeModeEnabled = false - case .code: - settings.simpleBotsEnabled = false - settings.codeModeEnabled = true - settings.startExperience = .code - settings.experience = .code - } + settings.homeLanding = landing } } -/// "Choose your mode": three cards to swipe through, each with a preview of the mode. Tapping one shows -/// its preview large. +/// "How do you want to start?": two choices and Continue. No Skip: the home needs an answer. @MainActor -struct FirstRunModeStep: View { +struct FirstRunHomeStep: View { let settings: SettingsStore let onChoose: () -> Void - @State private var selection: FirstRunMode? = .bots - @State private var previewing: FirstRunMode? - @BighelpThemeReader private var theme - - private var chosen: FirstRunMode { selection ?? .bots } + @State private var choice = FirstRunHome.bots var body: some View { - VStack(spacing: 0) { - VStack(spacing: BighelpTokens.space4) { - Text("Choose your mode") - .bighelpFont(.display) - .foregroundStyle(theme.primaryText) - .accessibilityAddTraits(.isHeader) - Text("You can change this later") - .bighelpFont(.metadata) - .foregroundStyle(theme.secondaryText) - .accessibilityIdentifier("onboarding.mode.later") - } - .padding(.top, BighelpTokens.space24) - .padding(.horizontal, BighelpTokens.space24) - - GeometryReader { geometry in - let cardWidth = min(geometry.size.width * 0.72, 300) - ScrollView(.horizontal, showsIndicators: false) { - LazyHStack(spacing: BighelpTokens.space16) { - ForEach(FirstRunMode.allCases) { mode in - card(mode, width: cardWidth, height: geometry.size.height - BighelpTokens.space32) - .id(mode) - } - } - .scrollTargetLayout() - } - .scrollTargetBehavior(.viewAligned) - .scrollPosition(id: $selection, anchor: .center) - .contentMargins(.horizontal, (geometry.size.width - cardWidth) / 2, for: .scrollContent) - .padding(.vertical, BighelpTokens.space16) - } - - HStack(spacing: BighelpTokens.space8) { - ForEach(FirstRunMode.allCases) { mode in - Circle() - .fill(mode == chosen ? theme.action : theme.secondaryText.opacity(0.3)) - .frame(width: 8, height: 8) - } + FirstRunStepLayout( + systemImage: "house.fill", + title: "How do you want to start?", + subtitle: "You can change this in Settings › Chat.", + subtitleIdentifier: "onboarding.mode.later", + primaryTitle: String(localized: "Continue"), + primaryIdentifier: "onboarding.mode.continue", + primary: { + choice.apply(to: settings) + onChoose() } - .accessibilityHidden(true) - .padding(.bottom, BighelpTokens.space8) - } - .safeAreaInset(edge: .bottom, spacing: 0) { - VStack(spacing: 0) { - Divider().overlay(theme.border) - Button { choose(chosen) } label: { - Text("Use \(chosen.title)") - .bighelpFont(.label, weight: .semibold) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.controlHeight) - .contentShape(.rect) + ) { + VStack(spacing: BighelpTokens.space12) { + ForEach(FirstRunHome.allCases) { home in + FirstRunHomeCard(home: home, isChosen: home == choice) { choice = home } } - .controlSize(.large) - .bighelpActionStyle(.primary) - .accessibilityIdentifier("onboarding.mode.continue") - .frame(maxWidth: 620) - .padding(.horizontal, BighelpTokens.space24) - .padding(.vertical, BighelpTokens.space12) } - .frame(maxWidth: .infinity) - .background(.bar) - } - .bighelpSheet(item: $previewing) { mode in - FirstRunModePreview(mode: mode) { - previewing = nil - choose(mode) - } onClose: { - previewing = nil - } - .bighelpSheetSize(.large) } .accessibilityElement(children: .contain) .accessibilityIdentifier("onboarding.mode") } +} - private func card(_ mode: FirstRunMode, width: CGFloat, height: CGFloat) -> some View { - let isChosen = mode == chosen - return Button { - withAnimation(.snappy) { selection = mode } - previewing = mode - } label: { - VStack(spacing: BighelpTokens.space12) { - Image(mode.previewImage) - .resizable() - .scaledToFit() - .clipShape(.rect(cornerRadius: 22)) - .overlay(RoundedRectangle(cornerRadius: 22).stroke(theme.border, lineWidth: BighelpTokens.hairline)) - .frame(maxHeight: .infinity) - .accessibilityHidden(true) - HStack(spacing: BighelpTokens.space8) { - Image(systemName: mode.systemImage) - .foregroundStyle(theme.action) - Text(mode.title) - .bighelpFont(.sectionTitle, weight: .semibold) +/// One choice: a small drawing of where it opens, its name and one line. +private struct FirstRunHomeCard: View { + let home: FirstRunHome + let isChosen: Bool + let onSelect: () -> Void + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @BighelpThemeReader private var theme + + var body: some View { + let shape = RoundedRectangle(cornerRadius: BighelpTokens.radius20, style: .continuous) + // At the largest text sizes the words get the card's whole width, under the drawing. + let layout = dynamicTypeSize.isAccessibilitySize + ? AnyLayout(VStackLayout(alignment: .leading, spacing: BighelpTokens.space12)) + : AnyLayout(HStackLayout(spacing: BighelpTokens.space16)) + Button(action: onSelect) { + layout { + FirstRunHomeSketch(home: home) + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + Text(home.title) + .bighelpFont(.label, weight: .semibold) .foregroundStyle(theme.primaryText) - if isChosen { - Image(systemName: "checkmark.circle.fill").foregroundStyle(theme.action) - } + Text(home.detail) + .bighelpFont(.metadata) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) } - Text(mode.detail) - .bighelpFont(.metadata) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + Image(systemName: isChosen ? "checkmark.circle.fill" : "circle") + .font(.bighelp(.title3)) + .foregroundStyle(isChosen ? theme.action : theme.tertiaryText) + .accessibilityHidden(true) } .padding(BighelpTokens.space16) - .frame(width: width, height: max(height, 200)) - .background(theme.surface, in: .rect(cornerRadius: 28)) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .background(shape.fill(isChosen ? theme.action.opacity(theme.isDarkPalette ? 0.16 : 0.08) : theme.surface)) .overlay { - RoundedRectangle(cornerRadius: 28) - .stroke(isChosen ? theme.action : theme.border, lineWidth: isChosen ? 2 : BighelpTokens.hairline) + shape.strokeBorder(isChosen ? theme.action : theme.border, + lineWidth: isChosen ? 2 : BighelpTokens.hairline) } - .contentShape(.rect(cornerRadius: 28)) + .contentShape(shape) } .buttonStyle(.plain) - .accessibilityLabel("\(mode.title). \(mode.detail)") - .accessibilityHint("Shows a preview") + .accessibilityLabel(home.title) + .accessibilityValue(home.detail) .accessibilityAddTraits(isChosen ? .isSelected : []) - .accessibilityIdentifier("onboarding.mode.\(mode.rawValue)") - } - - private func choose(_ mode: FirstRunMode) { - mode.apply(to: settings) - onChoose() + .accessibilityIdentifier("onboarding.mode.\(home.rawValue)") } } -/// A mode's preview, large, with the button to choose it. -private struct FirstRunModePreview: View { - let mode: FirstRunMode - let onUse: () -> Void - let onClose: () -> Void +/// A still drawing of the home each choice opens on, in the theme's colors: a face for each bot, or a +/// list of chats with their times. Drawn, not a screenshot, so it can't show a home that's gone. +private struct FirstRunHomeSketch: View { + let home: FirstRunHome @BighelpThemeReader private var theme var body: some View { - NavigationStack { - VStack(spacing: BighelpTokens.space16) { - Image(mode.previewImage) - .resizable() - .scaledToFit() - .clipShape(.rect(cornerRadius: 28)) - .overlay(RoundedRectangle(cornerRadius: 28).stroke(theme.border, lineWidth: BighelpTokens.hairline)) - .frame(maxHeight: .infinity) - .accessibilityLabel("Preview of \(mode.title)") - Text(mode.detail) - .bighelpFont(.body) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(.center) - .fixedSize(horizontal: false, vertical: true) - Button(action: onUse) { - Text("Use \(mode.title)") - .bighelpFont(.label, weight: .semibold) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.controlHeight) - .contentShape(.rect) - } - .controlSize(.large) - .bighelpActionStyle(.primary) - .accessibilityIdentifier("onboarding.mode.preview.use") - } - .padding(BighelpTokens.space24) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .navigationTitle(mode.title) - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Close", action: onClose) + VStack(alignment: .leading, spacing: 7) { + ForEach(0..<3, id: \.self) { row in + HStack(spacing: 6) { + switch home { + case .bots: + Circle().fill(faceTint(row)).frame(width: 14, height: 14) + bar(width: [30, 24, 34][row]) + case .chats: + VStack(alignment: .leading, spacing: 3) { + bar(width: [36, 28, 38][row]) + bar(width: [24, 32, 20][row]).opacity(0.6) + } + Spacer(minLength: 0) + bar(width: 8) + } } } } + .padding(10) + .frame(width: 76, height: 76, alignment: .topLeading) + .background(theme.canvas, in: .rect(cornerRadius: BighelpTokens.radius12)) + .overlay { + RoundedRectangle(cornerRadius: BighelpTokens.radius12).stroke(theme.border, lineWidth: BighelpTokens.hairline) + } + .accessibilityHidden(true) + } + + private func bar(width: CGFloat) -> some View { + Capsule().fill(theme.secondaryText.opacity(0.35)).frame(width: width, height: 5) + } + + private func faceTint(_ row: Int) -> Color { + [theme.action, theme.action.opacity(0.55), theme.secondaryText.opacity(0.45)][row] } } diff --git a/Bighelp/Hosts/FirstRunOnboardingView.swift b/Bighelp/Hosts/FirstRunOnboardingView.swift index e5fda7f9..290e1179 100644 --- a/Bighelp/Hosts/FirstRunOnboardingView.swift +++ b/Bighelp/Hosts/FirstRunOnboardingView.swift @@ -37,7 +37,7 @@ struct FirstRunOnboardingView: View { case .host: String(localized: "Step 2 of 4 · Connect") case .plugin: String(localized: "Step 3 of 4 · Plugin · Optional") case .notifications: String(localized: "Step 3 of 4 · Notifications · Optional") - case .mode: String(localized: "Step 4 of 4 · Your mode") + case .mode: String(localized: "Step 4 of 4 · How to start") } } @@ -69,13 +69,13 @@ struct FirstRunOnboardingView: View { case .host: String(localized: "Connect") case .plugin: String(localized: "Plugin") case .notifications: String(localized: "Notifications") - case .mode: String(localized: "Mode") + case .mode: String(localized: "How to start") } } /// After Connect, the computer is set up; Back can't undo that. var allowsBack: Bool { [.appearance, .host, .mode].contains(self) } - /// Steps a person can pass by: everything but connecting and choosing a mode. + /// Steps a person can pass by: everything but connecting and choosing how to start. var allowsSkip: Bool { [.appearance, .plugin, .notifications].contains(self) } } @@ -215,7 +215,7 @@ struct FirstRunOnboardingView: View { FirstRunNotificationsStep(registry: registry, onDone: { if step == .notifications { move(to: .mode) } }) .transition(stepTransition) case .mode: - FirstRunModeStep(settings: settings, onChoose: completeOnboarding) + FirstRunHomeStep(settings: settings, onChoose: completeOnboarding) .transition(stepTransition) } } @@ -425,7 +425,7 @@ struct FirstRunOnboardingView: View { if registry.onboardingHostID != nil { destination = .host } else if isAfterConnect { - // Connected already: pick up at the plugin, notifications or mode step. + // Connected already: pick up at the plugin, notifications or how-to-start step. destination = Step(rawValue: savedStepRawValue).flatMap { $0.rawValue > Step.host.rawValue ? $0 : nil } ?? .plugin } else { diff --git a/Bighelp/Kanban/KanbanAvailability.swift b/Bighelp/Kanban/KanbanAvailability.swift index 681bbc14..3e7dd89e 100644 --- a/Bighelp/Kanban/KanbanAvailability.swift +++ b/Bighelp/Kanban/KanbanAvailability.swift @@ -1,7 +1,7 @@ import Foundation import Observation -/// Whether the connected computer has Hermes' Kanban plugin, for the ☰ menu. +/// Whether the connected computer has Hermes' Kanban plugin, for Work's door. /// Remembered per computer, so reconnecting (every return to the app) doesn't /// hide it, and only a clear answer from the host changes it: a check that /// fails while the connection settles leaves Kanban where it was. diff --git a/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift b/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift index 30b1548b..03271ec3 100644 --- a/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift +++ b/Bighelp/Notifications/BighelpManagedNotificationNavigation.swift @@ -15,7 +15,7 @@ extension BighelpManagedNotificationService { /// Activity links identify a local scoped mapping, not a host supplied by URL. The tap hands /// the shell its computer, agent and exact chat; the shell opens it from its saved chats. /// Asking `session.list` first failed every Bot Chat (Hermes leaves them out) and so every - /// tap in Bots mode (#571). + /// tap on the Bots view (#571). @MainActor func openActivity(opaqueSessionID: String, opens: BighelpExternalSessionOpenCenter = .shared) throws { guard let owner = activityRuntime?.destination(opaqueSessionID: opaqueSessionID), diff --git a/Bighelp/Permissions/DeviceNavigationTool.swift b/Bighelp/Permissions/DeviceNavigationTool.swift index ac4abb04..11e444ed 100644 --- a/Bighelp/Permissions/DeviceNavigationTool.swift +++ b/Bighelp/Permissions/DeviceNavigationTool.swift @@ -10,8 +10,6 @@ final class DeviceNavigationTool { case invalidArguments = "invalid_arguments" /// No place has that id; `places` lists them. case unknownPlace = "unknown_place" - /// The place isn't in the mode the app is in (Bots, Chat or Code). - case notInThisMode = "not_in_this_mode" /// Only with Settings › Nerd Mode on. A drive never turns it on. case needsNerdMode = "needs_nerd_mode" /// A place inside one bot, and no bot on this computer has that id. @@ -24,6 +22,8 @@ final class DeviceNavigationTool { } static let operations: Set = ["navigation.places", "navigation.open"] + /// `open` still answers `mode`, which named Bots, Chat or Code. The app has one home now. + static let mode = "home" /// The plugin's bounds too. static let maximumQueryLength = 120 static let maximumNoteLength = 160 @@ -31,7 +31,6 @@ final class DeviceNavigationTool { /// What the tool needs from the app. struct Environment { - var mode: @MainActor () -> BighelpMode var nerdMode: @MainActor () -> Bool /// The bot's name, when this computer has a bot with that id. var botName: @MainActor (String) -> String? @@ -53,15 +52,14 @@ final class DeviceNavigationTool { case "navigation.places": let (query, limit) = try Self.placesArguments(arguments) try authorize() - let mode = environment.mode() - let found = DriveCatalog.search(query ?? "", mode: mode, nerdMode: environment.nerdMode(), limit: limit) + let found = DriveCatalog.search(query ?? "", nerdMode: environment.nerdMode(), limit: limit) return [ "places": .array(found.map { place in .object([ "id": .string(place.id), "title": .string(place.title), "what": .string(place.what), - "steps": .array((place.playbooks[mode] ?? []).map { .string($0.label(bot: nil)) }), + "steps": .array(place.steps.map { .string($0.label(bot: nil)) }), "needs": place.needs.contains(.bot) ? .string("bot") : .null, ]) }), @@ -70,8 +68,7 @@ final class DeviceNavigationTool { case "navigation.open": let request = try Self.openArguments(arguments) guard let place = DriveCatalog.place(request.place) else { throw Failure.unknownPlace } - let mode = environment.mode() - guard let steps = place.playbooks[mode] else { throw Failure.notInThisMode } + let steps = place.steps if place.needs.contains(.nerdMode), !environment.nerdMode() { throw Failure.needsNerdMode } var bot: (id: String, name: String)? if place.needs.contains(.bot) { @@ -82,7 +79,7 @@ final class DeviceNavigationTool { } try authorize() guard let trail = environment.open(place, steps, bot, request.note, context) else { throw Failure.busy } - return ["opened": .string(place.id), "steps": .array(trail.map { .string($0) }), "mode": .string(mode.rawValue)] + return ["opened": .string(place.id), "steps": .array(trail.map { .string($0) }), "mode": .string(Self.mode)] default: throw Failure.unsupportedOperation } diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/Contents.json b/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/Contents.json deleted file mode 100644 index a73c2738..00000000 --- a/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/Contents.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "images": [ - { - "filename": "onboarding-mode-bots-light.jpg", - "idiom": "universal" - }, - { - "filename": "onboarding-mode-bots-dark.jpg", - "idiom": "universal", - "appearances": [ - { - "appearance": "luminosity", - "value": "dark" - } - ] - } - ], - "info": { - "author": "xcode", - "version": 1 - } -} diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/onboarding-mode-bots-dark.jpg b/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/onboarding-mode-bots-dark.jpg deleted file mode 100644 index 3d79a05d..00000000 Binary files a/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/onboarding-mode-bots-dark.jpg and /dev/null differ diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/onboarding-mode-bots-light.jpg b/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/onboarding-mode-bots-light.jpg deleted file mode 100644 index 956376ef..00000000 Binary files a/Bighelp/Resources/Assets.xcassets/OnboardingModeBots.imageset/onboarding-mode-bots-light.jpg and /dev/null differ diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/Contents.json b/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/Contents.json deleted file mode 100644 index ce641b2f..00000000 --- a/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/Contents.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "images": [ - { - "filename": "onboarding-mode-code-light.jpg", - "idiom": "universal" - }, - { - "filename": "onboarding-mode-code-dark.jpg", - "idiom": "universal", - "appearances": [ - { - "appearance": "luminosity", - "value": "dark" - } - ] - } - ], - "info": { - "author": "xcode", - "version": 1 - } -} diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/onboarding-mode-code-dark.jpg b/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/onboarding-mode-code-dark.jpg deleted file mode 100644 index 249dd498..00000000 Binary files a/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/onboarding-mode-code-dark.jpg and /dev/null differ diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/onboarding-mode-code-light.jpg b/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/onboarding-mode-code-light.jpg deleted file mode 100644 index 6f99b6fe..00000000 Binary files a/Bighelp/Resources/Assets.xcassets/OnboardingModeCode.imageset/onboarding-mode-code-light.jpg and /dev/null differ diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/Contents.json b/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/Contents.json deleted file mode 100644 index 70e3db7d..00000000 --- a/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/Contents.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "images": [ - { - "filename": "onboarding-mode-sessions-light.jpg", - "idiom": "universal" - }, - { - "filename": "onboarding-mode-sessions-dark.jpg", - "idiom": "universal", - "appearances": [ - { - "appearance": "luminosity", - "value": "dark" - } - ] - } - ], - "info": { - "author": "xcode", - "version": 1 - } -} diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/onboarding-mode-sessions-dark.jpg b/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/onboarding-mode-sessions-dark.jpg deleted file mode 100644 index 169f931f..00000000 Binary files a/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/onboarding-mode-sessions-dark.jpg and /dev/null differ diff --git a/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/onboarding-mode-sessions-light.jpg b/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/onboarding-mode-sessions-light.jpg deleted file mode 100644 index 0f3aa645..00000000 Binary files a/Bighelp/Resources/Assets.xcassets/OnboardingModeSessions.imageset/onboarding-mode-sessions-light.jpg and /dev/null differ diff --git a/Bighelp/Resources/Localizable.xcstrings b/Bighelp/Resources/Localizable.xcstrings index 264305ea..b6f3b2ec 100644 --- a/Bighelp/Resources/Localizable.xcstrings +++ b/Bighelp/Resources/Localizable.xcstrings @@ -1,6 +1,40 @@ { "sourceLanguage": "en", "strings": { + " · %lld jobs": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": " · %lld jobs" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": " · %lld 个任务" + } + } + } + }, + " · 1 job": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": " · 1 job" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": " · 1 个任务" + } + } + } + }, "%@\n\nSelected host: %@": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -103,6 +137,23 @@ } } }, + "%@ can’t join group chats on this computer.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ can’t join group chats on this computer." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%@无法加入这台电脑上的群聊。" + } + } + } + }, "%@ chats": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -358,6 +409,23 @@ } } }, + "%@ isn't connected. Showing its last chats.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ isn't connected. Showing its last chats." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%@未连接。正在显示它最近的聊天。" + } + } + } + }, "%@ options": { "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { @@ -629,6 +697,40 @@ } } }, + "%lld chats are already working here.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%lld chats are already working here." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已有 %lld 个聊天正在这里工作。" + } + } + } + }, + "%lld coding sessions in %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%lld coding sessions in %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%2$@中的 %1$lld 个编程会话" + } + } + } + }, "%lld connected": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -749,6 +851,23 @@ } } }, + "%lld running": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%lld running" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%lld 个正在运行" + } + } + } + }, "%lld saved templates couldn't be opened, so they're hidden.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -852,6 +971,23 @@ } } }, + "1 chat is already working here.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "1 chat is already working here." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已有 1 个聊天正在这里工作。" + } + } + } + }, "1 group chat": { "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { @@ -954,6 +1090,23 @@ } } }, + "A group chat holds up to %lld bots.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A group chat holds up to %lld bots." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "群聊最多可包含 %lld 个机器人。" + } + } + } + }, "A new chat": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -1090,6 +1243,23 @@ } } }, + "About": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "About" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "关于" + } + } + } + }, "About %@": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -1243,6 +1413,23 @@ } } }, + "Across chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Across chats" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "按聊天" + } + } + } + }, "Actions beside each message": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -1260,6 +1447,23 @@ } } }, + "Actions for %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Actions for %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%@的操作" + } + } + } + }, "Active preset": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -1277,13 +1481,13 @@ } } }, - "Activity": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Activities": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Activity" + "value": "Activities" } }, "zh-Hans": { @@ -1294,36 +1498,36 @@ } } }, - "Add": { + "Activity": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add" + "value": "Activity" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "添加" + "value": "活动" } } } }, - "Add %@ to the bottom bar": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Add": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add %@ to the bottom bar" + "value": "Add" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "将%@添加到底部栏" + "value": "添加" } } } @@ -1345,70 +1549,70 @@ } } }, - "Add a computer": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Add a bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add a computer" + "value": "Add a bot" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "添加电脑" + "value": "添加机器人" } } } }, - "Add account credential": { + "Add a computer": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add account credential" + "value": "Add a computer" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "添加账户凭据" + "value": "添加电脑" } } } }, - "Add from %@": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Add account credential": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add from %@" + "value": "Add account credential" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "从%@添加" + "value": "添加账户凭据" } } } }, - "Add host": { + "Add from %@": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add host" + "value": "Add from %@" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "添加电脑" + "value": "从%@添加" } } } @@ -1464,19 +1668,36 @@ } } }, - "Add this project in Code to read its changes here.": { - "comment": "Simplified Chinese draft for the renamed modes (#527 after #528); fluent-speaker review pending.", + "Add this project in Work to read its changes here.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add this project in Code to read its changes here." + "value": "Add this project in Work to read its changes here." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "在代码模式中添加此项目后,即可在这里查看它的改动。" + "value": "在“工作”中添加此项目后,即可在这里查看它的改动。" + } + } + } + }, + "Add to Today": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add to Today" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "添加到“今天”" } } } @@ -1515,36 +1736,36 @@ } } }, - "Add to the bottom bar": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Add your name": { + "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add to the bottom bar" + "value": "Add your name" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "添加到底部栏" + "value": "添加你的名字" } } } }, - "Add your name": { - "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", + "Adding…": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Add your name" + "value": "Adding…" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "添加你的名字" + "value": "正在添加…" } } } @@ -1600,6 +1821,23 @@ } } }, + "Advanced Options": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Advanced Options" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "高级选项" + } + } + } + }, "Advanced options": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -1821,23 +2059,6 @@ } } }, - "Agents (multi)": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Agents (multi)" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "智能体(多台电脑)" - } - } - } - }, "Aggregator": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -2093,23 +2314,6 @@ } } }, - "All hosts": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "All hosts" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "所有电脑" - } - } - } - }, "All visible preset fields are round-tripped together. Hidden computer overrides outside this typed document are not cleared.": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -2229,70 +2433,70 @@ } } }, - "Answers stay open": { - "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", + "Answer a question": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Answers stay open" + "value": "Answer a question" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "回答保持展开" + "value": "回答问题" } } } }, - "Any bot on your computer can use this while its chat is open, and for a short time after you leave bighelp.": { + "Answers stay open": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Any bot on your computer can use this while its chat is open, and for a short time after you leave bighelp." + "value": "Answers stay open" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "你电脑上的任何机器人都可以在其聊天打开时使用,离开 bighelp 后的短时间内也可以。" + "value": "回答保持展开" } } } }, - "App": { - "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", + "Any bot on your computer can use this while its chat is open, and for a short time after you leave bighelp.": { + "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "App" + "value": "Any bot on your computer can use this while its chat is open, and for a short time after you leave bighelp." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "App" + "value": "你电脑上的任何机器人都可以在其聊天打开时使用,离开 bighelp 后的短时间内也可以。" } } } }, - "App layout": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "App": { + "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "App layout" + "value": "App" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "App 布局" + "value": "App" } } } @@ -2399,6 +2603,23 @@ } } }, + "Approvals": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Approvals" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "审批" + } + } + } + }, "Approvals are off on this computer: risky actions run without asking.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -2433,6 +2654,23 @@ } } }, + "Approve a command": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Approve a command" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "批准命令" + } + } + } + }, "Approve once": { "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", "localizations": { @@ -2484,6 +2722,40 @@ } } }, + "Archive": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Archive" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "归档" + } + } + } + }, + "Archived": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Archived" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已归档" + } + } + } + }, "Archived Chats": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -2790,6 +3062,23 @@ } } }, + "Background work": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Background work" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "后台工作" + } + } + } + }, "Backups": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -2858,6 +3147,23 @@ } } }, + "Board": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Board" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "栏目" + } + } + } + }, "Bot": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -2909,172 +3215,189 @@ } } }, - "Bots": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Bot page": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots" + "value": "Bot page" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人" + "value": "机器人页面" } } } }, - "Bots ask each other for help": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Bot page or Settings": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots ask each other for help" + "value": "Bot page or Settings" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人会互相求助" + "value": "机器人页面或设置" } } } }, - "Bots can change and delete events, reminders and contacts without asking each time.": { - "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", + "Bot's model": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots can change and delete events, reminders and contacts without asking each time." + "value": "Bot's model" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人可以更改和删除日程、提醒事项和联系人,无需每次询问。" + "value": "机器人的模型" } } } }, - "Bots messaging each other": { - "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", + "Bots": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots messaging each other" + "value": "Bots" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人之间的消息" + "value": "机器人" } } } }, - "Bots mode": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Bots ask each other for help": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots mode" + "value": "Bots ask each other for help" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人模式" + "value": "机器人会互相求助" } } } }, - "Bots see reactions": { + "Bots can change and delete events, reminders and contacts without asking each time.": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots see reactions" + "value": "Bots can change and delete events, reminders and contacts without asking each time." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人能看到回应" + "value": "机器人可以更改和删除日程、提醒事项和联系人,无需每次询问。" } } } }, - "Bots that use it speak with your computer's voice until you download it again.": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Bots messaging each other": { + "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots that use it speak with your computer's voice until you download it again." + "value": "Bots messaging each other" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "使用它的机器人会改用你电脑的声音说话,直到你再次下载。" + "value": "机器人之间的消息" } } } }, - "Bots, Chat and Code": { - "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", + "Bots see reactions": { + "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bots, Chat and Code" + "value": "Bots see reactions" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "机器人、聊天和代码" + "value": "机器人能看到回应" } } } }, - "Bottom bar": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Bots that use it speak with your computer's voice until you download it again.": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bottom bar" + "value": "Bots that use it speak with your computer's voice until you download it again." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "底部栏" + "value": "使用它的机器人会改用你电脑的声音说话,直到你再次下载。" } } } }, - "Bottom bar and menu order": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Branch": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Branch" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "分支" + } + } + } + }, + "Branch: %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Bottom bar and menu order" + "value": "Branch: %@" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "底部栏和菜单顺序" + "value": "分支:%@" } } } @@ -3232,70 +3555,70 @@ } } }, - "Calm home, just your bots": { - "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", + "Camera": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Calm home, just your bots" + "value": "Camera" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "安静的主页,只有你的机器人" + "value": "相机" } } } }, - "Camera": { + "Camera capture is unavailable on this device.": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Camera" + "value": "Camera capture is unavailable on this device." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "相机" + "value": "此设备无法拍摄照片。" } } } }, - "Camera capture is unavailable on this device.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Can you look over my notes before the meeting?": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Camera capture is unavailable on this device." + "value": "Can you look over my notes before the meeting?" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "此设备无法拍摄照片。" + "value": "开会前能帮我看看笔记吗?" } } } }, - "Can you look over my notes before the meeting?": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Can't show this": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Can you look over my notes before the meeting?" + "value": "Can't show this" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "开会前能帮我看看笔记吗?" + "value": "无法显示" } } } @@ -3504,6 +3827,23 @@ } } }, + "Changes aren't available": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Changes aren't available" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法查看改动" + } + } + } + }, "Channels": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -3589,23 +3929,6 @@ } } }, - "Chat and Code": { - "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Chat and Code" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "聊天和代码" - } - } - } - }, "Chat appearance": { "localizations": { "en": { @@ -3671,23 +3994,6 @@ } } }, - "Chat is always first. Drag to change the order. What you remove goes to the menu.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Chat is always first. Drag to change the order. What you remove goes to the menu." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "聊天始终排在第一位。拖动可更改顺序。移除的项目会放到菜单中。" - } - } - } - }, "Chat layout": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -3722,19 +4028,19 @@ } } }, - "Chat mode": { - "comment": "Simplified Chinese draft for the renamed modes (#527 after #528); fluent-speaker review pending.", + "Chat name": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Chat mode" + "value": "Chat name" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "聊天模式" + "value": "聊天名称" } } } @@ -3806,19 +4112,19 @@ } } }, - "Chats and menu": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Chats and menu" + "value": "Chats" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "聊天和菜单" + "value": "聊天" } } } @@ -3857,19 +4163,19 @@ } } }, - "Chats, Feed, Ideas & Goals": { - "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", + "Chats with this bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Chats, Feed, Ideas & Goals" + "value": "Chats with this bot" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "聊天、动态、想法和目标" + "value": "与这个机器人的聊天" } } } @@ -4027,6 +4333,23 @@ } } }, + "Checked out in the local folder": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Checked out in the local folder" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已在本地文件夹中检出" + } + } + } + }, "Checking notification setup…": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -4095,19 +4418,19 @@ } } }, - "Choose a host": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Choose a project first": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Choose a host" + "value": "Choose a project first" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "选择电脑" + "value": "请先选择项目" } } } @@ -4163,42 +4486,25 @@ } } }, - "Choose your mode": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Circle": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Choose your mode" + "value": "Circle" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "选择使用模式" + "value": "圆形" } } } }, - "Circle": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Circle" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "圆形" - } - } - } - }, - "Clean up chats": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Clean up chats": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { @@ -4451,53 +4757,87 @@ } } }, - "Code mode": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Coding": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Code mode" + "value": "Coding" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "代码模式" + "value": "编程" } } } }, - "Code needs your computer": { - "comment": "Simplified Chinese draft for the renamed modes (#527 after #528); fluent-speaker review pending.", + "Coding session": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Code needs your computer" + "value": "Coding session" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "代码模式需要你的电脑" + "value": "编程会话" } } } }, - "Coding": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Coding session in %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Coding" + "value": "Coding session in %@" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "编程" + "value": "%@中的编程会话" + } + } + } + }, + "Coding sessions can’t start right now": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Coding sessions can’t start right now" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "现在无法开始编程会话" + } + } + } + }, + "Coding sessions start with text only": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Coding sessions start with text only" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "编程会话只能以文字开头" } } } @@ -4655,23 +4995,6 @@ } } }, - "Computer filter": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Computer filter" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "电脑筛选" - } - } - } - }, "Computer voice test": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -4876,6 +5199,57 @@ } } }, + "Connect to your computer, then open Projects from Work.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Connect to your computer, then open Projects from Work." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "请先连接电脑,再从“工作”中打开“项目”。" + } + } + } + }, + "Connect to your computer, then open Tasks from Work.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Connect to your computer, then open Tasks from Work." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "请先连接电脑,再从“工作”中打开“任务”。" + } + } + } + }, + "Connect to your computer, then open Workflows from Work.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Connect to your computer, then open Workflows from Work." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "请先连接电脑,再从“工作”中打开“工作流”。" + } + } + } + }, "Connect your computer": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -5108,6 +5482,74 @@ } } }, + "Could not add this space. Try again.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not add this space. Try again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法添加这个空间。请重试。" + } + } + } + }, + "Could not delete it. Try again.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not delete it. Try again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法删除。请重试。" + } + } + } + }, + "Could not reach your computer. Try again.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not reach your computer. Try again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法连接到你的电脑。请重试。" + } + } + } + }, + "Could not update it. Try again.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not update it. Try again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法更新。请重试。" + } + } + } + }, "Couldn't confirm the change. Refresh before trying again.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -5142,6 +5584,23 @@ } } }, + "Couldn't delete this bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn't delete this bot" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法删除这个机器人" + } + } + } + }, "Couldn't hide this bot": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -5193,6 +5652,23 @@ } } }, + "Couldn't start": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn't start" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法开始" + } + } + } + }, "Cream": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -5397,6 +5873,23 @@ } } }, + "Dashboard": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Dashboard" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "仪表盘" + } + } + } + }, "Dashboard session token": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -5465,6 +5958,23 @@ } } }, + "Default Voice": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Default Voice" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "默认语音" + } + } + } + }, "Default bot": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -5567,6 +6077,23 @@ } } }, + "Delete %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "删除%@" + } + } + } + }, "Delete Group Chat": { "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { @@ -5601,6 +6128,40 @@ } } }, + "Delete bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete bot" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "删除机器人" + } + } + } + }, + "Delete this space?": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete this space?" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "要删除这个空间吗?" + } + } + } + }, "Delete “%@”?": { "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { @@ -5703,30 +6264,47 @@ } } }, - "Dev Factory needs a newer bighelp plugin on this computer. Update it in Settings, on your computer's page.": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Dev Factory isn't open": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Dev Factory needs a newer bighelp plugin on this computer. Update it in Settings, on your computer's page." + "value": "Dev Factory isn't open" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "Dev Factory 需要这台电脑上有更新的 bighelp 插件。请在“设置”中这台电脑的页面上更新。" + "value": "开发工厂未打开" } } } }, - "Device access": { - "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", + "Dev Factory needs a newer bighelp plugin on this computer. Update it in Settings, on your computer's page.": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Device access" + "value": "Dev Factory needs a newer bighelp plugin on this computer. Update it in Settings, on your computer's page." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Dev Factory 需要这台电脑上有更新的 bighelp 插件。请在“设置”中这台电脑的页面上更新。" + } + } + } + }, + "Device access": { + "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Device access" } }, "zh-Hans": { @@ -5839,6 +6417,23 @@ } } }, + "Draft": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Draft" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "草稿" + } + } + } + }, "Drag a tab to move it, then tap Done.": { "comment": "Simplified Chinese draft for a bot profile's tabs in Bots mode (Set Default, Rearrange); fluent-speaker review pending.", "localizations": { @@ -5958,6 +6553,23 @@ } } }, + "Duplicate": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Duplicate" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "复制" + } + } + } + }, "Dynamic Island": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -5975,36 +6587,53 @@ } } }, - "Edit Members": { - "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "Earlier": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Edit Members" + "value": "Earlier" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "编辑成员" + "value": "更早" } } } }, - "Edit Name and Role": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Edit": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "编辑" + } + } + } + }, + "Edit Members": { + "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Edit Name and Role" + "value": "Edit Members" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "编辑名字和角色" + "value": "编辑成员" } } } @@ -6179,19 +6808,19 @@ } } }, - "End voice": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Enter a name up to %lld characters.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "End voice" + "value": "Enter a name up to %lld characters." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "结束语音" + "value": "请输入不超过 %lld 个字符的名称。" } } } @@ -6281,19 +6910,19 @@ } } }, - "Every chat, tool and setting in the full bighelp app.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Every evening, post the top three AI stories to my feed.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Every chat, tool and setting in the full bighelp app." + "value": "Every evening, post the top three AI stories to my feed." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "使用 bighelp 的全部聊天、工具和设置。" + "value": "每天晚上,把最重要的三条 AI 新闻发到我的动态里。" } } } @@ -6315,6 +6944,23 @@ } } }, + "Every panel is hidden. Tap Edit to show one.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Every panel is hidden. Tap Edit to show one." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "所有面板都已隐藏。轻点“编辑”可显示一个。" + } + } + } + }, "Every tool iteration": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -6349,6 +6995,23 @@ } } }, + "Examples": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Examples" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "示例" + } + } + } + }, "Expand message editor": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -6502,6 +7165,23 @@ } } }, + "Feed, Ideas, Goals": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Feed, Ideas, Goals" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "动态、灵感、目标" + } + } + } + }, "File": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -6689,19 +7369,19 @@ } } }, - "Fire off coding chats against your projects.": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "First tab shows": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Fire off coding chats against your projects." + "value": "First tab shows" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "针对你的项目发起编程聊天。" + "value": "第一个标签显示" } } } @@ -6808,6 +7488,23 @@ } } }, + "Found on your computer": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Found on your computer" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "在你的电脑上找到" + } + } + } + }, "From": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -6927,6 +7624,23 @@ } } }, + "Give your bot a name": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Give your bot a name" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "给机器人起个名字" + } + } + } + }, "Goals": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -7063,36 +7777,104 @@ } } }, - "Haptics": { - "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", + "Group chat · %lld bots": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Haptics" + "value": "Group chat · %lld bots" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "触感反馈" + "value": "群聊 · %lld 个机器人" } } } }, - "Header mode switcher": { - "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", + "Group chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Group chats" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "群聊" + } + } + } + }, + "Group chats need a newer Hermes on this computer.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Group chats need a newer Hermes on this computer." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "这台电脑上的 Hermes 需要更新,才能使用群聊。" + } + } + } + }, + "Group chats start with text only": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Group chats start with text only" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "群聊只能以文字开头" + } + } + } + }, + "Handle": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Handle" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "用户名" + } + } + } + }, + "Haptics": { + "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Header mode switcher" + "value": "Haptics" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "顶部模式切换" + "value": "触感反馈" } } } @@ -7182,6 +7964,23 @@ } } }, + "Help me set one goal for this month, and track it on my Goals.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Help me set one goal for this month, and track it on my Goals." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "帮我设定一个本月目标,并记在我的目标里。" + } + } + } + }, "Helper results": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -7403,6 +8202,40 @@ } } }, + "Hide %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hide %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "隐藏%@" + } + } + } + }, + "Hide from Today": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hide from Today" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "从“今天”隐藏" + } + } + } + }, "Hides the steps.": { "comment": "Simplified Chinese draft for Settings › Chat › Agent's work and the chat's work block (#564); fluent-speaker review pending.", "localizations": { @@ -7488,70 +8321,70 @@ } } }, - "Home experience": { - "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", + "Host URL or IP address": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Home experience" + "value": "Host URL or IP address" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "主页体验" + "value": "电脑的网址或 IP 地址" } } } }, - "Host URL or IP address": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "How do you want to start?": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Host URL or IP address" + "value": "How do you want to start?" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "电脑的网址或 IP 地址" + "value": "你想怎么开始?" } } } }, - "Host: %@": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "How much of your space shows through bighelp": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Host: %@" + "value": "How much of your space shows through bighelp" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "电脑:%@" + "value": "透过 bighelp 能看到多少周围空间" } } } }, - "How much of your space shows through bighelp": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "How should this chat work?": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "How much of your space shows through bighelp" + "value": "How should this chat work?" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "透过 bighelp 能看到多少周围空间" + "value": "这个聊天要怎么工作?" } } } @@ -7590,8 +8423,25 @@ } } }, - "How voice chats sound": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "How to start": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "How to start" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "开始方式" + } + } + } + }, + "How voice chats sound": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { @@ -7692,36 +8542,53 @@ } } }, - "In the car": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "In a worktree": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "In the car" + "value": "In a worktree" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "在车上" + "value": "在工作树中" } } } }, - "Inbox": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "In the background": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "In the background" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "在后台" + } + } + } + }, + "In the car": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Inbox" + "value": "In the car" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "收件箱" + "value": "在车上" } } } @@ -8015,6 +8882,23 @@ } } }, + "It stops its updates and removes its page.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "It stops its updates and removes its page." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "它会停止更新,并移除它的页面。" + } + } + } + }, "It's behind Cloudflare Access": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -8083,6 +8967,23 @@ } } }, + "Its update failed": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Its update failed" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "它的更新失败了" + } + } + } + }, "Just your bots and their chats, nothing else.": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -8134,6 +9035,23 @@ } } }, + "Kanban isn't available": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Kanban isn't available" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法使用看板" + } + } + } + }, "Keep thinking open": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -8219,36 +9137,19 @@ } } }, - "Last bot used": { - "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Last bot used" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "上次使用的机器人" - } - } - } - }, - "Last chat": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Last run failed": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Last chat" + "value": "Last run failed" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "上次的聊天" + "value": "上次运行失败" } } } @@ -8457,23 +9358,6 @@ } } }, - "Listening to you": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Listening to you" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "正在聆听" - } - } - } - }, "Listens with": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -8525,70 +9409,70 @@ } } }, - "Live couldn't start in this chat, so this chat takes turns.": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Live voice": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Live couldn't start in this chat, so this chat takes turns." + "value": "Live voice" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "实时模式无法在此聊天中启动,因此此聊天改为轮流说话。" + "value": "实时语音" } } } }, - "Live voice": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Loading": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Live voice" + "value": "Loading" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "实时语音" + "value": "正在载入" } } } }, - "Loading Code": { - "comment": "Simplified Chinese draft for the renamed modes (#527 after #528); fluent-speaker review pending.", + "Loading channels…": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Loading Code" + "value": "Loading channels…" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "正在载入代码模式" + "value": "正在载入渠道…" } } } }, - "Loading channels…": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Loading chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Loading channels…" + "value": "Loading chats" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "正在载入渠道…" + "value": "正在载入聊天" } } } @@ -8610,6 +9494,23 @@ } } }, + "Loading sessions": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Loading sessions" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "正在载入会话" + } + } + } + }, "Loading…": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -8712,6 +9613,23 @@ } } }, + "Look through my week and suggest a few things you could take off my plate.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Look through my week and suggest a few things you could take off my plate." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "看看我这一周的安排,建议几件你可以帮我分担的事。" + } + } + } + }, "Make Primary Bot": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -8729,6 +9647,23 @@ } } }, + "Make a space": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Make a space" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "创建空间" + } + } + } + }, "Make bighelp feel like yours": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -8763,6 +9698,40 @@ } } }, + "Make me a space for Today: %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Make me a space for Today: %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "帮我为“今天”做一个空间:%@" + } + } + } + }, + "Make space": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Make space" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "创建空间" + } + } + } + }, "Making images": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -8814,6 +9783,40 @@ } } }, + "Manage worktrees": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manage worktrees" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "管理工作树" + } + } + } + }, + "Many chats, newest first.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Many chats, newest first." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "多个聊天,最新的排在前面。" + } + } + } + }, "Mark Read": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -8848,6 +9851,40 @@ } } }, + "Mark read": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mark read" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "标为已读" + } + } + } + }, + "Mark unread": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mark unread" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "标为未读" + } + } + } + }, "Marketing": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -8933,23 +9970,6 @@ } } }, - "Menu": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Menu" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "菜单" - } - } - } - }, "Message": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -9239,70 +10259,70 @@ } } }, - "Model & reasoning": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Mode: %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Model & reasoning" + "value": "Mode: %@" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "模型与推理" + "value": "模式:%@" } } } }, - "Models": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Model & reasoning": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Models" + "value": "Model & reasoning" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "模型" + "value": "模型与推理" } } } }, - "Models unavailable": { + "Models": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Models unavailable" + "value": "Models" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "模型不可用" + "value": "模型" } } } }, - "Modes": { - "comment": "Simplified Chinese draft for the simpler Settings (Connections, Modes); fluent-speaker review pending.", + "Models unavailable": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Modes" + "value": "Models unavailable" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "模式" + "value": "模型不可用" } } } @@ -9358,6 +10378,23 @@ } } }, + "More projects…": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "More projects…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "更多项目…" + } + } + } + }, "Morning! Want today's plan?": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -9528,23 +10565,6 @@ } } }, - "Multi-gateway": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Multi-gateway" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "多网关" - } - } - } - }, "Mute %@": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -9698,6 +10718,23 @@ } } }, + "Named from your message unless you type a name.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Named from your message unless you type a name." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "除非你自己输入,否则会根据你的消息命名。" + } + } + } + }, "Need help connecting?": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -9867,6 +10904,23 @@ } } }, + "New bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "New bot" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "新建机器人" + } + } + } + }, "New bot or group chat": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -9884,6 +10938,23 @@ } } }, + "New branch": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "New branch" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "新分支" + } + } + } + }, "New channels": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -9951,121 +11022,138 @@ } } }, - "New items": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "New section": { + "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "New items" + "value": "New section" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "有新内容" + "value": "新分组" } } } }, - "New section": { - "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "Newest": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "New section" + "value": "Newest" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "新分组" + "value": "最新" } } } }, - "New session": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Next": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "New session" + "value": "Next" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "新会话" + "value": "下一步" } } } }, - "Newest": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "No AI": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Newest" + "value": "No AI" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "最新" + "value": "不使用 AI" } } } }, - "Next": { + "No approvals yet": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No approvals yet" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "还没有审批" + } + } + } + }, + "No bots found": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Next" + "value": "No bots found" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "下一步" + "value": "未找到机器人" } } } }, - "Next mode": { - "comment": "Simplified Chinese draft for the renamed modes (#527 after #528); fluent-speaker review pending.", + "No bots on this computer yet.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Next mode" + "value": "No bots on this computer yet." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "下一个模式" + "value": "这台电脑上还没有机器人。" } } } }, - "No bots found": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "No bots or group chats match.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "No bots found" + "value": "No bots or group chats match." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未找到机器人" + "value": "没有匹配的机器人或群聊。" } } } @@ -10104,6 +11192,40 @@ } } }, + "No chats on %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No chats on %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%@上没有聊天" + } + } + } + }, + "No chats yet": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No chats yet" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "还没有聊天" + } + } + } + }, "No computer is connected.": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -10138,6 +11260,23 @@ } } }, + "No goals from any bot yet.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No goals from any bot yet." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "还没有任何机器人设定的目标。" + } + } + } + }, "No hidden bots": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -10155,6 +11294,23 @@ } } }, + "No ideas from any bot yet.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No ideas from any bot yet." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "还没有任何机器人提出的灵感。" + } + } + } + }, "No ideas yet": { "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", "localizations": { @@ -10240,6 +11396,57 @@ } } }, + "No posts from any bot yet.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No posts from any bot yet." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "还没有任何机器人发布的动态。" + } + } + } + }, + "No project": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No project" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无项目" + } + } + } + }, + "No projects on this computer yet. Add a folder below.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No projects on this computer yet. Add a folder below." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "这台电脑上还没有项目。请在下方添加文件夹。" + } + } + } + }, "No routines yet": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -10291,6 +11498,23 @@ } } }, + "No unread chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No unread chats" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "没有未读聊天" + } + } + } + }, "None": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -10348,234 +11572,404 @@ "en": { "stringUnit": { "state": "translated", - "value": "Not Requested" + "value": "Not Requested" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "未请求" + } + } + } + }, + "Not Supported": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not Supported" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "不支持" + } + } + } + }, + "Not connected": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not connected" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "未连接" + } + } + } + }, + "Not connected to %@": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not connected to %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "未连接到%@" + } + } + } + }, + "Not encrypted. Use plain HTTP only on a network you trust.": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not encrypted. Use plain HTTP only on a network you trust." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "此连接未加密。仅在可信网络中使用普通 HTTP。" + } + } + } + }, + "Not loaded": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not loaded" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "未载入" + } + } + } + }, + "Not on this computer": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not on this computer" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "此电脑上没有" + } + } + } + }, + "Not paired": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not paired" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "未配对" + } + } + } + }, + "Not reachable": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not reachable" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法连接" + } + } + } + }, + "Not selected": { + "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not selected" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "未选择" + } + } + } + }, + "Not set": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not set" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未请求" + "value": "未设置" } } } }, - "Not Supported": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Not signed in": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not Supported" + "value": "Not signed in" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "不支持" + "value": "未登录" } } } }, - "Not connected to %@": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Nothing done yet": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not connected to %@" + "value": "Nothing done yet" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未连接到%@" + "value": "还没有完成的事项" } } } }, - "Not encrypted. Use plain HTTP only on a network you trust.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Nothing hidden": { + "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not encrypted. Use plain HTTP only on a network you trust." + "value": "Nothing hidden" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "此连接未加密。仅在可信网络中使用普通 HTTP。" + "value": "没有隐藏的内容" } } } }, - "Not loaded": { + "Nothing in %@ matches %@.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not loaded" + "value": "Nothing in %@ matches %@." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未载入" + "value": "“%1$@”中没有与%2$@匹配的结果。" } } } }, - "Not on this computer": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Nothing in progress": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not on this computer" + "value": "Nothing in progress" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "此电脑上没有" + "value": "没有进行中的事项" } } } }, - "Not paired": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Nothing matches %@.": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not paired" + "value": "Nothing matches %@." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未配对" + "value": "没有与%@匹配的结果。" } } } }, - "Not reachable": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Nothing needs you": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not reachable" + "value": "Nothing needs you" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "无法连接" + "value": "没有需要你处理的事项" } } } }, - "Not selected": { - "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "Nothing runs until you add it.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not selected" + "value": "Nothing runs until you add it." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未选择" + "value": "添加之前不会运行任何内容。" } } } }, - "Not signed in": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Nothing to show here": { + "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Not signed in" + "value": "Nothing to show here" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "未登录" + "value": "这里没有可显示的内容" } } } }, - "Nothing hidden": { - "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "Nothing working": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Nothing hidden" + "value": "Nothing working" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "没有隐藏的内容" + "value": "没有正在工作的事项" } } } }, - "Nothing in %@ matches %@.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Nothing yet. Ask a bot for a goal.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Nothing in %@ matches %@." + "value": "Nothing yet. Ask a bot for a goal." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "“%1$@”中没有与%2$@匹配的结果。" + "value": "暂无内容。可以让机器人设定一个目标。" } } } }, - "Nothing matches %@.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Nothing yet. Ask a bot for ideas.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Nothing matches %@." + "value": "Nothing yet. Ask a bot for ideas." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "没有与%@匹配的结果。" + "value": "暂无内容。可以让机器人提出灵感。" } } } }, - "Nothing to show here": { - "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "Nothing yet. Ask a bot for posts.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Nothing to show here" + "value": "Nothing yet. Ask a bot for posts." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "这里没有可显示的内容" + "value": "暂无内容。可以让机器人发布动态。" } } } @@ -10835,6 +12229,40 @@ } } }, + "On GitHub": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "On GitHub" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "在 GitHub 上" + } + } + } + }, + "On Today": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "On Today" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "显示在“今天”" + } + } + } + }, "On it. Three things…": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -10971,6 +12399,40 @@ } } }, + "One line about what it does": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "One line about what it does" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "用一句话介绍它的作用" + } + } + } + }, + "One ongoing chat with each bot.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "One ongoing chat with each bot." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "与每个机器人保持一个持续的聊天。" + } + } + } + }, "One saved template couldn't be opened, so it's hidden.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -11090,6 +12552,57 @@ } } }, + "Open Today": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open Today" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "打开“今天”" + } + } + } + }, + "Open Work, then try again.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open Work, then try again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "请先打开“工作”,然后重试。" + } + } + } + }, + "Open a board": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open a board" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "打开看板" + } + } + } + }, "Open chat": { "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", "localizations": { @@ -11158,19 +12671,19 @@ } } }, - "Open it from the menu in Code.": { - "comment": "Simplified Chinese draft for the renamed modes (#527 after #528); fluent-speaker review pending.", + "Open it from a project in Work.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Open it from the menu in Code." + "value": "Open it from a project in Work." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "请在代码模式的菜单中打开它。" + "value": "请从“工作”中的项目打开它。" } } } @@ -11361,22 +12874,6 @@ } } }, - "Opens agent and chat details": { - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Opens agent and chat details" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "打开智能体和聊天详情" - } - } - } - }, "Opens its chat": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -11462,6 +12959,23 @@ } } }, + "Opens what's waiting": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Opens what's waiting" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "打开等待处理的内容" + } + } + } + }, "Optional appearance settings": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -11564,19 +13078,19 @@ } } }, - "Other agents": { - "comment": "Bots mode's sections and group chats (#858, #859); fluent-speaker review pending.", + "Other bots": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Other agents" + "value": "Other bots" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "其他智能体" + "value": "其他机器人" } } } @@ -11751,6 +13265,23 @@ } } }, + "Paused": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Paused" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已暂停" + } + } + } + }, "Paused for new messages": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -11768,6 +13299,23 @@ } } }, + "Paused in Scheduled tasks": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Paused in Scheduled tasks" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已在“定时任务”中暂停" + } + } + } + }, "Pauses for a moment": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -11921,6 +13469,23 @@ } } }, + "Photo actions": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Photo actions" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "照片操作" + } + } + } + }, "Photos and videos from your chats with %@.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -11950,7 +13515,41 @@ "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "电脑恢复连接后,照片和视频会显示在这里。" + "value": "电脑恢复连接后,照片和视频会显示在这里。" + } + } + } + }, + "Pick a bot to chat with.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pick a bot to chat with." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "选择要聊天的机器人。" + } + } + } + }, + "Pick a chat, or start a new one.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pick a chat, or start a new one." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "选择一个聊天,或开始新的聊天。" } } } @@ -12006,6 +13605,23 @@ } } }, + "Pick something to open.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pick something to open." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "选择要打开的内容。" + } + } + } + }, "Pick the channels": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -12023,6 +13639,23 @@ } } }, + "Pick who gets this": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pick who gets this" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "选择发给谁" + } + } + } + }, "Pictures and videos %@ sends you or makes show up here.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -12429,53 +14062,53 @@ } } }, - "Profile & Settings": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Profiles now open on %@": { + "comment": "Simplified Chinese draft for a bot profile's tabs in Bots mode (Set Default, Rearrange); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Profile & Settings" + "value": "Profiles now open on %@" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "个人资料与设置" + "value": "资料页现在从%@打开" } } } }, - "Profiles now open on %@": { + "Profiles open on this tab": { "comment": "Simplified Chinese draft for a bot profile's tabs in Bots mode (Set Default, Rearrange); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Profiles now open on %@" + "value": "Profiles open on this tab" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "资料页现在从%@打开" + "value": "资料页从此标签打开" } } } }, - "Profiles open on this tab": { - "comment": "Simplified Chinese draft for a bot profile's tabs in Bots mode (Set Default, Rearrange); fluent-speaker review pending.", + "Project": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Profiles open on this tab" + "value": "Project" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "资料页从此标签打开" + "value": "项目" } } } @@ -12514,6 +14147,40 @@ } } }, + "Project: %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Project: %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "项目:%@" + } + } + } + }, + "Project: none": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Project: none" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "项目:无" + } + } + } + }, "Projects": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -12531,6 +14198,23 @@ } } }, + "Projects aren't available": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Projects aren't available" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法使用项目" + } + } + } + }, "Prompts to start a chat": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -12667,36 +14351,36 @@ } } }, - "Purple": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Pull requests (%lld)": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Purple" + "value": "Pull requests (%lld)" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "紫色" + "value": "拉取请求(%lld)" } } } }, - "Puts the bottom bar and the menu back the way bighelp recommends.": { + "Purple": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Puts the bottom bar and the menu back the way bighelp recommends." + "value": "Purple" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "将底部栏和菜单恢复为 bighelp 推荐的样子。" + "value": "紫色" } } } @@ -12905,19 +14589,19 @@ } } }, - "Recent sessions": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Recent chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Recent sessions" + "value": "Recent chats" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "最近的会话" + "value": "最近的聊天" } } } @@ -13109,19 +14793,36 @@ } } }, - "Remove %@ from the bottom bar": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Remove attachments to pick another bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Remove attachments to pick another bot" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "移除附件后才能选择其他机器人" + } + } + } + }, + "Remove from list": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Remove %@ from the bottom bar" + "value": "Remove from list" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "从底部栏移除%@" + "value": "从列表中移除" } } } @@ -13194,6 +14895,23 @@ } } }, + "Removed": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Removed" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已移除" + } + } + } + }, "Removing this device from your computers…": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -13260,6 +14978,23 @@ } } }, + "Renamed, this becomes a regular chat, and tapping the bot starts a new Bot Chat.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Renamed, this becomes a regular chat, and tapping the bot starts a new Bot Chat." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "重命名后,它会变成普通聊天,轻点机器人将开始新的机器人聊天。" + } + } + } + }, "Render up to 25 selected pages for image understanding": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -13464,23 +15199,6 @@ } } }, - "Reset to Default Layout": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Reset to Default Layout" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "重置为默认布局" - } - } - } - }, "Reset to default": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -13515,19 +15233,19 @@ } } }, - "Reset to the default layout?": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Resize": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Reset to the default layout?" + "value": "Resize" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "重置为默认布局?" + "value": "调整大小" } } } @@ -13821,6 +15539,23 @@ } } }, + "Role": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Role" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "角色" + } + } + } + }, "Rose": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -14296,6 +16031,23 @@ } } }, + "Schedules": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Schedules" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "定时任务" + } + } + } + }, "Scheduling": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -14398,6 +16150,40 @@ } } }, + "Search branches": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Search branches" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "搜索分支" + } + } + } + }, + "Search chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Search chats" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "搜索聊天" + } + } + } + }, "Search templates": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -14500,19 +16286,19 @@ } } }, - "See all sessions": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "See all chats": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "See all sessions" + "value": "See all chats" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "查看所有会话" + "value": "查看全部聊天" } } } @@ -14568,6 +16354,23 @@ } } }, + "Send all %lld": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Send all %lld" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "全部发送(%lld)" + } + } + } + }, "Send another way": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -14653,23 +16456,6 @@ } } }, - "Send what you said": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Send what you said" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "发送你说的话" - } - } - } - }, "Sending": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -14959,6 +16745,23 @@ } } }, + "Setting up": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Setting up" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "正在设置" + } + } + } + }, "Settings": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -15090,41 +16893,24 @@ "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "显示智能体名字" - } - } - } - }, - "Show all": { - "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Show all" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "显示全部" + "value": "显示智能体名字" } } } }, - "Show all hosts": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Show all": { + "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Show all hosts" + "value": "Show all" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "显示所有电脑" + "value": "显示全部" } } } @@ -15197,36 +16983,36 @@ } } }, - "Show one host": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Show reasoning": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Show one host" + "value": "Show reasoning" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "显示一台电脑" + "value": "显示推理" } } } }, - "Show reasoning": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Show routines": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Show reasoning" + "value": "Show routines" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "显示推理" + "value": "显示例行任务" } } } @@ -15282,22 +17068,6 @@ } } }, - "Shows a preview": { - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Shows a preview" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "显示预览" - } - } - } - }, "Shows as": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -15315,23 +17085,6 @@ } } }, - "Shows every agent on every host in one list.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Shows every agent on every host in one list." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "在一个列表中显示所有电脑上的智能体。" - } - } - } - }, "Shows every step.": { "comment": "Simplified Chinese draft for Settings › Chat › Agent's work and the chat's work block (#564); fluent-speaker review pending.", "localizations": { @@ -15349,53 +17102,53 @@ } } }, - "Shows the selected host's agents and chats again.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Shows the steps.": { + "comment": "Simplified Chinese draft for Settings › Chat › Agent's work and the chat's work block (#564); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Shows the selected host's agents and chats again." + "value": "Shows the steps." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "重新显示所选电脑的智能体和聊天。" + "value": "显示步骤。" } } } }, - "Shows the steps.": { - "comment": "Simplified Chinese draft for Settings › Chat › Agent's work and the chat's work block (#564); fluent-speaker review pending.", + "Shows what the agents said to each other.": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Shows the steps." + "value": "Shows what the agents said to each other." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "显示步骤。" + "value": "显示智能体之间说了什么。" } } } }, - "Shows what the agents said to each other.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Sidebar": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Shows what the agents said to each other." + "value": "Sidebar" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "显示智能体之间说了什么。" + "value": "侧边栏" } } } @@ -15502,6 +17255,23 @@ } } }, + "Sign off": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sign off" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "签核" + } + } + } + }, "Sign off %@ · Run %lld?": { "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", "localizations": { @@ -15621,36 +17391,36 @@ } } }, - "Simple chats with your bots, like texting friends.": { + "Simple mode": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Simple chats with your bots, like texting friends." + "value": "Simple mode" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "轻松和机器人聊天,就像给朋友发消息。" + "value": "简易模式" } } } }, - "Simple mode": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Size": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Simple mode" + "value": "Size" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "简易模式" + "value": "尺寸" } } } @@ -15825,6 +17595,23 @@ } } }, + "Space": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Space" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "空间" + } + } + } + }, "Spacing": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -15893,6 +17680,40 @@ } } }, + "Stage": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Stage" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "暂存" + } + } + } + }, + "Staged": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Staged" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已暂存" + } + } + } + }, "Star": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -15927,36 +17748,36 @@ } } }, - "Start chatting": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Start a coding session from New chat.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Start chatting" + "value": "Start a coding session from New chat." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "开始聊天" + "value": "从“新聊天”开始一个编程会话。" } } } }, - "Start coding tasks on your projects and review the changes.": { + "Start chatting": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Start coding tasks on your projects and review the changes." + "value": "Start chatting" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "为项目启动编程任务,并查看改动。" + "value": "开始聊天" } } } @@ -15978,6 +17799,23 @@ } } }, + "Start from": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Start from" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "起始分支" + } + } + } + }, "Start from a template. It fills in the role, vibe and instructions.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -16029,6 +17867,23 @@ } } }, + "Start one with New chat.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Start one with New chat." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "点“新聊天”开始一个。" + } + } + } + }, "Start right at the edge of the screen.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -16046,19 +17901,19 @@ } } }, - "Start with": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Starting the chat…": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Start with" + "value": "Starting the chat…" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "开始时使用" + "value": "正在开始聊天…" } } } @@ -16165,19 +18020,19 @@ } } }, - "Step 4 of 4 · Your mode": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Step 4 of 4 · How to start": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Step 4 of 4 · Your mode" + "value": "Step 4 of 4 · How to start" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "第 4 步,共 4 步 · 选择模式" + "value": "第 4 步,共 4 步 · 开始方式" } } } @@ -16284,206 +18139,206 @@ } } }, - "Stopping": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Stopped updating": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Stopping" + "value": "Stopped updating" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "正在停止" + "value": "已停止更新" } } } }, - "Stopping response": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Stopped: its script changed": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Stopping response" + "value": "Stopped: its script changed" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "正在停止回复" + "value": "已停止:它的脚本已更改" } } } }, - "Succeeded": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Stopping": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Succeeded" + "value": "Stopping" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "已成功" + "value": "正在停止" } } } }, - "Suggestions": { - "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", + "Stopping response": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Suggestions" + "value": "Stopping response" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "建议" + "value": "正在停止回复" } } } }, - "Sunflower": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Succeeded": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Sunflower" + "value": "Succeeded" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "向日葵黄" + "value": "已成功" } } } }, - "Sure. I added two questions and fixed the dates.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Suggestions": { + "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Sure. I added two questions and fixed the dates." + "value": "Suggestions" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "好的。我加了两个问题,并改正了日期。" + "value": "建议" } } } }, - "Surprise me": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Summary": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Surprise me" + "value": "Summary" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "随机一个" + "value": "简介" } } } }, - "Swipe from left edge": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Sunflower": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Swipe from left edge" + "value": "Sunflower" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "从左边缘轻扫" + "value": "向日葵黄" } } } }, - "Swipe from right edge": { + "Sure. I added two questions and fixed the dates.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Swipe from right edge" + "value": "Sure. I added two questions and fixed the dates." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "从右边缘轻扫" + "value": "好的。我加了两个问题,并改正了日期。" } } } }, - "Switch between Bots, Chat and Code from the top of each home.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Surprise me": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Switch between Bots, Chat and Code from the top of each home." + "value": "Surprise me" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "在每个主页顶部切换机器人、聊天和代码。" + "value": "随机一个" } } } }, - "Switch host": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Swipe from left edge": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Switch host" + "value": "Swipe from left edge" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "切换电脑" + "value": "从左边缘轻扫" } } } }, - "Switch hosts or add one.": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Swipe from right edge": { + "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Switch hosts or add one." + "value": "Swipe from right edge" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "切换或添加电脑。" + "value": "从右边缘轻扫" } } } @@ -16573,6 +18428,23 @@ } } }, + "Takes this bot out of the chat.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Takes this bot out of the chat." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "将这个机器人移出聊天。" + } + } + } + }, "Taking a look": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -16664,13 +18536,30 @@ "en": { "stringUnit": { "state": "translated", - "value": "Talking" + "value": "Talking" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "说话方式" + } + } + } + }, + "Tall": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tall" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "说话方式" + "value": "高" } } } @@ -16742,6 +18631,23 @@ } } }, + "Task": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Task" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "任务" + } + } + } + }, "Tasks": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -16997,36 +18903,36 @@ } } }, - "The bot couldn't be made. Check the computer, then try again.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "The bot changed this space. Check it, then add it.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The bot couldn't be made. Check the computer, then try again." + "value": "The bot changed this space. Check it, then add it." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "无法创建机器人。请检查电脑,然后重试。" + "value": "机器人修改了这个空间。请先检查,再添加。" } } } }, - "The bottom bar becomes Chat, Feed, Ideas, Goals and Files again, and the menu returns to its standard order.": { + "The bot couldn't be made. Check the computer, then try again.": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "The bottom bar becomes Chat, Feed, Ideas, Goals and Files again, and the menu returns to its standard order." + "value": "The bot couldn't be made. Check the computer, then try again." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "底部栏会恢复为聊天、动态、灵感、目标和文件,菜单也会恢复为标准顺序。" + "value": "无法创建机器人。请检查电脑,然后重试。" } } } @@ -17048,23 +18954,6 @@ } } }, - "The bottom bar is full. Remove one to add another.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "The bottom bar is full. Remove one to add another." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "底部栏已满。请先移除一项再添加。" - } - } - } - }, "The card also shows a step's work, a waiting question and the answer's first lines, encrypted from your computer to this device.": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -17320,23 +19209,6 @@ } } }, - "The menu shows everything that isn't in the bottom bar, and always Agents and Settings. Drag to change the order.": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "The menu shows everything that isn't in the bottom bar, and always Agents and Settings. Drag to change the order." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "菜单会显示底部栏以外的所有项目,并始终包含智能体和设置。拖动可更改顺序。" - } - } - } - }, "The one in use": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -17507,6 +19379,40 @@ } } }, + "This batch isn't here anymore": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This batch isn't here anymore" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "这个批次已不存在" + } + } + } + }, + "This bot has as many spaces as it can keep. Delete one on Today first.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This bot has as many spaces as it can keep. Delete one on Today first." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "这个机器人的空间数量已达上限。请先在“今天”中删除一个。" + } + } + } + }, "This bot isn't here anymore": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -17778,6 +19684,40 @@ } } }, + "This space's script is missing. Ask the bot to make it again.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This space's script is missing. Ask the bot to make it again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "这个空间的脚本丢失了。请让机器人重新制作。" + } + } + } + }, + "Time my commute": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Time my commute" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "统计我的通勤时间" + } + } + } + }, "Time zone": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -17829,19 +19769,19 @@ } } }, - "Together or one by one": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "Today": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Together or one by one" + "value": "Today" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "一起更新或逐台更新" + "value": "今天" } } } @@ -17914,6 +19854,23 @@ } } }, + "Track my workouts": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Track my workouts" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "记录我的锻炼" + } + } + } + }, "Transparency": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -17999,6 +19956,40 @@ } } }, + "Try again": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Try again" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "重试" + } + } + } + }, + "Try again in a minute": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Try again in a minute" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "请一分钟后重试" + } + } + } + }, "Turn On Notifications": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -18339,6 +20330,23 @@ } } }, + "Update now": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Update now" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "立即更新" + } + } + } + }, "Update plugin": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -18441,6 +20449,57 @@ } } }, + "Update the plugin on %@ to see its spaces.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Update the plugin on %@ to see its spaces." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "更新%@上的插件即可查看它的空间。" + } + } + } + }, + "Update the plugin on your computer to add this.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Update the plugin on your computer to add this." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "更新电脑上的插件后即可添加。" + } + } + } + }, + "Updated %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Updated %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "更新于%@" + } + } + } + }, "Updates": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -18475,6 +20534,23 @@ } } }, + "Updating…": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Updating…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "正在更新…" + } + } + } + }, "Usage": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -18560,6 +20636,23 @@ } } }, + "Use with Siri": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use with Siri" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "与 Siri 搭配使用" + } + } + } + }, "Use your Hermes username and password.": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -18618,47 +20711,81 @@ "en": { "stringUnit": { "state": "translated", - "value": "Used once" + "value": "Used once" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "已使用 1 次" + } + } + } + }, + "Username": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Username" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "用户名" + } + } + } + }, + "Username & password": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Username & password" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "已使用 1 次" + "value": "用户名和密码" } } } }, - "Username": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Uses AI": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Username" + "value": "Uses AI" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "用户名" + "value": "使用 AI" } } } }, - "Username & password": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "Uses AI each update": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Username & password" + "value": "Uses AI each update" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "用户名和密码" + "value": "每次更新都会使用 AI" } } } @@ -18731,70 +20858,53 @@ } } }, - "Voice": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Voice" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "语音" - } - } - } - }, - "Voice chats": { - "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", + "View": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Voice chats" + "value": "View" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "语音聊天" + "value": "视图" } } } }, - "Voice choices": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Voice": { + "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Voice choices" + "value": "Voice" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "语音选项" + "value": "语音" } } } }, - "Voice is on": { - "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", + "Voice chats": { + "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Voice is on" + "value": "Voice chats" } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "语音已开启" + "value": "语音聊天" } } } @@ -18935,6 +21045,23 @@ } } }, + "Watch my garden": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Watch my garden" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "关注我的花园" + } + } + } + }, "Weather, tasks, budgets and approvals": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -18986,6 +21113,23 @@ } } }, + "What %@ asks to do shows up here.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "What %@ asks to do shows up here." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "%@请求执行的操作会显示在这里。" + } + } + } + }, "What %@ did": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -19003,6 +21147,23 @@ } } }, + "What do you want to see?": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "What do you want to see?" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "你想看到什么?" + } + } + } + }, "What it can use": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -19173,6 +21334,40 @@ } } }, + "Where it runs: %@": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Where it runs: %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "运行位置:%@" + } + } + } + }, + "Where should this chat run?": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Where should this chat run?" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "这个聊天在哪里运行?" + } + } + } + }, "Where you are": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -19207,6 +21402,23 @@ } } }, + "Wide": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Wide" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "宽" + } + } + } + }, "Window transparency": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -19241,6 +21453,23 @@ } } }, + "With a bot": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "With a bot" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "按机器人" + } + } + } + }, "With a keyboard attached": { "comment": "Simplified Chinese draft for Settings in named groups (#974); fluent-speaker review pending.", "localizations": { @@ -19258,6 +21487,23 @@ } } }, + "Work": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Work" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "工作" + } + } + } + }, "Work already running finishes; new messages wait.": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -19275,6 +21521,23 @@ } } }, + "Workflow": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Workflow" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "工作流" + } + } + } + }, "Workflows": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -19292,6 +21555,23 @@ } } }, + "Workflows aren't available": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Workflows aren't available" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无法使用工作流" + } + } + } + }, "Working": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -19394,23 +21674,6 @@ } } }, - "Worktrees, diffs & PRs": { - "comment": "Simplified Chinese draft for Needs you, blueprints in the message box and Settings › Modes; fluent-speaker review pending.", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Worktrees, diffs & PRs" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "needs_review", - "value": "工作树、差异和 PR" - } - } - } - }, "Writing code": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -19496,19 +21759,19 @@ } } }, - "You can change this later": { - "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", + "You can change this in Settings › Chat.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "You can change this later" + "value": "You can change this in Settings › Chat." } }, "zh-Hans": { "stringUnit": { "state": "needs_review", - "value": "之后可以更改" + "value": "之后可在“设置 › 聊天”中更改。" } } } @@ -19852,6 +22115,23 @@ } } }, + "Your computer can't run scheduled tasks right now.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your computer can't run scheduled tasks right now." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "你的电脑现在无法运行定时任务。" + } + } + } + }, "Your computer isn't connected": { "comment": "Simplified Chinese draft for Simple Bot mode, Teamwork and their Settings pages (#527); fluent-speaker review pending.", "localizations": { @@ -19869,6 +22149,23 @@ } } }, + "Your computer isn't connected.": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your computer isn't connected." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "你的电脑未连接。" + } + } + } + }, "Your computer's API key may incur separate usage charges. Subscription failures never switch providers automatically.": { "comment": "Simplified Chinese draft for one Settings (#976); fluent-speaker review pending.", "localizations": { @@ -20260,6 +22557,40 @@ } } }, + "default": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "default" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "默认" + } + } + } + }, + "e.g. Travel planner": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "e.g. Travel planner" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "例如:旅行规划师" + } + } + } + }, "group": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { @@ -20345,6 +22676,23 @@ } } }, + "step %lld of %lld": { + "comment": "Simplified Chinese draft for the one home (#977); fluent-speaker review pending.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "step %lld of %lld" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "第 %lld 步,共 %lld 步" + } + } + } + }, "your browser": { "comment": "Initial Simplified Chinese draft; fluent-speaker review pending.", "localizations": { diff --git a/Bighelp/Sessions/SessionCatalogStore.swift b/Bighelp/Sessions/SessionCatalogStore.swift index dc7126a8..ac022671 100644 --- a/Bighelp/Sessions/SessionCatalogStore.swift +++ b/Bighelp/Sessions/SessionCatalogStore.swift @@ -198,7 +198,7 @@ final class SessionCatalogStore { return record } - /// Code mode: a new chat with `agentID` working in exactly `folder`. + /// A coding session: a new chat with `agentID` working in exactly `folder`. func createDirect(agentID: String, folder: String, title: String, runtime: SessionStartRuntime = .init()) async throws -> SessionRecord { let generation = accountGeneration diff --git a/Bighelp/Sessions/SessionModels.swift b/Bighelp/Sessions/SessionModels.swift index 590fbb51..3b743e81 100644 --- a/Bighelp/Sessions/SessionModels.swift +++ b/Bighelp/Sessions/SessionModels.swift @@ -619,7 +619,7 @@ protocol SessionCatalogClient { func refreshMetadata(_ record: SessionRecord) async throws -> SessionRecord? func canonicalToolCallIDs(for record: SessionRecord) -> Set func create(kind: SessionKind, agentIDs: [String]) async throws -> SessionRecord - /// Code mode: a new direct chat in exactly `folder`, named `title`, on `runtime`'s model choices. + /// A coding session: a new direct chat in exactly `folder`, named `title`, on `runtime`'s model choices. func createSession(agentID: String, folder: String, title: String, runtime: SessionStartRuntime) async throws -> SessionRecord func hydrate(_ record: SessionRecord) async throws -> SessionRecord @@ -667,7 +667,7 @@ extension SessionCatalogClient { func hydrate(_ record: SessionRecord) async throws -> SessionRecord { record } - /// Only hosts that can start a chat in a chosen folder (native Hermes, demo) have Code mode. + /// Only hosts that can start a chat in a chosen folder (native Hermes, demo) can start coding sessions. func createSession(agentID: String, folder: String, title: String, runtime: SessionStartRuntime) async throws -> SessionRecord { throw WorkspaceClientError.unavailable(.unsupportedOperation) diff --git a/Bighelp/Sessions/SessionRow.swift b/Bighelp/Sessions/SessionRow.swift index 5364f825..c3bc1ccb 100644 --- a/Bighelp/Sessions/SessionRow.swift +++ b/Bighelp/Sessions/SessionRow.swift @@ -44,7 +44,7 @@ struct SessionRow: View { .foregroundStyle(theme.secondaryText) .lineLimit(1) .layoutPriority(1) - // Bots mode's dot, in the same place: after the time, clear of the live dot below. + // The Bots view's dot, in the same place: after the time, clear of the live dot below. if session.isUnread { Circle() .fill(theme.information) diff --git a/Bighelp/Sessions/SessionsView.swift b/Bighelp/Sessions/SessionsView.swift index 9e896841..0f7d97f0 100644 --- a/Bighelp/Sessions/SessionsView.swift +++ b/Bighelp/Sessions/SessionsView.swift @@ -56,9 +56,7 @@ struct SessionsView: View { /// Starts a Hermes hosted group chat (Bot Mode). Nil when the host can't create rooms. let onNewGroupChat: (() -> Void)? let onSelect: (SessionSummary) -> Void - /// The Agents list's hold menu for the "Your agents" rail. - var agentActionsConfig: AgentActionsConfig? = nil - @State private var agentActions = AgentActions() + /// Codex and Claude Code chats on this computer, and what identifies that list; nil hides them. let otherApps: (source: any OtherAppChatsSource, id: String)? /// Opens a chat brought in from another app, by its Hermes session ID. @@ -82,7 +80,7 @@ struct SessionsView: View { onStartChat: ((String?) -> Void)? = nil, onNewGroupChat: (() -> Void)? = nil, onSelect: @escaping (SessionSummary) -> Void, - agentActionsConfig: AgentActionsConfig? = nil, + otherApps: (source: any OtherAppChatsSource, id: String)? = nil, onOpenBroughtIn: ((String) -> Void)? = nil, appFilter: Binding? = nil, @@ -104,17 +102,6 @@ struct SessionsView: View { self.sessionOrganizationHostID = sessionOrganizationHostID self.onStartChat = onStartChat self.onSelect = onSelect - self.agentActionsConfig = agentActionsConfig - } - - /// Same as holding an agent in Agents; "Group chats" opens that list filtered. - private func performAgentAction(_ action: AgentRowMenuAction, agent: AgentProfile, config: AgentActionsConfig) { - guard action == .groups else { - agentActions.perform(action, agent: agent, config: config) - return - } - guard let owner = config.owner, let onAction = config.onAction else { return } - onAction(AgentWorkspaceActionRequest(owner: owner, action: .openAgentGroups(profileID: agent.id))) } var body: some View { @@ -233,7 +220,7 @@ struct SessionsView: View { Text(message) } } - .agentActionsPresentation(agentActions, config: agentActionsConfig) + .bighelpSheet(item: $projectMoveTarget) { session in if let projectMove, let agentID = session.agentIDs.first { MoveChatToProjectSheet(move: projectMove, chatTitle: session.title, agentID: agentID, @@ -574,13 +561,6 @@ struct SessionsView: View { } } .buttonStyle(.bighelpTilePress) - .contextMenu { - if let agentActionsConfig { - AgentActionMenuItems(actions: agentActions, agent: profile, config: agentActionsConfig) { action in - performAgentAction(action, agent: profile, config: agentActionsConfig) - } - } - } .accessibilityLabel("New chat with \(profile.name)") .accessibilityValue(state == .idle ? "" : state.label) .accessibilityIdentifier("sessions.start-with.\(profile.id)") @@ -775,7 +755,7 @@ struct SessionsView: View { } label: { VStack(spacing: 5) { SessionIdentityView(session: session, agents: agents, size: 64, state: state) - // As Bots mode's top bots: the dot after the name. + // As the Bots view's top bots: the dot after the name. HStack(spacing: BighelpTokens.space4) { Text(session.title) .font(.system(size: pinnedTitleSize, weight: session.isUnread ? .bold : .semibold)) diff --git a/Bighelp/Settings/AppLayout.swift b/Bighelp/Settings/AppLayout.swift deleted file mode 100644 index dea60671..00000000 --- a/Bighelp/Settings/AppLayout.swift +++ /dev/null @@ -1,171 +0,0 @@ -import Foundation - -/// A place in bighelp that ☰ lists and the bottom bar can hold. -enum BighelpPlace: String, CaseIterable, Codable, Identifiable, Sendable { - case feed, ideas, goals, files - case agents, sessions, projects, kanban, workflows, scheduledTasks, usage - case settings - - var id: Self { self } - - var title: String { - switch self { - case .feed: String(localized: "Feed") - case .ideas: String(localized: "Ideas") - case .goals: String(localized: "Goals") - case .files: String(localized: "Files") - case .agents: String(localized: "Agents") - case .sessions: String(localized: "Sessions") - case .projects: String(localized: "Projects") - case .kanban: String(localized: "Kanban") - case .workflows: String(localized: "Workflows") - case .scheduledTasks: String(localized: "Scheduled tasks") - case .usage: String(localized: "Usage") - case .settings: String(localized: "Settings") - } - } - - /// The symbol ☰ shows beside it. - var symbol: String { - switch self { - case .feed: "newspaper" - case .ideas: "lightbulb" - case .goals: "checkmark.square" - case .files: "square.on.circle" - case .agents: "person.2" - case .sessions: "bubble.left.and.bubble.right" - case .projects: "folder" - case .kanban: "rectangle.split.3x1" - case .workflows: "flowchart" - case .scheduledTasks: "calendar.badge.clock" - case .usage: "gauge.with.dots.needle.50percent" - case .settings: "gearshape" - } - } - - /// The tab it opens as in the bottom bar. - var tab: AppTab { - switch self { - case .feed: .feed - case .ideas: .ideas - case .goals: .goals - case .files: .apps - case .agents: .agents - // Every chat. Chat, the bar's first tab, is the agent's own chat. - case .sessions: .sessionList - case .projects: .projects - case .kanban: .kanban - case .workflows: .workflows - case .scheduledTasks: .scheduledTasks - case .usage: .usage - case .settings: .profile - } - } - - /// Settings stays in ☰, so it can always be reached. - var canPin: Bool { self != .settings } - - /// Listed in ☰ even while the bar holds it: quick screens hide the bar, and - /// these are how you get around from there. - var staysInMenu: Bool { self == .agents || self == .settings } - - /// The selected agent's Feed, Ideas, Goals and Files. - var isAgentBoard: Bool { tab.isAgentBoard } - - init?(tab: AppTab) { - guard let place = BighelpPlace.allCases.first(where: { $0.tab == tab }) else { return nil } - self = place - } -} - -/// What the bottom bar holds after Chat, and the order of ☰ (Settings › Appearance › -/// App layout). ☰ lists every place the bar doesn't, plus Agents and Settings -/// always, so each stays one tap away. -struct BighelpAppLayout: Equatable, Sendable { - /// Chat comes first; three more fill the bar, two either side of New chat. - static let maximumPinned = 3 - - private(set) var pinned: [BighelpPlace] - private(set) var menuOrder: [BighelpPlace] - - static let standard = BighelpAppLayout( - pinned: [.feed, .ideas, .goals], - menuOrder: [.agents, .sessions, .projects, .kanban, .workflows, .scheduledTasks, .usage, - .feed, .ideas, .goals, .files, .settings]) - - init(pinned: [BighelpPlace], menuOrder: [BighelpPlace]) { - var seen = Set() - self.pinned = Array(pinned.filter { $0.canPin && seen.insert($0).inserted }.prefix(Self.maximumPinned)) - seen = [] - // Every place once: the saved order, then any place it didn't know. - let known = menuOrder.filter { seen.insert($0).inserted } - self.menuOrder = known + BighelpPlace.allCases.filter { !seen.contains($0) } - } - - /// The bottom bar's tabs, Chat first. - var barTabs: [AppTab] { [.sessions] + pinned.map(\.tab) } - - /// ☰'s places, in order: whatever the bar doesn't hold, and Agents and Settings. - var menuPlaces: [BighelpPlace] { menuOrder.filter { $0.staysInMenu || !pinned.contains($0) } } - - var canPinMore: Bool { pinned.count < Self.maximumPinned } - - func isPinned(_ place: BighelpPlace) -> Bool { pinned.contains(place) } - - mutating func pin(_ place: BighelpPlace) { - guard place.canPin, canPinMore, !pinned.contains(place) else { return } - pinned.append(place) - } - - mutating func unpin(_ place: BighelpPlace) { - pinned.removeAll { $0 == place } - } - - mutating func movePinned(from source: IndexSet, to destination: Int) { - pinned.move(fromOffsets: source, toOffset: destination) - } - - /// Moves within ☰'s list, which leaves out what's pinned. A pinned place taken out - /// of the bar later comes back at the end. - mutating func moveMenu(from source: IndexSet, to destination: Int) { - var shown = menuPlaces - shown.move(fromOffsets: source, toOffset: destination) - menuOrder = shown + menuOrder.filter { !shown.contains($0) } - } - - /// Saved as JSON text; anything unreadable is the standard layout. - init(saved text: String?) { - guard let text, text.utf8.count <= 4_096, - let raw = try? JSONDecoder().decode(Raw.self, from: Data(text.utf8)) else { - self = .standard - return - } - // Names an older build doesn't know are dropped. - self.init(pinned: raw.pinned.compactMap(BighelpPlace.init(rawValue:)), - menuOrder: raw.menu.compactMap(BighelpPlace.init(rawValue:))) - } - - /// What UserDefaults holds: the saved JSON text, or a dictionary of names (how a - /// launch argument like `-bighelp.app-layout '{pinned=(agents,feed);menu=();}'` arrives). - init(savedObject object: Any?) { - if let text = object as? String { - self.init(saved: text) - } else if let dictionary = object as? [String: Any], - let pinned = dictionary["pinned"] as? [String] { - self.init(pinned: pinned.compactMap(BighelpPlace.init(rawValue:)), - menuOrder: ((dictionary["menu"] as? [String]) ?? []).compactMap(BighelpPlace.init(rawValue:))) - } else { - self = .standard - } - } - - var saved: String? { - (try? JSONEncoder().encode(Raw(pinned: pinned.map(\.rawValue), menu: menuOrder.map(\.rawValue)))) - .flatMap { String(data: $0, encoding: .utf8) } - } - - private struct Raw: Codable { - let pinned: [String] - let menu: [String] - } -} diff --git a/Bighelp/Settings/AppLayoutSettingsView.swift b/Bighelp/Settings/AppLayoutSettingsView.swift deleted file mode 100644 index acc78f84..00000000 --- a/Bighelp/Settings/AppLayoutSettingsView.swift +++ /dev/null @@ -1,150 +0,0 @@ -import SwiftUI - -/// Settings › Appearance › App layout: what the bottom bar holds after Chat, and the -/// order of ☰. Whatever isn't in the bar is in ☰, so nothing is ever out of reach. -struct AppLayoutSettingsView: View { - @Bindable var settings: SettingsStore - @State private var isResetConfirmationPresented = false - - private var layout: BighelpAppLayout { settings.appLayout } - - var body: some View { - List { - barSection - addSection - menuSection - Section { - Button("Reset to Default Layout", role: .destructive) { - isResetConfirmationPresented = true - } - .disabled(layout == .standard) - .accessibilityIdentifier("app-layout.reset") - } footer: { - Text("Puts the bottom bar and the menu back the way bighelp recommends.") - } - .listRowBackground(theme.surface) - } - .alert("Reset to the default layout?", isPresented: $isResetConfirmationPresented) { - Button("Reset", role: .destructive) { - withAnimation { settings.appLayout = .standard } - } - .accessibilityIdentifier("app-layout.reset.confirm") - Button("Cancel", role: .cancel) {} - } message: { - Text("The bottom bar becomes Chat, Feed, Ideas, Goals and Files again, and the menu returns to its standard order.") - } - // Handles to drag. Adding and removing are their own buttons. - .environment(\.editMode, .constant(.active)) - .environment(\.defaultMinListRowHeight, BighelpTokens.hitTarget) - .scrollContentBackground(.hidden) - .background(BighelpThemeCanvas(theme: theme).ignoresSafeArea()) - .navigationTitle("App layout") - .navigationBarTitleDisplayMode(.inline) - .accessibilityIdentifier("app-layout") - } - - // MARK: Bottom bar - - private var barSection: some View { - Section { - HStack(spacing: BighelpTokens.space12) { - Image(systemName: "lock.fill") - .font(.bighelp(.footnote)) - .foregroundStyle(theme.tertiaryText) - .frame(width: BighelpTokens.hitTarget) - .accessibilityHidden(true) - label(String(localized: "Chat"), symbol: "bubble.left") - } - .moveDisabled(true) - .accessibilityIdentifier("app-layout.bar.chat") - ForEach(layout.pinned) { place in - HStack(spacing: BighelpTokens.space12) { - circleButton("minus.circle.fill", tint: theme.danger, - label: String(localized: "Remove \(place.title) from the bottom bar"), - id: "app-layout.remove.\(place.rawValue)") { - withAnimation { settings.appLayout.unpin(place) } - } - label(place.title, symbol: place.symbol) - } - // Keeps the remove button's own identifier reachable. - .accessibilityElement(children: .contain) - .accessibilityIdentifier("app-layout.bar.\(place.rawValue)") - } - .onMove { settings.appLayout.movePinned(from: $0, to: $1) } - } header: { - Text("Bottom bar") - } footer: { - Text("Chat is always first. Drag to change the order. What you remove goes to the menu.") - } - .listRowBackground(theme.surface) - } - - private var addSection: some View { - Section { - ForEach(BighelpPlace.allCases.filter { $0.canPin && !layout.isPinned($0) }) { place in - HStack(spacing: BighelpTokens.space12) { - circleButton("plus.circle.fill", tint: layout.canPinMore ? theme.success : theme.tertiaryText, - label: String(localized: "Add \(place.title) to the bottom bar"), - id: "app-layout.add.\(place.rawValue)") { - withAnimation { settings.appLayout.pin(place) } - } - .disabled(!layout.canPinMore) - label(place.title, symbol: place.symbol) - } - .moveDisabled(true) - } - } header: { - Text("Add to the bottom bar") - } footer: { - Text(layout.canPinMore - ? "The bottom bar holds Chat and up to \(BighelpAppLayout.maximumPinned) more, around New chat." - : "The bottom bar is full. Remove one to add another.") - } - .listRowBackground(theme.surface) - } - - // MARK: Menu - - private var menuSection: some View { - Section { - ForEach(layout.menuPlaces) { place in - label(place.title, symbol: place.symbol) - .accessibilityIdentifier("app-layout.menu.\(place.rawValue)") - } - .onMove { settings.appLayout.moveMenu(from: $0, to: $1) } - } header: { - Text("Menu") - } footer: { - Text("The menu shows everything that isn't in the bottom bar, and always Agents and Settings. Drag to change the order.") - } - .listRowBackground(theme.surface) - } - - private func circleButton(_ symbol: String, tint: Color, label: String, id: String, - action: @escaping () -> Void) -> some View { - Button(action: action) { - Image(systemName: symbol) - .font(.bighelp(.title3)) - .foregroundStyle(tint) - .frame(minWidth: BighelpTokens.hitTarget, minHeight: BighelpTokens.hitTarget) - .contentShape(.rect) - } - .buttonStyle(.plain) - .accessibilityLabel(label) - .accessibilityIdentifier(id) - } - - private func label(_ title: String, symbol: String) -> some View { - HStack(spacing: BighelpTokens.space12) { - BighelpIconTile(systemName: symbol) - Text(title) - .bighelpFont(.body) - .foregroundStyle(theme.primaryText) - Spacer(minLength: 0) - } - .frame(minHeight: BighelpTokens.hitTarget) - .accessibilityElement(children: .combine) - } - - @BighelpThemeReader private var theme -} diff --git a/Bighelp/Settings/HomeSettingsMigration.swift b/Bighelp/Settings/HomeSettingsMigration.swift new file mode 100644 index 00000000..083ec37c --- /dev/null +++ b/Bighelp/Settings/HomeSettingsMigration.swift @@ -0,0 +1,145 @@ +import Foundation + +/// One home (#977): reads once what the three modes saved and decides where the home opens, which view +/// its first tab shows, whether every computer shows, and the edge swipes without the mode actions. +/// `SettingsStore.init` runs it while `markerKey` is unset. No key is renamed, and the old keys stay as +/// they were; only the new truth is written, and only what reading the old keys can't give by itself. +enum HomeSettingsMigration { + static let markerKey = "bighelp.home.migrated-v1" + + /// What the modes saved, as plain values. + struct Stored: Equatable, Sendable { + var botsMode = false + var codeMode = false + /// Settings › Modes' Code as the home a launch opens in (`code-mode.open-in`). + var codeOpensAtLaunch = false + /// `loopdy.home.landing`: one of the nine old screens, or already one of the four new values. + var landing: String? + var allHosts: Bool? + var multiGateway = false + var leftEdge: String? + var rightEdge: String? + /// Anything saved before: an install that ran the modes. A new one has none of it. + var isExistingInstall = false + } + + struct Outcome: Equatable, Sendable { + var landing: HomeLanding + var view: HomeConversationsView + var showsEveryComputer: Bool + var leftEdge: WorkspaceSwipeAction + var rightEdge: WorkspaceSwipeAction + } + + static let defaultLeftEdge = WorkspaceSwipeAction.sessions + static let defaultRightEdge = WorkspaceSwipeAction.newChat + + /// Where a person lands; the first row that matches wins (PLAN-shell § 4). + static func outcome(_ stored: Stored) -> Outcome { + let left = remapped(stored.leftEdge, edgeDefault: defaultLeftEdge) + let right = remapped(stored.rightEdge, edgeDefault: defaultRightEdge) + // A new install is asked at first run; skipped (a launch argument, a restored backup), it's Chats. + guard stored.isExistingInstall else { + return Outcome(landing: .chats, view: .chats, showsEveryComputer: true, leftEdge: left, rightEdge: right) + } + let wasAllHosts = stored.allHosts ?? false + // Bots mode had its own swipes whatever was saved: from the left your bots, from the right this + // bot's page. Written down, so nothing changes under the person's thumb. + if stored.botsMode { + return Outcome(landing: .bots, view: .bots, showsEveryComputer: stored.multiGateway, + leftEdge: .agents, rightEdge: .profile) + } + func landingOn(_ landing: HomeLanding, everyComputer: Bool) -> Outcome { + Outcome(landing: landing, view: landing == .bots ? .bots : .chats, showsEveryComputer: everyComputer, + leftEdge: left, rightEdge: right) + } + // Code mode ignored Opens on, so Code as the launch home comes before it. + if stored.codeMode, stored.codeOpensAtLaunch { return landingOn(.work, everyComputer: wasAllHosts) } + if let screen = stored.landing.flatMap(BighelpLandingScreen.init(rawValue:)) { + return landingOn(screen.homeLanding, everyComputer: screen == .allAgents || wasAllHosts) + } + if let landing = stored.landing.flatMap(HomeLanding.init(rawValue:)) { + return landingOn(landing, everyComputer: wasAllHosts) + } + return landingOn(wasAllHosts ? .bots : .chats, everyComputer: wasAllHosts) + } + + /// The mode swipes go: Bots mode becomes Bots; Next mode, Chat mode and Code mode become the edge's + /// default. An unknown value is the default too, as `SettingsStore` reads it. + static func remapped(_ raw: String?, edgeDefault: WorkspaceSwipeAction) -> WorkspaceSwipeAction { + WorkspaceSwipeAction.saved(raw, edgeDefault: edgeDefault) + } + + /// Runs once: while the marker is unset (UI tests can pin `-bighelp.home.migrated-v1 NO` to run it at + /// every launch, or `YES` never to run it). + static func runIfNeeded(defaults: UserDefaults) { + guard !defaults.bool(forKey: markerKey) else { return } + let stored = Stored(reading: defaults) + write(outcome(stored), over: stored, to: defaults) + defaults.set(true, forKey: markerKey) + } + + /// Writes only what differs from what the keys already say. A new install gets nothing: first run asks, + /// and an unset "Show every computer" reads as on. + static func write(_ outcome: Outcome, over stored: Stored, to defaults: UserDefaults) { + guard stored.isExistingInstall else { return } + // An old screen that maps to the same place stays as it is. + if BighelpLanding.homeLanding(stored: stored.landing) != outcome.landing { + defaults.set(outcome.landing.rawValue, forKey: BighelpLanding.screenKey) + } + defaults.set(outcome.view.rawValue, forKey: Keys.homeView) + if stored.allHosts != outcome.showsEveryComputer { + defaults.set(outcome.showsEveryComputer, forKey: Keys.everyComputer) + } + if (stored.leftEdge ?? defaultLeftEdge.rawValue) != outcome.leftEdge.rawValue { + defaults.set(outcome.leftEdge.rawValue, forKey: Keys.leftEdge) + } + if (stored.rightEdge ?? defaultRightEdge.rawValue) != outcome.rightEdge.rawValue { + defaults.set(outcome.rightEdge.rawValue, forKey: Keys.rightEdge) + } + } + + enum Keys { + /// `HomeConversationsView`: the first tab's view when the home opens on Today or Work. + static let homeView = "bighelp.home.view" + /// "Show every computer": the all-hosts view's key, kept. + static let everyComputer = "bighelp.hosts.all-hosts" + static let simpleBots = "bighelp.settings.simple-bots" + static let codeMode = "bighelp.settings.code-mode" + static let codeOpenIn = "bighelp.settings.code-mode.open-in" + static let multiGateway = "bighelp.simple-bots.multi-gateway" + static let leftEdge = "loopdy.workspace.leftEdgeSwipeAction" + static let rightEdge = "loopdy.workspace.rightEdgeSwipeAction" + + /// First run finished: the plainest sign that this isn't a new install. Written by the shell + /// (`RootShellView.hasCompletedFirstRunOnboarding`). + static let firstRunCompleted = "loopdy.onboarding.first-run-v1.completed" + + /// Keys any earlier run leaves behind. First run's own keys (its step, and that it finished) are + /// written only once it shows, after `SettingsStore` is made, so a new install has none of these. + static let existingInstall = [ + simpleBots, codeMode, codeOpenIn, multiGateway, leftEdge, rightEdge, + Keys.everyComputer, BighelpLanding.screenKey, BighelpLanding.legacyOpensChatKey, + BighelpLanding.startAgentKey, AIDataConsent.key, FirstRunOnboarding.afterConnectKey, + firstRunCompleted, + "loopdy.onboarding.first-run-v1.step", "bighelp.app-layout", "loopdy.settings.nerd-mode", + "loopdy.demo.appearance", "bighelp.settings.unified-mode-toggle", "bighelp.settings.chat-switcher", + ] + } +} + +extension HomeSettingsMigration.Stored { + init(reading defaults: UserDefaults) { + typealias Keys = HomeSettingsMigration.Keys + botsMode = defaults.bool(forKey: Keys.simpleBots) + codeMode = defaults.bool(forKey: Keys.codeMode) + codeOpensAtLaunch = defaults.string(forKey: Keys.codeOpenIn) == "code" + landing = defaults.string(forKey: BighelpLanding.screenKey) + allHosts = defaults.object(forKey: Keys.everyComputer) == nil + ? nil : defaults.bool(forKey: Keys.everyComputer) + multiGateway = defaults.bool(forKey: Keys.multiGateway) + leftEdge = defaults.string(forKey: Keys.leftEdge) + rightEdge = defaults.string(forKey: Keys.rightEdge) + isExistingInstall = Keys.existingInstall.contains { defaults.object(forKey: $0) != nil } + } +} diff --git a/Bighelp/Settings/PluginUpdateSection.swift b/Bighelp/Settings/PluginUpdateSection.swift deleted file mode 100644 index 9aa49a93..00000000 --- a/Bighelp/Settings/PluginUpdateSection.swift +++ /dev/null @@ -1,120 +0,0 @@ -import SwiftUI - -@MainActor -struct PluginUpdateSection: View { - let store: PluginUpdateStore? - let theme: BighelpTheme - var modelNames: ModelNameCatalogStore = .shared - @State private var confirmsUpdate = false - - var body: some View { - Group { - Section { - if let store { - VStack(alignment: .leading, spacing: BighelpTokens.space4) { - HStack { - Text(store.title).bighelpFont(.label, weight: .semibold) - if let connection = HostConnectionStatus(pluginUpdate: store) { - BighelpConnectionIndicator(phase: connection.phase) - } else if store.isWorking || store.isPending { - ProgressView().controlSize(.small) - } - } - if let message = store.message ?? store.status?.message { - Text(message).bighelpFont(.metadata).foregroundStyle(theme.secondaryText) - .fixedSize(horizontal: false, vertical: true) - } - if let revision = store.status?.activeRevision { - Text("Active revision: \(revision.prefix(12))") - .bighelpFont(.metadata).foregroundStyle(theme.tertiaryText) - } - } - .accessibilityIdentifier("settings.plugin-update-status") - } else { - Text("Connect to a paired host to update its bighelp plugin.") - .bighelpFont(.metadata).foregroundStyle(theme.secondaryText) - } - Button { - confirmsUpdate = true - } label: { - Label("Update bighelp Plugin", systemImage: "arrow.down.circle") - .frame(minHeight: BighelpTokens.hitTarget) - } - .disabled(store?.canStart != true) - .accessibilityIdentifier("settings.update-plugin") - if let store { - Button { - Task { await store.refreshStatus() } - } label: { - Label("Check Update Status", systemImage: "arrow.clockwise") - .frame(minHeight: BighelpTokens.hitTarget) - } - .disabled(store.isWorking) - .accessibilityIdentifier("settings.check-plugin-update") - } - } header: { - Text("bighelp plugin") - } footer: { - Text("Updating downloads the latest plugin and restarts the connected host’s gateway. Active work may be interrupted.") - } - .task(id: store?.pendingOperationID) { - if let store { await store.observe() } - } - .alert("Update bighelp Plugin?", isPresented: $confirmsUpdate) { - Button("Update and Restart", role: .destructive) { - if let store { Task { await store.start() } } - } - Button("Cancel", role: .cancel) {} - } message: { - Text("This downloads the latest bighelp plugin and restarts the connected host’s gateway. Active work may be interrupted. bighelp will reconnect and verify the updated plugin before reporting completion.") - } - - Section { - Button { - Task { await modelNames.refresh() } - } label: { - HStack { - Label("Update Model Names", systemImage: "text.badge.checkmark") - Spacer() - if modelNames.isRefreshing { ProgressView() } - } - .frame(minHeight: BighelpTokens.hitTarget) - } - .disabled(modelNames.isRefreshing) - .accessibilityIdentifier("settings.update-model-names") - if let message = modelNames.statusMessage { - Text(message).bighelpFont(.metadata).foregroundStyle(theme.secondaryText) - .accessibilityIdentifier("settings.model-names-status") - } - } header: { - Text("Model names") - } footer: { - Text("Refreshes display labels only. It does not restart the host or change model assignments.") - } - } - .foregroundStyle(theme.primaryText) - .tint(theme.action) - .listRowBackground(theme.surface) - - } -} - -#if DEBUG -/// Explicit simulator fixture, never selected for a production account. -@MainActor -final class PluginUpdatePreviewClient: PluginUpdateClient { - private var operationID: String? - func start(operationID: String) async throws -> PluginUpdateStatus { - self.operationID = operationID - return value(.waitingForActivation) - } - func status(operationID: String?) async throws -> PluginUpdateStatus { - value(self.operationID == nil ? .idle : .complete) - } - private func value(_ phase: PluginUpdateStatus.Phase) -> PluginUpdateStatus { - .init(operationID: operationID, phase: phase, - targetRevision: String(repeating: "a", count: 40), activeRevision: String(repeating: "a", count: 40), - runtimeID: phase == .idle ? "fixture_old" : "fixture_restarted", message: phase.title) - } -} -#endif diff --git a/Bighelp/Settings/SettingsDestination.swift b/Bighelp/Settings/SettingsDestination.swift index 0b4e6500..c5f56f5c 100644 --- a/Bighelp/Settings/SettingsDestination.swift +++ b/Bighelp/Settings/SettingsDestination.swift @@ -4,14 +4,13 @@ import Foundation /// (an agent's drive, a link) can open Settings straight to one with `AppState.openSettings(at:)`. /// Pages that are not reachable by a push (sheets, the host's own tools) are not listed. enum SettingsDestination: Hashable, Sendable { - /// One page by its `SettingsMenuSection` (Modes, Appearance, Chat, Voice, Help ...). + /// One page by its `SettingsMenuSection` (Appearance, Chat, Voice, Help ...). case section(SettingsMenuSection) /// The first row: your name and photo. case you /// Appearance › Chat layout. case chatLayout - /// Appearance › App layout: the bottom bar and the order of ☰. - case appLayout + /// Appearance › Thinking: the look of the Thinking control. case thinking /// Apps & skills: this device's access, the apps and skills bots can use (its own pages open diff --git a/Bighelp/Settings/SettingsPreferences.swift b/Bighelp/Settings/SettingsPreferences.swift index 7f467b32..71a224ca 100644 --- a/Bighelp/Settings/SettingsPreferences.swift +++ b/Bighelp/Settings/SettingsPreferences.swift @@ -318,119 +318,45 @@ enum ChatReasoningPlacement: String, CaseIterable, Identifiable, Sendable { static let staysOpenByDefault = true } -/// Which home bighelp shows: the everyday agent chat, or Code mode's coding -/// sessions (Settings › Code mode; ☰ switches between them). -enum BighelpExperience: String, CaseIterable, Identifiable, Sendable { - case bighelp - case code - - var id: Self { self } - - var title: String { - switch self { - case .bighelp: String(localized: "Chat") - case .code: String(localized: "Code") - } - } -} - -/// The three ways bighelp opens: Bots mode (`simpleBotsEnabled`), Chat, and Code -/// (`experience`, once Settings › Code mode is on). The Header mode switcher and the -/// mode edge swipes switch between them. -enum BighelpMode: String, CaseIterable, Identifiable, Sendable { - case bots - case chat - case code - - var id: Self { self } - - var title: String { - switch self { - case .bots: String(localized: "Bots") - case .chat: String(localized: "Chat") - case .code: String(localized: "Code") - } - } - - var shortDetail: String { - switch self { - case .bots: String(localized: "Calm home, just your bots") - case .chat: String(localized: "Chats, Feed, Ideas & Goals") - case .code: String(localized: "Worktrees, diffs & PRs") - } - } - - var systemImage: String { - switch self { - case .bots: "bubble.left.and.bubble.right.fill" - case .chat: "square.grid.2x2.fill" - case .code: "chevron.left.forwardslash.chevron.right" - } - } -} - -/// The Header mode switcher in a home's header: the modes on offer, the one showing, and the switch. -struct BighelpModeSwitch { - let modes: [BighelpMode] - let current: BighelpMode - let select: @MainActor (BighelpMode) -> Void -} - +/// What a swipe from the screen's left or right edge does (Settings › Chat › Advanced › Edge swipes). enum WorkspaceSwipeAction: String, CaseIterable, Identifiable, Sendable { case quickWorkspace case newChat case sessions case agents case home - case inbox case profile - case nextMode - case botsMode - case chatMode - case codeMode case none + /// In the picker's order. "Bot page or Settings" is this bot's page in a chat and Settings elsewhere; + /// "Sidebar" opens it where there is one, else Chats. static let allCases: [WorkspaceSwipeAction] = [ - .quickWorkspace, - .newChat, - .sessions, - .agents, - .home, - .profile, - .nextMode, - .botsMode, - .chatMode, - .codeMode, - .none, + .newChat, .sessions, .agents, .home, .profile, .quickWorkspace, .none, ] - /// Switches mode instead of opening a place, so it works in Bots mode too. - var mode: BighelpMode? { - switch self { - case .botsMode: .bots - case .chatMode: .chat - case .codeMode: .code - default: nil + /// Saved values no action has any more: Inbox, and the swipes that switched between the three modes. + static let retiredRawValues: Set = ["inbox", "nextMode", "botsMode", "chatMode", "codeMode"] + + /// What a saved value does now. Inbox is Home and Bots mode is Bots; the other mode swipes, and + /// anything unknown, are the edge's default. + static func saved(_ raw: String?, edgeDefault: WorkspaceSwipeAction) -> WorkspaceSwipeAction { + switch raw { + case "inbox": .home + case "botsMode": .agents + default: raw.flatMap(WorkspaceSwipeAction.init(rawValue:)) ?? edgeDefault } } - var switchesMode: Bool { self == .nextMode || mode != nil } - var id: Self { self } var title: String { switch self { - case .quickWorkspace: String(localized: "Menu") - case .newChat: String(localized: "New Chat") - case .sessions: String(localized: "Sessions") - case .agents: String(localized: "Agents") + case .quickWorkspace: String(localized: "Sidebar") + case .newChat: String(localized: "New chat") + case .sessions: String(localized: "Chats") + case .agents: String(localized: "Bots") case .home: String(localized: "Home") - case .inbox: String(localized: "Inbox") - case .profile: String(localized: "Profile & Settings") - case .nextMode: String(localized: "Next mode") - case .botsMode: String(localized: "Bots mode") - case .chatMode: String(localized: "Chat mode") - case .codeMode: String(localized: "Code mode") + case .profile: String(localized: "Bot page or Settings") case .none: String(localized: "Off") } } @@ -442,12 +368,7 @@ enum WorkspaceSwipeAction: String, CaseIterable, Identifiable, Sendable { case .sessions: "clock.arrow.circlepath" case .agents: "person.2" case .home: "house" - case .inbox: "tray" case .profile: "person.crop.circle" - case .nextMode: "arrow.left.arrow.right" - case .botsMode: "bubble.left.and.bubble.right" - case .chatMode: "message" - case .codeMode: "chevron.left.forwardslash.chevron.right" case .none: "hand.raised.slash" } } diff --git a/Bighelp/Settings/SettingsPresentation.swift b/Bighelp/Settings/SettingsPresentation.swift index 06cd408a..7c5f3b3d 100644 --- a/Bighelp/Settings/SettingsPresentation.swift +++ b/Bighelp/Settings/SettingsPresentation.swift @@ -1,7 +1,7 @@ import Foundation enum SettingsMenuSection: String, CaseIterable, Identifiable, Equatable, Sendable { - case modes + case appearance case chat case voice @@ -14,7 +14,7 @@ enum SettingsMenuSection: String, CaseIterable, Identifiable, Equatable, Sendabl var title: String { switch self { - case .modes: String(localized: "Modes") + case .chat: String(localized: "Chat") case .voice: String(localized: "Voice") case .notifications: String(localized: "Notifications") @@ -27,7 +27,7 @@ enum SettingsMenuSection: String, CaseIterable, Identifiable, Equatable, Sendabl var detail: String { switch self { - case .modes: String(localized: "Bots, Chat and Code") + case .chat: Self.chatDetail case .voice: String(localized: "How voice chats sound") case .notifications: String(localized: "Alerts from your bots") @@ -48,7 +48,7 @@ enum SettingsMenuSection: String, CaseIterable, Identifiable, Equatable, Sendabl var systemImage: String { switch self { - case .modes: "circle.hexagongrid" + case .chat: "bubble.left.and.bubble.right.fill" case .voice: "waveform" case .notifications: "bell.badge.fill" diff --git a/Bighelp/Settings/SettingsStore.swift b/Bighelp/Settings/SettingsStore.swift index f3c18096..583e5b1a 100644 --- a/Bighelp/Settings/SettingsStore.swift +++ b/Bighelp/Settings/SettingsStore.swift @@ -19,8 +19,7 @@ final class SettingsStore { private(set) var sessionSectionPreferencesRevision = 0 var appearanceContext: BighelpAppearanceContext { - // Bots mode takes the themes and bubbles picked in Appearance, like the rest of the app. - var context = BighelpAppearanceContext( + BighelpAppearanceContext( appearance: appearance, lightBackground: lightBackground, darkBackground: darkBackground, @@ -29,8 +28,6 @@ final class SettingsStore { bubbleFollowsTheme: bubbleFollowsTheme, windowTransparency: windowTransparency ) - context.simpleBots = simpleBotsEnabled - return context } /// Appearance studio: light and dark page colors and the bubble color. @@ -215,109 +212,12 @@ final class SettingsStore { didSet { defaults.set(rightEdgeSwipeAction.rawValue, forKey: Keys.rightEdgeSwipeAction) } } - /// What the edge swipes do. Bots mode hides most places they lead to, so there they're its - /// own: from the left, your bots; from the right, this bot's profile. A mode swipe stays a mode - /// swipe, so it can bring you back out of Bots mode. - var effectiveLeftEdgeSwipeAction: WorkspaceSwipeAction { - Self.effective(leftEdgeSwipeAction, botsMode: .agents, isBotsMode: simpleBotsEnabled, codeModeEnabled: codeModeEnabled) - } - var effectiveRightEdgeSwipeAction: WorkspaceSwipeAction { - Self.effective(rightEdgeSwipeAction, botsMode: .profile, isBotsMode: simpleBotsEnabled, codeModeEnabled: codeModeEnabled) - } - - nonisolated static func effective(_ action: WorkspaceSwipeAction, botsMode: WorkspaceSwipeAction, - isBotsMode: Bool, codeModeEnabled: Bool) -> WorkspaceSwipeAction { - // Code mode switched off later: its swipe does nothing rather than open Chat. - if action == .codeMode, !codeModeEnabled { return .none } - if action.switchesMode { return action } - return isBotsMode ? botsMode : action - } - - /// Settings › Modes › Header mode switcher: Bots, Chat and Code in a pill at the top of each - /// home. Off by default; ☰ keeps its Chat and Code switch while it's off. - var unifiedModeToggleEnabled: Bool { - didSet { defaults.set(unifiedModeToggleEnabled, forKey: Keys.unifiedModeToggle) } - } - - /// Settings › Modes › Chat switcher: the bots (Bots mode) or running sessions (Code mode) - /// beside a chat. On by default on phones, where only the iPhone Duo folded shows it; iPad and + /// Settings › Chat › Chat switcher: the bots, or a coding chat's running sessions, beside a chat. On by default on phones, where only the iPhone Duo folded shows it; iPad and /// Mac show it in landscape once it's turned on (`BighelpChatSwitcher`). var chatSwitcherEnabled: Bool { didSet { defaults.set(chatSwitcherEnabled, forKey: Keys.chatSwitcher) } } - /// The modes on offer: Code only while Settings › Code mode is on. - var availableModes: [BighelpMode] { codeModeEnabled ? [.bots, .chat, .code] : [.bots, .chat] } - - /// The mode showing now. Bots mode wins over Chat and Code, as its home does. - var currentMode: BighelpMode { - if simpleBotsEnabled { return .bots } - return codeModeEnabled && experience == .code ? .code : .chat - } - - /// The mode after this one, for the Next mode swipe: Bots, Chat, Code, then Bots again. - var nextMode: BighelpMode { - let modes = availableModes - let index = modes.firstIndex(of: currentMode) ?? 0 - return modes[(index + 1) % modes.count] - } - - /// Switches to `mode`. The shell follows `experience` and `simpleBotsEnabled` to that mode's home. - func switchMode(_ mode: BighelpMode) { - guard availableModes.contains(mode), mode != currentMode else { return } - Telemetry.featureUsed(.modeSwitched) - switch mode { - case .bots: - simpleBotsEnabled = true - case .chat: - experience = .bighelp - simpleBotsEnabled = false - case .code: - experience = .code - simpleBotsEnabled = false - } - } - - /// The home a launch opens in, which Settings › Modes' picker shows. Bots mode is its own switch; - /// between Chat and Code it's `startExperience`, not the home showing now (☰ and the pill switch that). - var homeMode: BighelpMode { - if simpleBotsEnabled { return .bots } - return codeModeEnabled && startExperience == .code ? .code : .chat - } - - /// Settings › Modes' picker: makes `mode` the home, now and at each launch. Picking Code turns - /// Code mode on; picking Chat or Bots leaves it as it is (its own switch turns it off). - /// Settings › Modes in one line: "Bots mode", "Code", "Chat and Code" or "Chat". - var modesSummary: String { - if simpleBotsEnabled { return String(localized: "Bots mode") } - if currentMode == .code { return String(localized: "Code") } - return codeModeEnabled ? String(localized: "Chat and Code") : String(localized: "Chat") - } - - func selectHomeMode(_ mode: BighelpMode) { - let changed = mode != currentMode - switch mode { - case .bots: - simpleBotsEnabled = true - case .chat: - simpleBotsEnabled = false - startExperience = .bighelp - experience = .bighelp - case .code: - simpleBotsEnabled = false - codeModeEnabled = true - startExperience = .code - experience = .code - } - if changed { Telemetry.featureUsed(.modeSwitched) } - } - - /// Settings › Modes › Code mode. Off while Code is the home goes back to Chat, now and at launch. - func setCodeMode(_ isOn: Bool) { - codeModeEnabled = isOn - if !isOn { startExperience = .bighelp } - } - var preferredBrowser: ChatBrowserPreference { didSet { defaults.set(preferredBrowser.rawValue, forKey: Keys.preferredBrowser) } } @@ -360,18 +260,6 @@ final class SettingsStore { didSet { defaults.set(showCronSessions, forKey: Keys.showCronSessions) } } - /// The bottom bar's tabs after Chat and the order of ☰ (Appearance › App layout). - var appLayout: BighelpAppLayout { - didSet { - guard appLayout != oldValue else { return } - if appLayout == .standard { - defaults.removeObject(forKey: Keys.appLayout) - } else { - defaults.set(appLayout.saved, forKey: Keys.appLayout) - } - } - } - /// Reveals host administration (files, gateways, plugins, logs, ...) in Settings. /// Off by default so everyday use stays a simple messaging app. var nerdModeEnabled: Bool { @@ -382,72 +270,79 @@ final class SettingsStore { } } - /// The all-hosts view: every agent on every host in one list. - var allHostsMode: Bool { - didSet { defaults.set(allHostsMode, forKey: Keys.allHostsMode) } + /// Settings › Your computers › Show every computer: every computer's bots and chats in the home, + /// and the other computers kept connected. Unset (a new install) is on; the migration writes what an + /// existing install had. + var showsEveryComputer: Bool { + get { everyComputer ?? true } + set { everyComputer = newValue } } - /// Settings › Code mode: a second home for coding sessions on the host's - /// projects. Off by default; Chat stays the out-of-box home. - var codeModeEnabled: Bool { + /// `bighelp.hosts.all-hosts` as saved; nil until something sets it. + private var everyComputer: Bool? { didSet { - defaults.set(codeModeEnabled, forKey: Keys.codeMode) - if !codeModeEnabled { experience = .bighelp } + if let everyComputer { defaults.set(everyComputer, forKey: Keys.allHostsMode) } + else { defaults.removeObject(forKey: Keys.allHostsMode) } } } - /// Settings › Bots mode: a calm home with just your bots, in place of - /// the tab bar and ☰. Its own Settings sheet turns it off again. - /// Bots mode's Multi-gateway: the home lists every gateway's bots, not only the selected one's. - var simpleBotsMultiGateway: Bool { - didSet { defaults.set(simpleBotsMultiGateway, forKey: Keys.simpleBotsMultiGateway) } - } - - /// Multi-gateway's Filter by Gateway: a filter button on the home that shows one gateway's bots. - var simpleBotsGatewayFilter: Bool { - didSet { defaults.set(simpleBotsGatewayFilter, forKey: Keys.simpleBotsGatewayFilter) } - } - - /// Multi-gateway's primary bot (gateway and bot, `FleetID`), kept on this device so it stays put - /// whichever gateway is in use. + /// The primary bot while every computer shows (computer and bot, `FleetID`), kept on this device so + /// it stays put whichever computer is in use. var simpleBotsMultiPrimary: String? { didSet { defaults.set(simpleBotsMultiPrimary, forKey: Keys.simpleBotsMultiPrimary) } } - var simpleBotsEnabled: Bool { - didSet { defaults.set(simpleBotsEnabled, forKey: Keys.simpleBots) } + /// Settings › Chat › Opens on: Bots, Chats, Today or Work. Saved under the old key; a screen saved + /// before maps to its place (`BighelpLanding.homeLanding(stored:)`), and nothing saved is Chats. + /// Bots and Chats also set the first tab's view. + var homeLanding: HomeLanding { + get { BighelpLanding.homeLanding(stored: savedLanding) ?? .chats } + set { + savedLanding = newValue.rawValue + switch newValue { + case .bots: savedHomeView = .bots + case .chats: savedHomeView = .chats + case .today, .work: break + } + } } - /// Settings › Open in: the home a launch starts on while Code mode is on. - var startExperience: BighelpExperience { - didSet { defaults.set(startExperience.rawValue, forKey: Keys.startExperience) } + /// The first tab's view: the one Opens on names, or Settings › Chat › First tab shows when the home + /// opens on Today or Work (default Chats). + var homeView: HomeConversationsView { + get { + switch homeLanding { + case .bots: .bots + case .chats: .chats + case .today, .work: savedHomeView ?? .chats + } + } + set { savedHomeView = newValue } } - /// The home on screen now. ☰ switches it; each launch starts on `startExperience`. - var experience: BighelpExperience + /// Where this launch opens, read once: a new pick applies next time. + let launchHomeLanding: HomeLanding - /// Settings › Chat › Opens on; nil until picked (the agent's latest chat). - var landingScreen: BighelpLandingScreen? { - didSet { defaults.set(landingScreen?.rawValue, forKey: BighelpLanding.screenKey) } + /// `loopdy.home.landing` as saved: one of the four, an old screen, or nil. + private var savedLanding: String? { + didSet { defaults.set(savedLanding, forKey: BighelpLanding.screenKey) } } - /// What this launch opens on, read once: a new pick applies next time. - let launchLanding: BighelpLandingChoice - - /// Settings › Chat › Start with, per computer (`cacheScopeID` → agent ID). - private(set) var startAgentIDs: [String: String] + private var savedHomeView: HomeConversationsView? { + didSet { defaults.set(savedHomeView?.rawValue, forKey: Keys.homeView) } + } private let defaults: UserDefaults init( defaults: UserDefaults = .standard, - legacyThemeLogoDirectory: URL? = nil, - now: @escaping () -> Date = Date.init + legacyThemeLogoDirectory: URL? = nil ) { self.defaults = defaults - self.now = now Self.removeRetiredThemes(defaults: defaults, logoDirectory: legacyThemeLogoDirectory ?? Self.defaultLegacyThemeLogoDirectory) + // Before anything below reads the keys it may write. + HomeSettingsMigration.runIfNeeded(defaults: defaults) let recoveredReflectiveVisionActivation = ReflectiveVisionRecoveryMarker( defaults: defaults ).consumePendingActivation() @@ -522,24 +417,10 @@ final class SettingsStore { reflectiveVisionEnabled = false defaults.set(false, forKey: Keys.reflectiveVision) } - let storedLeftEdgeSwipeAction = WorkspaceSwipeAction( - rawValue: defaults.string(forKey: Keys.leftEdgeSwipeAction) ?? "" - ) ?? .sessions - let storedRightEdgeSwipeAction = WorkspaceSwipeAction( - rawValue: defaults.string(forKey: Keys.rightEdgeSwipeAction) ?? "" - ) ?? .newChat - leftEdgeSwipeAction = storedLeftEdgeSwipeAction == .inbox - ? .home - : storedLeftEdgeSwipeAction - rightEdgeSwipeAction = storedRightEdgeSwipeAction == .inbox - ? .home - : storedRightEdgeSwipeAction - if storedLeftEdgeSwipeAction == .inbox { - defaults.set(WorkspaceSwipeAction.home.rawValue, forKey: Keys.leftEdgeSwipeAction) - } - if storedRightEdgeSwipeAction == .inbox { - defaults.set(WorkspaceSwipeAction.home.rawValue, forKey: Keys.rightEdgeSwipeAction) - } + leftEdgeSwipeAction = Self.savedEdgeSwipe(Keys.leftEdgeSwipeAction, + edgeDefault: HomeSettingsMigration.defaultLeftEdge, in: defaults) + rightEdgeSwipeAction = Self.savedEdgeSwipe(Keys.rightEdgeSwipeAction, + edgeDefault: HomeSettingsMigration.defaultRightEdge, in: defaults) preferredBrowser = ChatBrowserPreference( rawValue: defaults.string(forKey: Keys.preferredBrowser) ?? "" ) ?? .systemDefault @@ -573,69 +454,32 @@ final class SettingsStore { forKey: Keys.showCronSessions, default: false ) - appLayout = BighelpAppLayout(savedObject: defaults.object(forKey: Keys.appLayout)) nerdModeEnabled = defaults.bool(forKey: Keys.nerdMode, default: false) if defaults === UserDefaults.standard { BighelpActivityDetailLevel.showsNerdLine = defaults.bool(forKey: Keys.nerdMode, default: false) } - allHostsMode = defaults.bool(forKey: Keys.allHostsMode, default: false) - let codeMode = defaults.bool(forKey: Keys.codeMode, default: false) - let start = defaults.string(forKey: Keys.startExperience).flatMap(BighelpExperience.init(rawValue:)) ?? .bighelp - codeModeEnabled = codeMode - simpleBotsEnabled = defaults.bool(forKey: Keys.simpleBots, default: false) - unifiedModeToggleEnabled = defaults.bool(forKey: Keys.unifiedModeToggle, default: false) + everyComputer = defaults.object(forKey: Keys.allHostsMode) == nil + ? nil : defaults.bool(forKey: Keys.allHostsMode) chatSwitcherEnabled = defaults.bool(forKey: Keys.chatSwitcher, default: BighelpChatSwitcher.isOnByDefault) - simpleBotsMultiGateway = defaults.bool(forKey: Keys.simpleBotsMultiGateway, default: false) - simpleBotsGatewayFilter = defaults.bool(forKey: Keys.simpleBotsGatewayFilter, default: false) simpleBotsMultiPrimary = defaults.string(forKey: Keys.simpleBotsMultiPrimary) - startExperience = start - experience = codeMode ? start : .bighelp - let landing = defaults.string(forKey: BighelpLanding.screenKey).flatMap(BighelpLandingScreen.init(rawValue:)) - landingScreen = landing - let legacyOpensChat = defaults.object(forKey: BighelpLanding.legacyOpensChatKey) == nil - ? nil : defaults.bool(forKey: BighelpLanding.legacyOpensChatKey) - launchLanding = BighelpLanding.choice(screen: landing, legacyOpensChat: legacyOpensChat) - startAgentIDs = (defaults.dictionary(forKey: BighelpLanding.startAgentKey) as? [String: String] ?? [:]) - .filter { $0.key.utf8.count <= Self.maximumStartAgentKeyLength && $0.value.utf8.count <= Self.maximumStartAgentKeyLength } - } - - private static let maximumStartAgentKeyLength = 256 - - /// The agent this computer opens with; nil is Automatic. - func startAgentID(scope: String?) -> String? { - scope.flatMap { startAgentIDs[$0] } - } - - func setStartAgentID(_ id: String?, scope: String) { - guard scope.utf8.count <= Self.maximumStartAgentKeyLength, - (id?.utf8.count ?? 0) <= Self.maximumStartAgentKeyLength else { return } - startAgentIDs[scope] = id - defaults.set(startAgentIDs, forKey: BighelpLanding.startAgentKey) - } - - /// A picked Opens on decides, at launch, whether every computer's agents show. Bots mode - /// opens on its own home and ignores Opens on (its Multi-gateway switch shows every computer). - func applyLaunchLandingToAllHostsMode() { - guard !simpleBotsEnabled, - let on = BighelpLanding.allHostsMode(for: launchLanding), allHostsMode != on else { return } - modeBeforeLaunchLanding = (allHostsMode, now()) - allHostsMode = on - } - - /// A notification, widget or link that opened the app goes where it points, in the mode you - /// were in: Opens on decides only for a launch you started yourself. Only right after launch. - func restoreAllHostsModeForOutsideOpen() { - guard let before = modeBeforeLaunchLanding else { return } - modeBeforeLaunchLanding = nil - guard now().timeIntervalSince(before.at) < Self.outsideOpenWindow, allHostsMode != before.on else { return } - allHostsMode = before.on + let savedLanding = defaults.string(forKey: BighelpLanding.screenKey) + self.savedLanding = savedLanding + savedHomeView = defaults.string(forKey: Keys.homeView).flatMap(HomeConversationsView.init(rawValue:)) + launchHomeLanding = BighelpLanding.homeLanding(stored: savedLanding) ?? .chats + } + + /// An edge's swipe as saved. An action that is gone (Inbox, the mode swipes) is saved again as what + /// took its place, so the picker shows what the swipe does. + private static func savedEdgeSwipe(_ key: String, edgeDefault: WorkspaceSwipeAction, + in defaults: UserDefaults) -> WorkspaceSwipeAction { + let raw = defaults.string(forKey: key) + let action = WorkspaceSwipeAction.saved(raw, edgeDefault: edgeDefault) + if let raw, WorkspaceSwipeAction.retiredRawValues.contains(raw) { + defaults.set(action.rawValue, forKey: key) + } + return action } - /// The switch as it was before Opens on changed it at this launch. - @ObservationIgnored private var modeBeforeLaunchLanding: (on: Bool, at: Date)? - @ObservationIgnored private let now: () -> Date - private static let outsideOpenWindow: TimeInterval = 30 - /// Themes (Nous, Superpilot and your own, with their logos) were replaced by /// bubble colors and light and dark backgrounds. Picking a bubble color /// quietly replaced a chosen theme anyway. Their saved data and logo files @@ -896,16 +740,10 @@ private extension SettingsStore { static let showProjectChanges = "loopdy.chat.showProjectChanges" static let organizeChatsByProjects = "loopdy.sessions.organizeByProjects" static let showCronSessions = "loopdy.sessions.showCronSessions" - static let appLayout = "bighelp.app-layout" static let nerdMode = "loopdy.settings.nerd-mode" - static let allHostsMode = "bighelp.hosts.all-hosts" - static let codeMode = "bighelp.settings.code-mode" - static let startExperience = "bighelp.settings.code-mode.open-in" - static let simpleBots = "bighelp.settings.simple-bots" - static let unifiedModeToggle = "bighelp.settings.unified-mode-toggle" + static let allHostsMode = HomeSettingsMigration.Keys.everyComputer + static let homeView = HomeSettingsMigration.Keys.homeView static let chatSwitcher = "bighelp.settings.chat-switcher" - static let simpleBotsMultiGateway = "bighelp.simple-bots.multi-gateway" - static let simpleBotsGatewayFilter = "bighelp.simple-bots.gateway-filter" static let simpleBotsMultiPrimary = "bighelp.simple-bots.multi-gateway.primary" static let sessionSectionPreferences = "loopdy.sessions.section-preferences.v1" } diff --git a/Bighelp/Settings/SettingsView+Computers.swift b/Bighelp/Settings/SettingsView+Computers.swift index f8fbdfbb..b26ec1f0 100644 --- a/Bighelp/Settings/SettingsView+Computers.swift +++ b/Bighelp/Settings/SettingsView+Computers.swift @@ -9,7 +9,8 @@ struct SettingsArchivedChats { } /// Settings' Your computers: each computer opens its own page, then Add a computer, Show every -/// computer, the time zone of the computer in use and, with two or more, Update every computer. +/// computer (with two or more), the time zone of the computer in use and, with two or more, Update +/// every computer. extension SettingsView { @ViewBuilder var computersSection: some View { @@ -30,18 +31,11 @@ extension SettingsView { Text(error).bighelpFont(.metadata).foregroundStyle(theme.secondaryText) } } - if offersEveryComputer, let everyComputer = everyComputerBinding { + if offersEveryComputer { tileToggle(String(localized: "Show every computer"), symbol: "square.stack.3d.up.fill", - isOn: everyComputer) + isOn: everyComputerBinding) .accessibilityIdentifier("simple-bots.settings.multi-gateway") .driveTarget("simple-bots.settings.multi-gateway") - // Bots mode's home: a filter button beside Search, for one computer's bots. - if settings.simpleBotsEnabled, settings.simpleBotsMultiGateway { - tileToggle(String(localized: "Computer filter"), symbol: "line.3.horizontal.decrease", - isOn: $settings.simpleBotsGatewayFilter) - .accessibilityIdentifier("simple-bots.settings.gateway-filter") - .driveTarget("simple-bots.settings.gateway-filter") - } } if let computerTimeZone, hostRegistry?.selectedHostID != nil || usesDemoComputer { SettingsTimeZoneRow(make: computerTimeZone, @@ -121,16 +115,9 @@ extension SettingsView { } } - /// Show every computer, by `SettingsEveryComputer.choice`. Nil when there is no setting to change. - private var everyComputerBinding: Binding? { - switch SettingsEveryComputer.choice(botsModeOn: settings.simpleBotsEnabled, - canSetAllHosts: onSetAllHosts != nil) { - case .botsMultiGateway: return $settings.simpleBotsMultiGateway - case .allHosts: - guard let onSetAllHosts else { return nil } - return Binding(get: { settings.allHostsMode }, set: { onSetAllHosts($0) }) - case nil: return nil - } + /// Show every computer: one setting for everyone. + private var everyComputerBinding: Binding { + Binding(get: { settings.showsEveryComputer }, set: { settings.showsEveryComputer = $0 }) } /// Demo mode's made-up computer has no row in the registry, but its time zone still saves. @@ -155,19 +142,6 @@ extension SettingsView { } } -/// Which stored setting Show every computer changes: Bots mode's Multi-gateway while Bots mode is -/// on (its home lists every computer's bots), the all-hosts view elsewhere, which only the shell -/// can turn on and off. -enum SettingsEveryComputer: Equatable { - case botsMultiGateway - case allHosts - - static func choice(botsModeOn: Bool, canSetAllHosts: Bool) -> SettingsEveryComputer? { - if botsModeOn { return .botsMultiGateway } - return canSetAllHosts ? .allHosts : nil - } -} - /// Your computers › Time zone: the time zone every bot on the computer in use works in, or /// Automatic, which follows this device's (also after travel, when bighelp comes back). @MainActor @@ -183,7 +157,7 @@ struct SettingsTimeZoneRow: View { /// Whether a store was asked for yet; before that the row says nothing. @State private var asked = false @State private var isPickerPresented = false - // Kept under Bots mode's key, so the choice made there stays. + // Kept under the Bots view's key, so the choice made there stays. @AppStorage("bighelp.simple-bots.automatic-time-zone") private var automatic = false @Environment(\.scenePhase) private var scenePhase @BighelpThemeReader private var theme diff --git a/Bighelp/Settings/SettingsView+Experience.swift b/Bighelp/Settings/SettingsView+Experience.swift deleted file mode 100644 index f024833c..00000000 --- a/Bighelp/Settings/SettingsView+Experience.swift +++ /dev/null @@ -1,148 +0,0 @@ -import SwiftUI - -/// Settings › Modes: the home a launch opens in (Bots, Chat or Code), Code mode's own switch, and -/// the switcher that puts the modes at the top of each home. The chat switcher is in Settings › Chat. -extension SettingsView { - @ViewBuilder - var experienceSection: some View { - Section { - HomeExperienceModeCards(selected: settings.homeMode) { mode in - withAnimation(.snappy(duration: BighelpTokens.stateDuration)) { - settings.selectHomeMode(mode) - } - } - .listRowInsets(EdgeInsets(top: BighelpTokens.space4, leading: 0, bottom: BighelpTokens.space8, trailing: 0)) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } header: { - Text("Home experience") - } - - Section { - // Code can stay on beside a Chat or Bots home: ☰ and the switcher reach it. - Toggle(isOn: Binding(get: { settings.codeModeEnabled }, set: { settings.setCodeMode($0) })) { - HStack(spacing: BighelpTokens.space12) { - BighelpIconTile(systemName: "chevron.left.forwardslash.chevron.right") - settingLabel(String(localized: "Code mode"), detail: String(localized: "Fire off coding chats against your projects.")) - } - .padding(.horizontal, BighelpMenuRowLayout.labelInset) - } - .bighelpMacSettingsRowInsets() - .accessibilityIdentifier("settings.code-mode") - - Toggle(isOn: $settings.unifiedModeToggleEnabled) { - HStack(spacing: BighelpTokens.space12) { - BighelpIconTile(systemName: "capsule.lefthalf.filled") - settingLabel(String(localized: "Header mode switcher"), - detail: String(localized: "Switch between Bots, Chat and Code from the top of each home.")) - } - .padding(.horizontal, BighelpMenuRowLayout.labelInset) - } - .bighelpMacSettingsRowInsets() - .accessibilityIdentifier("settings.unified-mode-toggle") - } - .listRowBackground(theme.surface) - } -} - -private struct HomeExperienceModeCards: View { - let selected: BighelpMode - let onSelect: (BighelpMode) -> Void - - @Environment(\.dynamicTypeSize) private var dynamicTypeSize - @Environment(\.colorSchemeContrast) private var contrast - @BighelpThemeReader private var theme - - var body: some View { - let layout = dynamicTypeSize.isAccessibilitySize - ? AnyLayout(VStackLayout(spacing: BighelpTokens.space8)) - : AnyLayout(HStackLayout(spacing: BighelpTokens.space8)) - - layout { - ForEach(BighelpMode.allCases) { mode in - card(mode) - } - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("settings.modes.picker") - } - - private func card(_ mode: BighelpMode) -> some View { - let isSelected = mode == selected - let shape = RoundedRectangle(cornerRadius: BighelpTokens.radius16, style: .continuous) - - return Button { - onSelect(mode) - } label: { - Group { - if dynamicTypeSize.isAccessibilitySize { - HStack(spacing: BighelpTokens.space12) { - iconWell(mode, isSelected: isSelected) - VStack(alignment: .leading, spacing: 2) { - titleText(mode) - detailText(mode, alignment: .leading) - } - Spacer(minLength: 0) - } - } else { - VStack(spacing: BighelpTokens.space8) { - iconWell(mode, isSelected: isSelected) - VStack(spacing: 3) { - titleText(mode) - detailText(mode, alignment: .center) - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) - } - } - .padding(.horizontal, BighelpTokens.space8) - .padding(.vertical, BighelpTokens.space12) - .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) - .background( - shape.fill(isSelected ? theme.action.opacity(theme.isDarkPalette ? 0.16 : 0.10) : theme.surface) - ) - .overlay { - shape.strokeBorder( - isSelected ? theme.action : (contrast == .increased ? theme.primaryText : theme.border), - lineWidth: isSelected ? 1.75 : BighelpTokens.hairline - ) - } - .contentShape(shape) - } - .bighelpPlainButtonStyle(.rounded(BighelpTokens.radius16)) - .accessibilityElement(children: .combine) - .accessibilityLabel(mode.title) - .accessibilityValue(mode.shortDetail) - .accessibilityAddTraits(isSelected ? .isSelected : []) - .accessibilityIdentifier("settings.mode.\(mode.rawValue)") - .driveTarget("settings.mode.\(mode.rawValue)") - } - - private func iconWell(_ mode: BighelpMode, isSelected: Bool) -> some View { - Image(systemName: mode.systemImage) - .font(.bighelp(.subheadline, weight: .semibold)) - .foregroundStyle(isSelected ? theme.actionForeground : theme.primaryText) - .frame(width: BighelpTokens.scaled(32), height: BighelpTokens.scaled(32)) - .background( - RoundedRectangle(cornerRadius: BighelpTokens.radius8 + 2, style: .continuous) - .fill(isSelected ? theme.action : theme.raisedSurface) - ) - .accessibilityHidden(true) - } - - private func titleText(_ mode: BighelpMode) -> some View { - Text(mode.title) - .font(.bighelp(.subheadline, weight: .bold)) - .foregroundStyle(theme.primaryText) - .lineLimit(1) - } - - private func detailText(_ mode: BighelpMode, alignment: TextAlignment) -> some View { - Text(mode.shortDetail) - .font(.bighelp(.caption2)) - .foregroundStyle(theme.secondaryText) - .multilineTextAlignment(alignment) - .lineLimit(dynamicTypeSize.isAccessibilitySize ? 3 : 2) - .fixedSize(horizontal: false, vertical: true) - } -} diff --git a/Bighelp/Settings/SettingsView+Menu.swift b/Bighelp/Settings/SettingsView+Menu.swift index f7e488d8..c09c7a82 100644 --- a/Bighelp/Settings/SettingsView+Menu.swift +++ b/Bighelp/Settings/SettingsView+Menu.swift @@ -106,7 +106,7 @@ extension SettingsView { func menuDetail(_ section: SettingsMenuSection) -> String? { switch section { case .appearance: appearanceSummary - case .modes: settings.modesSummary + case .voice: voiceDetail default: nil } diff --git a/Bighelp/Settings/SettingsView+NerdMode.swift b/Bighelp/Settings/SettingsView+NerdMode.swift index d4763db4..eb8fa7fc 100644 --- a/Bighelp/Settings/SettingsView+NerdMode.swift +++ b/Bighelp/Settings/SettingsView+NerdMode.swift @@ -121,7 +121,7 @@ extension SettingsView { extension View { /// A Settings row with an icon tile that runs an action. On the Mac it takes the click - /// across the row and lights up under the pointer, with the ☰ menu's row layout; + /// across the row and lights up under the pointer, with the sidebar's row layout; /// elsewhere it's a plain button with the page's row insets. func bighelpSettingsButton() -> some View { bighelpPlainButtonStyle(BighelpMenuRowLayout.outline, padding: BighelpMenuRowLayout.highlightPadding) @@ -148,14 +148,14 @@ extension View { bighelpPointer(BighelpMenuRowLayout.outline, padding: BighelpMenuRowLayout.highlightPadding) } - /// The row insets of a Settings row with an icon tile; on the Mac, the ☰ menu's. + /// The row insets of a Settings row with an icon tile; on the Mac, the sidebar's. func bighelpSettingsRowInsets() -> some View { listRowInsets(BighelpPlatform.isMac ? BighelpMenuRowLayout.insets : EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)) } - /// The ☰ menu's row insets on the Mac, so a toggle's or the profile row's icon lines up + /// The sidebar's row insets on the Mac, so a toggle's or the profile row's icon lines up /// with the other rows'. Elsewhere the row keeps the List's own: these labels set no /// height, and without the List's room their wrapped text touched the card's edges. @ViewBuilder diff --git a/Bighelp/Settings/SettingsView+Preferences.swift b/Bighelp/Settings/SettingsView+Preferences.swift index 6632be14..8e0f3d66 100644 --- a/Bighelp/Settings/SettingsView+Preferences.swift +++ b/Bighelp/Settings/SettingsView+Preferences.swift @@ -3,7 +3,7 @@ import UIKit extension SettingsView { /// Settings › Appearance: colors, light and dark, and the rest of the look on one page, with - /// Chat layout, App layout, Thinking and the companion pet a row each. + /// Chat layout, Thinking and the companion pet a row each. var appearancePage: some View { AppearanceStudioView(settings: settings) { settingsLink(to: .chatLayout) { @@ -14,14 +14,6 @@ extension SettingsView { .buttonStyle(.plain) .accessibilityIdentifier("settings.appearance.chat-layout") .driveTarget("settings.appearance.chat-layout") - settingsLink(to: .appLayout) { - AppearanceStudioRow(title: String(localized: "App layout"), - detail: String(localized: "Bottom bar and menu order"), - systemImage: "rectangle.bottomthird.inset.filled") - } - .buttonStyle(.plain) - .accessibilityIdentifier("settings.appearance.app-layout") - .driveTarget("settings.appearance.app-layout") settingsLink(to: .thinking) { AppearanceStudioRow(title: String(localized: "Thinking"), detail: String(localized: "The look of the Thinking control"), @@ -154,10 +146,7 @@ extension SettingsView { .listRowBackground(theme.surface) } - /// Code mode's swipe only while Code mode is on (or already picked, so the picker still shows it). - func swipeChoices(keeping current: WorkspaceSwipeAction) -> [WorkspaceSwipeAction] { - WorkspaceSwipeAction.allCases.filter { $0 != .codeMode || settings.codeModeEnabled || current == .codeMode } - } + /// A Mac has no screen edges to swipe from. @ViewBuilder @@ -165,7 +154,7 @@ extension SettingsView { #if !targetEnvironment(macCatalyst) Section { Picker("Swipe from left edge", selection: $settings.leftEdgeSwipeAction) { - ForEach(swipeChoices(keeping: settings.leftEdgeSwipeAction)) { action in + ForEach(WorkspaceSwipeAction.allCases) { action in Label(action.title, systemImage: action.systemImage).tag(action) } } @@ -173,7 +162,7 @@ extension SettingsView { .accessibilityIdentifier("settings.left-edge-swipe") Picker("Swipe from right edge", selection: $settings.rightEdgeSwipeAction) { - ForEach(swipeChoices(keeping: settings.rightEdgeSwipeAction)) { action in + ForEach(WorkspaceSwipeAction.allCases) { action in Label(action.title, systemImage: action.systemImage).tag(action) } } @@ -189,34 +178,32 @@ extension SettingsView { #endif } - /// Where bighelp opens when it starts and with which bot (`BighelpLanding`), and what a tap - /// on a bot opens. Each row's second line is its value: the choices' own names say what they do. + /// Where bighelp opens when it starts, which view the first tab shows when that's Today or Work, + /// and what a tap on a bot opens. Each row's second line is its value: the choices' names say what + /// they do. A pick applies at the next launch. private var opening: some View { - let screen = settings.landingScreen ?? .lastChat - let startAgentID = settings.startAgentID(scope: landingScope).flatMap { id in - agents.contains { $0.id == id } ? id : nil - } - return Section { - Picker(selection: Binding(get: { screen }, set: { settings.landingScreen = $0 })) { - ForEach(BighelpLandingScreen.allCases) { choice in + Section { + Picker(selection: $settings.homeLanding) { + ForEach(HomeLanding.allCases, id: \.self) { choice in Text(choice.title).tag(choice) } } label: { settingTitle(String(localized: "Opens on")) } .accessibilityIdentifier("settings.landing.screen") + .driveTarget("settings.landing.screen") - if screen.offersStartAgent, let scope = landingScope, !agents.isEmpty { - Picker(selection: Binding(get: { startAgentID }, - set: { settings.setStartAgentID($0, scope: scope) })) { - Text("Last bot used").tag(String?.none) - ForEach(agents) { agent in - Text(agent.name).tag(Optional(agent.id)) + // Bots and Chats name the view themselves. + if settings.homeLanding == .today || settings.homeLanding == .work { + Picker(selection: $settings.homeView) { + ForEach(HomeConversationsView.allCases, id: \.self) { view in + Text(view.title).tag(view) } } label: { - settingTitle(String(localized: "Start with")) + settingTitle(String(localized: "First tab shows")) } - .accessibilityIdentifier("settings.landing.agent") + .accessibilityIdentifier("settings.landing.view") + .driveTarget("settings.landing.view") } Picker(selection: $settings.botChatExperience) { @@ -289,8 +276,8 @@ extension SettingsView { .accessibilityIdentifier("settings.chat.return-sends") .driveTarget("settings.chat.return-sends") - // The Duo folded, and iPad and Mac in landscape: Bots and Code mode's chats have it. - if settings.simpleBotsEnabled || settings.codeModeEnabled, BighelpChatSwitcher.isOffered(screen: screen) { + // The Duo folded, and iPad and Mac in landscape. + if BighelpChatSwitcher.isOffered(screen: screen) { Toggle(isOn: $settings.chatSwitcherEnabled) { settingLabel(String(localized: "Chat switcher"), detail: String(localized: "Your bots beside each chat")) } diff --git a/Bighelp/Settings/SettingsView.swift b/Bighelp/Settings/SettingsView.swift index 6f3dc722..61ac989b 100644 --- a/Bighelp/Settings/SettingsView.swift +++ b/Bighelp/Settings/SettingsView.swift @@ -14,8 +14,7 @@ struct SettingsView: View { let onOpenScheduledTasks: () -> Void let onClearLocalCache: @MainActor () async -> Bool let agentDirectory: AgentDirectoryStore? - /// The computer Start with is kept for (`cacheScopeID`). - let landingScope: String? + let voiceSettingsScope: String? let voiceSettingsClient: (any VoiceSettingsClient)? let voiceSettingsIsCurrent: @MainActor () -> Bool @@ -51,13 +50,11 @@ struct SettingsView: View { var archivedChats: SettingsArchivedChats? /// Your computers › Time zone, for the computer in use; nil (or nil from it) has no row to change. var computerTimeZone: (@MainActor () -> SimpleBotHostSettings?)? - /// Show every computer outside Bots mode: the all-hosts view, which the shell turns on and off. - var onSetAllHosts: ((Bool) -> Void)? + @State var teamworkModel: TeamworkModel? /// The computer `teamworkModel` was made for (`cacheScopeID`). @State var teamworkScope: String? - /// Shows just this page (Fleet settings links Appearance and Chat here, so there's one copy of each). - private var openSection: SettingsMenuSection? + /// Shows just this pushed page (the Settings sheet's stack pushes `SettingsDestination` values). private var pushedPage: SettingsDestination? /// The Settings sheet's stack takes value links; the main stack, typed `[AppRoute]`, ignores @@ -129,7 +126,7 @@ struct SettingsView: View { registerNotificationDevice _: (@MainActor () async throws -> BighelpNotificationRuntimeSnapshot)? = nil, notificationIsCurrent: @escaping @MainActor () -> Bool = { false }, agentDirectory: AgentDirectoryStore? = nil, - landingScope: String? = nil, + onOpenWorkspaceDestination: ((WorkspaceDestination) -> Void)? = nil, onOpenRoute: ((AppRoute) -> Void)? = nil, connectorApps: (@MainActor () -> ConnectorAppsModel?)? = nil, @@ -141,8 +138,7 @@ struct SettingsView: View { usage: ProviderUsageStore? = nil, pendingShares: PendingShareReviewContext? = nil, archivedChats: SettingsArchivedChats? = nil, - computerTimeZone: (@MainActor () -> SimpleBotHostSettings?)? = nil, - onSetAllHosts: ((Bool) -> Void)? = nil + computerTimeZone: (@MainActor () -> SimpleBotHostSettings?)? = nil ) { self.onOpenWorkspaceDestination = onOpenWorkspaceDestination self.onOpenRoute = onOpenRoute @@ -156,7 +152,7 @@ struct SettingsView: View { self.pendingShares = pendingShares self.archivedChats = archivedChats self.computerTimeZone = computerTimeZone - self.onSetAllHosts = onSetAllHosts + _settings = Bindable(wrappedValue: settings) _userIdentity = Bindable(wrappedValue: userIdentity) _displayNameDraft = State(initialValue: userIdentity.identity.name) @@ -168,7 +164,7 @@ struct SettingsView: View { self.onOpenScheduledTasks = onOpenScheduledTasks self.onClearLocalCache = onClearLocalCache self.agentDirectory = agentDirectory - self.landingScope = landingScope + self.voiceSettingsScope = voiceSettingsScope self.voiceSettingsClient = voiceSettingsClient self.voiceSettingsIsCurrent = voiceSettingsIsCurrent @@ -182,20 +178,12 @@ struct SettingsView: View { var body: some View { Group { if let pushedPage { settingsDone(page(for: pushedPage)) } - else if let openSection { destination(for: openSection) } else { menuPage } } } - /// This settings page alone. - func opening(_ section: SettingsMenuSection) -> Self { - var page = self - page.openSection = section - return page - } - - /// This pushed page alone, for the Settings sheet's `navigationDestination`. Built in `body`, - /// like `opening(_:)`, so the page reads the theme live. + /// This pushed page alone, for the Settings sheet's `navigationDestination`. Built in `body`, so + /// the page reads the theme live. func showing(_ destination: SettingsDestination) -> Self { var page = self page.pushedPage = destination @@ -226,7 +214,7 @@ struct SettingsView: View { case .section(let section): self.destination(for: section) case .you: settingsPage(title: String(localized: "You")) { localIdentity } case .chatLayout: ChatLayoutSettingsView() - case .appLayout: AppLayoutSettingsView(settings: settings) + case .thinking: ThinkingLookSettingsView() case .apps: connectionsPage case .connection: connectionPage @@ -265,7 +253,7 @@ struct SettingsView: View { BighelpDeferredSection { yourBotsSection } BighelpDeferredSection { settingsMenuGroup(header: String(localized: "This app"), - sections: [.appearance, .chat, .notifications, .modes]) + sections: [.appearance, .chat, .notifications]) } #if os(visionOS) BighelpDeferredSection { SpatialAvatarSettingsSection(settings: settings) } @@ -274,7 +262,7 @@ struct SettingsView: View { BighelpDeferredSection { helpAndAdvancedSection } } .animation(.snappy(duration: BighelpTokens.transitionDuration), value: settings.nerdModeEnabled) - .animation(.snappy(duration: BighelpTokens.transitionDuration), value: settings.simpleBotsMultiGateway) + .animation(.snappy(duration: BighelpTokens.transitionDuration), value: settings.showsEveryComputer) .bighelpFormSurface() .listSectionSpacing(20) .environment(\.defaultMinListRowHeight, BighelpTokens.hitTarget) @@ -403,8 +391,7 @@ struct SettingsView: View { @ViewBuilder func destination(for section: SettingsMenuSection) -> some View { switch section { - case .modes: - settingsPage(title: section.title) { experienceSection } + case .chat: chatPage case .voice: diff --git a/Bighelp/Settings/VoiceSettingsView.swift b/Bighelp/Settings/VoiceSettingsView.swift index e99f0bba..12c3f563 100644 --- a/Bighelp/Settings/VoiceSettingsView.swift +++ b/Bighelp/Settings/VoiceSettingsView.swift @@ -72,7 +72,7 @@ struct VoiceSettingsView: View { private static let allAgents = "*" /// Everything on the page is for this agent, the same choices its Default Voice and voice bar - /// make in Bots mode. All bots, or no connection, edits the default for every agent. + /// make. All bots, or no connection, edits the default for every agent. private var editedAgentID: String? { computer != nil && agents.contains(where: { $0.id == agentID }) ? agentID : nil } diff --git a/Bighelp/Share/PendingShareCenter.swift b/Bighelp/Share/PendingShareCenter.swift index 17d9fbda..cdb7bbec 100644 --- a/Bighelp/Share/PendingShareCenter.swift +++ b/Bighelp/Share/PendingShareCenter.swift @@ -26,7 +26,7 @@ final class PendingShareCenter: ChatShareTracking { let inbox: PendingShareInbox? private(set) var entries: [PendingShareInbox.Entry] = [] - /// Every share waiting, put off ones too (☰ › Shared with bighelp, or Bots mode's Settings). + /// Every share waiting, put off ones too (Shared with bighelp, or Settings' first screen). var isListShown = false /// Put off with Not now, taken out of a chat's message box, or unconfirmed: in the list, and /// offered on their own again only when another share arrives. diff --git a/Bighelp/Share/PendingShareReview.swift b/Bighelp/Share/PendingShareReview.swift index 9b2be380..ea3e1699 100644 --- a/Bighelp/Share/PendingShareReview.swift +++ b/Bighelp/Share/PendingShareReview.swift @@ -15,7 +15,7 @@ struct PendingShareReviewContext { } /// Offers a share another app saved for bighelp each time bighelp comes to the front, so the person -/// picks the agent and chat it goes to, and shows every waiting share when asked (☰ › Shared with +/// picks the agent and chat it goes to, and shows every waiting share when asked (Shared with /// bighelp). It waits for whatever has to come first: the AI data agreement, first setup, adding a /// computer, Settings, or, for a review on its own, no computer at all. @MainActor @@ -101,8 +101,8 @@ struct PendingShareReview: ViewModifier { } } -/// Every share waiting, put off ones too: open one to send it, or delete it. Reached from ☰ › -/// Shared with bighelp, or Bots mode's Settings, while any wait. +/// Every share waiting, put off ones too: open one to send it, or delete it. Reached from +/// Shared with bighelp, or Settings' first screen, while any wait. struct PendingShareListView: View { let center: PendingShareCenter let context: PendingShareReviewContext diff --git a/Bighelp/Shortcuts/BighelpShortcutLinks.swift b/Bighelp/Shortcuts/BighelpShortcutLinks.swift index f87084c3..bfd50d5a 100644 --- a/Bighelp/Shortcuts/BighelpShortcutLinks.swift +++ b/Bighelp/Shortcuts/BighelpShortcutLinks.swift @@ -79,7 +79,7 @@ enum BighelpShortcutLinks { } } -/// The places "Open in bighelp" goes: the bottom bar's tabs and ☰'s rows. +/// The places "Open in bighelp" goes: the bar's three places and Work's doors. /// Group chats aren't here: they're listed on Agents, and Open group chat /// opens one directly. enum BighelpShortcutDestination: String, CaseIterable, Sendable { diff --git a/Bighelp/Shortcuts/BighelpShortcutService+Actions.swift b/Bighelp/Shortcuts/BighelpShortcutService+Actions.swift index 2ed90176..72b5a5b9 100644 --- a/Bighelp/Shortcuts/BighelpShortcutService+Actions.swift +++ b/Bighelp/Shortcuts/BighelpShortcutService+Actions.swift @@ -284,7 +284,7 @@ extension BighelpShortcutService { throw BighelpShortcutServiceError.workflowsUnavailable } let host = hostServices.hostID() - // Dev Factory's recipes run from Code mode, with their projects. + // Dev Factory's recipes run from Dev Factory, with their projects. let workflows = list.workflows.filter { !$0.isCodeRecipe } let pinnedFirst = workflows.filter(\.pinned) + workflows.filter { !$0.pinned } return pinnedFirst.prefix(Self.listLimit).map { diff --git a/Bighelp/SimpleBots/BotProfileDetails.swift b/Bighelp/SimpleBots/BotProfileDetails.swift new file mode 100644 index 00000000..c6f83a5e --- /dev/null +++ b/Bighelp/SimpleBots/BotProfileDetails.swift @@ -0,0 +1,280 @@ +import SwiftUI + +/// One of a bot's words the page edits in place: what Agent Studio's Identity section edited. +enum BotProfileAboutField: String, CaseIterable, Identifiable, Sendable { + case name, role, summary + + var id: String { rawValue } + + var title: String { + switch self { + case .name: String(localized: "Name") + case .role: String(localized: "Role") + case .summary: String(localized: "Summary") + } + } + + var prompt: String { + switch self { + case .name: String(localized: "Give your bot a name") + case .role: String(localized: "e.g. Travel planner") + case .summary: String(localized: "One line about what it does") + } + } + + var draftKey: WritableKeyPath { + switch self { + case .name: \.name + case .role: \.role + case .summary: \.summary + } + } + + /// The editor model's field, for its validation message. + var editorField: AgentEditorModel.Field { + switch self { + case .name: .name + case .role: .role + case .summary: .summary + } + } + + func value(in profile: AgentProfile) -> String { + switch self { + case .name: profile.name + case .role: profile.role + case .summary: profile.summary + } + } +} + +/// A row in Info's About group: its title, its second line and whether a tap edits it. +struct BotProfileAboutRow: Identifiable, Equatable, Sendable { + enum Kind: Hashable, Sendable { case field(BotProfileAboutField), handle } + + let kind: Kind + let title: String + /// The value, or why the computer won't take an edit. + let detail: String + let isEditable: Bool + + var id: Kind { kind } + + var identifier: String { + switch kind { + case .field(let field): "simple-bots.profile.about.\(field.rawValue)" + case .handle: "simple-bots.profile.about.handle" + } + } +} + +enum BotProfileAbout { + /// Name, Role, Summary and Handle. A field the computer won't let the app change shows the + /// reason as its second line; the handle is only ever read (Hermes suggests it from the name). + static func rows(name: String, role: String, summary: String, handle: String, + canEdit: Bool, unavailableReason: String?) -> [BotProfileAboutRow] { + let reason = unavailableReason ?? String(localized: "This computer doesn't let the app change this bot.") + let values: [BotProfileAboutField: String] = [.name: name, .role: role, .summary: summary] + let fields = BotProfileAboutField.allCases.map { field in + let value = values[field, default: ""].trimmingCharacters(in: .whitespacesAndNewlines) + return BotProfileAboutRow( + kind: .field(field), title: field.title, + detail: canEdit ? (value.isEmpty ? String(localized: "Not set") : value) : reason, + isEditable: canEdit) + } + return fields + [BotProfileAboutRow(kind: .handle, title: String(localized: "Handle"), + detail: "@\(handle)", isEditable: false)] + } +} + +/// One About field, edited on its own and saved through the same `AgentEditorModel` path (and +/// validation, and errors) as the editor it replaces. +@MainActor +struct BotProfileFieldEditor: View { + let field: BotProfileAboutField + let model: AgentEditorModel + + @State private var text: String + @State private var isSaving = false + @FocusState private var isFocused: Bool + @Environment(\.dismiss) private var dismiss + @BighelpThemeReader private var theme + + init(field: BotProfileAboutField, model: AgentEditorModel) { + self.field = field + self.model = model + _text = State(initialValue: model.draft[keyPath: field.draftKey]) + } + + private var original: String { model.editedProfile.map(field.value(in:)) ?? model.draft[keyPath: field.draftKey] } + + /// This field's message first; another field's (the model checks them all) or the save's after it. + private var errorMessage: String? { + model.fieldErrors[field.editorField] + ?? BotProfileAboutField.allCases.lazy.compactMap { model.fieldErrors[$0.editorField] }.first + ?? model.fieldErrors[.instructions] ?? model.saveError + } + + var body: some View { + NavigationStack { + VStack(alignment: .leading, spacing: BighelpTokens.space12) { + TextField(field.title, text: $text, prompt: Text(field.prompt).bighelpFieldHint(theme), + axis: field == .summary ? .vertical : .horizontal) + .lineLimit(field == .summary ? 1...4 : 1...1) + .font(.bighelp(.body)) + .focused($isFocused) + .submitLabel(.done) + .onSubmit { if field != .summary { save() } } + .padding(.horizontal, BighelpTokens.space16) + .frame(minHeight: BighelpTokens.hitTarget) + .padding(.vertical, BighelpTokens.space4) + .background(theme.surface, in: .rect(cornerRadius: BighelpTokens.radius20, style: .continuous)) + .accessibilityLabel(field.title) + .accessibilityIdentifier("simple-bots.profile.about.editor.\(field.rawValue)") + if let errorMessage { + Label(errorMessage, systemImage: "exclamationmark.triangle.fill") + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.danger) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("simple-bots.profile.about.editor.error") + } + Spacer(minLength: 0) + } + .padding(BighelpTokens.space16) + .background(theme.canvas.ignoresSafeArea()) + .disabled(isSaving) + // A swipe down never throws away an unsaved change. + .interactiveDismissDisabled(isSaving || text != original) + .navigationTitle(field.title) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + .accessibilityIdentifier("simple-bots.profile.about.editor.cancel") + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { save() } + .disabled(isSaving || text == original || model.hasUnconfirmedSave) + .accessibilityIdentifier("simple-bots.profile.about.editor.save") + } + } + .onAppear { isFocused = true } + } + } + + private func save() { + guard !isSaving, text != original else { return } + isSaving = true + model.draft[keyPath: field.draftKey] = text + Task { @MainActor in + defer { isSaving = false } + // The model keeps its own message for each failure; the sheet stays open to show it. + guard (try? await model.save()) != nil else { return } + dismiss() + } + } +} + +/// What the bot asked permission for and what the person decided, newest first: the old +/// profile sheet's Approvals tab, as a page of its own. +@MainActor +struct BotApprovalsPage: View { + let store: AgentBoardStore + let botName: String + @BighelpThemeReader private var theme + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: BighelpTokens.space12) { + content + } + .padding(.horizontal, BighelpTokens.space20) + .padding(.vertical, BighelpTokens.space16) + // As wide as the bot page it opens from. + .frame(maxWidth: 720) + .frame(maxWidth: .infinity) + } + .background(theme.canvas.ignoresSafeArea()) + .navigationTitle("Approvals") + .navigationBarTitleDisplayMode(.inline) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("simple-bots.profile.approvals.page") + } + + @ViewBuilder + private var content: some View { + if !store.approvals.isEmpty { + SimpleBotsCard { + ForEach(Array(store.approvals.enumerated()), id: \.element.id) { index, entry in + if index > 0 { SimpleBotsDivider() } + row(entry) + } + } + } else { + switch store.logState { + case .failed(let message): + SimpleBotsMessageCard(systemImage: "exclamationmark.triangle", title: message) + case .unavailable: + SimpleBotsMessageCard(systemImage: "wifi.slash", title: String(localized: "Your computer isn't connected")) + case .loaded: + SimpleBotsMessageCard(systemImage: "checkmark.shield", + title: String(localized: "No approvals yet"), + detail: String(localized: "What \(botName) asks to do shows up here.")) + case .idle, .loading: + // Still, never a spinner that loops. + SimpleBotsMessageCard(systemImage: "checkmark.shield", title: String(localized: "Loading…")) + } + } + } + + private func row(_ entry: AgentApprovalEntry) -> some View { + HStack(alignment: .top, spacing: BighelpTokens.space12) { + Image(systemName: entry.wasAllowed ? "checkmark.shield" : "xmark.shield") + .font(.bighelp(.body, weight: .semibold)) + .foregroundStyle(entry.wasAllowed ? theme.secondaryText : theme.danger) + .frame(width: 28) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 2) { + Text(entry.description.isEmpty ? entry.command : entry.description) + .font(.bighelp(.body)) + .foregroundStyle(theme.primaryText) + .fixedSize(horizontal: false, vertical: true) + if !entry.sessionTitle.isEmpty { + Text(entry.sessionTitle) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + } + Text("\(entry.decisionLabel) · \(entry.createdAt.formatted(.relative(presentation: .named)))") + .font(.bighelp(.footnote)) + .foregroundStyle(theme.tertiaryText) + } + Spacer(minLength: 0) + } + .padding(.horizontal, BighelpTokens.space20) + .padding(.vertical, BighelpTokens.space12) + .accessibilityElement(children: .combine) + } +} + +/// The page while its bot's computer isn't the one in use yet: still, with Back, and nothing read +/// from the computer in use, so a bot there with the same ID never shows in its place. +@MainActor +struct BotProfileOpeningView: View { + /// Nil when the computer has no name to show. + let computerName: String? + + var body: some View { + VStack { + SimpleBotsMessageCard(systemImage: "desktopcomputer", + title: computerName.map { String(localized: "Opening \($0)…") } + ?? String(localized: "Opening…")) + .padding(.horizontal, BighelpTokens.space20) + .padding(.top, BighelpTokens.space24) + .frame(maxWidth: 720) + Spacer() + } + .frame(maxWidth: .infinity) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("simple-bots.profile.opening") + } +} diff --git a/Bighelp/SimpleBots/BotProfileMoreMenu.swift b/Bighelp/SimpleBots/BotProfileMoreMenu.swift new file mode 100644 index 00000000..f88c2c97 --- /dev/null +++ b/Bighelp/SimpleBots/BotProfileMoreMenu.swift @@ -0,0 +1,130 @@ +import SwiftUI + +/// One entry in a bot page's ⋯ menu. +enum BotProfileAction: String, CaseIterable, Identifiable, Sendable { + case message, newChat, chats, makePrimary, pin, unpin, shortcuts, duplicate + case showRoutines + case manageBots + case delete + + var id: String { rawValue } + + /// Actions on the bot, then managing the computer's bots, then Delete, each after a divider. + enum Group: Int, Comparable, Sendable { + case bot, manage, delete + static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } + } + + var group: Group { + switch self { + case .manageBots: .manage + case .delete: .delete + default: .bot + } + } + + var title: String { + switch self { + case .message: String(localized: "Message") + case .newChat: String(localized: "New chat") + case .chats: String(localized: "Chats with this bot") + case .makePrimary: String(localized: "Make Primary Bot") + case .pin: String(localized: "Pin") + case .unpin: String(localized: "Unpin") + case .shortcuts: String(localized: "Use with Siri") + case .duplicate: String(localized: "Duplicate") + + case .showRoutines: String(localized: "Show routines") + case .manageBots: String(localized: "Manage bots") + case .delete: String(localized: "Delete bot") + } + } + + var systemImage: String { + switch self { + case .message: "message" + case .newChat: "square.and.pencil" + case .chats: "clock.arrow.circlepath" + case .makePrimary: "star" + case .pin: "pin" + case .unpin: "pin.slash" + case .shortcuts: "waveform" + case .duplicate: "plus.square.on.square" + + case .showRoutines: "calendar.badge.clock" + case .manageBots: "person.2.badge.gearshape" + case .delete: "trash" + } + } + + /// `simple-bots.profile.more.`; Show routines keeps the id it had. + var identifier: String { + self == .showRoutines ? "simple-bots.profile.show-routines" : "simple-bots.profile.more.\(rawValue)" + } +} + +/// What a bot page can offer right now, from its context and the bot's state. +struct BotProfileMenuCapabilities: Equatable, Sendable { + /// False while the page waits for the bot's computer to be the one in use: nothing on it can run yet. + var isOnComputerInUse = true + var isPrimary = false + var offersNewChat = false + var offersChats = false + var offersPinning = false + var isPinned = false + /// Room for one more pin; a bot past the limit offers no Pin. + var canPinAnother = true + var offersShortcuts = false + var offersDuplicate = false + + /// The Dashboard is the tab on screen, where routines show. + var showsRoutinesToggle = false + var offersManage = false + var offersDelete = false + /// Hermes never deletes its default bot (`AgentDeletionPresentation.canDelete`). + var isDefaultBot = false + var isDeleting = false +} + +enum BotProfileMenu { + /// The ⋯ menu's entries in order: actions on the bot, Manage bots, then Delete bot. + static func actions(_ can: BotProfileMenuCapabilities) -> [BotProfileAction] { + guard can.isOnComputerInUse else { return [] } + var actions: [BotProfileAction] = [.message] + if can.offersNewChat { actions.append(.newChat) } + if can.offersChats { actions.append(.chats) } + if !can.isPrimary { actions.append(.makePrimary) } + if can.offersPinning { + if can.isPinned { actions.append(.unpin) } else if can.canPinAnother { actions.append(.pin) } + } + if can.offersShortcuts { actions.append(.shortcuts) } + if can.offersDuplicate { actions.append(.duplicate) } + + if can.showsRoutinesToggle { actions.append(.showRoutines) } + if can.offersManage { actions.append(.manageBots) } + if can.offersDelete, !can.isDefaultBot, !can.isDeleting { actions.append(.delete) } + return actions + } +} + +/// The ⋯ menu's items, with a divider between groups. The same items serve the ⋯ button and, +/// on the Mac, a right-click on the bot's face and name. +struct BotProfileMoreMenuItems: View { + let actions: [BotProfileAction] + @Binding var showsRoutines: Bool + let perform: (BotProfileAction) -> Void + + var body: some View { + ForEach(Array(actions.enumerated()), id: \.element) { index, action in + if index > 0, actions[index - 1].group != action.group { Divider() } + if action == .showRoutines { + Toggle(action.title, systemImage: action.systemImage, isOn: $showsRoutines) + .accessibilityIdentifier(action.identifier) + } else { + Button(action.title, systemImage: action.systemImage, + role: action == .delete ? .destructive : nil) { perform(action) } + .accessibilityIdentifier(action.identifier) + } + } + } +} diff --git a/Bighelp/SimpleBots/SimpleBotMark.swift b/Bighelp/SimpleBots/SimpleBotMark.swift index fb0df888..12ed4f9e 100644 --- a/Bighelp/SimpleBots/SimpleBotMark.swift +++ b/Bighelp/SimpleBots/SimpleBotMark.swift @@ -2,7 +2,7 @@ import Observation import SwiftUI import UIKit -/// A bot's mark in Bots mode: one of thirteen solid shapes in one of +/// A bot's mark on the Bots view: one of thirteen solid shapes in one of /// eleven colors, with two white eyes. It's the bot's picture everywhere: the /// host keeps a rendering of it, so other screens, devices and Hermes Desktop /// show the same bot. @@ -379,7 +379,7 @@ final class SimpleBotMarkStore { } } -/// A bot's face in Bots mode, in `AgentFace`'s order: its character, pet, Hermes face or mark, +/// A bot's face on the Bots view, in `AgentFace`'s order: its character, pet, Hermes face or mark, /// else its picture, else its starting mark. While its Bot Chat works, the face acts the work out /// (a mark or character plays the mood for it, a Hermes face the designer's state, a pet its move); /// a photo, or any face that can't move, shows a still badge instead. Needing you always shows diff --git a/Bighelp/SimpleBots/SimpleBotProfileExtras.swift b/Bighelp/SimpleBots/SimpleBotProfileExtras.swift index 4e90b85d..9d400b84 100644 --- a/Bighelp/SimpleBots/SimpleBotProfileExtras.swift +++ b/Bighelp/SimpleBots/SimpleBotProfileExtras.swift @@ -3,7 +3,7 @@ import SwiftUI /// Saves what the full avatar studio made for a bot, at once: the picture on the host (what every /// screen, device and Hermes Desktop shows), and here the character or pet that chats draw over -/// it. The bot's mark goes, so Bots mode shows the new avatar. +/// it. The bot's mark goes, so the Bots view shows the new avatar. @MainActor enum SimpleBotAvatarSaving { enum Failure: Error { case render, photo } diff --git a/Bighelp/SimpleBots/SimpleBotProfileView.swift b/Bighelp/SimpleBots/SimpleBotProfileView.swift index 459d3e39..680f6abf 100644 --- a/Bighelp/SimpleBots/SimpleBotProfileView.swift +++ b/Bighelp/SimpleBots/SimpleBotProfileView.swift @@ -10,7 +10,7 @@ struct SimpleBotProfileContext { let canEdit: Bool let onOpenChat: (String) -> Void let onOpenRoutine: (ScheduledTask) -> Void - let onEditDetails: (AgentProfile) -> Void + /// The bot's default model and reasoning, where the computer lets the app read and change them. var makeModelDefaults: ((String) -> AgentRuntimeDefaultsEditorModel?)? = nil /// The bot's helper task models (Default Model › Advanced); nil where the computer can't list them. @@ -38,8 +38,41 @@ struct SimpleBotProfileContext { var makeMediaClient: (() -> (any AgentMediaClient)?)? = nil /// Nerd Mode shows hidden files (names starting with "."). var showsHiddenFiles = false - /// Feed, Ideas and Goals as piles (Dashboard); nil hides the tab. + /// Feed, Ideas and Goals as piles (Dashboard); nil hides the tab. Its shell board also reads + /// the bot's approvals for Info's Approvals row. var dashboard: SimpleBotDashboardHooks? = nil + /// Why the computer won't let the app edit this bot, shown on About's rows; nil uses a general reason. + var editUnavailableReason: String? = nil + /// The model About saves a field through, with the shell's check that the computer is still the + /// same; nil makes one with no check. A closure that returns nil opens nothing. + var makeEditor: ((AgentProfile) -> AgentEditorModel?)? = nil + /// The name of the bot's computer while it isn't the one in use yet (a door pushed the page before + /// the switch finished). The page then shows "Opening …" and reads nothing, so a bot with + /// the same ID on the computer in use never shows in its place. Nil once it's in use. + var openingComputer: String? = nil + /// ⋯ › New chat with the bot (its ID); nil hides it. + var onNewChat: ((String) -> Void)? = nil + /// ⋯ › Chats with this bot; nil hides it. + var onOpenChats: ((String) -> Void)? = nil + /// ⋯ › Pin and Unpin, by the rules of the screen the bot is pinned on; nil hides them. + var pinning: BotProfilePinning? = nil + /// ⋯ › Use with Siri: its Shortcuts, which need a computer that can run them. + var offersShortcuts = false + /// ⋯ › Duplicate: a copy of the bot made on its computer; nil where it can't clone. + var makeDuplicate: ((AgentProfile) -> AgentDuplicateModel?)? = nil + /// ⋯ › Manage bots: export, import and the computer's default, opened on this bot; nil hides it. + var onManageBots: ((String) -> Void)? = nil + /// ⋯ › Delete bot; nil where the computer can't delete bots. The page closes once its bot is gone. + var deletion: AgentDeletionAction? = nil +} + +/// Pinning from a bot page: the screen whose pins they are decides the limit. +@MainActor +struct BotProfilePinning { + let isPinned: (String) -> Bool + /// Room for this bot's pin. + let canPin: (String) -> Bool + let setPinned: (String, Bool) -> Void } /// What a bot's Dashboard needs from the shell. @@ -58,11 +91,12 @@ struct SimpleBotDashboardHooks { let onBlueprint: (String, String) -> Void } -/// A bot's profile in Bots mode: its mark, name and role over every tab, then Dashboard (its -/// Feed, Ideas and Goals as piles to swipe), Info (Character, instructions and routines), +/// A bot's page, from every door: its mark, name and role over every tab, then Dashboard (its +/// Feed, Ideas and Goals as piles to swipe), Info (About, Character, instructions and routines), /// Computer (its screen, when the host has one), Files (its folder on the computer) and Media /// (photos and videos from its chats). Holding a tab offers Set Default (the tab profiles open -/// on; Dashboard until one is set) and Rearrange, both the same for every bot. +/// on; Dashboard until one is set) and Rearrange, both the same for every bot. ⋯ holds what's +/// done to the bot itself (`BotProfileMenu`). @MainActor struct SimpleBotProfileView: View { let agentID: String @@ -116,6 +150,17 @@ struct SimpleBotProfileView: View { @State private var files: SimpleBotFilesModel? @State private var media = AgentMediaStore() @State private var isMediaConnected = false + /// About: the field being edited and the model it saves through. + @State private var aboutEditing: AboutEditing? + /// The bot's approvals, on the shell board's connection; read once Info shows. + @State private var approvals = AgentBoardStore() + @State private var approvalsClient: ObjectIdentifier? + @State private var isApprovalsPresented = false + @State private var isShortcutsPresented = false + @State private var duplicate: AgentDuplicateModel? + @State private var isDeleteConfirmationPresented = false + @State private var isDeleting = false + @State private var deleteError: String? @Environment(\.dismiss) private var dismiss @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.dynamicTypeSize) private var dynamicTypeSize @@ -139,13 +184,37 @@ struct SimpleBotProfileView: View { } var body: some View { - Group { + if let computer = context.openingComputer { + // Nothing below runs until the bot's computer is in use: every task and sheet starts then. + BotProfileOpeningView(computerName: computer) + .safeAreaInset(edge: .top, spacing: 0) { openingHeader } + .background(theme.canvas.ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + } else { + page + } + } + + private var openingHeader: some View { + HStack { + SimpleBotsCircleButton(systemImage: "chevron.left", label: "Back", identifier: "simple-bots.profile.back") { + dismiss() + } + Spacer() + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space8) + .background { SimpleBotsHeaderFade() } + } + + private var page: some View { + actionPresentations(Group { if let profile { content(profile) } else { ContentUnavailableView("This bot isn't here anymore", systemImage: "questionmark.circle") } - } + }) .safeAreaInset(edge: .top, spacing: 0) { header } .background(theme.canvas.ignoresSafeArea()) // Deleted, here or on another device: back to where it opened from. Only once the agent @@ -192,6 +261,24 @@ struct SimpleBotProfileView: View { guard shownTab == .info, let vault, vault.state == .loading else { return } await vault.load() } + .task(id: approvalsKey) { + // The row's count: read once Info shows, and again only on a new connection. + guard shownTab == .info, let hooks = context.dashboard else { return } + guard let connection = hooks.shellBoard.followableConnection else { + // The shell sets its board up in a root task, which waits while this page covers the + // root; as the Dashboard does, bring it to the connection of the moment. Its own task, + // so this one ending for the new connection never cuts it short. + let key = hooks.shellBoardKey() + await Task { await hooks.configureShellBoard(key) }.value + return + } + let client = ObjectIdentifier(connection.client) + guard approvalsClient != client || approvals.logState != .loaded else { return } + await approvals.connect(client: connection.client, scope: connection.scope) + await approvals.loadLogs(agentID: agentID) + guard !Task.isCancelled else { return } + approvalsClient = client + } .task(id: agentID) { if context.dashboard != nil, dashboard?.agentID != agentID { dashboard = BoardDashboardModel(agentID: agentID) @@ -400,17 +487,7 @@ struct SimpleBotProfileView: View { identifier: "simple-bots.profile.template") { isSavingTemplate = true } .driveTarget("simple-bots.profile.template") Menu { - Button("Message", systemImage: "message") { context.onOpenChat(profile.id) } - if !isPrimary { - Button("Make Primary Bot", systemImage: "star") { _ = context.agents.setPrimaryAgent(profile.id) } - } - if context.canEdit { - Button("Edit Name and Role", systemImage: "pencil") { context.onEditDetails(profile) } - } - if shownTab == .dashboard { - Toggle("Show routines", systemImage: "calendar.badge.clock", isOn: $showsRoutines) - .accessibilityIdentifier("simple-bots.profile.show-routines") - } + moreMenuItems(profile) } label: { Image(systemName: "ellipsis") .font(.bighelp(.title3, weight: .medium)) @@ -429,11 +506,130 @@ struct SimpleBotProfileView: View { .background { SimpleBotsHeaderFade() } } + private func moreMenuItems(_ profile: AgentProfile) -> some View { + BotProfileMoreMenuItems(actions: BotProfileMenu.actions(menuCapabilities(profile)), + showsRoutines: $showsRoutines) { perform($0, on: profile) } + } + + private func menuCapabilities(_ profile: AgentProfile) -> BotProfileMenuCapabilities { + BotProfileMenuCapabilities( + isOnComputerInUse: context.openingComputer == nil, + isPrimary: isPrimary, + offersNewChat: context.onNewChat != nil, + offersChats: context.onOpenChats != nil, + offersPinning: context.pinning != nil, + isPinned: context.pinning?.isPinned(profile.id) == true, + canPinAnother: context.pinning?.canPin(profile.id) == true, + offersShortcuts: context.offersShortcuts, + offersDuplicate: context.makeDuplicate != nil, + + showsRoutinesToggle: shownTab == .dashboard, + offersManage: context.onManageBots != nil, + offersDelete: context.deletion != nil, + isDefaultBot: !AgentDeletionPresentation.canDelete(profile), + isDeleting: isDeleting) + } + + private func perform(_ action: BotProfileAction, on profile: AgentProfile) { + let id = profile.id + switch action { + case .message: context.onOpenChat(id) + case .newChat: context.onNewChat?(id) + case .chats: context.onOpenChats?(id) + case .makePrimary: _ = context.agents.setPrimaryAgent(id) + case .pin, .unpin: context.pinning?.setPinned(id, action == .pin) + case .shortcuts: isShortcutsPresented = true + case .duplicate: duplicate = context.makeDuplicate?(profile) + + case .showRoutines: showsRoutines.toggle() + case .manageBots: context.onManageBots?(id) + case .delete: isDeleteConfirmationPresented = true + } + } + + /// What ⋯ and About open: an About field's editor, Use with Siri, Duplicate, the Approvals page + /// and Delete bot's confirmation, progress and error. Kept apart from `page`'s own modifiers, + /// which are already as many as the type checker takes in one expression. + private func actionPresentations(_ content: some View) -> some View { + content + .bighelpSheet(item: $aboutEditing) { editing in + BotProfileFieldEditor(field: editing.field, model: editing.model) + .presentationDetents([.medium, .large]) + .presentationDragIndicator(.visible) + .bighelpSheetSize(.compact) + } + .bighelpSheet(isPresented: $isShortcutsPresented) { + if let profile { + AgentShortcutsView(agent: profile) + .bighelpSheetSize(.standard) + } + } + .bighelpSheet(item: $duplicate) { model in + AgentDuplicateView(model: model) { + duplicate = nil + let agents = context.agents + Task { await agents.loadReportingErrors() } + } + .bighelpSheetSize(.standard) + } + .navigationDestination(isPresented: $isApprovalsPresented) { + BotApprovalsPage(store: approvals, botName: profile?.name ?? "") + .toolbar(.visible, for: .navigationBar) + } + .confirmationDialog(profile.map(AgentDeletionPresentation.title) ?? "", + isPresented: $isDeleteConfirmationPresented, + titleVisibility: .visible, presenting: profile) { profile in + Button("Delete bot", role: .destructive) { delete(profile) } + .accessibilityIdentifier("simple-bots.profile.delete.confirm") + } message: { profile in + // Says what goes from the computer, at the control, every time. + Text(AgentDeletionPresentation.message(profile)) + } + .alert("Couldn't delete this bot", isPresented: Binding(get: { deleteError != nil }, + set: { if !$0 { deleteError = nil } })) { + Button("OK") { deleteError = nil } + } message: { Text(deleteError ?? "") } + .overlay(alignment: .bottom) { + if isDeleting, let profile { + // Still: the computer takes up to ten seconds, and nothing here needs to move meanwhile. + Text(AgentDeletionPresentation.progress(profile)) + .font(.bighelp(.subheadline, weight: .medium)) + .foregroundStyle(theme.primaryText) + .padding(.horizontal, BighelpTokens.space20) + .frame(minHeight: BighelpTokens.hitTarget) + .bighelpNavigationGlass(in: Capsule()) + .padding(.bottom, BighelpTokens.space24) + .accessibilityIdentifier("simple-bots.profile.deleting") + } + } + } + + /// After the confirmation. On success the shell closes the page (`closeScreens(ofDeletedAgent:)`), + /// and the page closes itself once its bot leaves the list anyway. + private func delete(_ profile: AgentProfile) { + guard let deletion = context.deletion, !isDeleting else { return } + isDeleting = true + Task { @MainActor in + defer { isDeleting = false } + do { + try await deletion.run(profile.id) + } catch { + deleteError = AgentDeletionPresentation.errorMessage(error) + } + } + } + private func content(_ profile: AgentProfile) -> some View { ScrollView { VStack(spacing: BighelpTokens.space24) { - face(profile) - identityCard(profile) + VStack(spacing: BighelpTokens.space24) { + face(profile) + identityCard(profile) + } + #if targetEnvironment(macCatalyst) + // The Mac's way to ⋯: a right-click on the bot's face or name. + .contextMenu { moreMenuItems(profile) } + #endif tabBar Group { switch shownTab { @@ -741,27 +937,99 @@ struct SimpleBotProfileView: View { : String(localized: "This computer doesn't let the app change this bot.")) } - /// Info: Personality, Defaults and What it can use, then Routines and, last, Advanced Options. - /// A group shows only the rows this computer offers, and none of a group that has none. + /// Info: About, Personality, Defaults and What it can use, then Routines and, last, Advanced + /// Options. A group shows only the rows this computer offers, and none of a group that has none. private func info(_ profile: AgentProfile) -> some View { VStack(alignment: .leading, spacing: BighelpTokens.space12) { + about(profile) infoGroup(String(localized: "Personality"), [.character, .instructions, .coreFiles], profile: profile) infoGroup(String(localized: "Defaults"), [.defaultModel, .defaultVoice, .activeProject], profile: profile) - infoGroup(String(localized: "What it can use"), [.connections, .marketplace, .credentialVault, .photoActions], - profile: profile) + infoGroup(String(localized: "What it can use"), + [.connections, .marketplace, .credentialVault, .photoActions, .approvals], profile: profile) routines(profile) infoGroup(nil, [.advancedOptions], profile: profile) } } + /// Name, Role, Summary and Handle, each with its value as its second line. A tap edits that one + /// field in a small sheet; a computer that won't take edits says why instead. + private func about(_ profile: AgentProfile) -> some View { + let rows = BotProfileAbout.rows( + name: profile.name, role: profile.role, summary: profile.summary, + handle: AgentHandle.unique(base: profile.name, excluding: profile.id, profiles: context.agents.profiles), + canEdit: context.canEdit, unavailableReason: context.editUnavailableReason) + return VStack(alignment: .leading, spacing: BighelpTokens.space12) { + SimpleBotsSectionLabel(title: String(localized: "About")) + SimpleBotsCard { + ForEach(Array(rows.enumerated()), id: \.element.id) { index, row in + if index > 0 { SimpleBotsDivider() } + aboutRow(row, profile: profile) + } + } + } + } + + @ViewBuilder + private func aboutRow(_ row: BotProfileAboutRow, profile: AgentProfile) -> some View { + if case .field(let field) = row.kind { + Button { editAbout(field, of: profile) } label: { + SimpleBotsRow(title: row.title, detail: row.detail) { + if row.isEditable { SimpleBotsDisclosure() } + } + } + .buttonStyle(.plain) + .disabled(!row.isEditable) + .driveTarget(row.identifier) + .accessibilityIdentifier(row.identifier) + } else { + SimpleBotsRow(title: row.title, detail: row.detail) { EmptyView() } + .accessibilityElement(children: .combine) + .accessibilityIdentifier(row.identifier) + } + } + + private func editAbout(_ field: BotProfileAboutField, of profile: AgentProfile) { + let model: AgentEditorModel? + if let makeEditor = context.makeEditor { + model = makeEditor(profile) + } else { + model = AgentEditorModel.editing(profile, store: context.agents, processor: AvatarImageProcessor()) + } + guard let model else { return } + aboutEditing = AboutEditing(field: field, model: model) + } + + private struct AboutEditing: Identifiable { + let field: BotProfileAboutField + let model: AgentEditorModel + var id: ObjectIdentifier { ObjectIdentifier(model) } + } + + /// Info's Approvals load again for a new connection, never for each look at the tab. + private struct ApprovalsKey: Hashable { + let isInfo: Bool + let client: ObjectIdentifier? + } + + private var approvalsKey: ApprovalsKey { + ApprovalsKey(isInfo: shownTab == .info, + client: context.dashboard?.shellBoard.followableConnection.map { ObjectIdentifier($0.client) }) + } + + /// How many approvals the bot has asked for, once read. + private var approvalsCount: String? { + approvals.logState == .loaded && approvalsClient != nil ? approvals.approvals.count.formatted() : nil + } + private enum InfoRow: Hashable { case character, instructions, coreFiles, defaultModel, defaultVoice, activeProject - case connections, marketplace, credentialVault, photoActions, advancedOptions + case connections, marketplace, credentialVault, photoActions, approvals, advancedOptions } private func offers(_ row: InfoRow) -> Bool { switch row { case .character, .instructions, .photoActions: true + case .approvals: context.dashboard != nil case .coreFiles: context.makeCoreFiles != nil case .defaultModel: modelDefaults != nil case .defaultVoice: voice != nil @@ -892,6 +1160,14 @@ struct SimpleBotProfileView: View { .disabled(!context.canEdit) .driveTarget("simple-bots.profile.photo-actions") .accessibilityIdentifier("simple-bots.profile.photo-actions") + case .approvals: + Button { isApprovalsPresented = true } label: { + SimpleBotsRow(title: String(localized: "Approvals"), leading: Image(systemName: "checkmark.shield"), + value: approvalsCount) + } + .buttonStyle(.plain) + .driveTarget("simple-bots.profile.approvals") + .accessibilityIdentifier("simple-bots.profile.approvals") case .advancedOptions: Button { isAdvancedPresented = true } label: { SimpleBotsRow(title: String(localized: "Advanced Options"), @@ -984,8 +1260,7 @@ struct SimpleBotProfileView: View { } } - /// The bot's board as the Feed, Ideas and Goals pages take it. Bots mode has no menu or agent - /// switcher, so those do nothing; the chat is always this bot's own. + /// The bot's board as the Feed, Ideas and Goals pages take it. The chat is always this bot's own. private func boardContext(_ profile: AgentProfile, hooks: SimpleBotDashboardHooks, store: AgentBoardStore) -> AgentBoardContext { let id = profile.id @@ -994,7 +1269,7 @@ struct SimpleBotProfileView: View { activity: .idle, store: store, onProfile: {}, onSwitchAgent: {}, onAsk: { hooks.onAsk(id, $0) }, onSend: { hooks.onSend(id, $0) }, onBlueprint: { hooks.onBlueprint(id, $0) }, - onMenu: {}, onNewChat: { context.onOpenChat(id) }, onPickAgents: {}, tools: []) + onNewChat: { context.onOpenChat(id) }) } private func mediaTab(_ profile: AgentProfile) -> some View { diff --git a/Bighelp/SimpleBots/SimpleBotVoiceBar.swift b/Bighelp/SimpleBots/SimpleBotVoiceBar.swift deleted file mode 100644 index e89b3048..00000000 --- a/Bighelp/SimpleBots/SimpleBotVoiceBar.swift +++ /dev/null @@ -1,296 +0,0 @@ -import SwiftUI - -/// Voice in Bots mode: a bar over the chat, so the chat stays in view and in use. The bot's face, -/// a visualizer from real audio levels (your voice in the page's ink, the bot's in its color, dots while -/// nobody speaks), the voice choices, the microphone, and End. -@MainActor -struct SimpleBotVoiceBar: View { - let presentation: VoicePresentation - let agentID: String - let agentName: String - let imageURL: URL? - let permissionCenter: PermissionCenter - let onSwitchMode: (VoiceConversationMode) -> Void - let onEnded: () -> Void - - @State private var levels = Array(repeating: 0.0, count: SimpleBotVoiceVisualizer.barCount) - @State private var speaker = SimpleBotVoiceVisualizer.Speaker.nobody - @Environment(\.companionAgentScope) private var scope - @AppStorage("loopdy.settings.nerd-mode") private var nerdMode = false - @AppStorage(LiveVoiceDebug.showsCopyKey) private var showsCopyReport = false - @BighelpThemeReader private var theme - - var body: some View { - VStack(spacing: BighelpTokens.space8) { - HStack(spacing: BighelpTokens.space12) { - SimpleBotFace(agentID: agentID, name: agentName, imageURL: imageURL, size: 44, blinks: true) - SimpleBotVoiceVisualizer(levels: levels, speaker: speaker, agentColor: agentColor) - .frame(maxWidth: .infinity, maxHeight: 40) - .accessibilityElement() - .accessibilityLabel(speaker == .agent ? "\(agentName) is speaking" - : speaker == .person ? "Listening to you" : "Voice is on") - .accessibilityIdentifier("simple-bots.voice.visualizer") - choicesMenu - microphoneButton - endButton - } - if let statusLine { - Text(statusLine) - .bighelpFont(.metadata) - .foregroundStyle(theme.secondaryText) - .lineLimit(2) - .frame(maxWidth: .infinity, alignment: .leading) - .accessibilityIdentifier("simple-bots.voice.status") - } - Capsule().fill(theme.tertiaryText.opacity(0.5)).frame(width: 36, height: 4) - .accessibilityHidden(true) - } - .padding(.leading, BighelpTokens.space16) - .padding(.trailing, BighelpTokens.space12) - .padding(.top, BighelpTokens.space12) - .padding(.bottom, BighelpTokens.space8) - .bighelpNavigationGlass(in: Capsule(), isInteractive: false) - .padding(.horizontal, BighelpTokens.space12) - .modifier(SimpleBotVoiceTurnLifecycle(model: presentation.liveModel == nil ? presentation.model : nil, - permissionCenter: permissionCenter)) - .task { presentation.liveModel?.start() } - .task { await sampleLevels() } - .onDisappear { - presentation.liveModel?.end() - presentation.model.stopMonitoring() - } - .accessibilityElement(children: .contain) - .accessibilityIdentifier("simple-bots.voice") - } - - private var isLive: Bool { presentation.liveModel != nil } - - /// What the call is doing, so a call that doesn't connect or ends never looks like one that works: - /// the step while it connects, an error, else the newest words from either side. - private var statusLine: String? { - guard let live = presentation.liveModel else { - return presentation.conversationMode == .codexLive - ? String(localized: "Live couldn't start in this chat, so this chat takes turns.") : nil - } - if let error = live.errorMessage ?? live.cleanupMessage { return error } - guard live.phase == .live else { return live.phase.title } - let words = live.assistantCaption.isEmpty ? live.userCaption : live.assistantCaption - return words.isEmpty ? nil : String(words.suffix(160)) - } - - private var agentColor: Color { - let mark = SimpleBotMarkStore.shared.mark(scope: scope, agentID: agentID) - return (mark ?? (imageURL == nil ? .defaultMark(for: agentID) : nil))?.color.color ?? theme.action - } - - private var isMicrophoneMuted: Bool { - presentation.liveModel?.isMuted ?? presentation.model.isMicrophoneMuted - } - - private var isAgentMuted: Bool { - presentation.liveModel?.isSpeakerMuted ?? presentation.model.isAgentAudioMuted - } - - private var choicesMenu: some View { - Menu { - // The bot's own voice type, as its Default Voice sets it; the same names as there. - Picker("Voice type", selection: Binding( - get: { presentation.conversationMode }, - set: { mode in if mode != presentation.conversationMode { onSwitchMode(mode) } })) { - Text(VoiceConversationMode.codexLive.title).tag(VoiceConversationMode.codexLive) - Text(VoiceConversationMode.turnBased.title).tag(VoiceConversationMode.turnBased) - } - Button(isAgentMuted ? "Unmute \(agentName)" : "Mute \(agentName)", - systemImage: isAgentMuted ? "speaker.wave.2" : "speaker.slash") { - if let live = presentation.liveModel { live.setSpeakerMuted(!live.isSpeakerMuted) } - else { presentation.model.toggleAgentAudio() } - } - // Settings › Voice › Debug's Copy report button: where the call's sound goes on this device. - if LiveVoiceDebug.parts(nerdMode: nerdMode, showsCopy: showsCopyReport).copy, - let live = presentation.liveModel, live.keepsAudioReport { - Button("Copy call audio report", systemImage: "doc.on.doc") { - UIPasteboard.general.string = live.audioReport() - } - } - } label: { - circle("gearshape", tint: theme.primaryText) - } - .menuStyle(.button) - .buttonStyle(.plain) - .accessibilityLabel("Voice choices") - .accessibilityIdentifier("simple-bots.voice.choices") - } - - @ViewBuilder - private var microphoneButton: some View { - let model = presentation.model - if !isLive, model.mode == .walkieTalkie { - // Walkie-talkie: tap to talk, tap again to send. - Button { - if model.isWalkieTalkieCapturing { - _ = model.endWalkieTalkieCapture(submit: true) - } else if let generation = model.armWalkieTalkieCapture() { - Task { _ = await model.startArmedWalkieTalkieCapture(generation: generation) } - } - } label: { - circle(model.isWalkieTalkieCapturing ? "waveform" : "mic", tint: theme.primaryText) - } - .buttonStyle(.plain) - .accessibilityLabel(model.isWalkieTalkieCapturing ? "Send what you said" : "Talk") - .accessibilityIdentifier("simple-bots.voice.microphone") - } else { - Button { - if let live = presentation.liveModel { live.setMuted(!live.isMuted) } else { model.toggleMicrophone() } - } label: { - circle(isMicrophoneMuted ? "mic.slash" : "mic", tint: theme.primaryText) - } - .buttonStyle(.plain) - .accessibilityLabel(isMicrophoneMuted ? "Unmute microphone" : "Mute microphone") - .accessibilityIdentifier("simple-bots.voice.microphone") - } - } - - private var endButton: some View { - Button { - if let live = presentation.liveModel { - live.end() - onEnded() - } else { - Task { if await presentation.model.end() { onEnded() } } - } - } label: { - Image(systemName: "xmark") - .font(.system(size: 17, weight: .semibold)) - .foregroundStyle(.white) - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - .background(Circle().fill(theme.danger)) - .contentShape(.circle) - } - .buttonStyle(.plain) - .accessibilityLabel("End voice") - .accessibilityIdentifier("simple-bots.voice.end") - } - - private func circle(_ systemImage: String, tint: Color) -> some View { - Image(systemName: systemImage) - .font(.system(size: 17, weight: .medium)) - .foregroundStyle(tint) - .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) - .background(Circle().fill(theme.incomingMessageBackground)) - .contentShape(.circle) - } - - /// Several readings a second of the real levels: the microphone's and the voice playing back. - private func sampleLevels() async { - while !Task.isCancelled { - let input: Double - let output: Double - if let live = presentation.liveModel { - await live.refreshLevels() - input = live.isMuted ? 0 : live.inputLevel - output = live.outputLevel - } else { - input = presentation.model.isMicrophoneMuted ? 0 : Double(presentation.model.inputLevel) - output = presentation.model.outputLevel - } - let next = SimpleBotVoiceVisualizer.next(levels: levels, input: input, output: output) - levels = next.levels - speaker = next.speaker - try? await Task.sleep(for: .milliseconds(120)) - } - } -} - -/// Bars from the newest levels (oldest on the left), or a row of dots while nobody speaks. -struct SimpleBotVoiceVisualizer: View { - enum Speaker: Equatable { case nobody, person, agent } - static let barCount = 26 - /// Below this, a reading is room noise, not speech. - static let quiet = 0.04 - - let levels: [Double] - let speaker: Speaker - let agentColor: Color - @BighelpThemeReader private var theme - - /// The levels after one more reading: who's speaking, and their loudness, slightly boosted so quiet - /// speech still shows. - static func next(levels: [Double], input: Double, output: Double) -> (levels: [Double], speaker: Speaker) { - let speaker: Speaker = max(input, output) < quiet ? .nobody : output >= input ? .agent : .person - let level = speaker == .nobody ? 0 : min(1, sqrt(max(input, output)) * 1.2) - return (Array((levels + [level]).suffix(barCount)), speaker) - } - - var body: some View { - let color = speaker == .person ? theme.primaryText : agentColor - GeometryReader { proxy in - let step = proxy.size.width / CGFloat(Self.barCount) - HStack(alignment: .center, spacing: 0) { - ForEach(Array(levels.enumerated()), id: \.offset) { _, level in - Group { - if speaker == .nobody || level < Self.quiet { - Circle().fill(color.opacity(0.45)).frame(width: 4, height: 4) - } else { - Capsule().fill(color) - .frame(width: max(3, step * 0.45), height: max(6, proxy.size.height * level)) - } - } - .frame(width: step, height: proxy.size.height) - } - } - .animation(.easeOut(duration: 0.12), value: levels) - } - } -} - -/// What turn-based voice needs while it's on screen, as its full-screen view does it: microphone and -/// speech permission, and listening only while the app is in front and the microphone is on. -private struct SimpleBotVoiceTurnLifecycle: ViewModifier { - let model: VoiceModel? - let permissionCenter: PermissionCenter - @State private var isVisible = false - @Environment(\.scenePhase) private var scenePhase - @Environment(\.accessibilityReduceMotion) private var reduceMotion - - func body(content: Content) -> some View { - content - .onAppear { - guard let model else { return } - isVisible = true - model.setReduceMotion(reduceMotion) - reconcile(model) - } - .task { - guard let model else { return } - guard await permissionCenter.authorizeContextualAccess(.microphone), - await permissionCenter.authorizeContextualAccess(.speech) || model.transcription == .hermes - else { model.stopMonitoring(); return } - reconcile(model) - } - .onDisappear { - isVisible = false - model?.setMonitoringAllowed(false) - model?.cancelWalkieTalkieCapture() - model?.stopMonitoring() - } - .onChange(of: scenePhase) { _, phase in - guard let model else { return } - if phase != .active { model.cancelWalkieTalkieCapture() } - reconcile(model) - } - .onChange(of: model?.status) { _, _ in if let model { reconcile(model) } } - .onChange(of: model?.isMicrophoneMuted) { _, _ in if let model { reconcile(model) } } - } - - private func reconcile(_ model: VoiceModel) { - let authorized = permissionCenter.status(for: .microphone).authorization == .authorized - && (model.transcription == .hermes || permissionCenter.status(for: .speech).authorization == .authorized) - let allowed = isVisible && scenePhase == .active && authorized - model.setMonitoringAllowed(allowed) - guard allowed, model.isActive, !model.isMicrophoneMuted, model.allowsInputMonitoring else { - model.stopMonitoring() - return - } - Task { await model.startMonitoring() } - } -} diff --git a/Bighelp/SimpleBots/SimpleBotsChatOpening.swift b/Bighelp/SimpleBots/SimpleBotsChatOpening.swift index 978e4ea9..833e6470 100644 --- a/Bighelp/SimpleBots/SimpleBotsChatOpening.swift +++ b/Bighelp/SimpleBots/SimpleBotsChatOpening.swift @@ -1,7 +1,7 @@ import Foundation import Observation -/// Bots mode: a bot's chat can take a few seconds to open when the computer has to find or +/// The Bots view: a bot's chat can take a few seconds to open when the computer has to find or /// resume its Bot Chat and read its history first. After a short grace, so a quick open never /// flashes it, the opening loader covers the wait until the chat can show its messages, or fails /// with its own error. Cancel goes back to where the tap came from. @@ -30,7 +30,7 @@ final class SimpleBotsChatOpening { private(set) var current: Opening? private(set) var isShowing = false - /// Set while Multi-gateway's loader hands over to this one, so the home never shows between them. + /// Set while Show every computer's loader hands over to this one, so the home never shows between them. @ObservationIgnored var showsNextAtOnce = false @ObservationIgnored private var graceTask: Task? @ObservationIgnored private let grace: Duration diff --git a/Bighelp/SimpleBots/SimpleBotsHomeSections.swift b/Bighelp/SimpleBots/SimpleBotsHomeSections.swift index 52bcdc6f..47df4bc5 100644 --- a/Bighelp/SimpleBots/SimpleBotsHomeSections.swift +++ b/Bighelp/SimpleBots/SimpleBotsHomeSections.swift @@ -1,6 +1,6 @@ import SwiftUI -/// What Bots mode's + offers, in this order, each only where it can work: nothing is gray. +/// What the Bots view's + offers, in this order, each only where it can work: nothing is gray. enum SimpleBotsNewItem: String, Identifiable, CaseIterable { case bot, groupChat = "group", section @@ -63,7 +63,7 @@ extension SimpleBotsContext { : Dictionary(fleet.hosts.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first })) } - /// The gateway in use's bots and group chats (hidden ones too), as one-gateway Bots mode lists them. + /// The gateway in use's bots and group chats (hidden ones too), as the Bots view lists them with one computer shown. var oneGatewayBots: [SimpleBotsBot] { agents.profiles.map { SimpleBotsBot($0, imageURL: agents.avatarURL(for: $0)) } } @@ -74,7 +74,7 @@ extension SimpleBotsContext { } } -// Sections and group chats on Bots mode's home, and a section's own page. +// Sections and group chats on the Bots view, and a section's own page. extension SimpleBotsHomeView { // MARK: Sections @@ -402,12 +402,12 @@ struct SimpleBotsGroupPreview: View { .padding(BighelpTokens.space20) } .frame(width: 320, alignment: .leading) - // A preview is drawn outside the app's own colors; the system's match Bots mode. + // A preview is drawn outside the app's own colors; the system's match the Bots view. .background(Color(uiColor: .systemBackground)) } } -/// Delete Group Chat asks first, in the words the Agents screen uses. +/// Delete Group Chat asks first. struct SimpleBotsGroupDeletion: ViewModifier { @Binding var group: SimpleBotsGroup? let delete: ((String) -> Void)? @@ -427,46 +427,3 @@ struct SimpleBotsGroupDeletion: ViewModifier { } } } - -/// Chat mode's Agents screen: the gateway in use's sections, as Bots mode's home shows them. A card -/// opens the same section page. Nothing shows while there are no sections. -struct SimpleBotsSectionsArea: View { - let context: SimpleBotsContext - @State private var prompt: SimpleBotsSectionPrompt? - private let unread = SimpleBotsUnreadStore.shared - private let order = SimpleBotsOrderStore.shared - - var body: some View { - let host = context.fleet?.selectedHostID - let home = SimpleBotsHomeProjection.home( - profiles: context.agents.profiles, primaryID: context.agents.primaryAgentID, - pinnedIDs: context.agents.pinnedAgentIDs, - summaries: context.catalog.recentSummaries(includeCronSessions: false), - order: order.order(scope: context.scope), picture: { context.agents.avatarURL(for: $0) }, - groupHost: host, rooms: context.rooms, - sectioning: SimpleBotsSectioning(fleet: context.fleet, shown: Set([host].compactMap { $0 }))) - if !home.sections.isEmpty { - SimpleBotsSectionGrid(cards: home.sections, isUnread: isUnread, open: { context.onOpenSection?($0.id) }, - prompt: { prompt = $0 }) - .modifier(SimpleBotsSectionPrompts( - prompt: $prompt, - model: context.sectionsModel(bots: context.oneGatewayBots, groups: context.oneGatewayGroups))) - } - } - - /// Hermes' read state where its rows carry one (a bot's Bot Chat, a group chat's row), else this device's mark. - private func isUnread(_ card: SimpleBotsSectionCard) -> Bool { - card.members.contains { item in - switch item.kind { - case .bot(let bot): - if let chat = SimpleBotsReadState.botChat(bot.profileID, in: context.catalog.records) { - return chat.isUnread == true - } - return unread.isUnread(bot.profileID, scope: context.scope) - case .group(let group): - if let summary = group.summary, summary.tracksUnread { return summary.isUnread } - return unread.isUnread(group.summary?.id ?? SimpleBotsGroup.catalogID(group.roomID), scope: context.scope) - } - } - } -} diff --git a/Bighelp/SimpleBots/SimpleBotsHomeView.swift b/Bighelp/SimpleBots/SimpleBotsHomeView.swift index f7fba148..f68c00d1 100644 --- a/Bighelp/SimpleBots/SimpleBotsHomeView.swift +++ b/Bighelp/SimpleBots/SimpleBotsHomeView.swift @@ -1,7 +1,7 @@ import Observation import SwiftUI -/// What Bots mode's home needs from the shell. +/// What the Bots view needs from the shell. @MainActor struct SimpleBotsContext { let agents: AgentDirectoryStore @@ -18,13 +18,15 @@ struct SimpleBotsContext { let onNewChat: (String) -> Void /// A model for a new bot, set up the way the shell creates agents; nil when this computer can't. let makeCreator: () -> AgentEditorModel? - /// Multi-gateway: every other gateway's bots too; nil when it's off. + /// Every computer shown: every other gateway's bots too; nil when it's off. var gateways: SimpleBotsGateways? = nil /// Which bots are working or need you, kept current while the home shows. var activity: BotChatActivityStore? = nil var activitySource: BotChatActivitySource? = nil - /// The Header mode switcher (Settings › Modes); nil while it's off. - var modeSwitch: BighelpModeSwitch? = nil + /// The first tab's Bots | Chats switch; nil on a page that isn't the home (a section). + var viewSwitch: HomeViewSwitch? = nil + /// Opens or closes the sidebar, where there is one (iPad at regular width, Mac, Vision Pro). + var onToggleSidebar: (() -> Void)? = nil /// The sections, and group chats' pins and hides (`FleetStore`); nil leaves sections out. var fleet: FleetStore? = nil /// New Group Chat on the gateway in use; nil when it can't make group chats. @@ -40,7 +42,7 @@ struct SimpleBotsContext { var onOpenGroup: ((String) -> Void)? = nil } -/// Bots mode's Multi-gateway: every gateway's bots in one home, the gateway in use's live and the +/// Show every computer: every gateway's bots in one home, the gateway in use's live and the /// others' from the copies the all-hosts view keeps (those gateways stay connected meanwhile). Opening or /// managing a bot on another gateway makes that gateway the one in use first. @MainActor @@ -63,13 +65,13 @@ struct SimpleBotsGateways { var groups: [SimpleBotsGroup] = [] } -/// A bot on the home: on the gateway in use (with its live profile) or, with Multi-gateway, on another +/// A bot on the home: on the gateway in use (with its live profile) or, with every computer shown, on another /// gateway (with the all-hosts copy of it). struct SimpleBotsBot: Identifiable, Equatable { - /// The profile ID with one gateway; the gateway and profile (`FleetID`) with Multi-gateway. + /// The profile ID with one gateway; the gateway and profile (`FleetID`) with every computer shown. let id: String let profileID: String - /// Multi-gateway: the gateway it's on. + /// Every computer shown: the gateway it's on. var hostID: UUID? = nil let name: String let role: String @@ -105,7 +107,7 @@ struct SimpleBotsBot: Identifiable, Equatable { placement = profile?.placement ?? fleetAgent?.placement } - /// A bot on the gateway in use; `hostID` with Multi-gateway. + /// A bot on the gateway in use; `hostID` with every computer shown. init(_ profile: AgentProfile, hostID: UUID? = nil, imageURL: URL? = nil) { self.init(id: hostID.map { FleetID.make($0, profile.id) } ?? profile.id, profileID: profile.id, hostID: hostID, name: profile.name, role: profile.role, imageURL: imageURL, isDefault: profile.isDefault, @@ -203,7 +205,7 @@ enum SimpleBotsHomeProjection { /// The gateway in use's group chats, with their members' faces: the catalog's (with their latest /// message), then Hermes' rooms with no messages yet, so a group chat just made shows at once. - /// `listsByKey`: Multi-gateway, where each row is named by its gateway too. + /// `listsByKey`: every computer shown, where each row is named by its gateway too. static func groups(_ summaries: [SessionSummary], rooms: [HermesBotModeRoomSummary] = [], hostID: UUID?, bots: [SimpleBotsBot], listsByKey: Bool = false) -> [SimpleBotsGroup] { let listed = summaries.compactMap { summary in @@ -329,7 +331,7 @@ enum SimpleBotsHomeProjection { /// Whether `id` can join the pinned bots. Only pins the home shows count: the /// primary bot (pinned as the default agent), hidden bots and bots this - /// computer no longer has share the Agents screen's list but take no room here. + /// computer no longer has share the bot directory's list but take no room here. static func canPin(_ id: String, profiles: [AgentProfile], primaryID: String?, pinnedIDs: [String], pinnedGroups: Int = 0) -> Bool { let bots = profiles.map { SimpleBotsBot($0) } @@ -375,7 +377,7 @@ enum SimpleBotsHomeProjection { } } -/// The order the person dragged Bots mode's list into, per computer. +/// The order the person dragged the Bots view's list into, per computer. @MainActor @Observable final class SimpleBotsOrderStore { @@ -445,7 +447,7 @@ private enum SimpleBotsSheet: Identifiable { } } -/// Bots mode's home: your circle top left, search and + top right, the +/// The Bots view: your circle top left, search and + top right, the /// primary bot large in the middle, then the sections and every other bot and /// group chat with its latest message. With `sectionID`, a section's page: its /// members, as the home lists them. @@ -514,11 +516,11 @@ struct SimpleBotsHomeView: View { return id } - /// The order is one across gateways with Multi-gateway on, and per gateway without it. + /// The order is one across gateways with every computer shown, and per gateway without it. var listScope: String { context.gateways == nil ? context.scope : "multi-gateway" } var topScope: String { "top|" + listScope } - // MARK: Acting on a bot (on another gateway with Multi-gateway) + // MARK: Acting on a bot (on another gateway with every computer shown) private func unreadKey(_ bot: SimpleBotsBot) -> (id: String, scope: String) { context.gateways == nil ? (bot.profileID, context.scope) : (bot.id, "multi-gateway") @@ -600,7 +602,7 @@ struct SimpleBotsHomeView: View { .frame(maxWidth: .infinity) } .scrollBounceBehavior(.basedOnSize) - // Multi-gateway: the other gateways' bots are read again here (at most once a minute). + // Every computer shown: the other gateways' bots are read again here (at most once a minute). .task(id: context.gateways != nil) { context.gateways?.refresh() } .refreshable { if let gateways = context.gateways { gateways.refresh() } } } else { @@ -659,27 +661,22 @@ struct SimpleBotsHomeView: View { .background { SimpleBotsHeaderFade() } } - @ViewBuilder + /// You, the Bots | Chats switch and New on one row; Search (and the computer filter, to its + /// right) on the row under it, so the switch keeps the middle to itself. private var homeHeader: some View { - if let modeSwitch = context.modeSwitch { - modeHeader(modeSwitch) - } else { - classicHeader - } - } - - /// With the Header mode switcher: you, the mode pill and New on one row; Search (and Filter by - /// Gateway, to its right) on the row under it, so the pill keeps the middle to itself. - private func modeHeader(_ modeSwitch: BighelpModeSwitch) -> some View { VStack(spacing: BighelpTokens.space12) { ZStack { - HStack { + HStack(spacing: BighelpTokens.space8) { + if let onToggleSidebar = context.onToggleSidebar { + SimpleBotsCircleButton(systemImage: "sidebar.leading", label: "Sidebar", + identifier: "home.sidebar-toggle", action: onToggleSidebar) + } SimpleBotsPersonButton(name: context.personName, imageURL: context.personImageURL, action: context.onOpenSettings) Spacer() newButton } - BighelpModePill(modeSwitch: modeSwitch) + if let viewSwitch = context.viewSwitch { HomeViewSwitchPill(viewSwitch: viewSwitch) } } HStack(spacing: BighelpTokens.space8) { Button { sheet = .search } label: { @@ -703,28 +700,12 @@ struct SimpleBotsHomeView: View { } } } - .padding(.horizontal, BighelpTokens.space20) - .padding(.top, BighelpTokens.space4) - .padding(.bottom, BighelpTokens.space8) - .background { SimpleBotsHeaderFade() } - } - - private var classicHeader: some View { - HStack(spacing: BighelpTokens.space8) { - SimpleBotsPersonButton(name: context.personName, imageURL: context.personImageURL, - action: context.onOpenSettings) - Spacer() - if let gateways = context.gateways?.filter { - gatewayFilterButton(gateways) - } - SimpleBotsCircleButton(systemImage: "magnifyingglass", label: "Search bots", - identifier: "simple-bots.search") { sheet = .search } - newButton - } - .padding(.horizontal, BighelpTokens.space20) - .padding(.top, BighelpTokens.space4) + // Placed as `HomeHeaderBar` places Chats', Today's and Work's, so nothing moves when the + // switch or the bar changes the root. + .padding(HeaderButtonMetrics.slop) + .bighelpHeaderButtonsPlacement() .padding(.bottom, BighelpTokens.space8) - .background { SimpleBotsHeaderFade() } + .background { HomeHeaderBackground() } } /// New Bot, New Group Chat and New Section; each only where it can work. @@ -859,7 +840,7 @@ struct SimpleBotsHomeView: View { .accessibilityLabel(isPrimary ? "\(bot.name), your primary bot" : "\(bot.name), pinned") .modifier(SimpleBotActivityValue(key: bot.activityKey, activity: context.activity)) .accessibilityHint("Opens its chat") - .accessibilityIdentifier(isPrimary ? "simple-bots.primary" : "simple-bots.pinned.\(bot.id)") + .accessibilityIdentifier("simple-bots.\(isPrimary ? "primary" : "pinned").\(bot.id)") } private func canPin(_ bot: SimpleBotsBot, home: SimpleBotsHomeProjection.Home) -> Bool { @@ -935,7 +916,7 @@ struct SimpleBotsHomeView: View { SimpleBotLiveFace(bot: bot, size: size, activity: context.activity) } - /// With Multi-gateway each action works on the bot's own gateway. + /// With every computer shown each action works on the bot's own gateway. @ViewBuilder private func botMenu(_ bot: SimpleBotsBot, isPrimary: Bool, home: SimpleBotsHomeProjection.Home) -> some View { let actions = SimpleBotsMenuAction.bot(isPrimary: isPrimary, isPinned: isPinned(bot), canPin: canPin(bot, home: home), @@ -1078,7 +1059,7 @@ struct SimpleBotsHomeView: View { }) .arrangeLift(key, dragging: dragging, offset: dragOffset(key), space: Self.arrangeSpace) { frames[key] = $0 } .accessibilityElement(children: .combine) - .accessibilityIdentifier(isPrimary ? "simple-bots.primary" : "simple-bots.pinned.\(item.id)") + .accessibilityIdentifier("simple-bots.\(isPrimary ? "primary" : "pinned").\(item.id)") .accessibilityHint("Drag to change its place") .accessibilityAction(named: "Move left") { step(item.id, by: -1, in: ids, top: true) } .accessibilityAction(named: "Move right") { step(item.id, by: 1, in: ids, top: true) } @@ -1324,7 +1305,7 @@ private struct SimpleBotsPreview: View { .padding(BighelpTokens.space20) } .frame(width: 320, alignment: .leading) - // A preview is drawn outside the app's own colors; the system's match Bots mode. + // A preview is drawn outside the app's own colors; the system's match the Bots view. .background(Color(uiColor: .systemBackground)) } } diff --git a/Bighelp/SimpleBots/SimpleBotsOpeningOverlay.swift b/Bighelp/SimpleBots/SimpleBotsOpeningOverlay.swift index e25ffd7b..0b079a5e 100644 --- a/Bighelp/SimpleBots/SimpleBotsOpeningOverlay.swift +++ b/Bighelp/SimpleBots/SimpleBotsOpeningOverlay.swift @@ -1,6 +1,6 @@ import SwiftUI -/// Over Bots mode while a bot's chat opens: the bighelp loader, what's opening (and on which +/// Over the Bots view while a bot's chat opens: the bighelp loader, what's opening (and on which /// gateway, when it's another one), and Cancel. struct SimpleBotsOpeningOverlay: View { let botName: String? diff --git a/Bighelp/SimpleBots/SimpleBotsReadState.swift b/Bighelp/SimpleBots/SimpleBotsReadState.swift index 0e65d17c..87ddf3d7 100644 --- a/Bighelp/SimpleBots/SimpleBotsReadState.swift +++ b/Bighelp/SimpleBots/SimpleBotsReadState.swift @@ -1,6 +1,6 @@ import Foundation -/// Bots mode's unread dots (#862). On a computer that keeps read state, a bot shows its Bot Chat's, +/// The Bots view's unread dots (#862). On a computer that keeps read state, a bot shows its Bot Chat's, /// a group chat its own, and Mark Read and Mark Unread go to Hermes, so every client agrees. The /// marks kept on this device (`SimpleBotsUnreadStore`) stand in where Hermes has none: a computer /// without read state, another gateway's bots, group chats that aren't Hermes chats. diff --git a/Bighelp/SimpleBots/SimpleBotsSearchView.swift b/Bighelp/SimpleBots/SimpleBotsSearchView.swift index ef8f23e7..9a7fc5ef 100644 --- a/Bighelp/SimpleBots/SimpleBotsSearchView.swift +++ b/Bighelp/SimpleBots/SimpleBotsSearchView.swift @@ -1,6 +1,6 @@ import SwiftUI -/// Search in Bots mode: every bot by name or what it's for. The filter +/// Search on the Bots view: every bot by name or what it's for. The filter /// shows hidden bots and group chats too, so a hidden one can come back, and /// leads to Edit Sections. @MainActor diff --git a/Bighelp/SimpleBots/SimpleBotsSectionSheets.swift b/Bighelp/SimpleBots/SimpleBotsSectionSheets.swift index 1564fe1c..ba81890e 100644 --- a/Bighelp/SimpleBots/SimpleBotsSectionSheets.swift +++ b/Bighelp/SimpleBots/SimpleBotsSectionSheets.swift @@ -1,7 +1,7 @@ import SwiftUI /// New Section, or a section's Edit Members: its name, and every bot and group chat to pick, by -/// computer with Multi-gateway. A bot is in one section at a time, so picking one from another +/// computer with every computer shown. A bot is in one section at a time, so picking one from another /// section moves it here. struct SimpleBotsSectionMembersSheet: View { let model: SimpleBotsSectionsModel @@ -27,7 +27,7 @@ struct SimpleBotsSectionMembersSheet: View { let items: [SimpleBotsItem] } - /// One list, or one per computer (the gateway in use first) with Multi-gateway. + /// One list, or one per computer (the gateway in use first) with every computer shown. private var computers: [Computer] { guard let hostNames = model.hostNames else { return [Computer(id: "all", title: nil, items: model.candidates)] diff --git a/Bighelp/SimpleBots/SimpleBotsSectionViews.swift b/Bighelp/SimpleBots/SimpleBotsSectionViews.swift index 4e5c828a..52d58ce2 100644 --- a/Bighelp/SimpleBots/SimpleBotsSectionViews.swift +++ b/Bighelp/SimpleBots/SimpleBotsSectionViews.swift @@ -200,7 +200,7 @@ struct SimpleBotsSectionsModel { let editor: SimpleBotsSectionEditor /// Bots and group chats that can go in a section here (not hidden), in the home's order. let candidates: [SimpleBotsItem] - /// Multi-gateway: each computer's name, so the members sheet lists them by computer. + /// Every computer shown: each computer's name, so the members sheet lists them by computer. var hostNames: [UUID: String]? = nil var sections: [FleetSection] { editor.fleet.sections } diff --git a/Bighelp/SimpleBots/SimpleBotsSections.swift b/Bighelp/SimpleBots/SimpleBotsSections.swift index c1b45084..141837f5 100644 --- a/Bighelp/SimpleBots/SimpleBotsSections.swift +++ b/Bighelp/SimpleBots/SimpleBotsSections.swift @@ -1,9 +1,9 @@ import Foundation -/// A group chat on Bots mode's home: on the gateway in use (its catalog row, which opens it) or, with -/// Multi-gateway, on another gateway (the all-hosts copy of it). +/// A group chat on the Bots view: on the gateway in use (its catalog row, which opens it) or, with +/// every computer shown, on another gateway (the all-hosts copy of it). struct SimpleBotsGroup: Identifiable, Equatable { - /// Its row's ID in the home's order: the catalog row's with one gateway, `FleetGroup.id` with Multi-gateway. + /// Its row's ID in the home's order: the catalog row's with one gateway, `FleetGroup.id` with every computer shown. let id: String let roomID: String /// The gateway it's on. Its section, pin and hide are kept by it (`key`); nil when that isn't known. @@ -24,7 +24,7 @@ struct SimpleBotsGroup: Identifiable, Equatable { var key: String? { hostID.map { FleetID.make($0, "group/" + roomID) } } var itemID: String { "group:" + id } - /// A catalog row on the gateway in use. `listsByKey` (Multi-gateway) names the row by its gateway too. + /// A catalog row on the gateway in use. `listsByKey` (every computer shown) names the row by its gateway too. init?(_ summary: SessionSummary, hostID: UUID?, members: [SimpleBotsBot], listsByKey: Bool = false) { guard summary.kind == .botMode else { return nil } let room = summary.hostedRoomID ?? summary.id @@ -172,7 +172,7 @@ struct SimpleBotsSectionCard: Identifiable, Equatable { var botCount: Int { members.count(where: { if case .bot = $0.kind { true } else { false } }) } var groupCount: Int { members.count - botCount } - /// The gateways its members are on, in the order they first show; more than one only with Multi-gateway. + /// The gateways its members are on, in the order they first show; more than one only with every computer shown. var hostIDs: [UUID] { var seen = Set() return members.compactMap { item -> UUID? in @@ -198,7 +198,7 @@ struct SimpleBotsSectionCard: Identifiable, Equatable { } } -/// Bots mode's sections, changed from the home, a section's page or the sheets: bots' sections are +/// The Bots view's sections, changed from the home, a section's page or the sheets: bots' sections are /// saved on each bot's own computer (its live profile on the gateway in use, its all-hosts copy on /// another), group chats' in the app (`FleetStore`). Members go by their row IDs (`SimpleBotsItem.id`). @MainActor @@ -283,7 +283,7 @@ struct SimpleBotsSectionEditor { } } -/// A touch-and-hold action on Bots mode's home, in the order its menu shows them. +/// A touch-and-hold action on the Bots view, in the order its menu shows them. enum SimpleBotsMenuAction: Hashable { case newChat, pin, unpin, rearrange, moveToSection, markRead, markUnread, botProfile, groupSettings /// A divider comes before these. @@ -322,7 +322,7 @@ enum SimpleBotsMenuAction: Hashable { #if DEBUG /// `-test-bot-sections`: demo mode's sections, for UI tests and screenshots. Home life holds Jordan /// and the Household team (`-preview-agent-groups`) on Home Hermes; Work holds Mina on Home Hermes -/// and Sage and the Launch crew on Studio Mac, so with Multi-gateway off it shows only Mina. +/// and Sage and the Launch crew on Studio Mac, so with one computer shown it shows only Mina. enum SimpleBotsDemoSections { static let argument = "-test-bot-sections" static var isOn: Bool { ProcessInfo.processInfo.arguments.contains(argument) } diff --git a/Bighelp/SimpleBots/SimpleBotsStyle.swift b/Bighelp/SimpleBots/SimpleBotsStyle.swift index 91e54610..a1f1204a 100644 --- a/Bighelp/SimpleBots/SimpleBotsStyle.swift +++ b/Bighelp/SimpleBots/SimpleBotsStyle.swift @@ -1,6 +1,6 @@ import SwiftUI -/// Bots mode's building blocks: round glass buttons, gray rounded cards +/// The Bots view's building blocks: round glass buttons, gray rounded cards /// with full-width rows, and quiet section labels, all in the system font. struct SimpleBotsCircleButton: View { let systemImage: String diff --git a/Bighelp/SimpleBots/SimpleBotsSwitcher.swift b/Bighelp/SimpleBots/SimpleBotsSwitcher.swift index f5d58265..8dc23738 100644 --- a/Bighelp/SimpleBots/SimpleBotsSwitcher.swift +++ b/Bighelp/SimpleBots/SimpleBotsSwitcher.swift @@ -1,6 +1,6 @@ import SwiftUI -/// Bots mode's switcher beside a chat (`BighelpChatSwitcher`): the bots on top of the home, in the +/// The Bots view's switcher beside a chat (`BighelpChatSwitcher`): the bots on top of the home, in the /// order the person arranged them, each face showing what its Bot Chat is doing. struct SimpleBotsSwitcher: View { let context: SimpleBotsContext @@ -15,7 +15,7 @@ struct SimpleBotsSwitcher: View { .botChatActivityUpdates(context.activity, source: context.activitySource, isActive: scenePhase == .active) } - /// The primary and pinned bots, as the home's top shows them (every gateway's with Multi-gateway), + /// The primary and pinned bots, as the home's top shows them (every gateway's with every computer shown), /// then the bots under them in the home's order, six in all. static func top(_ context: SimpleBotsContext) -> [SimpleBotsBot] { let home = home(context) diff --git a/Bighelp/Spaces/BighelpAppSpaces.swift b/Bighelp/Spaces/BighelpAppSpaces.swift new file mode 100644 index 00000000..43280255 --- /dev/null +++ b/Bighelp/Spaces/BighelpAppSpaces.swift @@ -0,0 +1,71 @@ +import SwiftUI + +extension BighelpApp { + /// Where Today's spaces come from (`SpacesHost`): every computer, the one in use first. The one + /// in use and the others Show every computer keeps connected are read live; the + /// rest show what the phone kept, by their saved cache scope. Demo mode's computer is + /// `DemoSpacesClient`, with its pages in `DemoHTMLAppsClient`. + static func wireSpaces(registry: BighelpHostRegistry, connections: WorkspaceConnectionStore, fleet: FleetStore, + nativeWorkspaces: NativeWorkspaceSelectionStore, demoHosts: DemoHosts, + demoAgents: AgentDirectoryStore, usesDemoWorkspace: Bool) { + let others = RegistryFleetReader(registry: registry) + let usesDemo: @MainActor () -> Bool = { usesDemoWorkspace && !connections.isDirectSelected } + SpacesHost.current = { + if usesDemo() { + let scope = (try? WorkspaceAuthority.fixture(id: demoHosts.selectedHostID ?? "demo"))?.cacheScopeID ?? "demo" + let name = demoHosts.hosts.first { $0.id == demoHosts.selectedHostID }?.name ?? "Demo" + return SpacesComputer(hostKey: "demo", scope: scope, name: name, + api: SpacesAPI(client: DemoSpacesClient.shared), + bots: demoAgents.profiles.map { SpacesBot(id: $0.id, name: $0.name) }, + isCurrent: true) + } + guard let owner = connections.owner, let hostID = registry.selectedHostID else { return nil } + // The bots come from the runtime of this same computer. During a switch or a reconnect + // the runtime may still be the last one's: then no bots are known and nothing is read. + let runtime = nativeWorkspaces.current + let bots: [SpacesBot] = runtime?.authority.cacheScopeID == owner.cacheScopeID + ? runtime?.agents.profiles.map { SpacesBot(id: $0.id, name: $0.name) } ?? [] : [] + return SpacesComputer(hostKey: hostID.uuidString, scope: owner.cacheScopeID, + name: registry.hosts.first { $0.id == hostID }?.name ?? "", + api: SpacesAPI(client: DirectHermesSpacesClient(workspace: { connections.workspace })), + bots: bots, isCurrent: true) + } + // A computer's spaces go only when the computer itself leaves the registry (or the sign-in + // behind it changes), never for a gap in the list below. + SpacesHost.hostKeys = { usesDemo() ? ["demo"] : Set(registry.hosts.map { $0.id.uuidString }) } + SpacesHost.computers = { + if usesDemo() { return SpacesHost.current().map { [$0] } ?? [] } + var list: [SpacesComputer] = [] + for host in registry.hosts { + if host.id == registry.selectedHostID, let current = SpacesHost.current() { + list.insert(current, at: 0) + continue + } + let workspace = others.connectedPluginWorkspace(host.id) + // A computer that isn't connected shows what the phone kept, by its saved scope. + guard let scope = workspace?.owner?.cacheScopeID + ?? registry.workspace(for: host).savedConnection?.workspaceAuthority?.cacheScopeID else { continue } + let api = workspace.map { workspace in + SpacesAPI(client: DirectHermesSpacesClient(workspace: { workspace })) + } + list.append(SpacesComputer(hostKey: host.id.uuidString, scope: scope, name: host.name, api: api, + bots: (fleet.snapshots[host.id]?.agents ?? []) + .map { SpacesBot(id: $0.profileID, name: $0.name) }, + isCurrent: false)) + } + return list + } + SpacesHost.pages = { scope in + if usesDemo() { return HTMLAppsAPI(client: DemoHTMLAppsClient.shared) } + if connections.owner?.cacheScopeID == scope { + return HTMLAppsAPI(client: DirectHermesHTMLAppsClient(workspace: { connections.workspace })) + } + for host in registry.hosts where host.id != registry.selectedHostID { + guard let workspace = others.connectedPluginWorkspace(host.id), + workspace.owner?.cacheScopeID == scope else { continue } + return HTMLAppsAPI(client: DirectHermesHTMLAppsClient(workspace: { workspace })) + } + return nil + } + } +} diff --git a/Bighelp/Spaces/DemoSpacesClient.swift b/Bighelp/Spaces/DemoSpacesClient.swift new file mode 100644 index 00000000..e7a66055 --- /dev/null +++ b/Bighelp/Spaces/DemoSpacesClient.swift @@ -0,0 +1,515 @@ +import Foundation + +/// Demo mode's computer: three live spaces and one draft on the demo bots, answering the way the +/// plugin does (docs/SPACES.md › Routes), so UI tests and the demo need no host. Add needs the +/// draft's revision, a repeated `operationId` gets the first answer only for the same request (and +/// `invalid_request` for another), Update now is held to the plugin's minimum gap and runs nothing +/// for a paused AI routine, and a deleted space is gone. Made-up data only. +@MainActor +final class DemoSpacesClient: SpacesClient { + static let shared = DemoSpacesClient() + + nonisolated static let commuteID = "s_c0e1a7e0c0e1a7e0c0e1a7e0c0e1a7e0" + nonisolated static let gardenID = "s_6a7d6a7d6a7d6a7d6a7d6a7d6a7d6a7d" + nonisolated static let workoutsID = "s_b0d1b0d1b0d1b0d1b0d1b0d1b0d1b0d1" + /// A draft in the finance bot's chat, waiting for Add to Today. + nonisolated static let spendingDraftID = "s_5e9d5e9d5e9d5e9d5e9d5e9d5e9d5e9d" + /// Their pages, served by `DemoHTMLAppsClient`. + nonisolated static let commutePageID = "a_c0e2c0e2c0e2c0e2c0e2c0e2c0e2c0e2" + nonisolated static let gardenPageID = "a_6a7e6a7e6a7e6a7e6a7e6a7e6a7e6a7e" + nonisolated static let workoutsPageID = "a_b0d2b0d2b0d2b0d2b0d2b0d2b0d2b0d2" + nonisolated static let spendingPageID = "a_5e9e5e9e5e9e5e9e5e9e5e9e5e9e5e9e" + /// The demo computer's bots (`AppFixtureClients`). + nonisolated static let agentIDs: Set = ["travel", "home", "finance"] + + private struct Record { + let agentID: String + let spaceID: String + var state: SpaceState + var title: String + var description: String + var size: SpaceSize + var hidden: Bool + var position: Double + var revision: Int + let pageID: String + let usesAI: Bool + let updates: String + let cadenceMinutes: Int + var routineState: SpaceRoutineState + var problem: String? + var updatedAt: Date + var checkedAt: Date? + var lastRefresh: Date? + /// Deleted while Hermes still had its task: off Today, never run, gone for every route but delete. + var isDeleting = false + let cards: @MainActor (Date) -> (card: [String: BighelpJSONValue], sizes: [String: BighelpJSONValue]) + } + + private struct Outcome { + /// The operation and its body, without the `operationId`. + let request: String + let answer: Result<[String: BighelpJSONValue], WorkspaceClientError> + } + + private var records: [String: Record] = [:] + /// Answers by `operationId`, refusals too: the same request again gets the first answer and + /// changes nothing. A 503 isn't kept, so the same request tries again. + private var operations: [String: Outcome] = [:] + private let clock: @MainActor () -> Date + /// Every call, for tests. + private(set) var calls: [(operation: SpacesOperation, payload: [String: BighelpJSONValue])] = [] + /// Spaces whose script is gone or fails the check: Add is refused with `invalid_request`. + var missingScripts: Set = [] + /// Spaces whose Hermes task won't go yet: delete takes them off Today and answers + /// `schedules_unavailable` until they leave this set. + var stuckTasks: Set = [] + + init(clock: @escaping @MainActor () -> Date = { Date() }) { + self.clock = clock + let now = clock() + for record in [ + Record(agentID: "travel", spaceID: Self.commuteID, state: .live, title: "Commute", + description: "Drive time to work, from live traffic.", size: .small, hidden: false, position: 1_024, + revision: 1, pageID: Self.commutePageID, usesAI: false, updates: "Every 15 minutes", + cadenceMinutes: 15, routineState: .running, updatedAt: now.addingTimeInterval(-4 * 60), + checkedAt: now.addingTimeInterval(-4 * 60), cards: DemoSpaceCards.commute), + // Stopped: nothing ran its routine for hours, so the panel offers Try again. + Record(agentID: "home", spaceID: Self.gardenID, state: .live, title: "Garden", + description: "Soil, temperature and the last watering.", size: .wide, hidden: false, position: 2_048, + revision: 1, pageID: Self.gardenPageID, usesAI: false, updates: "Every 30 minutes", + cadenceMinutes: 30, routineState: .late, updatedAt: now.addingTimeInterval(-3 * 3_600), + checkedAt: now.addingTimeInterval(-3 * 3_600), cards: DemoSpaceCards.garden), + Record(agentID: "home", spaceID: Self.workoutsID, state: .live, title: "Workouts", + description: "This week's training, read from the log each evening.", size: .tall, hidden: false, + position: 3_072, revision: 2, pageID: Self.workoutsPageID, usesAI: true, updates: "Every day at 20:00", + cadenceMinutes: 1_440, routineState: .running, updatedAt: now.addingTimeInterval(-40 * 60), + checkedAt: now.addingTimeInterval(-40 * 60), cards: DemoSpaceCards.workouts), + Record(agentID: "finance", spaceID: Self.spendingDraftID, state: .draft, title: "Spending", + description: "This month's spending against the budget.", size: .wide, hidden: false, + position: 4_096, revision: 1, pageID: Self.spendingPageID, usesAI: false, + updates: "Every 2 hours", cadenceMinutes: 120, routineState: .draft, + updatedAt: now.addingTimeInterval(-60), cards: DemoSpaceCards.spending), + ] { + records[Space.key(agentID: record.agentID, spaceID: record.spaceID)] = record + } + } + + func perform(_ operation: SpacesOperation, + payload: [String: BighelpJSONValue]) async throws -> [String: BighelpJSONValue] { + calls.append((operation, payload)) + guard operation.isMutation else { return try read(operation, payload) } + guard let operationID = payload["operationId"]?.string, operationID == operationID.lowercased(), + UUID(uuidString: operationID) != nil else { throw Self.refusal("invalid_request") } + let request = Self.request(operation, payload) + if let outcome = operations[operationID] { + // Another operation, space or body under a used `operationId` is refused, and nothing is done. + guard outcome.request == request else { throw Self.refusal("invalid_request") } + return try current(outcome.answer.get()) + } + let answer: Result<[String: BighelpJSONValue], WorkspaceClientError> + do { + answer = .success(try mutate(operation, payload)) + } catch let error as WorkspaceClientError { + answer = .failure(error) + } + if case .failure(.rejected(let code, _)) = answer, code == "schedules_unavailable" { + // Not kept: the same request tries again. + } else { + operations[operationID] = Outcome(request: request, answer: answer) + } + return try answer.get() + } + + /// A repeated request's answer, with its space as it is now (as the plugin reads it again). + private func current(_ answer: [String: BighelpJSONValue]) -> [String: BighelpJSONValue] { + guard let space = answer["space"]?.object, let agentID = space["agentId"]?.string, + let spaceID = space["spaceId"]?.string, + let record = records[Space.key(agentID: agentID, spaceID: spaceID)] else { return answer } + var answer = answer + answer["space"] = .object(json(record, cards: true)) + return answer + } + + private static func request(_ operation: SpacesOperation, _ payload: [String: BighelpJSONValue]) -> String { + var body = payload + body["operationId"] = nil + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = (try? encoder.encode(BighelpJSONValue.object(body))) ?? Data() + return operation.rawValue + " " + String(decoding: data, as: UTF8.self) + } + + private func read(_ operation: SpacesOperation, + _ payload: [String: BighelpJSONValue]) throws -> [String: BighelpJSONValue] { + if operation == .get { + let record = try stored(payload) + return ["space": .object(json(record, cards: true))] + } + guard let agents = payload["agentIds"]?.array?.compactMap(\.string), (1...64).contains(agents.count), + agents.allSatisfy(SpacesWire.isAgentID) else { throw Self.refusal("invalid_request") } + let known = payload["known"]?.object ?? [:] + let spaces = records.values + .filter { $0.state == .live && !$0.isDeleting && agents.contains($0.agentID) } + .sorted { $0.position < $1.position } + .map { record in + let key = Space.key(agentID: record.agentID, spaceID: record.spaceID) + return BighelpJSONValue.object(json(record, cards: known[key]?.string != cardsHash(record))) + } + let statuses = Dictionary(uniqueKeysWithValues: agents.map { agent in + (agent, BighelpJSONValue.string(Self.agentIDs.contains(agent) ? "ok" : "profile_not_found")) + }) + return ["spaces": .array(spaces), "agents": .object(statuses)] + } + + private func mutate(_ operation: SpacesOperation, + _ payload: [String: BighelpJSONValue]) throws -> [String: BighelpJSONValue] { + let now = clock() + if operation == .delete { + let key = try spaceKey(payload) + guard let record = records[key] else { + return ["spaceId": payload["spaceId"] ?? .null, "deleted": .boolean(true), "existed": .boolean(false)] + } + if stuckTasks.contains(record.spaceID) { + // Off Today at once; the delete finishes on a later try. + records[key]?.isDeleting = true + throw Self.refusal("schedules_unavailable") + } + records[key] = nil + return ["spaceId": payload["spaceId"] ?? .null, "deleted": .boolean(true), "existed": .boolean(true)] + } + var record = try stored(payload) + let key = Space.key(agentID: record.agentID, spaceID: record.spaceID) + var answer: [String: BighelpJSONValue] = [:] + switch operation { + case .add: + guard let revision = payload["draftRevision"]?.integer else { throw Self.refusal("invalid_request") } + guard revision == record.revision else { throw Self.refusal("draft_changed") } + if record.state == .draft { + guard !missingScripts.contains(record.spaceID) else { throw Self.refusal("invalid_request") } + let live = records.values.filter { $0.agentID == record.agentID && $0.state == .live } + guard live.count < SpacesWire.maximumLiveSpacesPerBot else { throw Self.refusal("spaces_full") } + record.state = .live + record.routineState = .running + record.checkedAt = now + if let size = payload["size"]?.string { record.size = SpaceSize(wire: .string(size)) } + record.position = payload["position"]?.number + ?? (live.map(\.position).max() ?? 0) + SpacesWire.positionStep + } + case .update: + guard let changes = payload["changes"]?.object, !changes.isEmpty else { throw Self.refusal("invalid_request") } + for (name, value) in changes { + switch (name, value) { + case ("size", .string(let size)) where SpaceSize(rawValue: size) != nil: + record.size = SpaceSize(wire: value) + case ("hidden", .boolean(let hidden)): + record.hidden = hidden + case ("position", _) where value.number.map({ $0.isFinite && abs($0) <= SpacesWire.maximumPositionMagnitude }) == true: + record.position = value.number ?? record.position + case ("title", .string(let title)) where (1...SpacesWire.maximumTitleLength).contains(title.unicodeScalars.count): + record.title = title + default: + throw Self.refusal("invalid_request") + } + } + case .refresh: + guard record.state == .live else { throw Self.refusal("invalid_request") } + let gap: TimeInterval = record.usesAI ? 600 : 60 + if let last = record.lastRefresh, now.timeIntervalSince(last) < gap { throw Self.refusal("refresh_too_soon") } + let paused = record.routineState == .paused + if record.usesAI { + // A paused AI routine runs nothing, and the next Update now stays free: only the + // person resumes it, in Scheduled tasks. + guard !paused else { + answer["ran"] = .string(SpaceRefreshRun.paused.rawValue) + break + } + // It runs on the computer's next tick. + record.lastRefresh = now + record.routineState = .running + record.problem = nil + answer["ran"] = .string(SpaceRefreshRun.queued.rawValue) + } else { + // A script that changed since Add doesn't run (the plugin's 502 `routine_failed`). + guard record.problem != SpacesWire.scriptChangedProblem else { throw Self.refusal("routine_failed") } + // A script runs at once, paused or not; a pause stays. + record.lastRefresh = now + if !paused { record.routineState = .running } + record.problem = nil + record.updatedAt = now + record.checkedAt = now + answer["ran"] = .string(SpaceRefreshRun.now.rawValue) + } + case .list, .get, .delete: + throw Self.refusal("invalid_request") + } + records[key] = record + answer["space"] = .object(json(record, cards: true)) + return answer + } + + private func spaceKey(_ payload: [String: BighelpJSONValue]) throws -> String { + guard let agentID = payload["agentId"]?.string, SpacesWire.isAgentID(agentID), + let spaceID = payload["spaceId"]?.string, SpacesWire.isSpaceID(spaceID) else { + throw Self.refusal("invalid_request") + } + guard Self.agentIDs.contains(agentID) else { throw Self.refusal("profile_not_found") } + return Space.key(agentID: agentID, spaceID: spaceID) + } + + private func stored(_ payload: [String: BighelpJSONValue]) throws -> Record { + guard let record = records[try spaceKey(payload)], !record.isDeleting else { throw Self.refusal("space_not_found") } + return record + } + + private static func refusal(_ code: String) -> WorkspaceClientError { .rejected(code: code) } + + private func cardsHash(_ record: Record) -> String { + let cards = record.cards(record.updatedAt) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = (try? encoder.encode(BighelpJSONValue.object(["card": .object(cards.card), "sizes": .object(cards.sizes)]))) ?? Data() + return SpacesWire.sha256(String(decoding: data, as: UTF8.self)) + } + + /// The route's space object; cards left out when the phone has them. + private func json(_ record: Record, cards withCards: Bool) -> [String: BighelpJSONValue] { + let now = clock() + let cadence = TimeInterval(record.cadenceMinutes * 60) + let status: SpaceStatus = if record.state == .draft { + .draft + } else if record.routineState != .running { + .stopped + } else if now.timeIntervalSince(record.updatedAt) > 3 * cadence { + .stale + } else { + .fresh + } + let checkedAt: BighelpJSONValue = record.checkedAt.map { .string(SpacesWire.text($0)) } ?? .null + var routine: [String: BighelpJSONValue] = [ + "kind": .string(record.usesAI ? "ai" : "script"), "usesAI": .boolean(record.usesAI), + "updates": .string(record.updates), "cadenceMinutes": .integer(record.cadenceMinutes), + "state": .string(record.routineState.rawValue), "pendingChange": .boolean(false), + ] + routine["problem"] = record.problem.map(BighelpJSONValue.string) ?? .null + if record.state == .live { + let next = (record.checkedAt ?? record.updatedAt).addingTimeInterval(cadence) + routine["nextRunAt"] = .string(SpacesWire.text(next)) + routine["lastRunAt"] = checkedAt + } + let page: [String: BighelpJSONValue] = ["appId": .string(record.pageID), "htmlSha256": .null, "live": .boolean(true)] + var space: [String: BighelpJSONValue] = [ + "spaceId": .string(record.spaceID), "agentId": .string(record.agentID), "state": .string(record.state.rawValue), + "title": .string(record.title), "description": .string(record.description), + "size": .string(record.size.rawValue), "hidden": .boolean(record.hidden), "position": .number(record.position), + "revision": .integer(record.revision), "cardOmitted": .boolean(false), "status": .string(status.rawValue), + ] + space["cardsSha256"] = .string(cardsHash(record)) + space["updatedAt"] = .string(SpacesWire.text(record.updatedAt)) + space["checkedAt"] = checkedAt + space["page"] = .object(page) + space["routine"] = .object(routine) + if withCards { + let cards = record.cards(record.updatedAt) + space["card"] = .object(cards.card) + if !cards.sizes.isEmpty { space["sizes"] = .object(cards.sizes) } + } + return space + } + + // MARK: For tests + + /// The bot changes its draft (`bighelp_draft_space` again): Add with the old revision is refused. + func reviseDraft(_ spaceID: String, agentID: String) { + records[Space.key(agentID: agentID, spaceID: spaceID)]?.revision += 1 + } + + /// The person pauses a routine in Scheduled tasks, or a run reports a problem + /// (`script_changed` once the bot changed the script after Add). + func setRoutine(_ spaceID: String, agentID: String, state: SpaceRoutineState, problem: String? = nil) { + let key = Space.key(agentID: agentID, spaceID: spaceID) + records[key]?.routineState = state + records[key]?.problem = problem + } +} + +/// The demo spaces' cards, as a bot's routine would write them: basic components, real-looking +/// numbers that move with the time of the update. +enum DemoSpaceCards { + static func commute(_ at: Date) -> (card: [String: BighelpJSONValue], sizes: [String: BighelpJSONValue]) { + let minutes = 24 + Calendar.current.component(.minute, from: at) % 9 + return (document("Commute", summary: "\(minutes) minutes to work.", at: at, elements: [ + "root": node("card", ["title": .string("Commute"), "subtitle": .string("To work")], ["time", "note"]), + "time": node("text", ["value": literal(.string("\(minutes) min")), "typography": .string("title")]), + "note": node("text", ["value": literal(.string("Leave by 8:05 · light traffic")), + "typography": .string("caption"), "color": .string("secondary"), "line_limit": .integer(2)]), + ]), [:]) + } + + static func garden(_ at: Date) -> (card: [String: BighelpJSONValue], sizes: [String: BighelpJSONValue]) { + let moisture = 38 + Calendar.current.component(.minute, from: at) % 6 + return (document("Garden", summary: "Soil moisture \(moisture) percent.", at: at, elements: [ + "root": node("card", ["title": .string("Garden"), "subtitle": .string("Back beds")], ["grid", "watered"]), + "grid": node("grid", ["columns": .integer(2), "spacing": .string("small")], ["moisture", "temperature"]), + "moisture": node("metric", ["label": .string("Soil moisture"), "value": literal(.integer(moisture)), + "format": .object(["style": .string("percent")]), "semantic": .string("accent")]), + "temperature": node("metric", ["label": .string("Temperature"), "value": literal(.string("18.4°C"))]), + "watered": node("text", ["value": literal(.string("Last watered Tuesday, 7:10 AM")), + "typography": .string("caption"), "color": .string("secondary")]), + ]), [:]) + } + + static func workouts(_ at: Date) -> (card: [String: BighelpJSONValue], sizes: [String: BighelpJSONValue]) { + let days: [(String, Int)] = [("Mon", 35), ("Tue", 0), ("Wed", 50), ("Thu", 20), ("Fri", 45), ("Sat", 60), ("Sun", 0)] + let points = BighelpJSONValue.array(days.map { day in + BighelpJSONValue.object(["x": .string(day.0), "y": literal(.integer(day.1))]) + }) + let card = document("Workouts", summary: "210 minutes of training this week.", at: at, elements: [ + "root": node("card", ["title": .string("Workouts"), "subtitle": .string("This week")], ["totals", "chart", "next"]), + "totals": node("hstack", ["spacing": .string("medium")], ["minutes", "sessions"]), + "minutes": node("metric", ["label": .string("Minutes"), "value": literal(.integer(210)), + "format": .object(["style": .string("integer")]), "semantic": .string("positive")]), + "sessions": node("metric", ["label": .string("Sessions"), "value": literal(.integer(5)), + "format": .object(["style": .string("integer")])]), + "chart": node("chart", ["kind": .string("bar"), "description": .string("Minutes each day this week"), + "series": .array([.object(["name": .string("Minutes"), "points": points])])]), + "next": node("text", ["value": literal(.string("Next: easy run, 30 minutes")), + "typography": .string("caption"), "color": .string("secondary")]), + ]) + // Small has room for the week's total only. + let small = document("Workouts", summary: "210 minutes of training this week.", at: at, elements: [ + "root": node("card", ["title": .string("Workouts")], ["minutes"]), + "minutes": node("metric", ["label": .string("This week"), "value": literal(.string("210 min")), + "semantic": .string("positive")]), + ]) + return (card, ["small": .object(small)]) + } + + static func spending(_ at: Date) -> (card: [String: BighelpJSONValue], sizes: [String: BighelpJSONValue]) { + (document("Spending", summary: "1,240 dollars spent of a 2,000 dollar budget.", at: at, elements: [ + "root": node("card", ["title": .string("Spending"), "subtitle": .string("This month")], ["spent", "groceries"]), + "spent": node("progress", ["label": .string("Spent"), "value": literal(.integer(1_240)), + "maximum": literal(.integer(2_000)), + "format": .object(["style": .string("currency"), "currency": .string("USD")]), + "semantic": .string("accent")]), + "groceries": node("text", ["value": literal(.string("Groceries $312 of $450")), + "typography": .string("caption"), "color": .string("secondary")]), + ]), [:]) + } + + /// A card as the plugin's `render_card` leaves it. + private static func document(_ title: String, summary: String, at: Date, + elements: [String: BighelpJSONValue]) -> [String: BighelpJSONValue] { + let hash = SpacesWire.sha256(title + summary + SpacesWire.text(at)) + return [ + "schema": .string("loopdy.card"), "version": .integer(1), "title": .string(title), + "spoken_summary": .string(summary), "data_sources": .array([]), "root": .string("root"), + "elements": .object(elements), "content_hash": .string(hash), "card_id": .string(String(hash.prefix(32))), + // The card validator reads `created_at` without fractions of a second. + "origin": .string("live"), "created_at": .string(ISO8601DateFormatter().string(from: at)), + ] + } + + private static func node(_ type: String, _ props: [String: BighelpJSONValue], _ children: [String] = []) -> BighelpJSONValue { + .object(["type": .string(type), "props": .object(props), "children": .array(children.map(BighelpJSONValue.string))]) + } + + private static func literal(_ value: BighelpJSONValue) -> BighelpJSONValue { + .object(["literal": value]) + } +} + +/// The demo spaces' pages, as a bot might write them: one small self-contained page each that +/// follows the phone's light or dark look and draws what `window.bighelp.onData` gives it. +enum DemoSpacePages { + static func commuteData(_ now: Date) -> BighelpJSONValue { + let minute = Calendar.current.component(.minute, from: now) + return .object(["minutes": .integer(24 + minute % 9), "leaveBy": .string("8:05"), + "route": .string("Ring road, then Harbor Street"), "traffic": .string("Light")]) + } + + static func gardenData(_ now: Date) -> BighelpJSONValue { + let tick = Int(now.timeIntervalSince1970 / 5) + return .object(["moisture": .integer(38 + tick % 6), "temperature": .number(18 + Double(tick % 5) / 10), + "lastWatered": .string("Tuesday, 7:10 AM")]) + } + + static func workoutsData(_ now: Date) -> BighelpJSONValue { + .object(["days": .array([35, 0, 50, 20, 45, 60, 0].map { BighelpJSONValue.integer($0) }), + "next": .string("Easy run, 30 minutes")]) + } + + static func spendingData(_ now: Date) -> BighelpJSONValue { + .object(["spent": .integer(1_240), "budget": .integer(2_000), + "parts": .array([ + .object(["name": .string("Groceries"), "spent": .integer(312)]), + .object(["name": .string("Eating out"), "spent": .integer(186)]), + .object(["name": .string("Transport"), "spent": .integer(142)]), + ])]) + } + + private static let style = """ + + + """ + + static let commute = """ + \(style)Commute +
Drive to work
–
+
Route
Traffic
+ + """ + + static let garden = """ + \(style)Garden +
Soil moisture
–
+
Temperature
Last watered
+ + """ + + static let workouts = """ + \(style)Workouts +
Minutes each day
MonSun
+
Next
+ + """ + + static let spending = """ + \(style)Spending +
Spent this month
–
+
+ + """ +} diff --git a/Bighelp/Spaces/SpaceDraftCardView.swift b/Bighelp/Spaces/SpaceDraftCardView.swift new file mode 100644 index 00000000..1f618e4e --- /dev/null +++ b/Bighelp/Spaces/SpaceDraftCardView.swift @@ -0,0 +1,528 @@ +import SwiftUI + +/// Where the draft card's Open Today goes. Set up by the app; does nothing until then. Chat rows +/// take only a few environment values from the chat (`ChatRowLiveValues`), so this can't come +/// through the environment. +@MainActor +enum SpaceDraftCardHost { + // One home: the shell sets this to select the Today tab once Today is a tab. + static var openToday: @MainActor () -> Void = {} +} + +/// Where a draft card is: reading the draft, waiting for Add, adding, or done. +enum SpaceDraftPhase: Equatable, Sendable { + case loading + case ready + case adding + case onToday + /// The bot deleted the draft, or the bot is gone. + case removed + case needsPluginUpdate +} + +/// A line under the card's details after something didn't go as asked. Add stays. +enum SpaceDraftNotice: Equatable, Sendable { + /// The bot made a newer draft than the card first showed: its preview is what Add adds now. + case changed + case unreachable + case full + case schedulesUnavailable + /// Add found the draft's script gone: the bot has to make it again. + case scriptMissing + case failed +} + +/// What the card shows about the draft: the bot's words on the card, or the computer's when the +/// bot has changed the draft since. +struct SpaceDraftDetails: Equatable, Sendable { + let title: String + let description: String + let updates: String + /// False only when nothing says an update uses AI: the card never says "No AI" by guess. + let usesAI: Bool + + /// A bot wrote the words: a card's title has no wire limit of its own, so the card never draws + /// more than the plugin accepts for a space. + init(title: String, description: String, updates: String, usesAI: Bool) { + self.title = String(title.prefix(SpacesWire.maximumTitleLength)) + self.description = String(description.prefix(SpacesWire.maximumDescriptionLength)) + self.updates = String(updates.prefix(SpacesWire.maximumUpdatesLength)) + self.usesAI = usesAI + } +} + +/// The draft card's rules, kept apart from the view so they can be tested. Every read and Add gets +/// a ticket; an answer counts only for the ticket the card waits on, so a late answer for an older +/// revision (or a read the card gave up on) never changes what it shows. +struct SpaceDraftFlow: Equatable, Sendable { + struct Ticket: Equatable, Sendable { + let number: Int + /// The draft revision the request was made for. + let revision: Int + } + + let draft: SpaceDraftCard + /// The revision Add sends: the card's own, or a newer one the computer showed. + private(set) var revision: Int + /// The draft as `spaces/get` read it; nil until then, or when it can't be read. + private(set) var preview: Space? + private(set) var phase: SpaceDraftPhase = .loading + private(set) var notice: SpaceDraftNotice? + private(set) var size: SpaceSize = .wide + private(set) var sizeChosen = false + private(set) var pending: Ticket? + private var issued = 0 + + init(draft: SpaceDraftCard) { + self.draft = draft + revision = draft.revision + } + + var canAdd: Bool { pending == nil && phase == .ready } + var showsSizes: Bool { phase == .loading || phase == .ready || phase == .adding } + + var details: SpaceDraftDetails { + guard let preview, preview.revision == revision, revision != draft.revision else { + // The card's own revision: its words, and AI if either the card or the computer says so. + let computerSaysAI = preview.map { $0.revision == draft.revision && $0.routine.usesAI } ?? false + return SpaceDraftDetails(title: draft.title, description: draft.description, updates: draft.updates, + usesAI: draft.usesAI || computerSaysAI) + } + // The bot changed the draft: the computer's words for the revision Add sends. + return SpaceDraftDetails( + title: preview.title.isEmpty ? draft.title : preview.title, + description: preview.description.isEmpty ? draft.description : preview.description, + updates: preview.routine.updates.isEmpty ? draft.updates : preview.routine.updates, + usesAI: preview.routine.usesAI) + } + + private mutating func issue() -> Ticket { + issued += 1 + let ticket = Ticket(number: issued, revision: revision) + pending = ticket + return ticket + } + + /// Reads the draft again (when the card shows, and after the bot changed it). + mutating func beginLoad() -> Ticket { + if phase != .onToday && phase != .removed { phase = .loading } + return issue() + } + + mutating func loaded(_ result: Result, ticket: Ticket) { + guard ticket == pending else { return } + pending = nil + switch result { + case .success(let space): + preview = space + if !sizeChosen { size = space.size } + if space.state == .live && !space.routine.pendingChange { + phase = .onToday + notice = nil + return + } + if space.revision != revision { + revision = space.revision + notice = .changed + } + phase = .ready + case .failure(.notFound): + phase = .removed + case .failure(.needsPluginUpdate): + phase = .needsPluginUpdate + case .failure: + // No preview, or the last one; Add still works. + if phase == .loading { phase = .ready } + } + } + + /// The card reads the draft when it shows: at first, after the bot changed it, and again when + /// the last read got no answer. A card that has its answer doesn't ask each time it scrolls by. + var wantsRead: Bool { phase == .loading || (phase == .ready && preview == nil) } + + mutating func choose(_ size: SpaceSize) { + // Once Add is on its way, the size it sent stays. + guard phase == .loading || phase == .ready else { return } + self.size = size + sizeChosen = true + } + + /// Add to Today: the ticket to send it with, or nil while the card can't add. + mutating func beginAdd() -> Ticket? { + guard canAdd else { return nil } + notice = nil + phase = .adding + return issue() + } + + /// Add's answer. True when the draft has to be read again (the bot changed it). + @discardableResult + mutating func added(_ result: Result, ticket: Ticket) -> Bool { + guard ticket == pending else { return false } + pending = nil + switch result { + case .success(let space): + preview = space + phase = .onToday + return false + case .failure(let error): + switch error { + case .draftChanged(let newer): + if let newer { revision = newer } + notice = .changed + phase = .loading + return true + case .notDraft: + phase = .onToday + case .notFound: + phase = .removed + case .needsPluginUpdate: + phase = .needsPluginUpdate + case .unreachable: + phase = .ready + notice = .unreachable + case .full: + phase = .ready + notice = .full + case .schedulesUnavailable: + phase = .ready + notice = .schedulesUnavailable + case .scriptMissing: + phase = .ready + notice = .scriptMissing + case .tooSoon, .routineFailed, .other: + phase = .ready + notice = .failed + } + return false + } + } +} + +/// Runs the card's reads and its Add. Owned by the card's `@State`: an Add the person started +/// finishes on the computer even if the card scrolls away, but a card that's gone changes nothing. +@MainActor +@Observable +final class SpaceDraftCardModel { + private(set) var flow: SpaceDraftFlow + /// Moves when the draft has to be read again; the card's read task follows it. + private(set) var reloads = 0 + + typealias Read = @MainActor (_ agentID: String, _ spaceID: String) async throws(SpacesError) -> Space + typealias Add = @MainActor (_ agentID: String, _ spaceID: String, _ revision: Int, _ size: SpaceSize, + _ preview: Space?) async throws(SpacesError) -> Space + + @ObservationIgnored private let read: Read + @ObservationIgnored private let addSpace: Add + + init(draft: SpaceDraftCard, + read: @escaping Read = { (agentID: String, spaceID: String) async throws(SpacesError) -> Space in + // The chat's computer is the one in use (`SpacesHost.current`). + guard let api = SpacesHost.current()?.api else { throw .unreachable } + return try await api.space(agentID: agentID, spaceID: spaceID) + }, + add: @escaping Add = { (agentID: String, spaceID: String, revision: Int, size: SpaceSize, + preview: Space?) async throws(SpacesError) -> Space in + try await TodaySpacesModel.shared.add(agentID: agentID, spaceID: spaceID, draftRevision: revision, + size: size, preview: preview) + }) { + flow = SpaceDraftFlow(draft: draft) + self.read = read + addSpace = add + } + + /// The card's `.task`: cancelled when the card goes, and then nothing changes. + func load(agentID: String) async { + guard flow.wantsRead else { return } + let ticket = flow.beginLoad() + let result: Result + do throws(SpacesError) { + result = .success(try await read(agentID, flow.draft.spaceID)) + } catch { + result = .failure(error) + } + guard !Task.isCancelled else { return } + flow.loaded(result, ticket: ticket) + } + + func choose(_ size: SpaceSize) { flow.choose(size) } + + func add(agentID: String) { + guard let ticket = flow.beginAdd() else { return } + let spaceID = flow.draft.spaceID + let size = flow.size + // Shown on Today at once only when it's the draft Add sends. + let preview = flow.preview.flatMap { $0.revision == ticket.revision ? $0 : nil } + let addSpace = addSpace + Task { [weak self] in + let result: Result + do throws(SpacesError) { + result = .success(try await addSpace(agentID, spaceID, ticket.revision, size, preview)) + } catch { + result = .failure(error) + } + guard let self else { return } + if self.flow.added(result, ticket: ticket) { self.reloads += 1 } + } + } +} + +/// The chat's card for a space the bot drafted (`space_draft`): what it shows, a preview of its +/// panel, how often it updates and whether that uses AI, a size, and Add to Today. Nothing runs on +/// the computer until Add. +@MainActor +struct SpaceDraftCardView: View { + let draft: SpaceDraftCard + let onOpenToday: @MainActor () -> Void + + @Environment(\.chatCardInteractions) private var interactions + @State private var model: SpaceDraftCardModel + @BighelpThemeReader private var theme + + init(draft: SpaceDraftCard, onOpenToday: @escaping @MainActor () -> Void = { SpaceDraftCardHost.openToday() }) { + self.draft = draft + self.onOpenToday = onOpenToday + _model = State(initialValue: SpaceDraftCardModel(draft: draft)) + } + + /// The bot whose chat this is, on the computer in use; nil while the chat's connection is closed. + private var agentID: String? { + guard let scope = interactions?.scope, scope.isUsable else { return nil } + return scope.profileID + } + + private struct ReadKey: Equatable { + let agentID: String? + let reloads: Int + } + + var body: some View { + let flow = model.flow + let details = flow.details + VStack(alignment: .leading, spacing: 14) { + SpaceDraftHeader(details: details) + SpaceDraftPreview(flow: flow) + SpaceDraftUpdatesLine(details: details) + if flow.showsSizes { + SpaceDraftSizeChips(selection: flow.size, choose: { model.choose($0) }) + } + if let notice = flow.notice { SpaceDraftNoticeLine(notice: notice) } + SpaceDraftAction(phase: flow.phase, canAdd: flow.canAdd && agentID != nil, + add: { if let agentID { model.add(agentID: agentID) } }, openToday: onOpenToday) + } + .padding(BighelpTokens.space16) + .frame(maxWidth: 420, alignment: .leading) + .background(theme.surface, in: .rect(cornerRadius: BighelpCardDesignTokens.cornerRadius, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: BighelpCardDesignTokens.cornerRadius, style: .continuous) + .stroke(theme.border, lineWidth: 0.5) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("space-draft.card") + .task(id: ReadKey(agentID: agentID, reloads: model.reloads)) { + guard let agentID else { return } + await model.load(agentID: agentID) + } + } +} + +private struct SpaceDraftHeader: View { + let details: SpaceDraftDetails + @BighelpThemeReader private var theme + + var body: some View { + HStack(alignment: .top, spacing: BighelpTokens.space12) { + Image(systemName: "square.grid.2x2") + .font(.bighelp(.title3, weight: .semibold)) + .foregroundStyle(theme.actionForeground) + .frame(width: 44, height: 44) + .background(theme.action, in: .rect(cornerRadius: 12, style: .continuous)) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 3) { + Text(verbatim: details.title) + .font(.bighelp(.headline)) + .foregroundStyle(theme.primaryText) + .lineLimit(2) + Text(verbatim: details.description) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .lineLimit(4) + } + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + } + .accessibilityElement(children: .combine) + } +} + +/// The panel as Today will draw it, at the chosen size. Still while it loads; left out when the +/// draft can't be read. +private struct SpaceDraftPreview: View { + let flow: SpaceDraftFlow + @BighelpThemeReader private var theme + + var body: some View { + if let preview = flow.preview { + framed(SpacePanelView(space: preview, size: flow.size)) + } else if flow.phase == .loading { + framed(SpacePanelPlaceholder().frame(height: SpacePanelView.cardHeight(flow.size))) + } + } + + private func framed(_ panel: some View) -> some View { + panel + .padding(BighelpTokens.space12) + .frame(maxWidth: flow.size == .small ? 200 : .infinity, alignment: .topLeading) + .background(theme.canvas, in: .rect(cornerRadius: BighelpTokens.radius16, style: .continuous)) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("space-draft.preview") + } +} + +/// "Every 15 minutes" and, beside it, what an update costs. Wraps at large text. +private struct SpaceDraftUpdatesLine: View { + let details: SpaceDraftDetails + @BighelpThemeReader private var theme + + var body: some View { + ViewThatFits(in: .horizontal) { + HStack(spacing: BighelpTokens.space8) { updates; cost } + VStack(alignment: .leading, spacing: BighelpTokens.space4) { updates; cost } + } + } + + private var updates: some View { + Label { Text(verbatim: details.updates) } icon: { Image(systemName: "clock.arrow.circlepath") } + .font(.bighelp(.footnote, weight: .medium)) + .foregroundStyle(theme.primaryText) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("space-draft.updates") + } + + private var cost: some View { + Group { + if details.usesAI { Text("Uses AI each update") } else { Text("No AI") } + } + .font(.bighelp(.footnote, weight: .medium)) + .foregroundStyle(theme.primaryText.opacity(0.8)) + .padding(.horizontal, 10) + .padding(.vertical, 4) + .background(theme.canvas, in: .capsule) + .overlay { Capsule().stroke(theme.border, lineWidth: 0.5) } + .accessibilityIdentifier("space-draft.ai") + } +} + +/// Small, Wide and Tall in one row that scrolls sideways. +private struct SpaceDraftSizeChips: View { + let selection: SpaceSize + let choose: (SpaceSize) -> Void + + var body: some View { + ScrollView(.horizontal) { + HStack(spacing: BighelpTokens.space8) { + ForEach(SpaceSize.allCases, id: \.self) { size in + SpacesChip(title: Text(TodayPanelSize(size).title), isOn: size == selection, + identifier: "space-draft.size.\(size.rawValue)") { choose(size) } + } + } + } + .scrollIndicators(.hidden) + .scrollBounceBehavior(.basedOnSize, axes: .horizontal) + .accessibilityElement(children: .contain) + .accessibilityLabel("Size") + } +} + +private struct SpaceDraftNoticeLine: View { + let notice: SpaceDraftNotice + @BighelpThemeReader private var theme + + var body: some View { + text + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("space-draft.notice") + } + + private var text: Text { + switch notice { + case .changed: Text("The bot changed this space. Check it, then add it.") + case .unreachable: Text("Could not reach your computer. Try again.") + case .full: Text("This bot has as many spaces as it can keep. Delete one on Today first.") + case .schedulesUnavailable: Text("Your computer can't run scheduled tasks right now.") + case .scriptMissing: Text("This space's script is missing. Ask the bot to make it again.") + case .failed: Text("Could not add this space. Try again.") + } + } +} + +private struct SpaceDraftAction: View { + let phase: SpaceDraftPhase + let canAdd: Bool + let add: () -> Void + let openToday: @MainActor () -> Void + @BighelpThemeReader private var theme + + var body: some View { + switch phase { + case .loading, .ready, .adding: + Button(action: add) { + Group { + if phase == .adding { Text("Adding…") } else { Text("Add to Today") } + } + .font(.bighelp(.body, weight: .semibold)) + .foregroundStyle(theme.actionForeground) + .frame(maxWidth: .infinity, minHeight: max(46, BighelpTokens.hitTarget)) + .background(theme.action.opacity(canAdd ? 1 : 0.5), + in: .rect(cornerRadius: 14, style: .continuous)) + .contentShape(.rect) + } + .buttonStyle(.plain) + .disabled(!canAdd) + .accessibilityIdentifier("space-draft.add") + case .onToday: + ViewThatFits(in: .horizontal) { + HStack(spacing: BighelpTokens.space12) { onToday; Spacer(minLength: 0); openButton } + VStack(alignment: .leading, spacing: BighelpTokens.space8) { onToday; openButton } + } + case .removed: + line(Text("Removed"), symbol: "trash") + .accessibilityIdentifier("space-draft.removed") + case .needsPluginUpdate: + line(Text("Update the plugin on your computer to add this."), symbol: "arrow.down.circle") + .accessibilityIdentifier("space-draft.update-plugin") + } + } + + private var onToday: some View { + Label("On Today", systemImage: "checkmark") + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .accessibilityIdentifier("space-draft.on-today") + } + + private var openButton: some View { + Button { + openToday() + } label: { + Text("Open Today") + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.action) + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("space-draft.open-today") + } + + private func line(_ text: Text, symbol: String) -> some View { + Label { text } icon: { Image(systemName: symbol) } + .font(.bighelp(.subheadline, weight: .medium)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + } +} diff --git a/Bighelp/Spaces/SpaceModels.swift b/Bighelp/Spaces/SpaceModels.swift new file mode 100644 index 00000000..c299af80 --- /dev/null +++ b/Bighelp/Spaces/SpaceModels.swift @@ -0,0 +1,426 @@ +import Foundation + +/// How much of Today a space takes: half a row, the whole row, or the whole row and twice the height. +enum SpaceSize: String, CaseIterable, Codable, Sendable { + case small, wide, tall + + /// A size this app doesn't know is drawn Wide. + init(wire value: BighelpJSONValue?) { + self = value?.string.flatMap(Self.init(rawValue:)) ?? .wide + } +} + +/// A draft waits in the chat for Add to Today; a live space is on Today and its routine runs. +enum SpaceState: String, Sendable { + case draft, live +} + +/// What the computer says about a space's routine (`routine.state`). +enum SpaceRoutineState: String, Sendable { + case running + /// Paused on the computer, for example in Scheduled tasks. + case paused + /// Its scheduled task was removed. + case missing + case failed + /// It should have run by now: nothing runs this computer's scheduled tasks. + case late + case draft + /// A state this app doesn't know. Drawn as stopped. + case unknown +} + +/// How current a space's panel is (`status`). +enum SpaceStatus: String, Sendable { + case draft, fresh + /// Not updated for three of its intervals while its routine runs. + case stale + /// Its routine isn't running. + case stopped + case unknown +} + +/// What updates a space, and whether that spends AI. +struct SpaceRoutine: Equatable, Sendable { + enum Kind: String, Sendable { + case script, ai, unknown + } + + var kind: Kind + /// Each update is a model turn. Unknown counts as yes: the person is never told "no AI" by guess. + var usesAI: Bool + /// The plugin's words for how often: "Every 15 minutes", "Weekdays at 7:00". + var updates: String + var cadenceMinutes: Int? + var state: SpaceRoutineState + var nextRunAt: Date? + var lastRunAt: Date? + /// A fixed code (`script_failed`, `no_update`, …), never the script's own output. + var problem: String? + /// A changed routine waits for Add again; the old one keeps running until then. + var pendingChange: Bool + + init(json: [String: BighelpJSONValue]?) { + let json = json ?? [:] + let kind = json["kind"]?.string.flatMap(Kind.init(rawValue:)) ?? .unknown + self.kind = kind + usesAI = json["usesAI"]?.boolean ?? (kind != .script) + updates = String((json["updates"]?.string ?? "").prefix(SpacesWire.maximumUpdatesLength)) + cadenceMinutes = json["cadenceMinutes"]?.integer.flatMap { $0 > 0 ? $0 : nil } + state = json["state"]?.string.flatMap(SpaceRoutineState.init(rawValue:)) ?? .unknown + nextRunAt = SpacesWire.date(json["nextRunAt"]) + lastRunAt = SpacesWire.date(json["lastRunAt"]) + problem = json["problem"]?.string.flatMap(Self.code) + pendingChange = json["pendingChange"]?.boolean ?? false + } + + var json: [String: BighelpJSONValue] { + var json: [String: BighelpJSONValue] = [ + "kind": .string(kind.rawValue), "usesAI": .boolean(usesAI), "updates": .string(updates), + "state": .string(state.rawValue), "pendingChange": .boolean(pendingChange), + ] + json["cadenceMinutes"] = cadenceMinutes.map(BighelpJSONValue.integer) + json["nextRunAt"] = nextRunAt.map { .string(SpacesWire.text($0)) } + json["lastRunAt"] = lastRunAt.map { .string(SpacesWire.text($0)) } + json["problem"] = problem.map(BighelpJSONValue.string) + return json + } + + /// Letters, digits and `_`, at most 64: the plugin's codes, nothing else. + private static func code(_ value: String) -> String? { + guard (1...64).contains(value.utf8.count), + value.utf8.allSatisfy({ (97...122).contains($0) || (48...57).contains($0) || $0 == 95 }) else { return nil } + return value + } +} + +/// The HTML app a space's panel opens (`html-apps/get` and `html-apps/data` with its `appId`). +struct SpacePage: Equatable, Sendable { + let appID: String + let htmlSHA256: String? + let isLive: Bool + + /// The card the page screen opens with. A space's page never sends a message. + func card(title: String, description: String) -> HTMLAppCard { + HTMLAppCard(appID: appID, title: title, description: description, sendsAnswers: false, isLive: isLive) + } +} + +/// One space as the computer describes it (`spaces/list`, `get`, and every mutation's answer). +/// Read leniently: unknown keys are ignored, unknown values fall back, and only a space without +/// its ids is left out, never the list it came in. +struct Space: Identifiable, Equatable, Sendable { + let spaceID: String + let agentID: String + var state: SpaceState + var title: String + var description: String + var size: SpaceSize + var hidden: Bool + var position: Double + var revision: Int + /// The hash of the card and the size cards together; `list` leaves out cards the phone has. + var cardsSHA256: String? + /// The panel for every size that has no card of its own. Nil until it's read, or when unreadable. + var card: BighelpCardDocument? + var sizes: [SpaceSize: BighelpCardDocument] + /// The list left the cards out to keep its answer small: `get` reads them. + var cardOmitted: Bool + /// The computer sent a card this app can't draw: its panel says so, the rest of Today draws. + var cardUnreadable: Bool + /// When the bot or its routine last changed what the panel shows. Never the phone's own time. + var updatedAt: Date? + /// When the routine last finished, also a run that had nothing new. + var checkedAt: Date? + var page: SpacePage? + var routine: SpaceRoutine + var status: SpaceStatus + + /// `agentId/spaceId`: unique on one computer, and the key `list`'s `known` uses. + var id: String { key } + var key: String { Self.key(agentID: agentID, spaceID: spaceID) } + + static func key(agentID: String, spaceID: String) -> String { agentID + "/" + spaceID } + + /// The card drawn at a size: the one made for it, else the space's own. + func card(for size: SpaceSize) -> BighelpCardDocument? { sizes[size] ?? card } + + /// The phone has every card the computer sent (drawable or not), so `list` may leave them out. + var holdsCards: Bool { card != nil || !sizes.isEmpty || cardUnreadable } + + /// The person paused its routine in Scheduled tasks; only they resume it there. + var isPaused: Bool { routine.state == .paused } + + /// The bot changed its script after the person added the space: it stays stopped until the bot + /// drafts it again and the person adds it again. Update now can't fix that. + var isScriptChanged: Bool { routine.problem == SpacesWire.scriptChangedProblem } + + /// Its panel says Stopped updating, with Try again. An unknown state counts as stopped. + var isStopped: Bool { + guard state == .live else { return false } + if status == .stopped { return true } + switch routine.state { + case .running, .draft: return false + case .paused, .missing, .failed, .late, .unknown: return true + } + } + + init?(json: [String: BighelpJSONValue]) { + guard let spaceID = json["spaceId"]?.string, SpacesWire.isSpaceID(spaceID), + let agentID = json["agentId"]?.string, SpacesWire.isAgentID(agentID) else { return nil } + self.spaceID = spaceID + self.agentID = agentID + state = json["state"]?.string.flatMap(SpaceState.init(rawValue:)) ?? .live + // A bot wrote this text: no longer than the plugin accepts, whatever the answer holds. + description = String((json["description"]?.string ?? "").prefix(SpacesWire.maximumDescriptionLength)) + size = SpaceSize(wire: json["size"]) + hidden = json["hidden"]?.boolean ?? false + position = json["position"]?.number.flatMap { + $0.isFinite && abs($0) <= SpacesWire.maximumPositionMagnitude ? $0 : nil + } ?? SpacesWire.maximumPositionMagnitude + revision = json["revision"]?.integer.flatMap { $0 >= 1 ? $0 : nil } ?? 1 + cardsSHA256 = json["cardsSha256"]?.string.flatMap { $0.utf8.count == 64 ? $0 : nil } + let card: BighelpCardDocument? + switch json["card"] { + case nil, .null?: + card = nil + // Only the phone's own copy writes this mark: the computer sends the card or nothing. + cardUnreadable = json["cardUnreadable"]?.boolean ?? false + case let value?: + card = Self.drawable(value) + cardUnreadable = card == nil + } + self.card = card + var sizes: [SpaceSize: BighelpCardDocument] = [:] + for (name, value) in json["sizes"]?.object ?? [:] { + // A size card that can't be drawn falls back to the space's own card. + guard let size = SpaceSize(rawValue: name), let card = Self.drawable(value) else { continue } + sizes[size] = card + } + self.sizes = sizes + cardOmitted = json["cardOmitted"]?.boolean ?? false + updatedAt = SpacesWire.date(json["updatedAt"]) + checkedAt = SpacesWire.date(json["checkedAt"]) + page = json["page"]?.object.flatMap { page in + guard let appID = page["appId"]?.string, HTMLAppCard.isAppID(appID) else { return nil } + return SpacePage(appID: appID, htmlSHA256: page["htmlSha256"]?.string, isLive: page["live"]?.boolean ?? true) + } + routine = SpaceRoutine(json: json["routine"]?.object) + status = json["status"]?.string.flatMap(SpaceStatus.init(rawValue:)) ?? .unknown + let title = (json["title"]?.string ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + self.title = String((title.isEmpty ? (card?.title ?? "") : title).prefix(SpacesWire.maximumTitleLength)) + } + + /// The route's shape again, for the phone's copy on disk; read back by `init(json:)`. + var json: [String: BighelpJSONValue] { + var json: [String: BighelpJSONValue] = [ + "spaceId": .string(spaceID), "agentId": .string(agentID), "state": .string(state.rawValue), + "title": .string(title), "description": .string(description), "size": .string(size.rawValue), + "hidden": .boolean(hidden), "position": .number(position), "revision": .integer(revision), + "cardOmitted": .boolean(cardOmitted), "routine": .object(routine.json), "status": .string(status.rawValue), + ] + json["cardsSha256"] = cardsSHA256.map(BighelpJSONValue.string) + json["card"] = card.map { .object($0.document) } + if card == nil, cardUnreadable { json["cardUnreadable"] = .boolean(true) } + if !sizes.isEmpty { + json["sizes"] = .object(Dictionary(uniqueKeysWithValues: sizes.map { size, card in + (size.rawValue, BighelpJSONValue.object(card.document)) + })) + } + json["updatedAt"] = updatedAt.map { .string(SpacesWire.text($0)) } + json["checkedAt"] = checkedAt.map { .string(SpacesWire.text($0)) } + json["page"] = page.map { page in + var object: [String: BighelpJSONValue] = ["appId": .string(page.appID), "live": .boolean(page.isLive)] + object["htmlSha256"] = page.htmlSHA256.map(BighelpJSONValue.string) + return .object(object) + } + return json + } + + /// The same space with the cards the phone has, when the computer left them out and they + /// haven't changed. + func takingCards(from cached: Space?) -> Space { + guard !holdsCards, let cached, cached.holdsCards, cached.cardsSHA256 != nil, + cached.cardsSHA256 == cardsSHA256 else { return self } + var space = self + space.card = cached.card + space.sizes = cached.sizes + space.cardUnreadable = cached.cardUnreadable + space.cardOmitted = false + return space + } + + /// The cards still have to be read with `get`. + var needsCards: Bool { !holdsCards && (cardOmitted || cardsSHA256 != nil) } + + /// A card the app can draw: a valid `loopdy.card` with no live data sources. + private static func drawable(_ value: BighelpJSONValue) -> BighelpCardDocument? { + guard let document = value.object, let card = try? BighelpCardDocument(document: document) else { return nil } + return try? BighelpCardValidator.validateForStaticRelease(card) + } +} + +/// What a bot's spaces read as, per bot in a `list` answer. +enum SpacesAgentStatus: Equatable, Sendable { + case ok + /// The bot isn't on the computer anymore: its spaces go. + case notFound + /// Anything else: its spaces stay as last read. + case other(String) + + init(_ value: String) { + switch value { + case "ok": self = .ok + case "profile_not_found": self = .notFound + default: self = .other(value) + } + } + + /// A bot the computer couldn't read just now keeps the spaces last read for it. + var keepsSpaces: Bool { + if case .other = self { return true } + return false + } +} + +/// One `spaces/list` answer. +struct SpacesList: Equatable, Sendable { + var spaces: [Space] + var agents: [String: SpacesAgentStatus] + + init(spaces: [Space] = [], agents: [String: SpacesAgentStatus] = [:]) { + self.spaces = spaces + self.agents = agents + } + + /// A space that doesn't read is left out; the first of two with one key wins. + init(json: [String: BighelpJSONValue]) { + var seen = Set() + spaces = (json["spaces"]?.array ?? []).prefix(SpacesWire.maximumSpacesPerAnswer).compactMap { value in + guard let object = value.object, let space = Space(json: object), seen.insert(space.key).inserted else { return nil } + return space + } + var agents: [String: SpacesAgentStatus] = [:] + for (agentID, status) in json["agents"]?.object ?? [:] { + guard SpacesWire.isAgentID(agentID), let text = status.string else { continue } + agents[agentID] = SpacesAgentStatus(text) + } + self.agents = agents + } +} + +/// What `spaces/update` changes. The phone keeps these until the computer says they're done. +struct SpaceChanges: Codable, Equatable, Sendable { + var size: SpaceSize? + var hidden: Bool? + var position: Double? + var title: String? + + init(size: SpaceSize? = nil, hidden: Bool? = nil, position: Double? = nil, title: String? = nil) { + self.size = size + self.hidden = hidden + self.position = position + self.title = title + } + + var isEmpty: Bool { size == nil && hidden == nil && position == nil && title == nil } + + var payload: [String: BighelpJSONValue] { + var changes: [String: BighelpJSONValue] = [:] + changes["size"] = size.map { .string($0.rawValue) } + changes["hidden"] = hidden.map(BighelpJSONValue.boolean) + changes["position"] = position.map(BighelpJSONValue.number) + changes["title"] = title.map(BighelpJSONValue.string) + return changes + } + + /// A later change on top of this one: its fields win. + func merging(_ newer: SpaceChanges) -> SpaceChanges { + SpaceChanges(size: newer.size ?? size, hidden: newer.hidden ?? hidden, + position: newer.position ?? position, title: newer.title ?? title) + } + + /// Without the fields `other` sets: what's left after those were refused. + func removing(_ other: SpaceChanges) -> SpaceChanges { + SpaceChanges(size: other.size == nil ? size : nil, hidden: other.hidden == nil ? hidden : nil, + position: other.position == nil ? position : nil, title: other.title == nil ? title : nil) + } + + func applied(to space: Space) -> Space { + var space = space + if let size { space.size = size } + if let hidden { space.hidden = hidden } + if let position { space.position = position } + if let title { space.title = title } + return space + } + + /// The computer's own value has caught up with every field. + func isSatisfied(by space: Space) -> Bool { + (size == nil || space.size == size) && (hidden == nil || space.hidden == hidden) + && (position == nil || space.position == position) && (title == nil || space.title == title) + } +} + +/// How `spaces/refresh` ran the routine: a script at once, an AI routine on the computer's next tick, +/// or nothing, for an AI routine the person paused in Scheduled tasks. +enum SpaceRefreshRun: String, Sendable { + case now, queued, paused +} + +/// A chat card's one `space_draft` element (the plugin's `space_draft_props`): which draft, what it +/// shows, how often it updates and whether that uses AI. Read exactly, as `HTMLAppCard` is. +struct SpaceDraftCard: Equatable, Sendable { + let spaceID: String + let title: String + let description: String + /// "Every 15 minutes": the plugin's words. + let updates: String + let usesAI: Bool + /// Add to Today sends it back (`draftRevision`); a bot that changed the draft since gets `draft_changed`. + let revision: Int + + init(spaceID: String, title: String, description: String, updates: String, usesAI: Bool, revision: Int) { + self.spaceID = spaceID + self.title = title + self.description = description + self.updates = updates + self.usesAI = usesAI + self.revision = revision + } + + init(props: [String: BighelpJSONValue], title: String) throws { + let keys: Set = ["space_id", "description", "updates", "uses_ai", "revision"] + guard Set(props.keys) == keys, + let spaceID = props["space_id"]?.string, SpacesWire.isSpaceID(spaceID), + case .string(let description)? = props["description"], + // Counted as the plugin counts them (Unicode scalars, Python's `len`). + description.unicodeScalars.count <= SpacesWire.maximumDescriptionLength, + !description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + case .string(let updates)? = props["updates"], + updates.unicodeScalars.count <= SpacesWire.maximumUpdatesLength, + !updates.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + case .boolean(let usesAI)? = props["uses_ai"], + case .integer(let revision)? = props["revision"], revision >= 1 else { + throw BighelpCardValidationError.invalid + } + self.init(spaceID: spaceID, title: title, description: description, updates: updates, + usesAI: usesAI, revision: revision) + } + + static func draft(in card: BighelpCardDocument) -> SpaceDraftCard? { + guard let elements = card.document["elements"]?.object else { return nil } + for element in elements.values { + guard let object = element.object, object["type"]?.string == SpacesWire.type, + let props = object["props"]?.object else { continue } + return try? SpaceDraftCard(props: props, title: card.title) + } + return nil + } + + /// The validator's composition rule: a draft is its card's only element. + static func validateComposition(_ elements: [String: BighelpJSONValue]) throws { + let drafts = elements.values.filter { $0.object?["type"]?.string == SpacesWire.type }.count + guard drafts == 0 || elements.count == 1 else { throw BighelpCardValidationError.invalid } + } +} diff --git a/Bighelp/Spaces/SpacePanelView.swift b/Bighelp/Spaces/SpacePanelView.swift new file mode 100644 index 00000000..732a2595 --- /dev/null +++ b/Bighelp/Spaces/SpacePanelView.swift @@ -0,0 +1,395 @@ +import SwiftUI + +/// How much of a card a panel shows (`BighelpCardRenderer` reads it): fewer list items, table rows +/// and columns, a shorter chart and fewer lines of text, so a card made for a chat fits a panel. +/// Nil in chats, where cards draw as they always have. +struct BighelpCardLimits: Equatable, Sendable { + var maxListItems: Int + var maxTableRows: Int + var maxTableColumns: Int + var chartHeight: CGFloat + var maxTextLines: Int + /// The panel's header already names the space, so the root card's own title isn't drawn again. + var omitsRootTitle: Bool + + static func panel(_ size: SpaceSize) -> Self { + switch size { + case .small: Self(maxListItems: 3, maxTableRows: 3, maxTableColumns: 3, chartHeight: 48, maxTextLines: 2, + omitsRootTitle: true) + case .wide: Self(maxListItems: 3, maxTableRows: 3, maxTableColumns: 5, chartHeight: 64, maxTextLines: 2, + omitsRootTitle: true) + case .tall: Self(maxListItems: 8, maxTableRows: 8, maxTableColumns: 8, chartHeight: 140, maxTextLines: 4, + omitsRootTitle: true) + } + } +} + +private struct BighelpCardLimitsKey: EnvironmentKey { + static let defaultValue: BighelpCardLimits? = nil +} + +extension EnvironmentValues { + var bighelpCardLimits: BighelpCardLimits? { + get { self[BighelpCardLimitsKey.self] } + set { self[BighelpCardLimitsKey.self] = newValue } + } +} + +/// What Try again on a stopped panel is doing, and what the computer said last. +enum SpacePanelRetry: Equatable, Sendable { + case idle + case running + /// Update now ran less than a minute ago (`refresh_too_soon`). + case tooSoon + /// The routine ran and failed (`routine_failed`). + case failed + + /// Only the two answers the person can act on get words; anything else offers Try again again. + static func after(_ error: SpacesError) -> Self { + switch error { + case .tooSoon: .tooSoon + case .routineFailed: .failed + default: .idle + } + } +} + +/// A panel's one footer line, from what the computer said about the space. Never the time the +/// panel was drawn: "Updated" is the space's own `updatedAt`. +enum SpacePanelFooter: Equatable, Sendable { + /// The card isn't read yet: a still placeholder. + case loading + /// The computer sent a card this app can't draw. + case unreadable + /// Its computer isn't connected: the last card stays above. + case notConnected + case updated(Date?, usesAI: Bool) + /// The routine isn't running: Try again, and what it did. + case stopped(SpacePanelRetry) + /// The person paused its routine in Scheduled tasks: only they resume it, there. No Try again. + case paused + /// The bot changed its script after the space was added: the bot drafts it again and the + /// person adds it again (the draft card). No Try again, which can't fix it. + case scriptChanged + /// A draft's preview in the chat: nothing has updated it yet. + case none + + static func state(for item: TodaySpace, size: SpaceSize, retry: SpacePanelRetry = .idle) -> Self { + state(space: item.space, size: size, isConnected: item.isConnected, retry: retry) + } + + static func state(space: Space, size: SpaceSize, isConnected: Bool, retry: SpacePanelRetry = .idle) -> Self { + if !isConnected { return .notConnected } + if space.card(for: size) == nil { return space.cardUnreadable ? .unreadable : .loading } + if space.state == .draft { return .none } + if space.isStopped { + if space.isScriptChanged { return .scriptChanged } + if space.isPaused { return .paused } + return .stopped(retry) + } + return .updated(space.updatedAt, usesAI: space.routine.usesAI) + } +} + +/// "2:14 PM" for today, "Nov 10" for another day this year, "Nov 10, 2025" before that. +enum SpacePanelTime { + static func text(_ date: Date, now: Date, calendar: Calendar = .current, locale: Locale = .current) -> String { + let zone = calendar.timeZone + if calendar.isDate(date, inSameDayAs: now) { + return date.formatted(Date.FormatStyle(date: .omitted, time: .shortened, locale: locale, + calendar: calendar, timeZone: zone)) + } + var style = Date.FormatStyle(locale: locale, calendar: calendar, timeZone: zone).month(.abbreviated).day() + if calendar.component(.year, from: date) != calendar.component(.year, from: now) { style = style.year() } + return date.formatted(style) + } +} + +/// Runs a panel's Try again and keeps its answer. Owned by the panel's `@State`: a panel that +/// goes away takes it with it, and a late answer then changes nothing. +@MainActor +@Observable +final class SpacePanelRetryModel { + private(set) var state: SpacePanelRetry = .idle + @ObservationIgnored private var running: Task? + + /// The action throws `SpacesError`. Its type says plain `throws`: a view can't keep a typed-throws + /// closure before iOS 18 (the runtime has no type for it). + func run(_ action: @escaping @MainActor () async throws -> SpaceRefreshRun) { + guard running == nil else { return } + state = .running + running = Task { [weak self] in + let next: SpacePanelRetry + do { + // A paused routine ran nothing (`.paused`): the space it came back with says so. + _ = try await action() + next = .idle + } catch { + next = SpacePanelRetry.after(error as? SpacesError ?? .other(code: nil)) + } + guard let self else { return } + self.state = next + self.running = nil + } + } +} + +/// One space on Today: its title and bot, its card at the panel's size in a fixed frame, and one +/// footer line. A tap opens its page. The grid around it (`TodayPanelCell`) draws the surface and +/// the long-press menu; the chat's draft card shows the same view as its preview. +struct SpacePanelView: View { + let space: Space + let size: SpaceSize + /// Small, beside the title. Nil leaves it out (a preview in the bot's own chat). + var botName: String? = nil + var isConnected = true + /// Opens the page. Nil for a space without one, and for a preview. + var onOpen: (() -> Void)? = nil + /// Try again on a stopped panel: Update now on its computer. Nil hides it. + var runNow: (@MainActor () async throws -> SpaceRefreshRun)? = nil + + @State private var retry = SpacePanelRetryModel() + @BighelpThemeReader private var theme + + /// The card's room at each size; header and footer come on top. + static func cardHeight(_ size: SpaceSize) -> CGFloat { + BighelpTokens.scaled(size == .tall ? 260 : 96) + } + + private var footerState: SpacePanelFooter { + SpacePanelFooter.state(space: space, size: size, isConnected: isConnected, retry: retry.state) + } + + var body: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + if let onOpen { + Button(action: onOpen) { content } + .bighelpPlainButtonStyle(.rounded(BighelpTokens.radius12)) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(verbatim: space.title)) + .accessibilityValue(Text(verbatim: space.card(for: size)?.spokenSummary ?? "")) + .accessibilityAddTraits(.isButton) + .accessibilityIdentifier("today.space.\(space.spaceID).open") + } else { + content + } + SpacePanelFooterLine(state: footerState, canRetry: runNow != nil) { + if let runNow { retry.run(runNow) } + } + } + .frame(maxWidth: .infinity, alignment: .topLeading) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.space.\(space.spaceID)") + } + + private var content: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + header + cardArea + } + .contentShape(.rect) + } + + private var header: some View { + ViewThatFits(in: .horizontal) { + HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space8) { + title + Spacer(minLength: BighelpTokens.space4) + bot + } + VStack(alignment: .leading, spacing: 2) { + title + bot + } + } + } + + private var title: some View { + Text(verbatim: space.title) + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .lineLimit(2) + } + + @ViewBuilder + private var bot: some View { + if let botName { + Text(verbatim: botName) + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1) + } + } + + private var cardArea: some View { + let height = Self.cardHeight(size) + return ZStack(alignment: .topLeading) { + if let card = space.card(for: size) { + // The card takes the panel's height and shows the rows and lines that fit, each whole + // (`BighelpCardWholeRows`): a line cut or faded at the edge reads as a broken panel. + BighelpCardRenderer(card: card) + .environment(\.bighelpCardLimits, .panel(size)) + .frame(maxWidth: .infinity, maxHeight: height, alignment: .topLeading) + } else if space.cardUnreadable { + Image(systemName: "rectangle.dashed") + .font(.bighelp(.title2)) + .foregroundStyle(theme.tertiaryText) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .accessibilityHidden(true) + } else { + SpacePanelPlaceholder() + } + } + .frame(maxWidth: .infinity, minHeight: height, maxHeight: height, alignment: .topLeading) + .clipped() + } +} + +/// A still block where the card will be. Never animated. +struct SpacePanelPlaceholder: View { + @BighelpThemeReader private var theme + + var body: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + RoundedRectangle(cornerRadius: 6, style: .continuous).frame(width: 64, height: 22) + RoundedRectangle(cornerRadius: 5, style: .continuous).frame(maxWidth: 140).frame(height: 12) + } + .foregroundStyle(theme.separator.opacity(0.6)) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .accessibilityHidden(true) + } +} + +/// The footer: one status and, on a stopped panel, Try again. It wraps under itself at large text. +private struct SpacePanelFooterLine: View { + let state: SpacePanelFooter + let canRetry: Bool + let onRetry: () -> Void + @BighelpThemeReader private var theme + + var body: some View { + switch state { + case .none: + EmptyView() + case .loading: + Capsule() + .fill(theme.separator.opacity(0.6)) + .frame(width: 80, height: 10) + .accessibilityHidden(true) + case .unreadable: + status(Text("Can't show this"), symbol: "exclamationmark.triangle") + case .notConnected: + status(Text("Not connected"), symbol: "bolt.horizontal.circle") + case .updated(let date, let usesAI): + ViewThatFits(in: .horizontal) { + HStack(spacing: BighelpTokens.space8) { updated(date); badge(usesAI) } + VStack(alignment: .leading, spacing: BighelpTokens.space4) { updated(date); badge(usesAI) } + } + case .paused: + status(Text("Paused in Scheduled tasks"), symbol: "pause.circle") + case .scriptChanged: + status(Text("Stopped: its script changed"), symbol: "exclamationmark.circle") + case .stopped(let retry): + ViewThatFits(in: .horizontal) { + HStack(spacing: BighelpTokens.space8) { + stoppedText(retry) + Spacer(minLength: 0) + retryControl(retry) + } + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + stoppedText(retry) + retryControl(retry) + } + } + } + } + + @ViewBuilder + private func updated(_ date: Date?) -> some View { + if let date { + Text("Updated \(SpacePanelTime.text(date, now: Date()))") + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("today.space.updated") + } + } + + @ViewBuilder + private func badge(_ usesAI: Bool) -> some View { + if usesAI { + Text("Uses AI") + .font(.bighelp(.caption2, weight: .semibold)) + .foregroundStyle(theme.secondaryText) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .overlay { Capsule().strokeBorder(theme.border) } + .accessibilityIdentifier("today.space.uses-ai") + } + } + + private func stoppedText(_ retry: SpacePanelRetry) -> some View { + let text: Text = switch retry { + case .idle, .running: Text("Stopped updating") + case .tooSoon: Text("Try again in a minute") + case .failed: Text("Its update failed") + } + return status(text, symbol: "pause.circle") + } + + @ViewBuilder + private func retryControl(_ retry: SpacePanelRetry) -> some View { + if retry == .running { + Text("Updating…") + .font(.bighelp(.caption, weight: .semibold)) + .foregroundStyle(theme.tertiaryText) + .frame(minHeight: BighelpTokens.hitTarget) + } else if canRetry { + Button(action: onRetry) { + Text("Try again") + .font(.bighelp(.caption, weight: .semibold)) + .foregroundStyle(theme.action) + .padding(.horizontal, BighelpTokens.space4) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("today.space.try-again") + } + } + + private func status(_ text: Text, symbol: String) -> some View { + Label { text } icon: { Image(systemName: symbol) } + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("today.space.status") + } +} + +/// One choice in a row of chips (sizes, examples): a capsule, filled while it's picked. +struct SpacesChip: View { + let title: Text + var isOn = false + let identifier: String + let action: () -> Void + @BighelpThemeReader private var theme + + var body: some View { + Button(action: action) { + title + .lineLimit(1) + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(isOn ? theme.actionForeground : theme.primaryText) + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: BighelpTokens.scaled(34)) + .background(isOn ? theme.action : theme.surface, in: .capsule) + .overlay { Capsule().strokeBorder(isOn ? .clear : theme.border) } + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle(.capsule) + .accessibilityAddTraits(isOn ? .isSelected : []) + .accessibilityIdentifier(identifier) + } +} diff --git a/Bighelp/Spaces/SpacesClient.swift b/Bighelp/Spaces/SpacesClient.swift new file mode 100644 index 00000000..e1324366 --- /dev/null +++ b/Bighelp/Spaces/SpacesClient.swift @@ -0,0 +1,234 @@ +import Foundation +import OSLog + +/// Why a space didn't load or change, as Today and the draft card act on it. +enum SpacesError: Error, Equatable, Sendable { + /// The computer's plugin context doesn't list `native-spaces-v1`: "Update the plugin on ". + case needsPluginUpdate + /// Not this bot's space, or the bot or the space is gone. + case notFound + /// The bot changed the draft after the card was drawn; nil when the computer couldn't be asked. + case draftChanged(revision: Int?) + /// Add on a space that is live with nothing waiting. + case notDraft + /// The bot has as many live spaces as it can. + case full + /// Update now again too soon; seconds to wait when the computer said. + case tooSoon(retryAfter: Int?) + /// The computer's Hermes can't run scheduled tasks right now. From delete: the space is off + /// Today already, and the same `operationId` finishes the delete later. + case schedulesUnavailable + /// Add found the draft's script gone, or it failed the computer's check (`invalid_request`). + case scriptMissing + /// Update now ran and failed; the space as it is now, when it could be read. + case routineFailed(Space?) + /// No answer, or no connection. Nothing is known to have changed. + case unreachable + /// Refused for another reason (a fixed code, or nil for an answer that didn't read). + case other(code: String?) + + /// The computer said no for good: undo what the phone showed. + var isDefinite: Bool { + switch self { + case .unreachable: false + default: true + } + } + + init(_ error: any Error) { + if let error = error as? SpacesError { self = error; return } + guard let error = error as? WorkspaceClientError else { self = .unreachable; return } + switch error { + case .unavailable(.unsupportedOperation), .unavailable(.pluginRequired): + // Only the client's context check says the feature is missing; this is a route + // that isn't reachable now. + self = .unreachable + case .rejected(let code, _): + switch code ?? "" { + case "space_not_found", "profile_not_found": self = .notFound + case "draft_changed": self = .draftChanged(revision: nil) + case "space_not_draft": self = .notDraft + case "spaces_full": self = .full + case "refresh_too_soon": self = .tooSoon(retryAfter: nil) + case "schedules_unavailable": self = .schedulesUnavailable + case "routine_failed": self = .routineFailed(nil) + // The plugin turned the feature off after the context listed it: a reload says. + case "spaces_unavailable": self = .unreachable + default: self = .other(code: code) + } + case .capacityExceeded: self = .other(code: "too_large") + case .invalidRequest: self = .other(code: "invalid_request") + case .invalidResponse: self = .other(code: nil) + case .unavailable, .ownerChanged, .authenticationRequired, .transportUnavailable, .conflict, .outcomeUnknown: + self = .unreachable + } + } +} + +/// One computer's `spaces` routes. +@MainActor +protocol SpacesClient: AnyObject, Sendable { + func perform(_ operation: SpacesOperation, + payload: [String: BighelpJSONValue]) async throws -> [String: BighelpJSONValue] +} + +/// The plugin's routes over one computer's connection, read again on every call (bighelp +/// reconnects every time it comes back). +@MainActor +final class DirectHermesSpacesClient: SpacesClient { + private let workspace: @MainActor () -> (any WorkspaceOperationPerforming)? + + init(workspace: @escaping @MainActor () -> (any WorkspaceOperationPerforming)?) { + self.workspace = workspace + } + + func perform(_ operation: SpacesOperation, + payload: [String: BighelpJSONValue]) async throws -> [String: BighelpJSONValue] { + guard let workspace = workspace(), let owner = workspace.owner else { + throw WorkspaceClientError.transportUnavailable + } + var reloadedContext = false + var askedAgain = false + while true { + do { + return try await workspace.perform(operation.workspaceOperation, payload: payload, owner: owner) + } catch WorkspaceClientError.conflict where !reloadedContext { + // The plugin's context changed (412): the next call loads it again. Once. + reloadedContext = true + } catch WorkspaceClientError.outcomeUnknown where operation.isMutation && !askedAgain { + // The same payload carries the same `operationId`: done once, the computer answers + // with what it did; not done, it does it now. + askedAgain = true + } catch WorkspaceClientError.unavailable(.unsupportedOperation), + WorkspaceClientError.unavailable(.pluginRequired) { + if await Self.lacksFeature(workspace, owner: owner) { throw SpacesError.needsPluginUpdate } + throw WorkspaceClientError.transportUnavailable + } + } + } + + /// Only the plugin's own context says the feature isn't there. A route refused while the + /// computer reconnects, or a context that didn't load, never does. + private static func lacksFeature(_ workspace: any WorkspaceOperationPerforming, owner: WorkspaceOwner) async -> Bool { + do { + let context = try await workspace.perform(.nativeContext, payload: [:], owner: owner) + guard let features = context["features"]?.array else { return false } + return !features.contains(.string(SpacesWire.feature)) + } catch WorkspaceClientError.unavailable(.pluginRequired) { + // No bighelp plugin answers on this computer at all. + return true + } catch { + return false + } + } +} + +/// Typed calls over a client: the payloads docs/SPACES.md names and lenient reading of the answers. +@MainActor +struct SpacesAPI: Sendable { + static let log = Logger(subsystem: "app.loopdy.mobile", category: "Spaces") + + let client: any SpacesClient + + init(client: any SpacesClient) { + self.client = client + } + + private func call(_ operation: SpacesOperation, + _ payload: [String: BighelpJSONValue]) async throws(SpacesError) -> [String: BighelpJSONValue] { + do { return try await client.perform(operation, payload: payload) } catch { + // The transport's own error, before it's folded into SpacesError. Codes only. + Self.log.error("spaces \(operation.rawValue, privacy: .public) failed: \(String(describing: error), privacy: .public)") + throw SpacesError(error) + } + } + + private func space(in reply: [String: BighelpJSONValue], agentID: String, spaceID: String) throws(SpacesError) -> Space { + guard let object = reply["space"]?.object, let space = Space(json: object), + space.agentID == agentID, space.spaceID == spaceID else { throw .other(code: nil) } + return space + } + + /// The live spaces of up to 64 bots. `known` (`agentId/spaceId` → `cardsSha256`) lets the + /// computer leave out cards the phone has. + func list(agentIDs: [String], known: [String: String]) async throws(SpacesError) -> SpacesList { + let agents = Array(agentIDs.filter(SpacesWire.isAgentID).prefix(SpacesWire.maximumAgentsPerList)) + guard !agents.isEmpty else { return SpacesList() } + let names = Set(agents) + let known = known.filter { key, hash in + hash.utf8.count == 64 && key.split(separator: "/").first.map { names.contains(String($0)) } == true + }.sorted { $0.key < $1.key }.prefix(SpacesWire.maximumKnownCards) + let reply = try await call(.list, [ + "agentIds": .array(agents.map(BighelpJSONValue.string)), + "known": .object(Dictionary(uniqueKeysWithValues: known.map { ($0.key, BighelpJSONValue.string($0.value)) })), + ]) + guard reply["spaces"]?.array != nil else { throw .other(code: nil) } + var list = SpacesList(json: reply) + // Only the bots asked about, so another bot's answer can't replace their spaces. + list.spaces.removeAll { !names.contains($0.agentID) } + return list + } + + /// One space with its cards; drafts too. + func space(agentID: String, spaceID: String) async throws(SpacesError) -> Space { + let reply = try await call(.get, ["agentId": .string(agentID), "spaceId": .string(spaceID)]) + return try space(in: reply, agentID: agentID, spaceID: spaceID) + } + + /// Turns a draft (or a live space's waiting routine change) into a live space at `draftRevision`. + func add(agentID: String, spaceID: String, draftRevision: Int, size: SpaceSize? = nil, position: Double? = nil, + operationID: String = SpacesWire.newOperationID()) async throws(SpacesError) -> Space { + var payload: [String: BighelpJSONValue] = [ + "agentId": .string(agentID), "spaceId": .string(spaceID), + "draftRevision": .integer(draftRevision), "operationId": .string(operationID), + ] + payload["size"] = size.map { .string($0.rawValue) } + payload["position"] = position.map(BighelpJSONValue.number) + do throws(SpacesError) { + return try space(in: try await call(.add, payload), agentID: agentID, spaceID: spaceID) + } catch .draftChanged { + // The refusal's revision doesn't reach the app; the space itself says it. + throw .draftChanged(revision: try? await space(agentID: agentID, spaceID: spaceID).revision) + } catch .other(let code) where code == "invalid_request" { + // This app's payload always fits, and its `operationId` is new: the script is the problem. + throw .scriptMissing + } + } + + func update(agentID: String, spaceID: String, changes: SpaceChanges, + operationID: String = SpacesWire.newOperationID()) async throws(SpacesError) -> Space { + let reply = try await call(.update, [ + "agentId": .string(agentID), "spaceId": .string(spaceID), + "operationId": .string(operationID), "changes": .object(changes.payload), + ]) + return try space(in: reply, agentID: agentID, spaceID: spaceID) + } + + /// Runs the routine now: a script answers with its new state, an AI routine is queued, and a + /// paused AI routine runs nothing (`.paused`). + func refresh(agentID: String, spaceID: String, + operationID: String = SpacesWire.newOperationID()) async throws(SpacesError) -> (space: Space, ran: SpaceRefreshRun) { + do throws(SpacesError) { + let reply = try await call(.refresh, [ + "agentId": .string(agentID), "spaceId": .string(spaceID), "operationId": .string(operationID), + ]) + let ran = reply["ran"]?.string.flatMap(SpaceRefreshRun.init(rawValue:)) ?? .queued + return (try space(in: reply, agentID: agentID, spaceID: spaceID), ran) + } catch .routineFailed { + throw .routineFailed(try? await space(agentID: agentID, spaceID: spaceID)) + } + } + + /// Stops the routine and removes the space and its page. True when it was there. A + /// `schedulesUnavailable` refusal means the space is off Today and the delete isn't finished: + /// call again with the same `operationID`. + @discardableResult + func delete(agentID: String, spaceID: String, + operationID: String = SpacesWire.newOperationID()) async throws(SpacesError) -> Bool { + let reply = try await call(.delete, [ + "agentId": .string(agentID), "spaceId": .string(spaceID), "operationId": .string(operationID), + ]) + guard reply["deleted"]?.boolean == true else { throw .other(code: nil) } + return reply["existed"]?.boolean ?? true + } +} diff --git a/Bighelp/Spaces/SpacesFixture.swift b/Bighelp/Spaces/SpacesFixture.swift new file mode 100644 index 00000000..ffaa3017 --- /dev/null +++ b/Bighelp/Spaces/SpacesFixture.swift @@ -0,0 +1,148 @@ +#if DEBUG +import SwiftUI + +/// Spaces on made-up data: the demo computer (`DemoSpacesClient`) with its three live spaces and +/// one draft, its bots, and the draft's chat card. +@MainActor +enum SpacesFixture { + /// The demo computer as Today reads it. + static var demoComputer: SpacesComputer { + SpacesComputer(hostKey: "demo", scope: "spaces-fixture", name: "Demo computer", + api: SpacesAPI(client: DemoSpacesClient.shared), + bots: [SpacesBot(id: "finance", name: "Avery Park"), SpacesBot(id: "travel", name: "Mina Shah"), + SpacesBot(id: "home", name: "Jordan Lee")], + isCurrent: true) + } + + /// The demo draft as `bighelp_draft_space` delivers it: one `space_draft` element, alone in its card. + nonisolated static var spendingDraft: SpaceDraftCard { + SpaceDraftCard(spaceID: DemoSpacesClient.spendingDraftID, title: "Spending", + description: "This month's spending against the budget.", updates: "Every 2 hours", + usesAI: false, revision: 1) + } + + nonisolated static func document(_ draft: SpaceDraftCard) -> [String: BighelpJSONValue] { + var document: [String: BighelpJSONValue] = [ + "schema": .string("loopdy.card"), "version": .integer(1), "title": .string(draft.title), + "spoken_summary": .string("A space to add to Today: \(draft.title). \(draft.updates), without AI."), + "data_sources": .array([]), "root": .string("space"), + "elements": .object(["space": .object([ + "type": .string(SpacesWire.type), + "props": .object(["space_id": .string(draft.spaceID), "description": .string(draft.description), + "updates": .string(draft.updates), "uses_ai": .boolean(draft.usesAI), + "revision": .integer(draft.revision)]), + "children": .array([]), + ])]), + ] + let hash = SpacesWire.sha256(draft.spaceID + "/\(draft.revision)") + document["content_hash"] = .string(hash) + document["card_id"] = .string(String(hash.prefix(32))) + document["origin"] = .string("live") + document["created_at"] = .string("2026-11-12T12:00:00Z") + return document + } + + /// The card fenced the way hosts deliver cards in a reply. + nonisolated static func fenced(_ draft: SpaceDraftCard) -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let json = (try? encoder.encode(BighelpJSONValue.object(document(draft)))) ?? Data() + return "```\(ChatCardMessageProjection.fenceLanguage)\n" + String(decoding: json, as: UTF8.self) + "\n```" + } +} + +extension ConversationFixtures { + /// `-test-spaces`: the person asks the finance bot for a space and gets its draft card. + static var spacesPreview: SessionRecord { + let agent = TimelineSender.agent(id: "finance", snapshot: .init(name: "Avery Park")) + let person = TimelineSender.user(snapshot: .init(name: "You")) + let items = [ + TimelineItem(id: "spaces-q1", role: .human, sender: person, + content: .message("Make me a space for Today: my spending this month."), + metadata: .init(sourceOrder: 1)), + TimelineItem(id: "spaces-draft", role: .assistant, sender: agent, + content: .message("Here it is. A script updates it every 2 hours, with no AI. " + + "Add it when it looks right.\n\n" + + SpacesFixture.fenced(SpacesFixture.spendingDraft)), + metadata: .init(sourceOrder: 10)), + ] + return SessionRecord(id: "demo-finance", kind: .direct, agentIDs: ["finance"], title: "Spending space", + items: items, hasAcceptedMessage: true) + } +} + +/// `-test-spaces-today`: Today's grid with the demo computer's spaces through `SpacesTodayBridge`, +/// before the shell shows them. Every run starts from the demo's own sizes and order. +struct SpacesTodayFixture: View { + static let launchArgument = "-test-spaces-today" + static var isRequested: Bool { ProcessInfo.processInfo.arguments.contains(launchArgument) } + /// Emptied once a run, so every run starts from the computer's sizes and order. + private static let layoutDefaults: UserDefaults = { + let suite = "bighelp.spaces.fixture" + UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) + return UserDefaults(suiteName: suite) ?? .standard + }() + + @State private var model = TodaySpacesModel(computers: { [SpacesFixture.demoComputer] }, + current: { SpacesFixture.demoComputer }, + pages: { _ in HTMLAppsAPI(client: DemoHTMLAppsClient.shared) }, + cacheFolder: nil) + @State private var layout = TodayPanelLayoutStore(defaults: SpacesTodayFixture.layoutDefaults) + @State private var isEditing = false + @State private var deleting: TodayPanelDescriptor? + @State private var openPage: TodaySpace? + @Environment(\.scenePhase) private var scenePhase + + private var bridge: SpacesTodayBridge { + SpacesTodayBridge(model: model) { openPage = $0 } + } + + var body: some View { + TodayView(context: context) + // The shell does the same where it builds Today. + .onAppear { layout.ownedChanges = bridge.ownedChanges } + .spacesDeleteConfirmation($deleting, bridge: bridge, layout: layout) + .task(id: scenePhase == .active) { + guard scenePhase == .active else { return } + await model.watch() + } + .bighelpFullScreenCover(item: $openPage) { item in + if let page = item.space.page { + // A space's page never sends a message. + HTMLAppScreen(app: page.card(title: item.space.title, description: item.space.description), + agentID: item.space.agentID, connection: model.pageConnection(item), + send: { _ in throw SpacesError.other(code: nil) }) + } + } + } + + private var context: TodayContext { + let bridge = bridge + var context = TodayContext( + header: AnyView(header), + needsYou: nil, + onOpenNeedsYou: {}, + panels: bridge.descriptors(from: model.items), + makePanel: { bridge.panel(for: $0) }, + layout: layout, + isEditing: $isEditing, + onDeletePanel: { deleting = $0 }) + context.aboveGrid = AnyView(SpacesTodayNotes(notes: bridge.notes)) + context.belowGrid = isEditing ? nil : AnyView( + TodayCreateBox(bots: SpacesFixture.demoComputer.bots, primaryBotID: "finance") { _, _ in }) + context.panelMenu = { bridge.menuItems(for: $0) } + return context + } + + private var header: some View { + HStack { + Text("Today") + .font(.bighelp(.title2, weight: .bold)) + Spacer() + TodayEditButton(isEditing: $isEditing) + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space8) + } +} +#endif diff --git a/Bighelp/Spaces/SpacesHost.swift b/Bighelp/Spaces/SpacesHost.swift new file mode 100644 index 00000000..16ee1e06 --- /dev/null +++ b/Bighelp/Spaces/SpacesHost.swift @@ -0,0 +1,40 @@ +import Foundation + +/// A bot on a computer, as Today names it. +struct SpacesBot: Equatable, Sendable { + /// Its `agentId` (Hermes' profile id). + let id: String + let name: String +} + +/// One of the person's computers, as Today reads it: its cache scope (the key its spaces are kept +/// by), its routes while it's connected, and its bots. +struct SpacesComputer: Sendable { + /// The host registry's id, or "demo". + let hostKey: String + /// `WorkspaceAuthority.cacheScopeID`: the same across reconnects, never the owner. + let scope: String + let name: String + /// Nil while it isn't connected: Today shows its last panels. + let api: SpacesAPI? + /// The bots whose spaces to read. Empty while they aren't known yet: nothing is read. + let bots: [SpacesBot] + /// The computer in use, where chats (and their draft cards) are. + let isCurrent: Bool +} + +/// Where Spaces find the person's computers. Set up by the app (`BighelpApp`); empty until then. +@MainActor +enum SpacesHost { + /// The computer in use: a chat's draft card adds its space here. + static var current: @MainActor () -> SpacesComputer? = { nil } + /// Every computer Today shows, the one in use first: connected ones with their routes and bots, + /// the others with their saved scope only. + static var computers: @MainActor () -> [SpacesComputer] = { [] } + /// The `hostKey` of every computer the app has, whether or not it can be read now. Nil when the + /// app can't say: only the computers listed above then count. + static var hostKeys: @MainActor () -> Set? = { nil } + /// The HTML app routes of the computer with this cache scope, where a space's page is; nil + /// while it isn't connected. + static var pages: @MainActor (_ scope: String) -> HTMLAppsAPI? = { _ in nil } +} diff --git a/Bighelp/Spaces/SpacesStore.swift b/Bighelp/Spaces/SpacesStore.swift new file mode 100644 index 00000000..908287df --- /dev/null +++ b/Bighelp/Spaces/SpacesStore.swift @@ -0,0 +1,487 @@ +import Foundation +import Observation + +/// How one computer's spaces read last. +enum SpacesPhase: Equatable, Sendable { + /// Not read yet on this run. What the phone kept may show meanwhile. + case loading + case ready + /// The computer's plugin context doesn't list `native-spaces-v1`. + case needsPluginUpdate + /// Not connected, or the last read failed: what was read before stays. + case unreachable +} + +/// A change the computer hasn't confirmed: sent again, with the same `operationId`, until it answers. +/// Any change on top of it is a new request with a new `operationId` (`SpacesStore.stage`). +struct SpacesPendingChange: Codable, Equatable, Sendable { + var changes: SpaceChanges + var operationID: String +} + +/// A delete the computer hasn't finished: no answer, not connected, or `schedules_unavailable` (the +/// space is off Today there, and Hermes still has its task). The space stays off Today on this phone, +/// and the same request goes again at each read until the computer answers it. +struct SpacesPendingDelete: Codable, Equatable, Sendable { + let agentID: String + let spaceID: String + let operationID: String +} + +/// The phone's copy of one computer's spaces (Caches), so Today draws at once and a computer that +/// isn't connected shows its last panels. +struct SpacesCacheFile: Codable, Sendable { + static let currentVersion = 1 + + var version = Self.currentVersion + var scope: String + var lastLoaded: Date? + /// Each space in the route's own shape (`Space.json`), read back as an answer is. + var spaces: [[String: BighelpJSONValue]] + var pending: [String: SpacesPendingChange] + /// Optional, so a copy written before deletes waited reads too. + var deleting: [String: SpacesPendingDelete]? + + static func url(scope: String, folder: URL) -> URL { + folder.appendingPathComponent(SpacesWire.sha256(scope) + ".json") + } + + /// Nil for a missing, oversized, unreadable or other computer's file. + static func read(scope: String, folder: URL) -> SpacesCacheFile? { + let url = url(scope: scope, folder: folder) + guard let size = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.size] as? Int, + size <= SpacesWire.maximumCacheBytes, + let data = try? Data(contentsOf: url), + let file = try? JSONDecoder().decode(SpacesCacheFile.self, from: data), + file.version == currentVersion, file.scope == scope else { return nil } + return file + } + + /// Removes one computer's copy. + static func erase(scope: String, folder: URL) { + try? FileManager.default.removeItem(at: url(scope: scope, folder: folder)) + } + + /// Writes the copy whole or not at all. A copy too big for the limit keeps its spaces without + /// their cards, which the next read brings back. + static func write(_ file: SpacesCacheFile, folder: URL) { + let encoder = JSONEncoder() + guard var data = try? encoder.encode(file) else { return } + if data.count > SpacesWire.maximumCacheBytes { + var lighter = file + lighter.spaces = file.spaces.map { space in + space.filter { !["card", "sizes", "cardUnreadable"].contains($0.key) } + } + guard let smaller = try? encoder.encode(lighter), smaller.count <= SpacesWire.maximumCacheBytes else { return } + data = smaller + } + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try? data.write(to: url(scope: file.scope, folder: folder), options: .atomic) + } +} + +/// One computer's spaces, kept by its cache scope (`WorkspaceAuthority.cacheScopeID`): a reconnect is +/// a new owner with the same scope, and the same store. A computer that isn't connected keeps what +/// was read last. Changes the person makes show at once and wait for the computer's word: a definite +/// refusal undoes them, no answer keeps them for the next time the computer answers. +@MainActor +@Observable +final class SpacesStore { + nonisolated static let defaultCacheFolder = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + .appendingPathComponent("BighelpSpaces", isDirectory: true) + + let scope: String + private(set) var hostKey: String + /// What the computer said, with this phone's unconfirmed changes on top. Drafts too, when one + /// was added from a chat before the computer answered. + private(set) var spaces: [Space] = [] + private(set) var phase: SpacesPhase = .loading + /// When a read last worked; nil before any did. + private(set) var lastLoaded: Date? + /// Changes the computer hasn't confirmed, by space key. + private(set) var pending: [String: SpacesPendingChange] = [:] + /// Deletes the computer hasn't finished, by space key. Those spaces never show meanwhile. + private(set) var deleting: [String: SpacesPendingDelete] = [:] + + @ObservationIgnored private var confirmed: [Space] = [] + /// A newer read makes an older one's answer moot. + @ObservationIgnored private var readGeneration = 0 + /// Counts what mutations did to `confirmed`, so a read that began before keeps their result. + @ObservationIgnored private var changeCount = 0 + @ObservationIgnored private var changedAt: [String: Int] = [:] + /// Mutation answers land in the order they were sent, per space. + @ObservationIgnored private var sendCount = 0 + @ObservationIgnored private var acceptedSend: [String: Int] = [:] + @ObservationIgnored private var cacheWrite: Task? + /// Space keys with an update request on its way: one at a time per space. + @ObservationIgnored private var sending: Set = [] + @ObservationIgnored private var sendWaiters: [String: [CheckedContinuation]] = [:] + /// Set once the computer is removed: nothing is written to its copy on disk again. + @ObservationIgnored private var isRetired = false + @ObservationIgnored private let cacheFolder: URL? + @ObservationIgnored private let clock: @MainActor () -> Date + + init(scope: String, hostKey: String, cacheFolder: URL? = SpacesStore.defaultCacheFolder, + clock: @escaping @MainActor () -> Date = { Date() }) { + self.scope = scope + self.hostKey = hostKey + self.cacheFolder = cacheFolder + self.clock = clock + if let cacheFolder, let file = SpacesCacheFile.read(scope: scope, folder: cacheFolder) { + var seen = Set() + confirmed = file.spaces.compactMap { json in + guard let space = Space(json: json), seen.insert(space.key).inserted else { return nil } + return space + } + pending = file.pending.filter { seen.contains($0.key) && !$0.value.changes.isEmpty } + deleting = file.deleting ?? [:] + lastLoaded = file.lastLoaded + publish() + } + } + + /// `agentId/spaceId` → `cardsSha256` for every space whose cards the phone has. + var knownCards: [String: String] { + var known: [String: String] = [:] + for space in confirmed where space.holdsCards { + if let hash = space.cardsSHA256 { known[space.key] = hash } + } + return known + } + + /// The space as the computer last said, without this phone's unconfirmed changes. + func confirmedSpace(_ key: String) -> Space? { confirmed.first { $0.key == key } } + + // MARK: Reading + + /// Reads the computer's spaces for its bots. Not connected, or no bots known yet, the copy stays. + func load(_ computer: SpacesComputer) async { + hostKey = computer.hostKey + guard let api = computer.api else { + if phase != .needsPluginUpdate { phase = .unreachable } + return + } + var agentIDs: [String] = [] + for bot in computer.bots where SpacesWire.isAgentID(bot.id) && !agentIDs.contains(bot.id) { + agentIDs.append(bot.id) + } + guard !agentIDs.isEmpty else { return } + // Bots the phone holds spaces for are asked about too: one deleted on the computer is in no + // list any more, and only the computer saying it's gone takes its spaces off Today. + for space in confirmed where SpacesWire.isAgentID(space.agentID) && !agentIDs.contains(space.agentID) { + agentIDs.append(space.agentID) + } + readGeneration += 1 + let generation = readGeneration + let start = changeCount + func isCurrent() -> Bool { readGeneration == generation && !Task.isCancelled } + do throws(SpacesError) { + var list = SpacesList() + let known = knownCards + for first in stride(from: 0, to: agentIDs.count, by: SpacesWire.maximumAgentsPerList) { + let part = try await api.list( + agentIDs: Array(agentIDs[first..) -> [Space] { + let old = Dictionary(confirmed.map { ($0.key, $0) }, uniquingKeysWith: { first, _ in first }) + let kept = Set(list.agents.filter { $0.value.keepsSpaces }.keys) + func keepsOld(_ agentID: String) -> Bool { kept.contains(agentID) || !asked.contains(agentID) } + var read = list.spaces.filter { !keepsOld($0.agentID) }.map { $0.takingCards(from: old[$0.key]) } + read += confirmed.filter { keepsOld($0.agentID) } + return read + } + + /// Takes a read's spaces, except where a mutation answered (or a space was added or deleted + /// here) after the read began: those keep what they are now. + private func commit(_ read: [Space], readSince start: Int) { + let touched = Set(changedAt.filter { $0.value > start }.keys) + var next = read.filter { !touched.contains($0.key) } + next += confirmed.filter { touched.contains($0.key) } + // A delete the computer hasn't finished: the space may still be listed there. + next.removeAll { deleting[$0.key] != nil } + confirmed = next + // Changes the computer now has, or for spaces that are gone, are done. + pending = pending.filter { key, change in + guard let space = confirmed.first(where: { $0.key == key }) else { return false } + return !change.changes.isSatisfied(by: space) + } + publish() + } + + // MARK: Changing + + /// Puts a change on top of the space at once and keeps it until the computer confirms it. + /// False for a space this store doesn't have. + @discardableResult + func stage(_ changes: SpaceChanges, for key: String) -> Bool { + guard !changes.isEmpty, confirmed.contains(where: { $0.key == key }) else { return false } + let merged = (pending[key]?.changes ?? SpaceChanges()).merging(changes) + // A new operation: what the computer may have done for the last one is part of this one. + pending[key] = SpacesPendingChange(changes: merged, operationID: SpacesWire.newOperationID()) + publish() + saveCache() + return true + } + + /// Size, hidden or position: shown at once, then sent. Not connected, it waits for the next + /// read. Throws only when the computer refused it for good (and it was undone). + func change(_ key: String, _ changes: SpaceChanges, api: SpacesAPI?) async throws(SpacesError) { + guard stage(changes, for: key) else { throw .notFound } + guard let api else { return } + try await send(key, api: api) + } + + /// Sends the space's unconfirmed change. No answer keeps it for the next read. One request per + /// space at a time: a send that finds one on its way waits for it, then sends whatever is + /// pending by then (the person's last choice), so the computer never takes two changes to one + /// space in the wrong order. A change still waiting repeats with its own `operationId`. + func send(_ key: String, api: SpacesAPI) async throws(SpacesError) { + while sending.contains(key) { + await withCheckedContinuation { sendWaiters[key, default: []].append($0) } + } + sending.insert(key) + defer { + sending.remove(key) + for waiter in sendWaiters.removeValue(forKey: key) ?? [] { waiter.resume() } + } + guard let change = pending[key], let space = confirmed.first(where: { $0.key == key }) else { return } + sendCount += 1 + let stamp = sendCount + do throws(SpacesError) { + let answer = try await api.update(agentID: space.agentID, spaceID: space.spaceID, + changes: change.changes, operationID: change.operationID) + accept(answer, sent: stamp) + if pending[key]?.operationID == change.operationID { pending[key] = nil } + publish() + saveCache() + } catch .unreachable { + return + } catch { + if case .notFound = error { remove(key) } + // Undo what was refused; a change made since goes on its own way. + if pending[key]?.operationID == change.operationID { pending[key] = nil } + publish() + saveCache() + throw error + } + } + + private func sendPending(_ api: SpacesAPI) async { + for key in pending.keys.sorted() { + try? await send(key, api: api) + } + } + + /// Runs the space's routine now. A failed run's space shows as the computer says. + func runNow(_ key: String, api: SpacesAPI?) async throws(SpacesError) -> SpaceRefreshRun { + guard let api else { throw .unreachable } + guard let space = confirmed.first(where: { $0.key == key }) else { throw .notFound } + sendCount += 1 + let stamp = sendCount + do throws(SpacesError) { + let answer = try await api.refresh(agentID: space.agentID, spaceID: space.spaceID) + let space = await withCards(answer.space, api: api) + accept(space, sent: stamp) + publish() + saveCache() + return answer.ran + } catch .routineFailed(let failed) { + if let failed { + accept(failed, sent: stamp) + publish() + saveCache() + } + throw .routineFailed(failed) + } catch .notFound { + remove(key) + publish() + saveCache() + throw .notFound + } + } + + /// Takes the space off at once. A delete the computer hasn't finished (no answer, not connected, + /// or `schedules_unavailable`) keeps it off and goes again, as the same request, at each read. + /// Only a definite refusal brings it back, and throws. + func delete(_ key: String, api: SpacesAPI?) async throws(SpacesError) { + guard let index = confirmed.firstIndex(where: { $0.key == key }) else { return } + let space = confirmed[index] + let change = pending[key] + let request = SpacesPendingDelete(agentID: space.agentID, spaceID: space.spaceID, + operationID: SpacesWire.newOperationID()) + remove(key) + deleting[key] = request + publish() + saveCache() + guard let api else { return } + do throws(SpacesError) { + try await sendDelete(request, key: key, api: api) + } catch { + if !confirmed.contains(where: { $0.key == key }) { + confirmed.insert(space, at: min(index, confirmed.count)) + pending[key] = change + touch(key) + publish() + saveCache() + } + throw error + } + } + + /// One delete request. Finished or gone: forgotten. Not finished: kept for the next read. + /// Refused for good: forgotten, and thrown, so the space can come back. + private func sendDelete(_ request: SpacesPendingDelete, key: String, api: SpacesAPI) async throws(SpacesError) { + do throws(SpacesError) { + try await api.delete(agentID: request.agentID, spaceID: request.spaceID, operationID: request.operationID) + } catch .notFound { + // Gone already. + } catch .unreachable, .schedulesUnavailable { + return + } catch { + if deleting[key] == request { deleting[key] = nil } + saveCache() + throw error + } + if deleting[key] == request { deleting[key] = nil } + saveCache() + } + + private func sendDeletes(_ api: SpacesAPI) async { + for (key, request) in deleting.sorted(by: { $0.key < $1.key }) { + // A refusal is forgotten in `sendDelete`; the next read lists the space again. + try? await sendDelete(request, key: key, api: api) + } + } + + /// Adds a draft to Today. With the draft as `get` read it, it shows at once, and goes again + /// unless the computer says it's live. + func add(agentID: String, spaceID: String, draftRevision: Int, size: SpaceSize?, position: Double?, + preview: Space?, api: SpacesAPI?) async throws(SpacesError) -> Space { + guard let api else { throw .unreachable } + let key = Space.key(agentID: agentID, spaceID: spaceID) + var shown: Space? + if var preview, preview.key == key, !confirmed.contains(where: { $0.key == key }) { + preview.state = .live + if let size { preview.size = size } + if let position { preview.position = position } + confirmed.append(preview) + touch(key) + publish() + shown = preview + } + sendCount += 1 + let stamp = sendCount + do throws(SpacesError) { + let added = try await api.add(agentID: agentID, spaceID: spaceID, draftRevision: draftRevision, + size: size, position: position) + let answer = await withCards(added, api: api) + accept(answer, sent: stamp) + publish() + saveCache() + return answer + } catch { + // Real data only: a space the computer didn't confirm doesn't stay on Today. + if let shown, confirmed.first(where: { $0.key == key }) == shown { + remove(key) + publish() + } + throw error + } + } + + // MARK: Helpers + + /// A mutation's answer, unless a later one for the same space already landed. + private func accept(_ answer: Space, sent stamp: Int) { + // A late answer for a space being deleted never brings it back. + guard (acceptedSend[answer.key] ?? 0) < stamp, deleting[answer.key] == nil else { return } + acceptedSend[answer.key] = stamp + let current = confirmed.first { $0.key == answer.key } + let space = answer.takingCards(from: current) + if let index = confirmed.firstIndex(where: { $0.key == answer.key }) { + confirmed[index] = space + } else if space.state == .live { + confirmed.append(space) + } + touch(answer.key) + if let change = pending[answer.key], change.changes.isSatisfied(by: space) { pending[answer.key] = nil } + } + + /// The space with its cards, read with `get` when the answer left them out. + private func withCards(_ space: Space, api: SpacesAPI) async -> Space { + let space = space.takingCards(from: confirmed.first { $0.key == space.key }) + guard space.needsCards else { return space } + return (try? await api.space(agentID: space.agentID, spaceID: space.spaceID)) ?? space + } + + private func remove(_ key: String) { + confirmed.removeAll { $0.key == key } + pending[key] = nil + touch(key) + } + + private func touch(_ key: String) { + changeCount += 1 + changedAt[key] = changeCount + } + + private func publish() { + let shown = confirmed.map { space in pending[space.key]?.changes.applied(to: space) ?? space } + if shown != spaces { spaces = shown } + } + + /// Written off the main thread, one write after the other, so the newest copy is the one kept. + private func saveCache() { + guard let cacheFolder, !isRetired else { return } + let file = SpacesCacheFile(scope: scope, lastLoaded: lastLoaded, spaces: confirmed.map(\.json), pending: pending, + deleting: deleting) + let previous = cacheWrite + cacheWrite = Task.detached(priority: .utility) { + await previous?.value + SpacesCacheFile.write(file, folder: cacheFolder) + } + } + + /// The computer was removed: its copy on disk is erased by the caller, and nothing writes it again. + func retire() { + isRetired = true + } + + /// Waits for the copy on disk to be written, for tests. + func savedToDisk() async { + await cacheWrite?.value + } +} diff --git a/Bighelp/Spaces/SpacesTodayBridge.swift b/Bighelp/Spaces/SpacesTodayBridge.swift new file mode 100644 index 00000000..880c051b --- /dev/null +++ b/Bighelp/Spaces/SpacesTodayBridge.swift @@ -0,0 +1,244 @@ +import SwiftUI + +extension TodayPanelSize { + init(_ size: SpaceSize) { + switch size { + case .small: self = .small + case .wide: self = .wide + case .tall: self = .tall + } + } +} + +extension SpaceSize { + init(_ size: TodayPanelSize) { + switch size { + case .small: self = .small + case .wide: self = .wide + case .tall: self = .tall + } + } +} + +/// The spaces on Today's grid: a descriptor for each space, its panel, and what the grid's menu +/// and Edit do to it. A space's size, hidden state and place live on its computer (the bot designs +/// for its size), so its descriptor `keepsOwnLayout` and the layout store hands those changes here +/// (`ownedChanges`), to go there through `TodaySpacesModel`, which shows each at once and undoes it +/// if the computer says no. +@MainActor +struct SpacesTodayBridge { + static let kind = "space" + + let model: TodaySpacesModel + /// Opens a space's page full screen. The shell presents `HTMLAppScreen` with the page's card + /// (`space.page?.card(title:description:)`) on the space's own computer (`model.pageConnection`). + let openPage: (TodaySpace) -> Void + + init(model: TodaySpacesModel = .shared, openPage: @escaping (TodaySpace) -> Void) { + self.model = model + self.openPage = openPage + } + + /// A panel id that stays the same across launches and reconnects: the space's own id + /// (`TodaySpace.id`, its key and its computer's cache scope, hashed). + static func panelID(for item: TodaySpace) -> String { item.id } + + /// Every space Today has, hidden ones too (Edit lists them), in the computers' order. + func descriptors(from items: [TodaySpace]) -> [TodayPanelDescriptor] { + items.map { item in + TodayPanelDescriptor(id: Self.panelID(for: item), kind: Self.kind, + title: item.space.title.isEmpty ? String(localized: "Space") : item.space.title, + size: TodayPanelSize(item.space.size), canDelete: true, + keepsOwnLayout: true, isHidden: item.space.hidden) + } + } + + /// What the layout store sends here for a space's panel (`TodayPanelLayoutStore.ownedChanges`). + var ownedChanges: TodayOwnedPanelChanges { + TodayOwnedPanelChanges(resize: { resize($0, to: $1) }, setHidden: { setHidden($0, $1) }, + reorder: { reorder($0) }) + } + + func item(for panel: TodayPanelDescriptor) -> TodaySpace? { + guard panel.kind == Self.kind else { return nil } + return model.items.first { Self.panelID(for: $0) == panel.id } + } + + /// The panel for a space descriptor, at the descriptor's size. Empty for one that's gone. + func panel(for panel: TodayPanelDescriptor) -> AnyView { + guard let item = item(for: panel) else { return AnyView(EmptyView()) } + let model = model + let openPage = openPage + let id = item.id + return AnyView(SpacePanelView( + space: item.space, size: SpaceSize(panel.size), botName: botLine(item), isConnected: item.isConnected, + onOpen: item.space.page == nil ? nil : { openPage(item) }, + runNow: { () async throws(SpacesError) -> SpaceRefreshRun in try await model.runNow(id) })) + } + + /// A space's own rows in its panel's long-press menu, beside Resize, Hide and Delete: Open and + /// Update now. Update now shows its result on the panel itself. + func menuItems(for panel: TodayPanelDescriptor) -> AnyView { + guard let item = item(for: panel) else { return AnyView(EmptyView()) } + let model = model + let openPage = openPage + let id = item.id + return AnyView(Group { + if item.space.page != nil { + Button("Open", systemImage: "arrow.up.forward.app") { openPage(item) } + .accessibilityIdentifier("today.space.menu.open") + } + Button("Update now", systemImage: "arrow.clockwise") { + Task { await Self.updateNow(id, model: model) } + } + .disabled(!item.isConnected) + .accessibilityIdentifier("today.space.menu.update") + }) + } + + /// Update now from the menu. What the person can act on shows as Today's notice line: the panel's + /// own footer only says it for the panel's Try again. + private static func updateNow(_ id: String, model: TodaySpacesModel) async { + do throws(SpacesError) { + let run = try await model.runNow(id) + if let message = SpacesTodayMessage.updateNow(ran: run) { TodayNotice.shared.show(message) } + } catch { + TodayNotice.shared.show(SpacesTodayMessage.updateNow(error)) + } + } + + /// The bot's name, and its computer's when Today shows spaces from two or more. + private func botLine(_ item: TodaySpace) -> String { + model.showsComputerNames ? "\(item.botName) · \(item.computerName)" : item.botName + } + + // MARK: What the grid and Edit do to a space + + /// Small, Wide or Tall, kept on the space's computer. Shown at once; a refusal is undone in the + /// space's store, with nothing else to show. + func resize(_ panel: TodayPanelDescriptor, to size: TodayPanelSize) { + guard let id = item(for: panel)?.id else { return } + model.changeNow(id, SpaceChanges(size: SpaceSize(size))) + } + + /// Hidden spaces keep updating; Today only stops drawing them. + func setHidden(_ panel: TodayPanelDescriptor, _ hidden: Bool) { + guard let id = item(for: panel)?.id else { return } + model.changeNow(id, SpaceChanges(hidden: hidden)) + } + + /// Every panel in its new order after Edit's drag: the spaces among them get new places on + /// their computers, in that order. The places change before this returns. + func reorder(_ panels: [TodayPanelDescriptor]) { + let known = Set(model.items.map(\.id)) + let ids = panels.map(\.id).filter { known.contains($0) } + guard !ids.isEmpty else { return } + model.reorder(ids) + } + + /// Stops its routine and removes it and its page; then the layout forgets its place. A delete + /// the computer hasn't finished keeps the space off Today and goes again at the next read; a + /// space the computer refused to delete comes back on Today, and keeps its place. + func delete(_ panel: TodayPanelDescriptor, layout: TodayPanelLayoutStore) { + guard let id = item(for: panel)?.id else { return } + let model = model + let panelID = panel.id + Task { + do throws(SpacesError) { + try await model.delete(id) + layout.forget(panelID) + } catch { + // A definite refusal: the store put the space back, and the person is told. + TodayNotice.shared.show(SpacesTodayMessage.deleteRefused) + } + } + } + + // MARK: Notes above the grid + + /// One for each computer whose plugin doesn't know spaces yet. + var notes: [SpacesTodayNote] { + model.statuses.filter { $0.phase == .needsPluginUpdate }.map { SpacesTodayNote(id: $0.scope, computerName: $0.name) } + } +} + +/// The short words for what a panel's action came back with. Words the panel and the draft card +/// already use stay the same (docs/SPACES.md). +enum SpacesTodayMessage { + /// What Update now answered when it ran: only a paused routine has something to say. + static func updateNow(ran: SpaceRefreshRun) -> String? { + ran == .paused ? String(localized: "Paused in Scheduled tasks") : nil + } + + static func updateNow(_ error: SpacesError) -> String { + switch error { + case .tooSoon: String(localized: "Try again in a minute") + case .routineFailed: String(localized: "Its update failed") + case .unreachable: String(localized: "Could not reach your computer. Try again.") + case .schedulesUnavailable: String(localized: "Your computer can't run scheduled tasks right now.") + default: String(localized: "Could not update it. Try again.") + } + } + + /// A delete only throws once the computer refused it for good. + static var deleteRefused: String { + String(localized: "Could not delete it. Try again.") + } +} + +/// A computer whose plugin has to be updated before Today can show its spaces. +struct SpacesTodayNote: Identifiable, Equatable, Sendable { + /// The computer's cache scope. + let id: String + let computerName: String +} + +/// The quiet lines Today shows above the grid, one per computer. +struct SpacesTodayNotes: View { + let notes: [SpacesTodayNote] + @BighelpThemeReader private var theme + + var body: some View { + if !notes.isEmpty { + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + ForEach(notes) { note in + Text("Update the plugin on \(note.computerName) to see its spaces.") + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.spaces.notes") + } + } +} + +/// Delete's confirmation for a space panel. The shell sets `panel` from Today's `onDeletePanel`. +private struct SpacesDeleteConfirmation: ViewModifier { + @Binding var panel: TodayPanelDescriptor? + let bridge: SpacesTodayBridge + let layout: TodayPanelLayoutStore + + func body(content: Content) -> some View { + content.confirmationDialog("Delete this space?", + isPresented: Binding(get: { panel != nil }, set: { if !$0 { panel = nil } }), + titleVisibility: .visible, presenting: panel) { panel in + Button("Delete", role: .destructive) { bridge.delete(panel, layout: layout) } + .accessibilityIdentifier("today.space.delete.confirm") + Button("Cancel", role: .cancel) {} + .accessibilityIdentifier("today.space.delete.cancel") + } message: { _ in + Text("It stops its updates and removes its page.") + } + } +} + +extension View { + /// Asks before a space is deleted, then deletes it on its computer. + func spacesDeleteConfirmation(_ panel: Binding, bridge: SpacesTodayBridge, + layout: TodayPanelLayoutStore) -> some View { + modifier(SpacesDeleteConfirmation(panel: panel, bridge: bridge, layout: layout)) + } +} diff --git a/Bighelp/Spaces/SpacesWire.swift b/Bighelp/Spaces/SpacesWire.swift new file mode 100644 index 00000000..09cee5eb --- /dev/null +++ b/Bighelp/Spaces/SpacesWire.swift @@ -0,0 +1,96 @@ +import CryptoKit +import Foundation + +/// Spaces (plugin feature `native-spaces-v1`, the plugin's docs/SPACES.md): live panels on Today +/// that a bot makes on the person's computer. Each is a native card the app draws, an HTML app +/// opened from it, and a routine on the computer that updates both. The computer is the truth; +/// the phone keeps a copy so Today draws at once. +enum SpacesWire { + static let feature = "native-spaces-v1" + /// The chat card element a bot's `bighelp_draft_space` makes, with Add to Today. + static let type = "space_draft" + /// What the speaker note adds to `renders` when the plugin lists the feature. + static let renders = [type] + + static let maximumTitleLength = 60 + static let maximumDescriptionLength = 240 + static let maximumUpdatesLength = 60 + /// Live spaces one bot can have; the plugin refuses more (`spaces_full`). + static let maximumLiveSpacesPerBot = 24 + /// Bots one `spaces/list` names, and card hashes it carries. + static let maximumAgentsPerList = 64 + static let maximumKnownCards = 512 + /// Spaces read from one answer; more are left out. + static let maximumSpacesPerAnswer = maximumAgentsPerList * maximumLiveSpacesPerBot + /// Today's order is by `position`; a reorder places spaces this far apart. + static let positionStep: Double = 1_024 + /// The plugin refuses positions further from zero. + static let maximumPositionMagnitude: Double = 1e12 + /// Spaces whose cards a list left out (`cardOmitted`) read with `get` in one refresh. + static let maximumCardReadsPerLoad = 24 + /// The phone's copy of one computer's spaces; cards are left out of a bigger copy. + static let maximumCacheBytes = 6 * 1_024 * 1_024 + /// Today reads its computers at most this often while it shows. + static let refreshInterval: Duration = .seconds(60) + /// `routine.problem` when the bot changed the script after the person added the space. + static let scriptChangedProblem = "script_changed" + + /// `s_` and 32 lowercase hex digits, as the plugin makes them. + static func isSpaceID(_ value: String) -> Bool { + let digits = value.utf8.dropFirst(2) + return value.hasPrefix("s_") && digits.count == 32 + && digits.allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + } + + /// A bot's id as the routes take it: `^[a-z0-9][a-z0-9_-]{0,63}$`. + static func isAgentID(_ value: String) -> Bool { + let bytes = Array(value.utf8) + guard let first = bytes.first, (1...64).contains(bytes.count), + (48...57).contains(first) || (97...122).contains(first) else { return false } + return bytes.allSatisfy { (48...57).contains($0) || (97...122).contains($0) || $0 == 45 || $0 == 95 } + } + + /// A mutation's retry key: one per request. Sent again only with the very same request (the + /// client's one retry, a change or delete the computer hasn't confirmed); the plugin refuses an + /// `operationId` it saw with another operation, space or body (`invalid_request`). + static func newOperationID() -> String { UUID().uuidString.lowercased() } + + /// RFC 3339, with or without fractions of a second; nil for anything else. + static func date(_ value: BighelpJSONValue?) -> Date? { + guard let text = value?.string else { return nil } + if let date = ISO8601DateFormatter().date(from: text) { return date } + let fractional = ISO8601DateFormatter() + fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return fractional.date(from: text) + } + + /// With milliseconds, so the phone's copy keeps the computer's times exactly. + static func text(_ date: Date) -> String { + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return formatter.string(from: date) + } + + static func sha256(_ text: String) -> String { + SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined() + } +} + +/// The plugin's six routes (`POST /native/spaces/{operation}`). +enum SpacesOperation: String, CaseIterable, Sendable { + case list, get, add, update, refresh, delete + + var workspaceOperation: WorkspaceOperation { + switch self { + case .list: .spacesList + case .get: .spacesGet + case .add: .spacesAdd + case .update: .spacesUpdate + case .refresh: .spacesRefresh + case .delete: .spacesDelete + } + } + + /// Mutations carry an `operationId`, so a retry after a lost answer is never done twice. + var isMutation: Bool { self != .list && self != .get } +} diff --git a/Bighelp/Spaces/TodayCreateBox.swift b/Bighelp/Spaces/TodayCreateBox.swift new file mode 100644 index 00000000..31355a1c --- /dev/null +++ b/Bighelp/Spaces/TodayCreateBox.swift @@ -0,0 +1,157 @@ +import SwiftUI + +/// "Make a space", under Today's grid: what the person wants to see, which bot builds it, and a +/// few examples. Submitting hands the words to the shell, which leaves "Make me a space for Today: +/// " in a new chat with that bot. Nothing is sent from here: the person taps Send. +struct TodayCreateBox: View { + /// The bots on the computer in use. + let bots: [SpacesBot] + /// The bot picked until the person picks another (the primary bot). + let primaryBotID: String? + let onCreate: (_ agentID: String, _ text: String) -> Void + + @State private var text = "" + @State private var pickedBotID: String? + @FocusState private var isFocused: Bool + @BighelpThemeReader private var theme + + private static let examples: [(id: String, text: LocalizedStringResource)] = [ + ("commute", "Time my commute"), + ("workouts", "Track my workouts"), + ("garden", "Watch my garden"), + ] + + private var bot: SpacesBot? { + bots.first { $0.id == pickedBotID } ?? bots.first { $0.id == primaryBotID } ?? bots.first + } + + private var trimmed: String { text.trimmingCharacters(in: .whitespacesAndNewlines) } + private var canCreate: Bool { bot != nil && !trimmed.isEmpty } + + var body: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space12) { + ViewThatFits(in: .horizontal) { + HStack(spacing: BighelpTokens.space8) { + title + Spacer(minLength: BighelpTokens.space8) + botChip + } + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + title + botChip + } + } + HStack(spacing: BighelpTokens.space8) { + field + goButton + } + examples + Text("Nothing runs until you add it.") + .font(.bighelp(.caption)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + } + .padding(BighelpTokens.space16) + .frame(maxWidth: .infinity, alignment: .leading) + .bighelpSurface(.card) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.create") + } + + private var title: some View { + Text("Make a space") + .font(.bighelp(.headline)) + .foregroundStyle(theme.primaryText) + } + + @ViewBuilder + private var botChip: some View { + if let bot { + Menu { + ForEach(bots, id: \.id) { choice in + Button { + pickedBotID = choice.id + } label: { + if choice.id == bot.id { + Label { Text(verbatim: choice.name) } icon: { Image(systemName: "checkmark") } + } else { + Text(verbatim: choice.name) + } + } + .accessibilityIdentifier("today.create.bot.\(choice.id)") + } + } label: { + HStack(spacing: 4) { + Text(verbatim: bot.name).lineLimit(1) + Image(systemName: "chevron.down") + .imageScale(.small) + .accessibilityHidden(true) + } + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: BighelpTokens.scaled(34)) + .background(theme.canvas, in: .capsule) + .overlay { Capsule().strokeBorder(theme.border) } + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .menuStyle(.button) + .buttonStyle(.plain) + .accessibilityLabel(Text("Bot")) + .accessibilityValue(Text(verbatim: bot.name)) + .accessibilityIdentifier("today.create.bot") + } + } + + private var field: some View { + TextField("What do you want to see?", text: $text) + .font(.bighelp(.body)) + .foregroundStyle(theme.primaryText) + .focused($isFocused) + .submitLabel(.go) + .onSubmit(create) + .padding(.horizontal, BighelpTokens.space12) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget) + .background(theme.canvas, in: .rect(cornerRadius: BighelpTokens.inputCornerRadius, style: .continuous)) + .accessibilityIdentifier("today.create.field") + } + + private var goButton: some View { + Button(action: create) { + Image(systemName: "arrow.up") + .font(.bighelp(.body, weight: .semibold)) + .foregroundStyle(theme.actionForeground) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .background(theme.action.opacity(canCreate ? 1 : 0.4), in: .circle) + .contentShape(.circle) + } + .bighelpPlainButtonStyle(.circle) + .disabled(!canCreate) + .accessibilityLabel(Text("Make space")) + .accessibilityIdentifier("today.create.go") + } + + private var examples: some View { + ScrollView(.horizontal) { + HStack(spacing: BighelpTokens.space8) { + ForEach(Self.examples, id: \.id) { example in + SpacesChip(title: Text(example.text), identifier: "today.create.example.\(example.id)") { + text = String(localized: example.text) + } + } + } + } + .scrollIndicators(.hidden) + .scrollBounceBehavior(.basedOnSize, axes: .horizontal) + .accessibilityElement(children: .contain) + .accessibilityLabel(Text("Examples")) + } + + private func create() { + guard let bot, canCreate else { return } + onCreate(bot.id, trimmed) + text = "" + isFocused = false + } +} diff --git a/Bighelp/Spaces/TodaySpacesModel.swift b/Bighelp/Spaces/TodaySpacesModel.swift new file mode 100644 index 00000000..66b99025 --- /dev/null +++ b/Bighelp/Spaces/TodaySpacesModel.swift @@ -0,0 +1,302 @@ +import Foundation +import Observation + +/// One space on Today, with the computer and bot it belongs to. +struct TodaySpace: Identifiable, Equatable, Sendable { + /// Unique across computers, the same across launches and reconnects, and safe in accessibility + /// ids and the layout's file: `id(scope:key:)`. Today's grid knows the panel by it too. + let id: String + /// As the computer said, with this phone's unconfirmed changes on top. + let space: Space + let scope: String + let hostKey: String + let computerName: String + /// The bot's name, or its id when the computer's bots aren't known. + let botName: String + /// False while its computer isn't connected: the panel says "Not connected", the rest still draws. + let isConnected: Bool + + /// The computer's cache scope and the space's key, hashed (a scope can hold any character). + static func id(scope: String, key: String) -> String { + "space-" + String(SpacesWire.sha256(scope + "\n" + key).prefix(24)) + } +} + +/// How each computer's spaces read, for "Update the plugin on " and "Not connected". +struct TodaySpacesComputerStatus: Identifiable, Equatable, Sendable { + var id: String { scope } + let scope: String + let hostKey: String + let name: String + let phase: SpacesPhase + let isConnected: Bool + let lastLoaded: Date? +} + +/// Today's spaces from every computer, in one order: by position, then computer, then title. +/// Each computer's spaces live in its own `SpacesStore`, kept by cache scope; this model only +/// reads them together and sends each action to the space's own computer. +@MainActor +@Observable +final class TodaySpacesModel { + static let shared = TodaySpacesModel() + + /// By cache scope. + private(set) var stores: [String: SpacesStore] = [:] + private(set) var isRefreshing = false + private var computers: [ComputerInfo] = [] + + private struct ComputerInfo: Equatable { + let hostKey: String + let scope: String + let name: String + let bots: [SpacesBot] + let isConnected: Bool + } + + @ObservationIgnored private let source: @MainActor () -> [SpacesComputer] + @ObservationIgnored private let current: @MainActor () -> SpacesComputer? + @ObservationIgnored private let pages: @MainActor (String) -> HTMLAppsAPI? + @ObservationIgnored private let hostKeys: @MainActor () -> Set? + @ObservationIgnored private let cacheFolder: URL? + @ObservationIgnored private let clock: @MainActor () -> Date + @ObservationIgnored private var reading: Task? + + init(computers: @escaping @MainActor () -> [SpacesComputer] = { SpacesHost.computers() }, + current: @escaping @MainActor () -> SpacesComputer? = { SpacesHost.current() }, + pages: @escaping @MainActor (String) -> HTMLAppsAPI? = { SpacesHost.pages($0) }, + hostKeys: @escaping @MainActor () -> Set? = { SpacesHost.hostKeys() }, + cacheFolder: URL? = SpacesStore.defaultCacheFolder, + clock: @escaping @MainActor () -> Date = { Date() }) { + source = computers + self.current = current + self.pages = pages + self.hostKeys = hostKeys + self.cacheFolder = cacheFolder + self.clock = clock + } + + // MARK: What Today shows + + /// Every live space, hidden ones too, in Today's order (Edit Today's list). + var items: [TodaySpace] { + var rows: [(item: TodaySpace, computer: Int)] = [] + for (order, computer) in computers.enumerated() { + guard let store = stores[computer.scope] else { continue } + let names = Dictionary(computer.bots.map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) + for space in store.spaces where space.state == .live { + let item = TodaySpace(id: TodaySpace.id(scope: computer.scope, key: space.key), space: space, + scope: computer.scope, hostKey: computer.hostKey, computerName: computer.name, + botName: names[space.agentID] ?? space.agentID, isConnected: computer.isConnected) + rows.append((item, order)) + } + } + return rows.sorted { lhs, rhs in + if lhs.item.space.position != rhs.item.space.position { return lhs.item.space.position < rhs.item.space.position } + if lhs.computer != rhs.computer { return lhs.computer < rhs.computer } + switch lhs.item.space.title.localizedStandardCompare(rhs.item.space.title) { + case .orderedAscending: return true + case .orderedDescending: return false + case .orderedSame: return lhs.item.id < rhs.item.id + } + }.map { $0.item } + } + + /// The panels Today draws. + var shown: [TodaySpace] { items.filter { !$0.space.hidden } } + + var hiddenCount: Int { items.filter { $0.space.hidden }.count } + + /// Computer names show beside panels only when they come from two or more computers. + var showsComputerNames: Bool { Set(items.map(\.scope)).count >= 2 } + + var statuses: [TodaySpacesComputerStatus] { + computers.compactMap { computer in + guard let store = stores[computer.scope] else { return nil } + return TodaySpacesComputerStatus(scope: computer.scope, hostKey: computer.hostKey, name: computer.name, + phase: store.phase, isConnected: computer.isConnected, + lastLoaded: store.lastLoaded) + } + } + + // MARK: Reading + + /// Today's `.task` while it shows and the app is active: reads every computer now, then every + /// minute. Coming back to the app starts it again, which reads at once. + func watch() async { + while !Task.isCancelled { + await refresh() + try? await Task.sleep(for: SpacesWire.refreshInterval) + } + } + + /// Reads every connected computer at once, side by side. A read already under way is joined. + func refresh() async { + if let reading { + await reading.value + return + } + let reads = Task { await readAll() } + reading = reads + await reads.value + reading = nil + } + + private func readAll() async { + let list = sync() + isRefreshing = true + let reads = list.compactMap { computer in + stores[computer.scope].map { store in Task { await store.load(computer) } } + } + for read in reads { await read.value } + isRefreshing = false + } + + /// The computers as the app knows them now: a store for each new scope (with what the phone + /// kept), and none for a computer that's gone. A computer missing from the list only for now (no + /// scope while it reconnects or the selection moves) keeps its store, with its waiting changes: + /// a store goes when its computer leaves the registry, or the same computer shows under another scope. + @discardableResult + private func sync() -> [SpacesComputer] { + var seen = Set() + let list = source().filter { seen.insert($0.scope).inserted } + for computer in list where stores[computer.scope] == nil { + stores[computer.scope] = SpacesStore(scope: computer.scope, hostKey: computer.hostKey, + cacheFolder: cacheFolder, clock: clock) + } + let known = hostKeys() + let listed = Set(list.map(\.hostKey)) + for (scope, store) in stores where !seen.contains(scope) { + let isGone = known.map { !$0.contains(store.hostKey) } ?? true + guard isGone || listed.contains(store.hostKey) else { continue } + store.retire() + stores[scope] = nil + } + let info = list.map { + ComputerInfo(hostKey: $0.hostKey, scope: $0.scope, name: $0.name, bots: $0.bots, isConnected: $0.api != nil) + } + if info != computers { computers = info } + return list + } + + /// A removed computer: its panels leave Today and its copy on this phone is erased. The host + /// registry calls it from `remove(_:)`, with the saved scope when it has one. Nothing else + /// removes a computer's spaces. + func forget(hostKey: String, scope: String?) { + var scopes = Set(stores.filter { $0.value.hostKey == hostKey }.keys) + if let scope { scopes.insert(scope) } + for scope in scopes { + let store = stores.removeValue(forKey: scope) + store?.retire() + guard let cacheFolder else { continue } + // A write already under way finishes first, so it can't bring the file back. + Task { + await store?.savedToDisk() + SpacesCacheFile.erase(scope: scope, folder: cacheFolder) + } + } + computers.removeAll { $0.hostKey == hostKey } + } + + /// The connection `HTMLAppScreen` opens a space's page through: the space's own computer, + /// read each time it's asked, since bighelp reconnects every time it comes back. + func pageConnection(_ item: TodaySpace) -> @MainActor () -> (scope: String, api: HTMLAppsAPI)? { + let scope = item.scope + let pages = self.pages + return { pages(scope).map { (scope: scope, api: $0) } } + } + + // MARK: Acting on a space + + private func locate(_ id: String) throws(SpacesError) -> (store: SpacesStore, item: TodaySpace, api: SpacesAPI?) { + guard let item = items.first(where: { $0.id == id }), let store = stores[item.scope] else { throw .notFound } + // The connection as it is now: bighelp reconnects every time it comes back. + return (store, item, source().first { $0.scope == item.scope }?.api) + } + + func resize(_ id: String, to size: SpaceSize) async throws(SpacesError) { + let target = try locate(id) + try await target.store.change(target.item.space.key, SpaceChanges(size: size), api: target.api) + } + + /// Hidden spaces keep updating; only Today stops drawing them. + func setHidden(_ id: String, _ hidden: Bool) async throws(SpacesError) { + let target = try locate(id) + try await target.store.change(target.item.space.key, SpaceChanges(hidden: hidden), api: target.api) + } + + /// Today's grid and Edit: the change shows before this returns (a drag or a picker never draws + /// the old value for a frame), then goes to the space's computer. A refusal is undone in its + /// store. The task ends when the computer answered. + @discardableResult + func changeNow(_ id: String, _ changes: SpaceChanges) -> Task? { + guard let target = try? locate(id), target.store.stage(changes, for: target.item.space.key), + let api = target.api else { return nil } + let store = target.store + let key = target.item.space.key + return Task { try? await store.send(key, api: api) } + } + + /// Update now, and a stopped panel's Try again. + func runNow(_ id: String) async throws(SpacesError) -> SpaceRefreshRun { + let target = try locate(id) + return try await target.store.runNow(target.item.space.key, api: target.api) + } + + /// Stops its routine and removes it and its page from the computer. + func delete(_ id: String) async throws(SpacesError) { + let target = try locate(id) + try await target.store.delete(target.item.space.key, api: target.api) + } + + /// The person's new order (Edit Today's whole list; ids left out keep their order after the + /// rest). Every space gets a place 1,024 apart, and only those whose place changed are sent, + /// each to its own computer. The new places show before this returns, so a drag never jumps + /// back for a frame; the task ends when every computer answered. + @discardableResult + func reorder(_ ids: [String]) -> Task { + let current = items + var byID = Dictionary(current.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + var ordered = ids.compactMap { byID.removeValue(forKey: $0) } + ordered += current.filter { byID[$0.id] != nil } + var moved: [(store: SpacesStore, key: String, scope: String)] = [] + for (index, item) in ordered.enumerated() { + let position = Double(index + 1) * SpacesWire.positionStep + guard item.space.position != position, let store = stores[item.scope], + store.stage(SpaceChanges(position: position), for: item.space.key) else { continue } + moved.append((store, item.space.key, item.scope)) + } + let apis = Dictionary(source().map { ($0.scope, $0.api) }, uniquingKeysWith: { first, _ in first }) + let sends = moved + return Task { + for scope in Set(sends.map { $0.scope }).sorted() { + // A computer that isn't connected gets its places at its next read. + guard let api = apis[scope] ?? nil else { continue } + for move in sends where move.scope == scope { + try? await move.store.send(move.key, api: api) + } + } + } + } + + /// A chat's draft card: adds the draft on the computer in use, after every space on Today + /// unless Today already has a place for it. With the draft as `get` read it, it shows at once. + func add(agentID: String, spaceID: String, draftRevision: Int, size: SpaceSize?, + preview: Space? = nil) async throws(SpacesError) -> Space { + guard let computer = current() else { throw .unreachable } + // Today may not have shown yet this run: know the computers (so the space shows on Today at + // once) and read this one, so the new place comes after what's there. + sync() + let store: SpacesStore + if let existing = stores[computer.scope] { + store = existing + } else { + store = SpacesStore(scope: computer.scope, hostKey: computer.hostKey, cacheFolder: cacheFolder, clock: clock) + stores[computer.scope] = store + } + if store.phase == .loading { await store.load(computer) } + let last = items.map(\.space.position).filter { $0 < SpacesWire.maximumPositionMagnitude }.max() ?? 0 + return try await store.add(agentID: agentID, spaceID: spaceID, draftRevision: draftRevision, size: size, + position: last + SpacesWire.positionStep, preview: preview, api: computer.api) + } +} diff --git a/Bighelp/Spatial/SpatialAvatarScenes.swift b/Bighelp/Spatial/SpatialAvatarScenes.swift index 14f91c5e..1e860a72 100644 --- a/Bighelp/Spatial/SpatialAvatarScenes.swift +++ b/Bighelp/Spatial/SpatialAvatarScenes.swift @@ -352,7 +352,7 @@ struct SpatialAvatarVolume: View { agentImageURL: model.agent?.imageURL, permissionCenter: permissionCenter, onEnded: { model.endVoice() }, - onWorkspaceTap: openChat, + onOpenChat: openChat, onUseTurnBased: useTurnBasedVoice, onTryAgain: tryLiveVoiceAgain, chatActivity: { model.activity } @@ -377,7 +377,7 @@ struct SpatialAvatarVolume: View { /// Hooks on the main window: Settings and the menu find the avatar, and the /// avatar knows whether it must offer to reopen this window. The avatar never -/// opens by itself; the person chooses it (☰ › Simple mode, or Settings). +/// opens by itself; the person chooses it (the sidebar's Simple mode, or Settings). struct SpatialAvatarMainWindowHooks: ViewModifier { let model: SpatialAvatarModel diff --git a/Bighelp/Telemetry/TelemetryEvent.swift b/Bighelp/Telemetry/TelemetryEvent.swift index 082c8154..4291aa86 100644 --- a/Bighelp/Telemetry/TelemetryEvent.swift +++ b/Bighelp/Telemetry/TelemetryEvent.swift @@ -13,6 +13,7 @@ enum TelemetryFeature: String, CaseIterable, Codable, Sendable { case voiceTurn = "voice_turn" case voiceLive = "voice_live" case workflowRun = "workflow_run" + /// Not sent any more (the app has one home); the contract still lists it. case modeSwitched = "mode_switched" case agentOpened = "agent_opened" case fileOpened = "file_opened" diff --git a/Bighelp/Today/TodayBoardPage.swift b/Bighelp/Today/TodayBoardPage.swift new file mode 100644 index 00000000..40c4a5d8 --- /dev/null +++ b/Bighelp/Today/TodayBoardPage.swift @@ -0,0 +1,177 @@ +import SwiftUI + +/// See all from Today's boards panel: a row of bot chips (All bots first) over that kind's board. +/// All bots lists every bot's items newest first; one bot shows its own full board (`AgentFeedView`, +/// `AgentIdeasView`, `AgentGoalsView`) from a store of this page's that follows the shell's connection, +/// so the shell's board, which the widgets publish, stays on its own bot. +struct TodayBoardPage: View { + let context: TodayBoardsContext + let kind: AgentBoardItem.Kind + /// The board for one bot, as the shell builds it for a bot's Dashboard. Its header buttons are + /// this page's, so the shell turns the board's own off. + let makeBoardContext: (SimpleBotsBot, AgentBoardStore) -> AgentBoardContext + let onBack: () -> Void + /// The bot picked; nil is All bots. + @State private var agentID: String? + @State private var store = AgentBoardStore() + + init(context: TodayBoardsContext, kind: AgentBoardItem.Kind, agentID: String? = nil, + makeBoardContext: @escaping (SimpleBotsBot, AgentBoardStore) -> AgentBoardContext, + onBack: @escaping () -> Void) { + self.context = context + self.kind = kind + self.makeBoardContext = makeBoardContext + self.onBack = onBack + _agentID = State(initialValue: agentID) + } + + var body: some View { + Group { + if let bot = agentID.flatMap({ context.bot($0) }) { + board(for: bot) + .id(bot.id) + .task(id: TodayBoardFollowKey(agentID: bot.profileID, shell: context.shellBoard)) { + await follow(bot.profileID) + } + } else { + TodayBoardAllBots(context: context, kind: kind) + } + } + .safeAreaInset(edge: .top, spacing: 0) { header } + .background(theme.canvas.ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.board-page") + } + + @ViewBuilder + private func board(for bot: SimpleBotsBot) -> some View { + let boardContext = makeBoardContext(bot, store) + switch kind { + case .feed: AgentFeedView(context: boardContext) + case .idea: AgentIdeasView(context: boardContext) + case .goal: AgentGoalsView(context: boardContext) + } + } + + private var header: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + HStack(spacing: BighelpTokens.space8) { + Button(action: onBack) { + Image(systemName: "chevron.left") + .font(.bighelp(.title3, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(Rectangle()) + } + .bighelpPlainButtonStyle() + .accessibilityLabel("Back") + .accessibilityIdentifier("today.board-page.back") + Text(kind.todayTitle) + .font(.bighelp(.headline, weight: .bold)) + .foregroundStyle(theme.primaryText) + .accessibilityAddTraits(.isHeader) + Spacer(minLength: 0) + } + .padding(.horizontal, BighelpTokens.space8) + chips + } + .padding(.bottom, BighelpTokens.space8) + .background(theme.canvas.ignoresSafeArea(edges: .top)) + } + + /// One row that scrolls sideways, never two. + private var chips: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: BighelpTokens.space8) { + BoardFilterChip(title: String(localized: "All bots"), isSelected: agentID == nil) { agentID = nil } + .accessibilityIdentifier("today.board-page.chip.all") + ForEach(context.localBots) { bot in + BoardFilterChip(title: bot.name, isSelected: agentID == bot.profileID) { agentID = bot.profileID } + .accessibilityIdentifier("today.board-page.chip.\(bot.profileID)") + } + } + .padding(.horizontal, BighelpTokens.space16) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.board-page.chips") + } + + /// Uses the shell's connection: the same computer and client, this bot's board. + private func follow(_ agentID: String) async { + let shell = context.shellBoard + if let connection = shell.followableConnection { + await store.connect(client: connection.client, scope: connection.scope) + if store.agentID != agentID || store.state == .idle { await store.load(agentID: agentID) } + } else if shell.isWaitingForConnection { + store.waitForConnection() + await store.load(agentID: agentID) + } else { + store.configure(client: nil, isDisconnected: shell.isDisconnected) + } + } + + @BighelpThemeReader private var theme +} + +/// What following the shell's board depends on. +private struct TodayBoardFollowKey: Equatable { + let agentID: String + let client: ObjectIdentifier? + let waiting: Bool + let disconnected: Bool + + @MainActor + init(agentID: String, shell: AgentBoardStore) { + self.agentID = agentID + client = shell.followableConnection.map { ObjectIdentifier($0.client) } + waiting = shell.isWaitingForConnection + disconnected = shell.isDisconnected + } +} + +/// All bots: every bot's items of one kind, newest first, from `TodayBoardsStore`. +private struct TodayBoardAllBots: View { + let context: TodayBoardsContext + let kind: AgentBoardItem.Kind + + var body: some View { + let entries = context.store.entries(kind, agentIDs: context.localBots.map(\.profileID)) + ScrollView { + LazyVStack(alignment: .leading, spacing: BighelpTokens.space12) { + if entries.isEmpty { + Text(context.store.hasRead ? kind.todayEmptyPage : String(localized: "Your computer isn't connected.")) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .accessibilityIdentifier("today.board-page.empty") + } + ForEach(entries) { entry in + TodayBoardsRow(entry: entry, bot: context.bot(entry.agentID), + showsUnread: context.store.tracksUnread) { + context.onOpenItem(entry.agentID, entry.item) + } + } + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space8) + .frame(maxWidth: ChatCanvasLayout.regularLaneMaximumWidth) + .frame(maxWidth: .infinity) + } + .task { await TodayBoardsReading.refresh(context) } + .bighelpRefreshable { await TodayBoardsReading.refresh(context, force: true) } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.board-page.all") + } + + @BighelpThemeReader private var theme +} + +private extension AgentBoardItem.Kind { + var todayEmptyPage: String { + switch self { + case .feed: String(localized: "No posts from any bot yet.") + case .idea: String(localized: "No ideas from any bot yet.") + case .goal: String(localized: "No goals from any bot yet.") + } + } +} diff --git a/Bighelp/Today/TodayBoardsPanel.swift b/Bighelp/Today/TodayBoardsPanel.swift new file mode 100644 index 00000000..4879e3e4 --- /dev/null +++ b/Bighelp/Today/TodayBoardsPanel.swift @@ -0,0 +1,267 @@ +import SwiftUI + +/// What the Feed, Ideas and Goals panel and its See all page need from the shell. +@MainActor +struct TodayBoardsContext { + let store: TodayBoardsStore + /// The bots on the computer in use, in the order the home shows them. + let bots: [SimpleBotsBot] + /// The shell's board (`RootShellView.agentBoard`): its connection is the one read here, and + /// See all's board for one bot follows it. + let shellBoard: AgentBoardStore + /// Opens an item in full, by its bot's profile ID. + let onOpenItem: (String, AgentBoardItem) -> Void + /// See all: the kind, and the bot picked (nil for all bots). The shell pushes `TodayBoardPage`. + let onSeeAll: (AgentBoardItem.Kind, String?) -> Void + /// Opens a chat with a bot (by profile ID) with the text in its message box. Nothing is sent. + let onAsk: (String, String) -> Void + + /// Bots on the computer in use (with every computer shown, the others' bots are left out: + /// their boards aren't read here). + var localBots: [SimpleBotsBot] { bots.filter { $0.fleetAgent == nil || $0.isOnGatewayInUse } } + + func bot(_ agentID: String) -> SimpleBotsBot? { localBots.first { $0.profileID == agentID } } +} + +extension AgentBoardItem.Kind { + /// The panel's and See all's name for it. + var todayTitle: String { + switch self { + case .feed: String(localized: "Feed") + case .idea: String(localized: "Ideas") + case .goal: String(localized: "Goals") + } + } + + fileprivate var emptyLine: String { + switch self { + case .feed: String(localized: "Nothing yet. Ask a bot for posts.") + case .idea: String(localized: "Nothing yet. Ask a bot for ideas.") + case .goal: String(localized: "Nothing yet. Ask a bot for a goal.") + } + } + + /// What Ask leaves in the message box, as the bot's own empty board words it. + fileprivate var askText: String { + switch self { + case .feed: String(localized: "Every evening, post the top three AI stories to my feed.") + case .idea: String(localized: "Look through my week and suggest a few things you could take off my plate.") + case .goal: String(localized: "Help me set one goal for this month, and track it on my Goals.") + } + } +} + +/// Today's built-in panel: the newest Feed posts, ideas or goals across bots, each with its bot. +struct TodayBoardsPanel: View { + static let kind = "boards" + /// Its place on Today, Tall to start with. + static var descriptor: TodayPanelDescriptor { + TodayPanelDescriptor(id: "today.boards", kind: kind, title: String(localized: "Feed, Ideas, Goals"), size: .tall) + } + + let context: TodayBoardsContext + let size: TodayPanelSize + @State private var kind: AgentBoardItem.Kind = .feed + @Environment(\.scenePhase) private var scenePhase + + var body: some View { + let entries = context.store.entries(kind, agentIDs: context.localBots.map(\.profileID)) + VStack(alignment: .leading, spacing: BighelpTokens.space12) { + Picker("Board", selection: $kind) { + ForEach([AgentBoardItem.Kind.feed, .idea, .goal], id: \.self) { kind in + Text(kind.todayTitle).tag(kind) + } + } + .labelsHidden() + .bighelpSegmentedPicker() + .accessibilityIdentifier("today.boards.kind") + + content(entries) + + // An empty board's page has its starters and Blueprints, so See all stays once it's read. + if !entries.isEmpty || context.store.hasRead { + Button { + context.onSeeAll(kind, nil) + } label: { + Text("See all") + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.action) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(Rectangle()) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("today.boards.see-all") + } + } + .task(id: TodayBoardsReadKey(context: context, isActive: scenePhase == .active)) { + guard scenePhase == .active else { return } + await TodayBoardsReading.refresh(context) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.boards") + } + + @ViewBuilder + private func content(_ entries: [TodayBoardsEntry]) -> some View { + let store = context.store + if entries.isEmpty { + if !store.hasRead { + if store.isReading || context.shellBoard.followableConnection != nil { + TodayBoardsPlaceholder(rows: rowLimit) + } else { + Text("Your computer isn't connected.") + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .accessibilityIdentifier("today.boards.offline") + } + } else { + empty + } + } else { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + ForEach(entries.prefix(rowLimit)) { entry in + TodayBoardsRow(entry: entry, bot: context.bot(entry.agentID), + showsUnread: store.tracksUnread, compact: size == .small) { + context.onOpenItem(entry.agentID, entry.item) + } + } + } + } + } + + /// One sentence and Ask: boards start empty, and nothing runs until the person asks. + @ViewBuilder + private var empty: some View { + let bot = context.localBots.first { !$0.isHidden } ?? context.localBots.first + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + Text(kind.emptyLine) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + if let bot { + Button { + context.onAsk(bot.profileID, kind.askText) + } label: { + Text("Ask \(bot.name)") + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.action) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(Rectangle()) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("today.boards.ask") + } + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.boards.empty") + } + + private var rowLimit: Int { + switch size { + case .small: 2 + case .wide: 3 + case .tall: 6 + } + } + + @BighelpThemeReader private var theme +} + +/// What a read depends on: the computer, its connection and the bots on it. +private struct TodayBoardsReadKey: Equatable { + let scope: String? + let client: ObjectIdentifier? + let bots: [String] + let isActive: Bool + + @MainActor + init(context: TodayBoardsContext, isActive: Bool) { + let connection = context.shellBoard.followableConnection + scope = connection?.scope + client = connection.map { ObjectIdentifier($0.client) } + bots = context.localBots.map(\.profileID) + self.isActive = isActive + } +} + +@MainActor +enum TodayBoardsReading { + /// Reads the boards on the shell's connection; nothing while there is none (what was read stays). + static func refresh(_ context: TodayBoardsContext, force: Bool = false) async { + guard let connection = context.shellBoard.followableConnection else { return } + let bots = context.localBots + await context.store.refresh(client: connection.client, scope: connection.scope, + botIDs: bots.map(\.profileID), + hiddenIDs: Set(bots.filter(\.isHidden).map(\.profileID)), force: force) + } +} + +/// An item with its bot's face and name, and a dot while it's new. +struct TodayBoardsRow: View { + let entry: TodayBoardsEntry + let bot: SimpleBotsBot? + let showsUnread: Bool + var compact = false + let action: () -> Void + + var body: some View { + let item = entry.item + Button(action: action) { + HStack(alignment: .top, spacing: BighelpTokens.space8) { + SimpleBotFace(agentID: entry.agentID, name: bot?.name ?? "", imageURL: bot?.imageURL, + size: compact ? 24 : 32) + VStack(alignment: .leading, spacing: 2) { + if let name = bot?.name, !name.isEmpty { + Text(name) + .font(.bighelp(.caption, weight: .medium)) + .foregroundStyle(theme.secondaryText) + .lineLimit(1) + } + Text(item.title) + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + .lineLimit(compact ? 2 : 3) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + } + Spacer(minLength: 0) + if showsUnread, !item.read { + Circle() + .fill(theme.action) + .frame(width: 8, height: 8) + .padding(.top, BighelpTokens.space4) + .accessibilityLabel("New") + } + } + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .contentShape(Rectangle()) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("today.boards.item.\(entry.id)") + } + + @BighelpThemeReader private var theme +} + +/// Still rows while the first read runs: no motion. +private struct TodayBoardsPlaceholder: View { + let rows: Int + + var body: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space12) { + ForEach(0.. Date + + init(now: @escaping () -> Date = Date.init) { + self.now = now + } + + /// Shown bots first in the order given, then the hidden ones, at most `maximumBots`. + static func readOrder(botIDs: [String], hiddenIDs: Set) -> [String] { + var seen: Set = [] + let unique = botIDs.filter { seen.insert($0).inserted } + return Array((unique.filter { !hiddenIDs.contains($0) } + unique.filter { hiddenIDs.contains($0) }) + .prefix(maximumBots)) + } + + /// Reads the boards of `botIDs` on `client`, at most once a minute per computer unless `force`. + /// Another computer shows its last read at once while this one runs; a bot whose read fails + /// keeps what it had. + func refresh(client: any AgentBoardClient, scope: String, botIDs: [String], hiddenIDs: Set = [], + force: Bool = false) async { + if scope != self.scope { + generation &+= 1 + isReading = false + self.scope = scope + boards = byScope[scope] ?? [:] + hasRead = !(byScope[scope]?.isEmpty ?? true) + } + if !force, let last = readAt[scope], now().timeIntervalSince(last) < Self.freshness { return } + if isReading, !force { return } + generation &+= 1 + let generation = generation + isReading = true + tracksUnread = client.supportsFeedback + let wanted = Self.readOrder(botIDs: botIDs, hiddenIDs: hiddenIDs) + let previous = byScope[scope] ?? [:] + var next: [String: [AgentBoardItem]] = [:] + var allWorked = true + for id in wanted { + guard generation == self.generation else { return } + guard !Task.isCancelled else { isReading = false; return } + if let items = try? await client.items(agentID: id) { + next[id] = items + } else { + allWorked = false + if let kept = previous[id] { next[id] = kept } + } + guard generation == self.generation else { return } + // Each bot shows as it arrives; bots not read yet keep what they had. + var shown = previous.filter { wanted.contains($0.key) } + shown.merge(next) { _, new in new } + byScope[scope] = shown + if shown != boards { boards = shown } + } + guard generation == self.generation else { return } + guard !Task.isCancelled else { isReading = false; return } + byScope[scope] = next + if next != boards { boards = next } + // A read where every bot failed and nothing was held before says nothing: Today keeps its + // offline state, not "Nothing yet". + hasRead = !next.isEmpty || !previous.isEmpty + isReading = false + // Only a read where every bot answered counts, so a dropping connection doesn't hold off the next. + if allWorked { readAt[scope] = now() } + } + + /// The newest items of `kind` across bots, as each bot's own board lists them. + func entries(_ kind: AgentBoardItem.Kind, agentIDs: [String]? = nil) -> [TodayBoardsEntry] { + Self.entries(kind, boards: boards, agentIDs: agentIDs) + } + + static func entries(_ kind: AgentBoardItem.Kind, boards: [String: [AgentBoardItem]], + agentIDs: [String]? = nil) -> [TodayBoardsEntry] { + let ids = agentIDs ?? Array(boards.keys) + // In named steps: as one expression the Vision Pro build couldn't type-check it in time. + let entries: [TodayBoardsEntry] = ids.flatMap { id -> [TodayBoardsEntry] in + let items: [AgentBoardItem] = boards[id] ?? [] + // Ideas answered with Let's do it are under Completed on the bot's own board, not here. + let shown = items.filter { $0.kind == kind && !$0.dismissed && !$0.isCompleted } + return shown.map { TodayBoardsEntry(agentID: id, item: $0) } + } + return entries.sorted { first, second in + if first.item.createdAt != second.item.createdAt { return first.item.createdAt > second.item.createdAt } + return first.id < second.id + } + } +} diff --git a/Bighelp/Today/TodayFixture.swift b/Bighelp/Today/TodayFixture.swift new file mode 100644 index 00000000..01b14dc6 --- /dev/null +++ b/Bighelp/Today/TodayFixture.swift @@ -0,0 +1,78 @@ +#if DEBUG +import SwiftUI + +/// Today alone on made-up data, behind `-test-today-home`, before the shell shows it. +/// Three made-up bots read their boards from the demo's board client; Needs you and a share wait. +struct TodayFixture: View { + static let launchArgument = "-test-today-home" + static var isRequested: Bool { ProcessInfo.processInfo.arguments.contains(launchArgument) } + + private struct SeeAll: Hashable { + let kind: AgentBoardItem.Kind + let agentID: String? + } + + @State private var shellBoard = AgentBoardStore() + @State private var boards = TodayBoardsStore() + @State private var layout = TodayPanelLayoutStore( + defaults: UserDefaults(suiteName: "bighelp.today.fixture") ?? .standard) + @State private var isEditing = false + @State private var path: [SeeAll] = [] + + private static let bots = [ + SimpleBotsBot(id: "mina", profileID: "mina", name: "Mina", role: "Travel", isDefault: true), + SimpleBotsBot(id: "avery", profileID: "avery", name: "Avery", role: "Money"), + SimpleBotsBot(id: "jordan", profileID: "jordan", name: "Jordan", role: "Home"), + ] + + var body: some View { + NavigationStack(path: $path) { + TodayView(context: context) + .toolbar(.hidden, for: .navigationBar) + .navigationDestination(for: SeeAll.self) { seeAll in + TodayBoardPage(context: boardsContext, kind: seeAll.kind, agentID: seeAll.agentID, + makeBoardContext: boardContext, onBack: { path.removeLast() }) + } + } + .task { await shellBoard.connect(client: DemoAgentBoardClient(), scope: "today-fixture") } + } + + private var context: TodayContext { + TodayContext( + header: AnyView(header), + needsYou: TodayNeedsYouSummary(count: 3, agentID: "mina", botName: "Mina", + line: "Book the 7:40 AM flight for $412?"), + onOpenNeedsYou: {}, + pendingShares: TodayPendingShares(count: 1, open: {}), + panels: [TodayBoardsPanel.descriptor], + makePanel: { descriptor in + AnyView(TodayBoardsPanel(context: boardsContext, size: descriptor.size)) + }, + layout: layout, + isEditing: $isEditing) + } + + private var boardsContext: TodayBoardsContext { + TodayBoardsContext(store: boards, bots: Self.bots, shellBoard: shellBoard, + onOpenItem: { _, _ in }, + onSeeAll: { kind, agentID in path.append(SeeAll(kind: kind, agentID: agentID)) }, + onAsk: { _, _ in }) + } + + private func boardContext(_ bot: SimpleBotsBot, _ store: AgentBoardStore) -> AgentBoardContext { + AgentBoardContext(agentID: bot.profileID, agentName: bot.name, imageURL: nil, activity: .idle, store: store, + onProfile: {}, onSwitchAgent: {}, onAsk: { _ in }, onSend: { _ in }, onBlueprint: { _ in }) + } + + private var header: some View { + HStack { + Text("Today") + .font(.bighelp(.title2, weight: .bold)) + Spacer() + TodayEditButton(isEditing: $isEditing) + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space8) + } +} +#endif diff --git a/Bighelp/Today/TodayNeedsYouCard.swift b/Bighelp/Today/TodayNeedsYouCard.swift new file mode 100644 index 00000000..28a09669 --- /dev/null +++ b/Bighelp/Today/TodayNeedsYouCard.swift @@ -0,0 +1,119 @@ +import SwiftUI + +/// What waits for the person, from the shell's Needs you entries (`RootShellView.needsYouEntries`): +/// how many, and the first one's bot and one line. +struct TodayNeedsYouSummary: Equatable { + let count: Int + /// The first waiting item's bot (its profile ID for its face), and what it asks, in one line. + let agentID: String? + let botName: String + let line: String + var imageURL: URL? = nil +} + +/// Shares waiting in Shared with bighelp (`PendingShareCenter`). +@MainActor +struct TodayPendingShares { + let count: Int + let open: () -> Void +} + +/// Today's top card while something waits: it opens the Needs you deck, where every answer is given. +struct TodayNeedsYouCard: View { + let summary: TodayNeedsYouSummary + let open: () -> Void + + var body: some View { + Button(action: open) { + HStack(alignment: .top, spacing: BighelpTokens.space12) { + if let agentID = summary.agentID { + SimpleBotFace(agentID: agentID, name: summary.botName, imageURL: summary.imageURL, size: 40) + } else { + TodayCardSymbol(systemImage: "hand.raised.fill", tint: theme.action) + } + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: BighelpTokens.space8) { + Text("Needs you") + .font(.bighelp(.headline, weight: .bold)) + .foregroundStyle(theme.primaryText) + Spacer(minLength: BighelpTokens.space8) + Text(summary.count, format: .number) + .font(.bighelp(.subheadline, weight: .bold)) + .foregroundStyle(theme.actionForeground) + .padding(.horizontal, BighelpTokens.space8) + .frame(minWidth: 24, minHeight: 24) + .background(theme.action, in: Capsule()) + } + Text(summary.botName) + .font(.bighelp(.subheadline, weight: .semibold)) + .foregroundStyle(theme.primaryText) + Text(summary.line) + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .lineLimit(2) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(BighelpTokens.space16) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .bighelpSurface(.card, isInteractive: true) + .contentShape(RoundedRectangle(cornerRadius: BighelpTokens.cardCornerRadius, style: .continuous)) + } + .bighelpPlainButtonStyle() + .accessibilityElement(children: .combine) + .accessibilityHint("Opens what's waiting") + .accessibilityIdentifier("today.needs-you") + } + + @BighelpThemeReader private var theme +} + +/// "Shared with bighelp" while shares wait, in the same quiet style. +struct TodaySharesCard: View { + let shares: TodayPendingShares + + var body: some View { + Button(action: shares.open) { + HStack(spacing: BighelpTokens.space12) { + TodayCardSymbol(systemImage: "square.and.arrow.down", tint: theme.secondaryText) + VStack(alignment: .leading, spacing: 2) { + Text("Shared with bighelp") + .font(.bighelp(.body, weight: .semibold)) + .foregroundStyle(theme.primaryText) + Text("\(shares.count) waiting") + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + } + Spacer(minLength: BighelpTokens.space8) + Image(systemName: "chevron.right") + .font(.bighelp(.footnote, weight: .semibold)) + .foregroundStyle(theme.tertiaryText) + .accessibilityHidden(true) + } + .padding(BighelpTokens.space16) + .frame(maxWidth: .infinity, minHeight: BighelpTokens.hitTarget, alignment: .leading) + .bighelpSurface(.card, isInteractive: true) + .contentShape(RoundedRectangle(cornerRadius: BighelpTokens.cardCornerRadius, style: .continuous)) + } + .bighelpPlainButtonStyle() + .accessibilityElement(children: .combine) + .accessibilityIdentifier("today.shares") + } + + @BighelpThemeReader private var theme +} + +private struct TodayCardSymbol: View { + let systemImage: String + let tint: Color + + var body: some View { + Image(systemName: systemImage) + .font(.bighelp(.body, weight: .semibold)) + .foregroundStyle(tint) + .frame(width: 40, height: 40) + .background(tint.opacity(0.12), in: Circle()) + .accessibilityHidden(true) + } +} diff --git a/Bighelp/Today/TodayNotice.swift b/Bighelp/Today/TodayNotice.swift new file mode 100644 index 00000000..06a192e6 --- /dev/null +++ b/Bighelp/Today/TodayNotice.swift @@ -0,0 +1,52 @@ +import SwiftUI +import Observation + +/// One quiet line under Today's header for what a panel's action did when it needs saying: Update +/// now that came back "too soon", a delete the computer refused. It goes by itself, and is read +/// out to VoiceOver as it appears. +@MainActor +@Observable +final class TodayNotice { + static let shared = TodayNotice() + /// How long a line stays. + static let duration: Duration = .seconds(6) + + private(set) var message: String? + @ObservationIgnored private var clearing: Task? + + func show(_ message: String) { + self.message = message + AccessibilityNotification.Announcement(message).post() + clearing?.cancel() + clearing = Task { [weak self] in + try? await Task.sleep(for: Self.duration) + guard !Task.isCancelled else { return } + self?.message = nil + } + } + + func dismiss() { + clearing?.cancel() + clearing = nil + message = nil + } +} + +/// The line, under the header. Nothing is drawn while there is none. +struct TodayNoticeBar: View { + var notice: TodayNotice = .shared + @BighelpThemeReader private var theme + + var body: some View { + if let message = notice.message { + Text(verbatim: message) + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, BighelpTokens.space16) + .padding(.vertical, BighelpTokens.space8) + .accessibilityIdentifier("today.notice") + } + } +} diff --git a/Bighelp/Today/TodayPanelGrid.swift b/Bighelp/Today/TodayPanelGrid.swift new file mode 100644 index 00000000..26487e21 --- /dev/null +++ b/Bighelp/Today/TodayPanelGrid.swift @@ -0,0 +1,270 @@ +import SwiftUI + +/// One row of Today's grid: Small panels side by side, or one Wide or Tall panel. +struct TodayPanelRow: Identifiable, Equatable { + let panels: [TodayPanelDescriptor] + + var id: String { panels.first?.id ?? "" } + var takesRow: Bool { panels.count == 1 && panels[0].size.takesRow } +} + +/// Packs panels into rows, keeping their order: Small panels fill a row up to `columns`; Wide and Tall +/// start a row of their own, so a Small one before them stays alone with the rest of its row empty. +enum TodayPanelPacking { + static func rows(_ panels: [TodayPanelDescriptor], columns: Int = 2) -> [TodayPanelRow] { + let columns = max(1, columns) + var rows: [TodayPanelRow] = [] + var pending: [TodayPanelDescriptor] = [] + for panel in panels { + if panel.size.takesRow { + if !pending.isEmpty { rows.append(TodayPanelRow(panels: pending)); pending = [] } + rows.append(TodayPanelRow(panels: [panel])) + } else { + pending.append(panel) + if pending.count == columns { rows.append(TodayPanelRow(panels: pending)); pending = [] } + } + } + if !pending.isEmpty { rows.append(TodayPanelRow(panels: pending)) } + return rows + } + + /// Two columns on a phone, more where the column is wide, one at accessibility text sizes. + static func columns(width: CGFloat, isAccessibilitySize: Bool) -> Int { + if isAccessibilitySize { return 1 } + return max(2, min(4, Int(width / 260))) + } +} + +/// Today's panels on a grid. Each panel is drawn by the shell's factory; the grid gives it its +/// card, its size and the long-press menu (Resize, Hide, Delete). +struct TodayPanelGrid: View { + /// Shown panels, in order, at the sizes the person chose (`TodayPanelLayoutStore.shown`). + let panels: [TodayPanelDescriptor] + let columns: Int + let makePanel: (TodayPanelDescriptor) -> AnyView + let layout: TodayPanelLayoutStore + var onDelete: ((TodayPanelDescriptor) -> Void)? + /// A panel's own rows in its long-press menu, before Hide (a Space's Open and Update now). + var menuItems: ((TodayPanelDescriptor) -> AnyView)? = nil + + var body: some View { + VStack(spacing: BighelpTokens.space12) { + ForEach(TodayPanelPacking.rows(panels, columns: columns)) { row in + if row.takesRow { + cell(row.panels[0]) + } else { + HStack(alignment: .top, spacing: BighelpTokens.space12) { + ForEach(row.panels) { cell($0) } + // A lone Small panel keeps its width; the rest of the row stays empty. + ForEach(row.panels.count.. some View { + TodayPanelCell(panel: panel, content: makePanel(panel), layout: layout, onDelete: onDelete, menuItems: menuItems) + } +} + +/// A panel's card and its long-press (right-click on the Mac) menu. +private struct TodayPanelCell: View { + let panel: TodayPanelDescriptor + let content: AnyView + let layout: TodayPanelLayoutStore + let onDelete: ((TodayPanelDescriptor) -> Void)? + let menuItems: ((TodayPanelDescriptor) -> AnyView)? + + var body: some View { + content + .padding(BighelpTokens.space16) + .frame(maxWidth: .infinity, minHeight: Self.minimumHeight(panel.size), maxHeight: .infinity, + alignment: .topLeading) + .bighelpSurface(.card) + .contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: BighelpTokens.cardCornerRadius, + style: .continuous)) + .contextMenu { TodayPanelMenu(panel: panel, layout: layout, onDelete: onDelete, menuItems: menuItems) } + .overlay(alignment: .topTrailing) { + TodayPanelAccessibilityActions(panel: panel, layout: layout, onDelete: onDelete, menuItems: menuItems) + } + .accessibilityElement(children: .contain) + .accessibilityLabel(panel.title) + .accessibilityIdentifier("today.panel.\(panel.id)") + } + + static func minimumHeight(_ size: TodayPanelSize) -> CGFloat { + BighelpTokens.scaled(size == .tall ? 340 : 150) + } +} + +/// The long-press menu is out of reach for VoiceOver, and a container can't carry actions of its +/// own, so a panel also holds one element that only VoiceOver and Switch Control find: a menu with +/// the same rows (Open, Update now, Hide, Delete). It draws nothing. +private struct TodayPanelAccessibilityActions: View { + let panel: TodayPanelDescriptor + let layout: TodayPanelLayoutStore + let onDelete: ((TodayPanelDescriptor) -> Void)? + let menuItems: ((TodayPanelDescriptor) -> AnyView)? + + var body: some View { + Menu { + TodayPanelMenu(panel: panel, layout: layout, onDelete: onDelete, menuItems: menuItems) + } label: { + Color.clear.frame(width: 1, height: 1) + } + .accessibilityLabel(Text("Actions for \(panel.title)")) + .accessibilityIdentifier("today.panel.actions.\(panel.id)") + } +} + +/// Resize, the panel's own rows, Hide and, for panels the shell can delete, Delete. +struct TodayPanelMenu: View { + let panel: TodayPanelDescriptor + let layout: TodayPanelLayoutStore + let onDelete: ((TodayPanelDescriptor) -> Void)? + var menuItems: ((TodayPanelDescriptor) -> AnyView)? = nil + + var body: some View { + Menu { + TodayPanelSizePicker(panel: panel, layout: layout) + .pickerStyle(.inline) + } label: { + Label("Resize", systemImage: "arrow.up.left.and.arrow.down.right") + } + .accessibilityIdentifier("today.panel.resize") + menuItems?(panel) + Button("Hide from Today", systemImage: "eye.slash") { layout.setHidden(panel, true) } + .accessibilityIdentifier("today.panel.hide") + if panel.canDelete, let onDelete { + Divider() + Button("Delete", systemImage: "trash", role: .destructive) { onDelete(panel) } + .accessibilityIdentifier("today.panel.delete") + } + } +} + +/// Small, Wide or Tall; the pick sticks (`TodayPanelLayoutStore.setSize`). +struct TodayPanelSizePicker: View { + let panel: TodayPanelDescriptor + let layout: TodayPanelLayoutStore + + var body: some View { + Picker("Size", selection: Binding(get: { layout.size(of: panel) }, + set: { layout.setSize($0, for: panel) })) { + ForEach(TodayPanelSize.allCases, id: \.self) { size in + Text(size.title).tag(size) + } + } + .accessibilityIdentifier("today.panel.size.\(panel.id)") + } +} + +/// Edit Today: drag to order, a size for each panel, the eye to hide; hidden panels below with Show. +struct TodayPanelEditList: View { + let panels: [TodayPanelDescriptor] + let layout: TodayPanelLayoutStore + /// Delete for a panel that `canDelete`; the shell asks first. + var onDelete: ((TodayPanelDescriptor) -> Void)? = nil + + var body: some View { + let shown = layout.shown(panels) + let hidden = layout.hiddenPanels(panels) + List { + Section("On Today") { + ForEach(shown) { panel in + row(panel) + } + .onMove { layout.move(fromOffsets: $0, toOffset: $1, among: panels) } + } + if !hidden.isEmpty { + Section("Hidden") { + ForEach(hidden) { panel in + hiddenRow(panel) + } + } + } + } + .environment(\.editMode, .constant(.active)) + .scrollContentBackground(.hidden) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.edit.list") + } + + private func row(_ panel: TodayPanelDescriptor) -> some View { + HStack(spacing: BighelpTokens.space12) { + VStack(alignment: .leading, spacing: 2) { + Text(panel.title) + .font(.bighelp(.body)) + .foregroundStyle(theme.primaryText) + .lineLimit(2) + // Its second line is its size, and picks it. + TodayPanelSizePicker(panel: panel, layout: layout) + .pickerStyle(.menu) + .labelsHidden() + .tint(theme.secondaryText) + .buttonStyle(.borderless) + } + Spacer(minLength: BighelpTokens.space8) + Button { + layout.setHidden(panel, true) + } label: { + Image(systemName: "eye") + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .accessibilityLabel("Hide \(panel.title)") + .accessibilityIdentifier("today.edit.hide.\(panel.id)") + deleteButton(panel) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.edit.row.\(panel.id)") + } + + private func hiddenRow(_ panel: TodayPanelDescriptor) -> some View { + HStack(spacing: BighelpTokens.space12) { + Text(panel.title) + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + .lineLimit(2) + Spacer(minLength: BighelpTokens.space8) + Button("Show") { layout.setHidden(panel, false) } + .font(.bighelp(.body, weight: .semibold)) + .tint(theme.action) + .buttonStyle(.borderless) + .frame(minHeight: BighelpTokens.hitTarget) + .accessibilityIdentifier("today.edit.show.\(panel.id)") + deleteButton(panel) + } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.edit.hidden.\(panel.id)") + } + + /// A space's Delete, in Edit too. The same confirmation as the menu's Delete. + @ViewBuilder + private func deleteButton(_ panel: TodayPanelDescriptor) -> some View { + if panel.canDelete, let onDelete { + Button { + onDelete(panel) + } label: { + Image(systemName: "trash") + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(Rectangle()) + } + .buttonStyle(.borderless) + .accessibilityLabel("Delete \(panel.title)") + .accessibilityIdentifier("today.edit.delete.\(panel.id)") + } + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Today/TodayPanelLayoutStore.swift b/Bighelp/Today/TodayPanelLayoutStore.swift new file mode 100644 index 00000000..edf33b35 --- /dev/null +++ b/Bighelp/Today/TodayPanelLayoutStore.swift @@ -0,0 +1,190 @@ +import Foundation +import Observation + +/// How much room a panel on Today takes: half a row, the whole row, or the whole row and more height. +enum TodayPanelSize: String, CaseIterable, Codable, Sendable { + case small, wide, tall + + var title: String { + switch self { + case .small: String(localized: "Small") + case .wide: String(localized: "Wide") + case .tall: String(localized: "Tall") + } + } + + /// Small shares its row; Wide and Tall take it. + var takesRow: Bool { self != .small } +} + +/// One panel on Today, as the shell lists it. The grid knows panels only by this and the shell's +/// factory, so a new kind of panel (a bot's Space) needs no change here. +struct TodayPanelDescriptor: Identifiable, Equatable, Sendable { + let id: String + /// What draws it, for the shell's factory ("boards", "space"). + let kind: String + /// Its name in Edit and in VoiceOver, one to three words. + let title: String + /// The size it starts at; once the person picks one, `TodayPanelLayoutStore` keeps theirs. + var size: TodayPanelSize + /// The long-press menu offers Delete, which the shell confirms and carries out. + var canDelete = false + /// Its size, hidden state and place belong to its owner, not to this device (a bot's Space keeps + /// them on its computer): `size` and `isHidden` are the owner's, and changes go to + /// `TodayPanelLayoutStore.ownedChanges`. + var keepsOwnLayout = false + /// The owner's hidden state, for a panel that `keepsOwnLayout`. + var isHidden = false +} + +/// What the person chose for Today's panels: their order, which are hidden and each one's size. +/// Ids of panels not listed right now (a Space whose computer hasn't answered yet) are kept; +/// only `forget` drops one. +struct TodayPanelLayout: Codable, Equatable, Sendable { + var order: [String] = [] + var hidden: Set = [] + var sizes: [String: TodayPanelSize] = [:] + + /// The panels to show, in the person's order with their sizes. A panel the layout doesn't know + /// goes last, in the order the shell listed it, at its own size (as `BighelpAppLayout` does). + func shown(_ panels: [TodayPanelDescriptor]) -> [TodayPanelDescriptor] { + arranged(panels).filter { !isHidden($0) } + } + + /// The hidden panels, in the same order, for Edit's Hidden list. + func hiddenPanels(_ panels: [TodayPanelDescriptor]) -> [TodayPanelDescriptor] { + arranged(panels).filter { isHidden($0) } + } + + /// The panels in the person's order with their sizes. Panels that keep their own layout fill + /// the places they hold in the order the shell listed them (their owner's order), at their own + /// sizes. + func arranged(_ panels: [TodayPanelDescriptor]) -> [TodayPanelDescriptor] { + var seen = Set() + var owned = panels.filter { $0.keepsOwnLayout && seen.insert($0.id).inserted }.makeIterator() + return listed(panels).map { panel in + if panel.keepsOwnLayout { return owned.next() ?? panel } + var panel = panel + if let size = sizes[panel.id] { panel.size = size } + return panel + } + } + + /// The panels in `order`, then the ones it doesn't know in the shell's order; each id once. + func listed(_ panels: [TodayPanelDescriptor]) -> [TodayPanelDescriptor] { + var byID: [String: TodayPanelDescriptor] = [:] + for panel in panels where byID[panel.id] == nil { byID[panel.id] = panel } + var known = order.compactMap { byID.removeValue(forKey: $0) } + known += panels.filter { byID.removeValue(forKey: $0.id) != nil } + return known + } + + private func isHidden(_ panel: TodayPanelDescriptor) -> Bool { + panel.keepsOwnLayout ? panel.isHidden : hidden.contains(panel.id) + } + + /// Moves among the shown panels (Edit's drag). Panels not shown keep their place after them. + mutating func move(fromOffsets source: IndexSet, toOffset destination: Int, among panels: [TodayPanelDescriptor]) { + var ids = shown(panels).map(\.id) + let moving = source.sorted().filter { ids.indices.contains($0) }.map { ids[$0] } + guard !moving.isEmpty else { return } + let insertion = destination - source.filter { $0 < destination }.count + ids.removeAll { moving.contains($0) } + ids.insert(contentsOf: moving, at: max(0, min(insertion, ids.count))) + let rest = arranged(panels).map(\.id).filter { !ids.contains($0) } + let unlisted = order.filter { !ids.contains($0) && !rest.contains($0) } + order = ids + rest + unlisted + } + + mutating func setHidden(_ id: String, _ isHidden: Bool) { + if isHidden { hidden.insert(id) } else { hidden.remove(id) } + } + + mutating func forget(_ id: String) { + order.removeAll { $0 == id } + hidden.remove(id) + sizes[id] = nil + } +} + +/// Where a panel that keeps its own layout sends the person's changes to it (a Space: its +/// computer, through `SpacesTodayBridge`). Each shows the change before it returns. +@MainActor +struct TodayOwnedPanelChanges { + let resize: @MainActor (TodayPanelDescriptor, TodayPanelSize) -> Void + let setHidden: @MainActor (TodayPanelDescriptor, Bool) -> Void + /// Every panel in the order the person left them, owned or not. + let reorder: @MainActor ([TodayPanelDescriptor]) -> Void +} + +/// Today's panel layout on this device, saved under `bighelp.today.panels`. +@MainActor +@Observable +final class TodayPanelLayoutStore { + static let key = "bighelp.today.panels" + + private(set) var layout: TodayPanelLayout + /// Set by the shell for panels that `keepsOwnLayout`; their changes are dropped while it's nil. + @ObservationIgnored var ownedChanges: TodayOwnedPanelChanges? + @ObservationIgnored private let defaults: UserDefaults + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + layout = defaults.data(forKey: Self.key) + .flatMap { try? JSONDecoder().decode(TodayPanelLayout.self, from: $0) } ?? TodayPanelLayout() + } + + func shown(_ panels: [TodayPanelDescriptor]) -> [TodayPanelDescriptor] { layout.shown(panels) } + func hiddenPanels(_ panels: [TodayPanelDescriptor]) -> [TodayPanelDescriptor] { layout.hiddenPanels(panels) } + + func size(of panel: TodayPanelDescriptor) -> TodayPanelSize { + panel.keepsOwnLayout ? panel.size : (layout.sizes[panel.id] ?? panel.size) + } + + func setSize(_ size: TodayPanelSize, for id: String) { + change { $0.sizes[id] = size } + } + + /// The grid's and Edit's size picker: the owner's for a panel that keeps its own layout. + func setSize(_ size: TodayPanelSize, for panel: TodayPanelDescriptor) { + if panel.keepsOwnLayout { + ownedChanges?.resize(panel, size) + } else { + setSize(size, for: panel.id) + } + } + + func setHidden(_ id: String, _ isHidden: Bool) { + change { $0.setHidden(id, isHidden) } + } + + /// Hide and Show: the owner's for a panel that keeps its own layout. + func setHidden(_ panel: TodayPanelDescriptor, _ isHidden: Bool) { + if panel.keepsOwnLayout { + ownedChanges?.setHidden(panel, isHidden) + } else { + setHidden(panel.id, isHidden) + } + } + + /// Edit's drag. Panels that keep their own layout also get their new order from their owner + /// (`ownedChanges.reorder`), which `arranged` then follows. + func move(fromOffsets source: IndexSet, toOffset destination: Int, among panels: [TodayPanelDescriptor]) { + change { $0.move(fromOffsets: source, toOffset: destination, among: panels) } + // `listed`, not `arranged`: the owned panels' places from the drag, before their owner moves them. + if panels.contains(where: \.keepsOwnLayout) { ownedChanges?.reorder(layout.listed(panels)) } + } + + /// After the shell deletes a panel (a Space): its place, size and hidden state go with it. + func forget(_ id: String) { + change { $0.forget(id) } + } + + private func change(_ edit: (inout TodayPanelLayout) -> Void) { + var next = layout + edit(&next) + guard next != layout else { return } + layout = next + if let data = try? JSONEncoder().encode(next) { defaults.set(data, forKey: Self.key) } + } +} diff --git a/Bighelp/Today/TodayView.swift b/Bighelp/Today/TodayView.swift new file mode 100644 index 00000000..c175a267 --- /dev/null +++ b/Bighelp/Today/TodayView.swift @@ -0,0 +1,131 @@ +import SwiftUI + +/// What the Today tab needs from the shell. +@MainActor +struct TodayContext { + /// The home header (`HomeHeaderBar`), drawn on top. Its trailing slot holds `TodayEditButton`. + let header: AnyView + /// Nil while nothing waits: then there is no card. + var needsYou: TodayNeedsYouSummary? + /// Opens the Needs you deck. + let onOpenNeedsYou: () -> Void + /// Nil while no share waits. + var pendingShares: TodayPendingShares? = nil + /// Every panel there is: the built-in boards panel (`TodayBoardsPanel.descriptor`), later Spaces. + let panels: [TodayPanelDescriptor] + /// Draws a panel's content at the size in the descriptor it's given. + let makePanel: (TodayPanelDescriptor) -> AnyView + let layout: TodayPanelLayoutStore + /// Edit Today, toggled by the header's `TodayEditButton`. + let isEditing: Binding + /// Delete for a panel that `canDelete`: the shell confirms, deletes, then calls `layout.forget`. + var onDeletePanel: ((TodayPanelDescriptor) -> Void)? = nil + /// Which bots work or need you, kept current while Today shows (the tab's dot reads it too). + var activity: BotChatActivityStore? = nil + var activitySource: BotChatActivitySource? = nil + /// Just above the grid: one line per computer whose plugin can't show spaces (`SpacesTodayNotes`). + var aboveGrid: AnyView? = nil + /// Just below the grid: Make a space (`TodayCreateBox`). + var belowGrid: AnyView? = nil + /// A panel's own rows in its long-press menu (a Space's Open and Update now). + var panelMenu: ((TodayPanelDescriptor) -> AnyView)? = nil +} + +/// Today: Needs you on top while something waits, waiting shares, then the person's panels. +struct TodayView: View { + let context: TodayContext + @State private var width: CGFloat = 0 + @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @Environment(\.scenePhase) private var scenePhase + + var body: some View { + Group { + if context.isEditing.wrappedValue { + TodayPanelEditList(panels: context.panels, layout: context.layout, onDelete: context.onDeletePanel) + .frame(maxWidth: ChatCanvasLayout.regularLaneMaximumWidth) + .frame(maxWidth: .infinity) + } else { + scroll + } + } + .safeAreaInset(edge: .top, spacing: 0) { + VStack(spacing: 0) { + context.header + TodayNoticeBar() + } + } + .background(theme.canvas.ignoresSafeArea()) + .botChatActivityUpdates(context.activity, source: context.activitySource, isActive: scenePhase == .active) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("today.home") + } + + private var scroll: some View { + ScrollView { + VStack(spacing: BighelpTokens.space12) { + if let needsYou = context.needsYou, needsYou.count > 0 { + TodayNeedsYouCard(summary: needsYou, open: context.onOpenNeedsYou) + } + if let shares = context.pendingShares, shares.count > 0 { + TodaySharesCard(shares: shares) + } + context.aboveGrid + BighelpDeferredSection { + panels + } + context.belowGrid + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.top, BighelpTokens.space8) + .padding(.bottom, BighelpTokens.space32) + .frame(maxWidth: ChatCanvasLayout.regularLaneMaximumWidth) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width = $0 } + .frame(maxWidth: .infinity) + } + .scrollBounceBehavior(.basedOnSize) + } + + @ViewBuilder + private var panels: some View { + let shown = context.layout.shown(context.panels) + if shown.isEmpty { + // Every panel is hidden: Edit brings them back. + Text("Every panel is hidden. Tap Edit to show one.") + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, BighelpTokens.space16) + .accessibilityIdentifier("today.panels.empty") + } else { + TodayPanelGrid(panels: shown, + columns: TodayPanelPacking.columns(width: width - 2 * BighelpTokens.space16, + isAccessibilitySize: dynamicTypeSize.isAccessibilitySize), + makePanel: context.makePanel, layout: context.layout, onDelete: context.onDeletePanel, + menuItems: context.panelMenu) + } + } + + @BighelpThemeReader private var theme +} + +/// Edit and Done for the header's trailing slot. +struct TodayEditButton: View { + @Binding var isEditing: Bool + + var body: some View { + Button { + isEditing.toggle() + } label: { + Text(isEditing ? "Done" : "Edit") + .font(.bighelp(.body, weight: isEditing ? .semibold : .regular)) + .foregroundStyle(theme.action) + .padding(.horizontal, BighelpTokens.space8) + .frame(minWidth: BighelpTokens.hitTarget, minHeight: BighelpTokens.hitTarget) + .contentShape(Rectangle()) + } + .bighelpPlainButtonStyle() + .accessibilityIdentifier("today.edit") + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Usage/ProviderUsageStore.swift b/Bighelp/Usage/ProviderUsageStore.swift index 6df8312b..ae53470d 100644 --- a/Bighelp/Usage/ProviderUsageStore.swift +++ b/Bighelp/Usage/ProviderUsageStore.swift @@ -150,7 +150,7 @@ final class ProviderUsageStore { } /// Opens the Usage page; the app sets it. Screens that offer Usage (chat ⋯, - /// the context window, ☰) call `show(agentID:)` and stay out of navigation. + /// the context window, the sidebar) call `show(agentID:)` and stay out of navigation. @ObservationIgnored var onOpen: (@MainActor () -> Void)? /// Opens Usage with an agent's view of the plans (its provider first) and diff --git a/Bighelp/Usage/UsageView.swift b/Bighelp/Usage/UsageView.swift index 379c8996..7f50f0f2 100644 --- a/Bighelp/Usage/UsageView.swift +++ b/Bighelp/Usage/UsageView.swift @@ -1,6 +1,6 @@ import SwiftUI -/// ☰ › Usage: plans and limits, then what the agents used. Cost or tokens over +/// Usage: plans and limits, then what the agents used. Cost or tokens over /// 7, 30 or 90 days, totals, when you use it, and the models, agents and (with /// All hosts) computers behind it. Tap a bar for its day, a row to chart it. struct UsageView: View { diff --git a/Bighelp/Vault/CredentialVaultView.swift b/Bighelp/Vault/CredentialVaultView.swift index be5e764b..2362c748 100644 --- a/Bighelp/Vault/CredentialVaultView.swift +++ b/Bighelp/Vault/CredentialVaultView.swift @@ -963,7 +963,7 @@ extension RootShellView { return CredentialVaultModel(service: service, agents: list, agentID: homeAgent?.id ?? "default") } - /// One bot's own vault, for its profile in Bots mode; nil while the computer isn't connected. + /// One bot's own vault, for its page; nil while the computer isn't connected. func makeCredentialVault(for agentID: String) -> CredentialVaultModel? { guard let service = makeCredentialVaultService() else { return nil } let name = agents.profiles.first { $0.id == agentID }?.name ?? agentID diff --git a/Bighelp/Voice/AgentVoiceChoices.swift b/Bighelp/Voice/AgentVoiceChoices.swift index 0e5f1d1c..5c08c165 100644 --- a/Bighelp/Voice/AgentVoiceChoices.swift +++ b/Bighelp/Voice/AgentVoiceChoices.swift @@ -150,8 +150,8 @@ extension SettingsStore { setVoiceConversationMode(.turnBased, computer: computer, agentID: agentID, choices: choices) } - /// The person picked a voice type for one agent, anywhere (Settings › Voice, its Default Voice in - /// Bots mode, the voice bar over its chat): that agent's own choice, the same in every mode. + /// The person picked a voice type for one agent, anywhere (Settings › Voice, its page's Default Voice, + /// the voice bar over its chat): that agent's own choice, the same everywhere. /// Without an agent to keep it for, the default for every agent. func setVoiceConversationMode(_ mode: VoiceConversationMode, computer: String?, agentID: String?, choices: AgentVoiceChoices = .shared) { diff --git a/Bighelp/Voice/VoicePresentationContainer.swift b/Bighelp/Voice/VoicePresentationContainer.swift index bf114a22..5f9e47fc 100644 --- a/Bighelp/Voice/VoicePresentationContainer.swift +++ b/Bighelp/Voice/VoicePresentationContainer.swift @@ -10,7 +10,8 @@ struct VoicePresentationContainer: View { var agentImageURL: URL? = nil let permissionCenter: PermissionCenter let onEnded: () -> Void - let onWorkspaceTap: () -> Void + /// Opens the chat, where voice isn't over it (the agent in the room). Nil over a chat. + var onOpenChat: (() -> Void)? = nil /// Switches Settings to turn-based voice and reopens voice. var onUseTurnBased: (() -> Void)? = nil /// Opens live voice again, once what stopped it may be gone. @@ -26,7 +27,7 @@ struct VoicePresentationContainer: View { VoiceView(model: presentation.model, agentID: agentID, agentImageURL: agentImageURL, permissionCenter: permissionCenter, - onEnded: onEnded, onWorkspaceTap: onWorkspaceTap, + onEnded: onEnded, onOpenChat: onOpenChat, chatActivity: chatActivity, chatStep: chatStep) } else if let live = presentation.liveModel { NavigationStack { diff --git a/Bighelp/Voice/VoiceView.swift b/Bighelp/Voice/VoiceView.swift index 0997083c..e5f353b9 100644 --- a/Bighelp/Voice/VoiceView.swift +++ b/Bighelp/Voice/VoiceView.swift @@ -15,7 +15,9 @@ struct VoiceView: View { let transcriptRows: [VoiceTranscriptRow]? let permissionCenter: PermissionCenter? let onEnded: () -> Void - let onWorkspaceTap: () -> Void + /// Opens the chat this voice is for, where it isn't on screen already (the agent in the room on + /// Vision Pro). Nil leaves the button out: over a chat, closing voice shows it. + let onOpenChat: (() -> Void)? /// The chat's live work (a running tool, thinking), for the avatar's moves. var chatActivity: () -> AgentActivityKind = { .idle } /// The step the agent is on, in plain words, for the line under the bars. @@ -29,7 +31,7 @@ struct VoiceView: View { showsTranscript: Bool = false, permissionCenter: PermissionCenter? = nil, onEnded: @escaping () -> Void = {}, - onWorkspaceTap: @escaping () -> Void = {}, + onOpenChat: (() -> Void)? = nil, chatActivity: @escaping () -> AgentActivityKind = { .idle }, chatStep: @escaping () -> String? = { nil } ) { @@ -42,7 +44,7 @@ struct VoiceView: View { _isTranscriptExpanded = State(initialValue: showsTranscript) self.permissionCenter = permissionCenter self.onEnded = onEnded - self.onWorkspaceTap = onWorkspaceTap + self.onOpenChat = onOpenChat } var body: some View { @@ -96,13 +98,30 @@ struct VoiceView: View { } + @ViewBuilder + private var openChatButton: some View { + if let onOpenChat { + Button(action: onOpenChat) { + Image(systemName: "bubble.left") + .font(.bighelp(.body).weight(.semibold)) + .foregroundStyle(.primary) + .frame(width: 44, height: 44) + .contentShape(.circle) + } + .buttonStyle(.plain) + .bighelpNavigationGlass(in: Circle(), isInteractive: true) + .accessibilityLabel("Open chat") + .accessibilityIdentifier("voice.open-chat") + } + } + private var voiceLayout: some View { VStack(spacing: 0) { HStack(alignment: .center, spacing: BighelpTokens.space8) { - WorkspaceMenuButton(accessibilityIdentifier: "voice.workspace-menu", action: onWorkspaceTap) + // The same width on both sides, so the status pill stays centered with or without it. + openChatButton.frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) authoritativeStatus .frame(maxWidth: .infinity) - // Balances the menu button so the status pill stays centered. Color.clear.frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) } .padding(.horizontal, BighelpTokens.space16) diff --git a/Bighelp/Work/WorkCards.swift b/Bighelp/Work/WorkCards.swift new file mode 100644 index 00000000..4d1fa4f8 --- /dev/null +++ b/Bighelp/Work/WorkCards.swift @@ -0,0 +1,176 @@ +import SwiftUI + +/// One row on Work: Code home's own card for coding work, `WorkRowCard` for everything else. +struct WorkItemCard: View { + let item: WorkItem + let onOpen: (WorkTarget) -> Void + /// Code home's long-press actions; nil without a Code store. + var code: CodeHomeStore? + + var body: some View { + switch item.card { + case .session(let record, let status, let pullRequest): + Button { onOpen(.codeSession(record.id)) } label: { + CodeSessionCard(session: record, status: status, pullRequest: pullRequest) + } + .buttonStyle(.bighelpTilePress) + .contextMenu { + Button("Changes", systemImage: "plus.forwardslash.minus") { onOpen(.codeChanges(record.id)) } + if let code { + Button("Remove from list", systemImage: "eye.slash") { code.forget(record) } + } + } + .accessibilityIdentifier("work.item.\(item.id)") + case .launch(let launch): + // A send still starting has nothing to open until Hermes has its session. + CodeLaunchCard(launch: launch) { code?.dismiss(launch) } + .onTapGesture { if let target = item.target { onOpen(target) } } + .accessibilityIdentifier("work.item.\(item.id)") + case .batch(let batch, let lines, let startedCount): + Button { onOpen(.codeBatch(batch.id)) } label: { + CodeBatchCard(batch: batch, lines: lines.map { line in + CodeBatchCard.Line(id: line.id, title: line.title, color: CodeSessionColor.color(at: line.index), + status: line.status) + }, startedCount: startedCount) + } + .buttonStyle(.bighelpTilePress) + .contextMenu { + if let code { + Button("Remove from list", systemImage: "eye.slash") { code.forget(batch) } + } + } + .accessibilityIdentifier("work.item.\(item.id)") + case .row: + if let target = item.target { + Button { onOpen(target) } label: { WorkRowCard(item: item) } + .buttonStyle(.bighelpTilePress) + .accessibilityIdentifier("work.item.\(item.id)") + } else { + WorkRowCard(item: item) + .accessibilityIdentifier("work.item.\(item.id)") + } + } + } +} + +/// A workflow run, Kanban card, chat, background work or scheduled task, drawn like Code home's +/// session card: the status dot, the title, where it is, then the pill and when. +struct WorkRowCard: View { + let item: WorkItem + + var body: some View { + HStack(alignment: .top, spacing: BighelpTokens.space12) { + dot + VStack(alignment: .leading, spacing: BighelpTokens.space4) { + Text(item.title) + .font(.bighelp(.headline)) + .foregroundStyle(theme.primaryText) + .lineLimit(2) + if !item.line.isEmpty { + HStack(alignment: .firstTextBaseline, spacing: BighelpTokens.space4) { + Image(systemName: item.lineSymbol) + Text(item.line).lineLimit(2) + } + .font(.bighelp(.footnote)) + .foregroundStyle(theme.secondaryText) + } + statusLine + .padding(.top, BighelpTokens.space4) + } + Spacer(minLength: 0) + } + .padding(BighelpTokens.space16) + .frame(maxWidth: .infinity, alignment: .leading) + .background(theme.surface, in: .rect(cornerRadius: BighelpTokens.radius16)) + .overlay { + RoundedRectangle(cornerRadius: BighelpTokens.radius16) + .stroke(theme.border, lineWidth: BighelpTokens.hairline) + } + .contentShape(.rect) + .accessibilityElement(children: .combine) + } + + /// Code home's dot for live states; an upcoming task waits, so it gets a still clock instead. + @ViewBuilder + private var dot: some View { + switch item.tone { + case .needsYou: CodeStatusDot(status: .needsYou("")) + case .working: CodeStatusDot(status: .running(nil)) + case .done: CodeStatusDot(status: .ready) + case .failed: CodeStatusDot(status: .failed("")) + case .upcoming: + Image(systemName: "clock") + .font(.system(size: 13, weight: .semibold)) + .foregroundStyle(theme.secondaryText) + .frame(width: 18, height: 18) + .padding(.top, 2) + .accessibilityHidden(true) + } + } + + private var statusLine: some View { + HStack(spacing: BighelpTokens.space8) { + if let pill = item.pill { + CodePill(text: pill, tint: tint, systemImage: item.tone == .needsYou ? "hand.raised" : nil) + } + Spacer(minLength: 0) + // Worked out when the card draws; no ticking timer. An upcoming task's time is in its pill. + if item.bucket != .upcoming, let time = item.time { + Text(time.formatted(.relative(presentation: .named, unitsStyle: .abbreviated))) + .foregroundStyle(theme.secondaryText) + } + } + .font(.bighelp(.subheadline)) + } + + private var tint: Color { + switch item.tone { + case .needsYou: theme.warning + case .working: theme.action + case .done: theme.success + case .failed: theme.danger + case .upcoming: theme.secondaryText + } + } + + @BighelpThemeReader private var theme +} + +/// All, Needs you, Working, Done: one row that scrolls sideways, in Code home's chip style. +struct WorkFilterChips: View { + @Binding var filter: WorkFilter + let counts: [WorkFilter: Int] + + var body: some View { + ScrollView(.horizontal) { + HStack(spacing: BighelpTokens.space8) { + ForEach(WorkFilter.allCases) { chip in + let isOn = filter == chip + Button { filter = chip } label: { + HStack(spacing: BighelpTokens.space4) { + Text(chip.title) + Text("\(counts[chip] ?? 0)") + .foregroundStyle(isOn ? theme.canvas.opacity(0.7) : theme.secondaryText) + } + .font(.bighelp(.subheadline).weight(.semibold)) + .foregroundStyle(isOn ? theme.canvas : theme.primaryText) + .lineLimit(1) + .fixedSize() + .padding(.horizontal, BighelpTokens.space12) + .frame(minHeight: 34) + .background(isOn ? theme.primaryText : theme.surface, in: .capsule) + .contentShape(.capsule) + } + .bighelpPlainButtonStyle(.capsule) + .accessibilityAddTraits(isOn ? .isSelected : []) + .accessibilityIdentifier("work.filter.\(chip.rawValue)") + } + } + } + .scrollIndicators(.hidden) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("work.filters") + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Work/WorkDoors.swift b/Bighelp/Work/WorkDoors.swift new file mode 100644 index 00000000..735063b6 --- /dev/null +++ b/Bighelp/Work/WorkDoors.swift @@ -0,0 +1,141 @@ +import SwiftUI + +/// A board one tap down from Work: its full page keeps every tool it has. The shell lists only the +/// doors this computer can open (Kanban and Workflows need their features). +struct WorkDoor: Identifiable { + enum Kind: String, CaseIterable, Sendable { + case projects, tasks, workflows, schedules + + var title: String { + switch self { + case .projects: String(localized: "Projects") + case .tasks: String(localized: "Tasks") + case .workflows: String(localized: "Workflows") + case .schedules: String(localized: "Schedules") + } + } + + var systemImage: String { + switch self { + case .projects: "folder" + case .tasks: "checklist" + case .workflows: "point.3.connected.trianglepath.dotted" + case .schedules: "clock" + } + } + } + + let kind: Kind + /// What its store counts (projects, open cards, workflows, scheduled tasks); nil shows none. + var count: Int? = nil + let open: () -> Void + + var id: Kind { kind } +} + +/// Work filtered to a project: the header's ⋯ (`WorkProjectMenu`). +struct WorkProjectActions { + let onPullRequests: () -> Void + let onWorktrees: () -> Void + /// Nil when this computer has no Dev Factory. + var onDevFactory: (() -> Void)? = nil + /// Open pull requests in the project, for the row's value. + var openPullRequests = 0 +} + +/// "Open a board": the doors as rows of one card. +struct WorkDoorsSection: View { + let doors: [WorkDoor] + + var body: some View { + VStack(alignment: .leading, spacing: BighelpTokens.space8) { + Text("Open a board") + .font(.bighelp(.footnote).weight(.semibold)) + .foregroundStyle(theme.secondaryText) + .padding(.leading, BighelpTokens.space4) + .accessibilityAddTraits(.isHeader) + VStack(spacing: 0) { + ForEach(Array(doors.enumerated()), id: \.element.id) { index, door in + if index > 0 { + Divider().padding(.leading, BighelpTokens.space48) + } + row(door) + } + } + .background(theme.surface, in: .rect(cornerRadius: BighelpTokens.radius16)) + .overlay { + RoundedRectangle(cornerRadius: BighelpTokens.radius16) + .stroke(theme.border, lineWidth: BighelpTokens.hairline) + } + } + .padding(.top, BighelpTokens.space12) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("work.doors") + } + + private func row(_ door: WorkDoor) -> some View { + Button(action: door.open) { + HStack(spacing: BighelpTokens.space12) { + Image(systemName: door.kind.systemImage) + .font(.bighelp(.subheadline).weight(.semibold)) + .foregroundStyle(theme.action) + .frame(width: BighelpTokens.scaled(24)) + Text(door.kind.title) + .font(.bighelp(.body)) + .foregroundStyle(theme.primaryText) + Spacer(minLength: BighelpTokens.space8) + if let count = door.count { + Text("\(count)") + .font(.bighelp(.body)) + .foregroundStyle(theme.secondaryText) + } + Image(systemName: "chevron.right") + .font(.bighelp(.footnote).weight(.semibold)) + .foregroundStyle(theme.secondaryText) + } + .padding(.horizontal, BighelpTokens.space16) + .frame(minHeight: BighelpTokens.hitTarget) + .contentShape(.rect) + } + .bighelpPlainButtonStyle(.rounded(BighelpTokens.radius16)) + .accessibilityIdentifier("work.door.\(door.kind.rawValue)") + } + + @BighelpThemeReader private var theme +} + +/// ⋯ for Work filtered to a project: Pull requests, Worktrees and Dev Factory. The shell puts it in +/// the header's `trailing` slot. +struct WorkProjectMenu: View { + let actions: WorkProjectActions + + var body: some View { + Menu { + Button(action: actions.onPullRequests) { + if actions.openPullRequests > 0 { + Label("Pull requests (\(actions.openPullRequests))", systemImage: "arrow.triangle.pull") + } else { + Label("Pull requests", systemImage: "arrow.triangle.pull") + } + } + .accessibilityIdentifier("work.project.pull-requests") + Button("Worktrees", systemImage: "arrow.triangle.branch", action: actions.onWorktrees) + .accessibilityIdentifier("work.project.worktrees") + if let onDevFactory = actions.onDevFactory { + Button("Dev Factory", systemImage: "gearshape.2", action: onDevFactory) + .accessibilityIdentifier("work.project.dev-factory") + } + } label: { + Image(systemName: "ellipsis") + .font(.bighelp(.title3, weight: .medium)) + .foregroundStyle(.primary) + .frame(width: BighelpTokens.hitTarget, height: BighelpTokens.hitTarget) + .contentShape(.circle) + .bighelpNavigationGlass(in: Circle(), isInteractive: true) + } + .menuOrder(.fixed) + .buttonStyle(.plain) + .accessibilityLabel("More") + .accessibilityIdentifier("work.project.more") + } +} diff --git a/Bighelp/Work/WorkFixture.swift b/Bighelp/Work/WorkFixture.swift new file mode 100644 index 00000000..09d75d8a --- /dev/null +++ b/Bighelp/Work/WorkFixture.swift @@ -0,0 +1,84 @@ +#if DEBUG +import SwiftUI + +/// Work alone on made-up data, before the shell shows it: launch with `-test-work-screen` +/// (add `-test-work-project` for Work filtered to a project). Nothing here reaches a computer. +enum WorkFixture { + static let launchArgument = "-test-work-screen" + static let projectArgument = "-test-work-project" + static var isOn: Bool { ProcessInfo.processInfo.arguments.contains(launchArgument) } + + static let projectID = "demo-app" + + @MainActor + static func view() -> some View { + WorkFixtureView(filtered: ProcessInfo.processInfo.arguments.contains(projectArgument)) + } + + @MainActor + static func sources(now: Date = .now) -> WorkSources { + var sources = WorkSources(now: now) + sources.botNames = ["avery": "Avery", "jordan": "Jordan"] + sources.codeSessions = [ + WorkCodeSession(record: session("s1", "Fix the widget tap when asleep", branch: "fix-widget-tap", + startedAt: now.addingTimeInterval(-600)), + status: .running("Running the tests")), + WorkCodeSession(record: session("s2", "Tighten the Usage chart", branch: "tighten-usage-chart", + startedAt: now.addingTimeInterval(-7_200)), + status: .ready, + pullRequest: StockGitPullRequest(number: 128, branch: "tighten-usage-chart", + title: "Tighten the Usage chart", + url: URL(string: "https://example.com/pull/128")!, + state: "open", isDraft: false)), + ] + sources.background = ["jordan": BotBackgroundWork(count: 1, title: "Compare three plumbers")] + sources.workflowsWaiting = [ + WorkflowRunSummary(id: "run-1", number: 4, workflowID: "monthly", workflowName: "Monthly report", + revision: 1, state: .waitingForYou, stageKey: "review", stageTitle: "Review", + stageState: .waitingForYou, stagesDone: 2, stageCount: 4, + startedAt: now.addingTimeInterval(-3_600), updatedAt: now.addingTimeInterval(-300), + waiting: .init(kind: "signoff", stageKey: "review", since: now.addingTimeInterval(-300)), + version: 1), + ] + sources.tasks = [ + DemoKanbanService.task("t1", "Draft the trip budget", status: .done, assignee: "avery", priority: 0, + createdAt: now.addingTimeInterval(-86_400), + completedAt: now.addingTimeInterval(-10_800)), + ] + sources.schedules = [ + ScheduledTask(id: "brief", agentID: "avery", name: "Morning brief", instructions: "", + schedule: .naturalLanguage("every weekday at 7", timeZoneID: "UTC"), + scheduleDescription: "Every weekday", nextRun: now.addingTimeInterval(36_000), + status: .active, lastResult: nil), + ] + return sources + } + + private static func session(_ id: String, _ title: String, branch: String, startedAt: Date) -> CodeSessionRecord { + CodeSessionRecord(id: id, agentID: "avery", projectID: projectID, projectName: "demo-app", title: title, + folder: "/work/demo-app/.worktrees/\(branch)", branch: branch, placement: .newWorktree, + startedAt: startedAt) + } +} + +private struct WorkFixtureView: View { + let filtered: Bool + @State private var filter: WorkFilter = .all + + var body: some View { + let header = HomeHeaderBar(context: HomeHeaderContext( + personName: "Sam", personImageURL: nil, onOpenSettings: {}, + title: filtered ? "demo-app" : String(localized: "Work"), + trailing: filtered ? AnyView(WorkProjectMenu(actions: WorkProjectActions( + onPullRequests: {}, onWorktrees: {}, onDevFactory: {}, openPullRequests: 1))) : nil)) + WorkList(context: WorkContext( + header: AnyView(header), projectID: filtered ? WorkFixture.projectID : nil, onOpen: { _ in }, + doors: WorkDoor.Kind.allCases.map { kind in + WorkDoor(kind: kind, count: kind == .schedules ? 1 : kind == .projects ? 1 : nil, open: {}) + }, + onRefresh: {}), + items: WorkProjection.items(WorkFixture.sources()), filter: $filter) + .toolbar(.hidden, for: .navigationBar) + } +} +#endif diff --git a/Bighelp/Work/WorkItem.swift b/Bighelp/Work/WorkItem.swift new file mode 100644 index 00000000..fa262df9 --- /dev/null +++ b/Bighelp/Work/WorkItem.swift @@ -0,0 +1,111 @@ +import Foundation + +/// What a row on Work is: each kind is read from the store that already holds it. +enum WorkKind: String, CaseIterable, Sendable { + /// A Code session, a send still starting one, or a batch (`CodeHomeStore`). + case coding + /// A chat working right now (`DashboardModel.workInFlightItems`). + case chat + /// A bot's background work: subagents, commands and task runs (`BotChatActivity.background`). + case background + /// A workflow run (`WorkflowsStore`). + case workflow + /// A Kanban card (`KanbanBoardModel`). + case task + /// A scheduled task (`ScheduledTasksStore`). + case schedule +} + +/// Which chip a row counts under. `upcoming` shows only under All: a scheduled task that hasn't failed +/// is waiting for its next run, and nothing reports one as working. +enum WorkBucket: String, Sendable { + case needsYou, working, done, upcoming +} + +/// The chips over the list. +enum WorkFilter: String, CaseIterable, Identifiable, Sendable { + case all, needsYou, working, done + + var id: Self { self } + + var title: String { + switch self { + case .all: String(localized: "All") + case .needsYou: String(localized: "Needs you") + case .working: String(localized: "Working") + case .done: String(localized: "Done") + } + } + + func includes(_ bucket: WorkBucket) -> Bool { + switch self { + case .all: true + case .needsYou: bucket == .needsYou + case .working: bucket == .working + case .done: bucket == .done + } + } +} + +/// What a tap on a row opens. The shell maps each to the page that already shows it. +enum WorkTarget: Hashable, Sendable { + /// A Code session's chat, by its app session ID. + case codeSession(String) + /// A Code session's Changes (its long-press menu). + case codeChanges(String) + case codeBatch(UUID) + /// A chat that's working, by its session ID. + case chat(String) + /// A bot whose work runs in the background, by profile ID: its Bot Chat. + case bot(String) + case workflowRun(String) + case kanbanTask(String) + case scheduledTask(ScheduledTaskIdentity) +} + +/// The dot and pill color a row takes. +enum WorkTone: Sendable { + case needsYou, working, done, failed, upcoming +} + +/// One line of a batch card: a session or a job still starting, with its live status. +struct WorkBatchLine: Identifiable, Equatable, Sendable { + let id: String + let title: String + /// Its place in the batch, which picks its color (`CodeSessionColor`). + let index: Int + let status: CodeSessionStatus +} + +/// How a row draws: Code home's own cards for coding work, one shared row for the rest. +enum WorkCard: Equatable, Sendable { + case session(CodeSessionRecord, CodeSessionStatus, pullRequest: StockGitPullRequest?) + case launch(CodeLaunch) + case batch(CodeBatch, lines: [WorkBatchLine], startedCount: Int) + case row +} + +/// One row on Work: only what its store says, never a guess. +struct WorkItem: Identifiable, Equatable, Sendable { + let kind: WorkKind + /// Unique across kinds (`kind:storeID`). + let id: String + let title: String + /// The status pill: "Sign off", "Working", "7:00 AM". Nil leaves it out. + let pill: String? + /// The second line: where it runs or what it is, and its bot. + let line: String + let lineSymbol: String + /// The bot's name, when the store names one. + let bot: String? + /// The last activity; for an upcoming scheduled task, its next run. Nil while it works now and the + /// store gives no time. + let time: Date? + let bucket: WorkBucket + let tone: WorkTone + /// The project it belongs to, for Work filtered to a project. + let projectID: String? + /// Nil when there's nothing to open (a send that failed before it had a session). + let target: WorkTarget? + var card: WorkCard = .row +} diff --git a/Bighelp/Work/WorkProjection.swift b/Bighelp/Work/WorkProjection.swift new file mode 100644 index 00000000..3982027a --- /dev/null +++ b/Bighelp/Work/WorkProjection.swift @@ -0,0 +1,327 @@ +import Foundation + +/// A Code session as Work shows it: its record, the status its card reads and its pull request. +struct WorkCodeSession: Equatable, Sendable { + let record: CodeSessionRecord + let status: CodeSessionStatus + var pullRequest: StockGitPullRequest? +} + +/// A batch with its lines resolved the way Code home's batch card resolves them. +struct WorkCodeBatch: Equatable, Sendable { + let batch: CodeBatch + let lines: [WorkBatchLine] + let startedCount: Int +} + +/// What Work reads from each store, at one moment. A store that's nil (never opened, or the computer +/// lacks it) leaves its part empty. +struct WorkSources: Sendable { + /// Sessions that aren't in a batch. + var codeSessions: [WorkCodeSession] = [] + /// Sends with no session yet that aren't in a batch. + var codeLaunches: [CodeLaunch] = [] + var codeBatches: [WorkCodeBatch] = [] + var chatWork: [DashboardWorkItem] = [] + /// Bots with background work, by profile ID. + var background: [String: BotBackgroundWork] = [:] + var workflowsWaiting: [WorkflowRunSummary] = [] + var workflowsActive: [WorkflowRunSummary] = [] + var workflowsRecent: [WorkflowRunSummary] = [] + var tasks: [HermesKanbanTask] = [] + var schedules: [ScheduledTask] = [] + /// Bot names by profile ID. + var botNames: [String: String] = [:] + var now: Date = .now +} + +/// Work's list: every source's rows in one order, newest activity first. Pure, so tests drive it. +enum WorkProjection { + /// Finished Kanban cards shown at most; the board keeps the rest. + static let doneTaskLimit = 20 + + static func items(_ sources: WorkSources) -> [WorkItem] { + var items: [WorkItem] = [] + items += sources.codeLaunches.map(launchItem) + items += sources.codeBatches.map(batchItem) + items += sources.codeSessions.map(sessionItem) + // A Code session's chat is also a chat with active work: its card already says so. + let codeIDs = Set(sources.codeSessions.map(\.record.id)) + .union(sources.codeBatches.flatMap(\.batch.sessionIDs)) + items += sources.chatWork.filter { !codeIDs.contains($0.sessionID) }.map(chatItem) + items += sources.background.map { backgroundItem(profileID: $0.key, work: $0.value, sources: sources) } + items += workflowItems(sources) + items += taskItems(sources) + items += sources.schedules.map { scheduleItem($0, sources: sources) } + return ordered(items, now: sources.now) + } + + /// The rows a chip and, for Work filtered to a project, that project show. + static func visible(_ items: [WorkItem], filter: WorkFilter, projectID: String?) -> [WorkItem] { + items.filter { filter.includes($0.bucket) && (projectID == nil || $0.projectID == projectID) } + } + + /// Each chip's count, under the project filter. + static func counts(_ items: [WorkItem], projectID: String?) -> [WorkFilter: Int] { + Dictionary(uniqueKeysWithValues: WorkFilter.allCases.map { filter in + (filter, visible(items, filter: filter, projectID: projectID).count) + }) + } + + /// Newest activity first; work running now with no time counts as now. Upcoming scheduled tasks + /// go last, the next to run first. + static func ordered(_ items: [WorkItem], now: Date) -> [WorkItem] { + let (upcoming, rest) = items.reduce(into: ([WorkItem](), [WorkItem]())) { result, item in + if item.bucket == .upcoming { result.0.append(item) } else { result.1.append(item) } + } + let recent = rest.sorted { left, right in + let l = left.time ?? now, r = right.time ?? now + return l != r ? l > r : left.id < right.id + } + let later = upcoming.sorted { left, right in + switch (left.time, right.time) { + case let (l?, r?) where l != r: l < r + case (.some, nil): true + case (nil, .some): false + default: left.id < right.id + } + } + return recent + later + } + + // MARK: Coding + + static func bucket(for status: CodeSessionStatus) -> WorkBucket { + switch status { + case .needsYou: .needsYou + case .starting, .running: .working + case .ready, .failed: .done + } + } + + static func tone(for status: CodeSessionStatus) -> WorkTone { + switch status { + case .needsYou: .needsYou + case .starting, .running: .working + case .ready: .done + case .failed: .failed + } + } + + private static func sessionItem(_ session: WorkCodeSession) -> WorkItem { + let record = session.record + return WorkItem(kind: .coding, id: "coding:" + record.id, title: record.title, pill: nil, + line: record.projectName, lineSymbol: "arrow.triangle.branch", bot: nil, + time: record.startedAt, bucket: bucket(for: session.status), tone: tone(for: session.status), + projectID: record.projectID, target: .codeSession(record.id), + card: .session(record, session.status, pullRequest: session.pullRequest)) + } + + private static func launchItem(_ launch: CodeLaunch) -> WorkItem { + let status: CodeSessionStatus = launch.step.isFailed ? .failed("") : .starting("") + return WorkItem(kind: .coding, id: "launch:" + launch.id.uuidString, title: launch.title, pill: nil, + line: "", lineSymbol: "arrow.triangle.branch", bot: nil, time: nil, + bucket: bucket(for: status), tone: tone(for: status), projectID: launch.projectID, + target: launch.sessionID.map(WorkTarget.codeSession), card: .launch(launch)) + } + + /// A batch needs you when any of its sessions does, works while any works, else it's done. + private static func batchItem(_ batch: WorkCodeBatch) -> WorkItem { + let lineBuckets = batch.lines.map { Self.bucket(for: $0.status) } + let result: WorkBucket = lineBuckets.contains(.needsYou) ? .needsYou + : lineBuckets.contains(.working) || batch.startedCount < batch.batch.jobCount ? .working : .done + let tone: WorkTone = switch result { + case .needsYou: .needsYou + case .working: .working + case .done, .upcoming: .done + } + return WorkItem(kind: .coding, id: "batch:" + batch.batch.id.uuidString, title: batch.batch.title, + pill: nil, line: "", lineSymbol: "square.stack.3d.up", bot: nil, + time: batch.batch.createdAt, bucket: result, tone: tone, projectID: batch.batch.projectID, + target: .codeBatch(batch.batch.id), + card: .batch(batch.batch, lines: batch.lines, startedCount: batch.startedCount)) + } + + // MARK: Chats and background work + + private static func chatItem(_ work: DashboardWorkItem) -> WorkItem { + WorkItem(kind: .chat, id: "chat:" + work.sessionID, title: work.title, pill: String(localized: "Working"), + line: work.subtitle, lineSymbol: "bubble.left", bot: nil, time: nil, bucket: .working, + tone: .working, projectID: nil, target: .chat(work.sessionID)) + } + + private static func backgroundItem(profileID: String, work: BotBackgroundWork, sources: WorkSources) -> WorkItem { + let bot = sources.botNames[profileID] + let count = work.count > 1 ? String(localized: "\(work.count) running") : nil + let line = joined([String(localized: "In the background"), count, bot]) + return WorkItem(kind: .background, id: "background:" + profileID, + title: work.title ?? String(localized: "Background work"), pill: String(localized: "Working"), + line: line, lineSymbol: "square.stack.3d.up", bot: bot, time: nil, bucket: .working, + tone: .working, projectID: nil, target: .bot(profileID)) + } + + // MARK: Workflows + + private static func workflowItems(_ sources: WorkSources) -> [WorkItem] { + var seen = Set() + var items: [WorkItem] = [] + for run in sources.workflowsWaiting where seen.insert(run.id).inserted { + items.append(workflowItem(run, bucket: .needsYou)) + } + for run in sources.workflowsActive where seen.insert(run.id).inserted { + items.append(workflowItem(run, bucket: .working)) + } + for run in sources.workflowsRecent where run.state.isFinished && seen.insert(run.id).inserted { + items.append(workflowItem(run, bucket: .done)) + } + return items + } + + private static func workflowItem(_ run: WorkflowRunSummary, bucket: WorkBucket) -> WorkItem { + let pill: String + var tone: WorkTone = bucket == .needsYou ? .needsYou : bucket == .working ? .working : .done + switch bucket { + case .needsYou: + pill = run.waiting?.kind == "signoff" ? String(localized: "Sign off") : String(localized: "Needs you") + case .working: + pill = String(localized: "Working") + case .done, .upcoming: + switch run.state { + case .failed: + pill = String(localized: "Failed") + tone = .failed + case .cancelled: pill = String(localized: "Cancelled") + default: pill = String(localized: "Done") + } + } + let step = bucket != .done && run.stageCount > 0 + ? String(localized: "step \(min(run.stagesDone + 1, run.stageCount)) of \(run.stageCount)") : nil + return WorkItem(kind: .workflow, id: "workflow:" + run.id, title: run.workflowName, pill: pill, + line: joined([String(localized: "Workflow"), step]), lineSymbol: "point.3.connected.trianglepath.dotted", + bot: nil, time: run.endedAt ?? run.updatedAt ?? run.startedAt, bucket: bucket, tone: tone, + projectID: nil, target: .workflowRun(run.id)) + } + + // MARK: Kanban + + /// Needs you, Working and Done lanes; cards still waiting to be picked up stay on the board. + private static func taskItems(_ sources: WorkSources) -> [WorkItem] { + let done = sources.tasks.filter { $0.lane == .done } + .sorted { ($0.completedAt ?? $0.createdAt) > ($1.completedAt ?? $1.createdAt) } + .prefix(doneTaskLimit) + let open = sources.tasks.filter { $0.lane == .needsYou || $0.lane == .working } + return (open + done).map { taskItem($0, sources: sources) } + } + + private static func taskItem(_ task: HermesKanbanTask, sources: WorkSources) -> WorkItem { + let bucket: WorkBucket + let pill: String + let tone: WorkTone + switch task.lane { + case .needsYou?: + bucket = .needsYou + pill = task.statusNote ?? String(localized: "Needs you") + tone = task.gotStuck ? .failed : .needsYou + case .working?: + bucket = .working + pill = String(localized: "Working") + tone = .working + default: + bucket = .done + pill = String(localized: "Done") + tone = .done + } + let bot = task.assignee.map { sources.botNames[$0] ?? $0 } + return WorkItem(kind: .task, id: "task:" + task.id, title: task.title, pill: pill, + line: joined([String(localized: "Task"), bot]), lineSymbol: "checklist", bot: bot, + time: task.completedAt ?? task.lastHeartbeatAt ?? task.startedAt ?? task.createdAt, + bucket: bucket, tone: tone, projectID: task.projectID, target: .kanbanTask(task.id)) + } + + // MARK: Scheduled tasks + + /// Needs you only when its last run failed. Otherwise it waits for its next run: never Working, + /// since nothing reports a run in progress. + private static func scheduleItem(_ task: ScheduledTask, sources: WorkSources) -> WorkItem { + let bot = sources.botNames[task.agentID] + let line = joined([task.scheduleDescription.isEmpty ? nil : task.scheduleDescription, bot]) + let failed = task.lastError != nil || task.status == .failed + let pill: String? + if failed { + pill = String(localized: "Last run failed") + } else if task.status == .paused { + pill = String(localized: "Paused") + } else if task.status == .completed { + pill = String(localized: "Finished") + } else { + pill = task.nextRun.map { nextRunText($0, now: sources.now) } + } + return WorkItem(kind: .schedule, id: "schedule:\(task.identity.accessibilitySuffix)", title: task.name, + pill: pill, line: line, lineSymbol: "clock", bot: bot, + time: failed ? task.lastRun : task.nextRun, bucket: failed ? .needsYou : .upcoming, + tone: failed ? .failed : .upcoming, projectID: nil, target: .scheduledTask(task.identity)) + } + + /// "7:00 AM" today, "Tue 7:00 AM" later. + static func nextRunText(_ date: Date, now: Date, calendar: Calendar = .current) -> String { + calendar.isDate(date, inSameDayAs: now) + ? date.formatted(date: .omitted, time: .shortened) + : date.formatted(.dateTime.weekday(.abbreviated).hour().minute()) + } + + /// Short parts of one line ("Workflow · step 3 of 4"): names and values, never sentence fragments. + private static func joined(_ parts: [String?]) -> String { + parts.compactMap { $0?.isEmpty == false ? $0 : nil }.joined(separator: " · ") + } +} + +@MainActor +extension WorkSources { + /// Reads every store in the context now. Called from the view's body, so each store it reads is + /// observed and the list redraws when one changes. + init(context: WorkContext, now: Date = .now) { + self.init(now: now) + if let code = context.code, let reader = context.codeStatus { + readCode(code, reader: reader) + } + chatWork = context.dashboard?.workInFlightItems ?? [] + for (profileID, activity) in context.activity?.liveActivities() ?? [:] { + if case .background(let work) = activity { background[profileID] = work } + } + if let workflows = context.workflows { + workflowsWaiting = workflows.waiting + workflowsActive = workflows.active + workflowsRecent = workflows.recentRuns + } + // The board's own cards, not `tasks(in:)`: that applies the Kanban page's agent filter and search. + tasks = context.kanban?.snapshot?.tasks ?? [] + schedules = context.schedules?.tasks ?? [] + botNames = Dictionary((context.agents?.profiles ?? []).map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }) + } + + private mutating func readCode(_ code: CodeHomeStore, reader: any CodeSessionStatusReading) { + codeSessions = code.sessions.filter { $0.batchID == nil }.map { record in + // The store reads git for its selected project only. + let pullRequest = record.projectID == code.projectID + ? record.branch.flatMap { branch in code.git?.pullRequests.first { $0.branch == branch } } : nil + return WorkCodeSession(record: record, status: code.status(of: record, reader: reader), + pullRequest: pullRequest) + } + codeLaunches = code.launches.filter { $0.sessionID == nil && $0.batchID == nil } + // As Code home's batch card: its sessions, then its jobs still starting. + codeBatches = code.batches.map { batch in + let members = CodeBatchMember.members(of: batch, sessions: code.sessions) + let pending = code.pendingLaunches(of: batch).reversed() + let lines = members.map { member in + WorkBatchLine(id: member.id, title: member.title, index: member.index, + status: code.sessions.first { $0.id == member.id } + .map { code.status(of: $0, reader: reader) } ?? .ready) + } + pending.enumerated().map { offset, launch in + WorkBatchLine(id: launch.id.uuidString, title: launch.title, index: members.count + offset, + status: launch.step.isFailed ? .failed(String(localized: "Couldn't start")) + : .starting(String(localized: "Setting up"))) + } + return WorkCodeBatch(batch: batch, lines: lines, startedCount: members.count) + } + } +} diff --git a/Bighelp/Work/WorkView.swift b/Bighelp/Work/WorkView.swift new file mode 100644 index 00000000..a09bc5cd --- /dev/null +++ b/Bighelp/Work/WorkView.swift @@ -0,0 +1,159 @@ +import SwiftUI + +/// What Work needs from the shell, for the computer in use. A store that's nil (its page was never +/// made, or the computer lacks the feature) just gives no rows of its kind. +@MainActor +struct WorkContext { + /// The home header (`HomeHeaderBar`), drawn on top; nil on a pushed page that has its own. + let header: AnyView? + /// Work filtered to a project: what Code home shows for that project. + var projectID: String? = nil + var code: CodeHomeStore? = nil + var codeStatus: (any CodeSessionStatusReading)? = nil + var dashboard: DashboardModel? = nil + /// Bots' background work, kept current while Work shows. + var activity: BotChatActivityStore? = nil + var activitySource: BotChatActivitySource? = nil + var workflows: WorkflowsStore? = nil + var kanban: KanbanBoardModel? = nil + var schedules: ScheduledTasksStore? = nil + /// Bot names for the rows. + var agents: AgentDirectoryStore? = nil + let onOpen: (WorkTarget) -> Void + /// Projects, Tasks, Workflows, Schedules: only the ones this computer can open. + var doors: [WorkDoor] = [] + /// Work filtered to a project; the shell puts `WorkProjectMenu(actions:)` in the header. + var projectActions: WorkProjectActions? = nil + /// Reads every store again (pull to refresh, and each time Work shows on a new connection). + let onRefresh: () async -> Void + /// Changes with each connection to the computer, so Work reads again once it's up. + var connectionKey: String? = nil +} + +/// The Work tab: what the bots are doing on the computer in use, newest first, in Code home's cards, +/// with the four boards one tap down. +struct WorkView: View { + let context: WorkContext + @State private var filter: WorkFilter = .all + @Environment(\.scenePhase) private var scenePhase + + var body: some View { + // Read in the body, so every store it touches is observed. + let items = WorkProjection.items(WorkSources(context: context)) + WorkList(context: context, items: items, isLoading: isLoading, filter: $filter) + .botChatActivityUpdates(context.activity, source: context.activitySource, + isActive: scenePhase == .active) + .task(id: context.connectionKey) { await refresh() } + } + + private func refresh() async { + await context.onRefresh() + } + + /// A first read still under way: the list draws a still placeholder, not the empty state. + private var isLoading: Bool { + context.code?.isLoading == true || context.dashboard?.state == .loading + || context.workflows?.state == .loading || context.schedules?.loadState == .loading + } +} + +/// Work's list, given its rows. `WorkView` reads them from the stores; the fixture hands in samples. +struct WorkList: View { + let context: WorkContext + let items: [WorkItem] + var isLoading = false + @Binding var filter: WorkFilter + + var body: some View { + let projectItems = WorkProjection.visible(items, filter: .all, projectID: context.projectID) + let shown = WorkProjection.visible(items, filter: filter, projectID: context.projectID) + ScrollView { + LazyVStack(alignment: .leading, spacing: BighelpTokens.space12) { + WorkFilterChips(filter: $filter, counts: WorkProjection.counts(items, projectID: context.projectID)) + if projectItems.isEmpty { + if isLoading { WorkLoadingPlaceholder() } else { empty } + } else if shown.isEmpty { + emptyFilter + } + ForEach(shown) { item in + WorkItemCard(item: item, onOpen: context.onOpen, code: context.code) + } + if context.projectID == nil, !context.doors.isEmpty { + WorkDoorsSection(doors: context.doors) + } + } + .padding(.horizontal, BighelpTokens.space16) + .padding(.top, BighelpTokens.space4) + .padding(.bottom, BighelpTokens.space32) + .frame(maxWidth: 720) + .frame(maxWidth: .infinity) + } + .scrollIndicators(.hidden) + .bighelpRefreshable { await refresh() } + .safeAreaInset(edge: .top, spacing: 0) { + if let header = context.header { header } + } + .background(theme.canvas.ignoresSafeArea()) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("work.screen") + } + + private func refresh() async { + await context.onRefresh() + } + + private var empty: some View { + VStack(spacing: BighelpTokens.space8) { + Text("Nothing in progress") + .font(.bighelp(.title3).weight(.semibold)) + .foregroundStyle(theme.primaryText) + Text("Start a coding session from New chat.") + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + } + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .padding(.vertical, BighelpTokens.space32) + .accessibilityElement(children: .combine) + .accessibilityIdentifier("work.empty") + } + + private var emptyFilter: some View { + Group { + switch filter { + case .needsYou: Text("Nothing needs you") + case .working: Text("Nothing working") + case .done, .all: Text("Nothing done yet") + } + } + .font(.bighelp(.subheadline)) + .foregroundStyle(theme.secondaryText) + .frame(maxWidth: .infinity) + .padding(.vertical, BighelpTokens.space24) + .accessibilityIdentifier("work.empty-filter") + } + + @BighelpThemeReader private var theme +} + +/// Three still cards while the first read is under way: no loop runs. +private struct WorkLoadingPlaceholder: View { + var body: some View { + VStack(spacing: BighelpTokens.space12) { + ForEach(0..<3, id: \.self) { _ in + RoundedRectangle(cornerRadius: BighelpTokens.radius16) + .fill(theme.surface) + .frame(height: BighelpTokens.scaled(92)) + .overlay { + RoundedRectangle(cornerRadius: BighelpTokens.radius16) + .stroke(theme.border, lineWidth: BighelpTokens.hairline) + } + } + } + .accessibilityElement() + .accessibilityLabel("Loading") + .accessibilityIdentifier("work.loading") + } + + @BighelpThemeReader private var theme +} diff --git a/Bighelp/Workflows/WorkflowsAvailability.swift b/Bighelp/Workflows/WorkflowsAvailability.swift index 78e5dd4d..0fcce5ce 100644 --- a/Bighelp/Workflows/WorkflowsAvailability.swift +++ b/Bighelp/Workflows/WorkflowsAvailability.swift @@ -44,7 +44,7 @@ enum WorkflowsSupport: Equatable, Sendable { return code } - /// ☰ shows Workflows for a computer that has them or says why it can't run them. + /// Work shows Workflows for a computer that has them or says why it can't run them. var showsMenuRow: Bool { self != .missing } var canEdit: Bool { self == .available(canEdit: true) } @@ -67,7 +67,7 @@ enum WorkflowsSupport: Equatable, Sendable { } } -/// Whether the connected computer's bighelp plugin has Workflows, for the ☰ menu. +/// Whether the connected computer's bighelp plugin has Workflows, for Work's door. /// Remembered per computer, so reconnecting (every return to the app) doesn't /// hide it, and only a clear answer from the host changes it: a check that /// fails while the connection settles leaves Workflows where it was. @@ -85,7 +85,7 @@ final class WorkflowsAvailability { self.retryDelays = retryDelays } - /// The ☰ row: shown for a computer that has Workflows or says why it can't run them. + /// Work's door: shown for a computer that has Workflows or says why it can't run them. var isAvailable: Bool? { support.map(\.showsMenuRow) } /// Switches to a computer. True when it's a different one; the last answer for it diff --git a/Bighelp/Workflows/WorkflowsHomeView.swift b/Bighelp/Workflows/WorkflowsHomeView.swift index d999f930..6462ed41 100644 --- a/Bighelp/Workflows/WorkflowsHomeView.swift +++ b/Bighelp/Workflows/WorkflowsHomeView.swift @@ -32,7 +32,7 @@ struct WorkflowsContext { } } -/// ☰ › Workflows: what waits for you, what's running, and your workflows. +/// Work › Workflows: what waits for you, what's running, and your workflows. struct WorkflowsHomeView: View { let context: WorkflowsContext @State private var isUsingTemplate = false diff --git a/Bighelp/Workflows/WorkflowsStore.swift b/Bighelp/Workflows/WorkflowsStore.swift index 4eb26fbe..d720424c 100644 --- a/Bighelp/Workflows/WorkflowsStore.swift +++ b/Bighelp/Workflows/WorkflowsStore.swift @@ -27,7 +27,7 @@ enum WorkflowsLoadState: Equatable, Sendable { } } -/// ☰ › Workflows home: the host's status, what waits for you, active runs and +/// Work › Workflows: the host's status, what waits for you, active runs and /// your workflows. One per computer. It asks the host every 15 seconds while /// the home is on screen, and never when it isn't. @MainActor @@ -45,7 +45,7 @@ final class WorkflowsStore { private(set) var support: WorkflowsSupport? /// What the plugin adds (parallel blocks, delivery, outcomes): the editor offers only these. private(set) var features: WorkflowFeatures = [] - /// Asked once per visit, apart from `support`: the ☰ menu's check fills that before this screen opens. + /// Asked once per visit, apart from `support`: Work's check fills that before this screen opens. @ObservationIgnored private var askedFeatures = false var canParallel: Bool { features.contains(.parallel) } /// A change from a long-press menu that didn't work, in plain words. @@ -108,7 +108,7 @@ final class WorkflowsStore { let recentValue = try await client.runs(workflowID: nil, filter: .all, before: nil, limit: 20) guard !Task.isCancelled else { return } self.status = statusValue - // Dev Factory's recipes and runs live in Code mode (☰ › Dev Factory), not here. + // Dev Factory's recipes and runs live in Dev Factory (a project's ⋯ on Work), not here. var shown = listValue shown.workflows.removeAll(where: \.isCodeRecipe) shown.waiting.removeAll { $0.code != nil } diff --git a/Bighelp/Workspace/WorkspaceOperation.swift b/Bighelp/Workspace/WorkspaceOperation.swift index d0bbef28..386caaf1 100644 --- a/Bighelp/Workspace/WorkspaceOperation.swift +++ b/Bighelp/Workspace/WorkspaceOperation.swift @@ -251,6 +251,14 @@ enum WorkspaceOperation: String, CaseIterable, Sendable { /// Agents' HTML apps: an app's page and its latest data (plugin `native-html-apps-v1`, docs/HTML_APPS.md). case htmlAppsGet = "html-apps.get" case htmlAppsData = "html-apps.data" + /// Spaces: live panels on Today that a bot makes and a routine on the computer updates + /// (plugin `native-spaces-v1`, docs/SPACES.md). + case spacesList = "spaces.list" + case spacesGet = "spaces.get" + case spacesAdd = "spaces.add" + case spacesUpdate = "spaces.update" + case spacesRefresh = "spaces.refresh" + case spacesDelete = "spaces.delete" /// Composio Connect in Hermes, for Settings › Connections › Composio Apps (plugin `native-composio-v1`). case composioStatus = "composio.status" case composioInstall = "composio.install" diff --git a/BighelpTests/AgentAvatarBackdropTests.swift b/BighelpTests/AgentAvatarBackdropTests.swift index 891d4148..af403e51 100644 --- a/BighelpTests/AgentAvatarBackdropTests.swift +++ b/BighelpTests/AgentAvatarBackdropTests.swift @@ -18,15 +18,6 @@ struct AgentAvatarBackdropTests { } } - @Test func theEditorPreviewDrawsNothingBehindACharacter() throws { - let preview = try section(of: "Bighelp/Agents/AgentEditorView.swift", - from: "private func avatarPreview(", to: "} else if model.pendingAvatar != nil, let look = model.pendingLook") - #expect(preview.contains("CompanionAvatar(")) - for shape in ["Circle()", ".fill(", ".background("] { - #expect(!preview.contains(shape), "Something is drawn behind the character: \(shape)") - } - } - private func section(of path: String, from start: String, to end: String) throws -> String { let source = try String(contentsOf: repository.appending(path: path), encoding: .utf8) let lower = try #require(source.range(of: start), "\(start) in \(path)") diff --git a/BighelpTests/AgentDirectoryStoreTests.swift b/BighelpTests/AgentDirectoryStoreTests.swift index 89606ac2..1c738fb5 100644 --- a/BighelpTests/AgentDirectoryStoreTests.swift +++ b/BighelpTests/AgentDirectoryStoreTests.swift @@ -453,11 +453,6 @@ struct AgentDirectoryStoreTests { #expect(restored.pinnedAgents.map(\.id) == ["default", "finance"]) } - @Test func pinLimitCopyMatchesTheStoreLimit() { - #expect(AgentActionPresentation.pinnedAgentLimit == AgentDirectoryStore.pinnedAgentLimit) - #expect(AgentActionPresentation.pinLimitHint.contains("5")) - } - @Test func deletingTheAccountErasesPersistedAgentPreferences() async throws { let defaults = isolatedDefaults() let client = AgentDirectoryFixtureClient(profiles: [.defaultFixture, .financeFixture]) @@ -483,43 +478,6 @@ struct AgentDirectoryStoreTests { #expect(store.isInitialLoadPending) } - @Test func cachedAgentsUseInlineRefreshWhileAnEmptyDirectoryUsesFullLoading() { - #expect(AgentDirectoryPresentation.loadingMode(isLoading: true, hasProfiles: true) == .inline) - #expect(AgentDirectoryPresentation.loadingMode(isLoading: true, hasProfiles: false) == .fullScreen) - } - - @Test func visibleDirectorySuppressesOnlyTheInternalBighelpPlaceholder() { - let canonicalDefault = AgentProfile( - id: "default", - name: "Juno", - role: "Household agent", - summary: "Keeps things moving.", - instructions: "Be useful.", - isDefault: true - ) - - #expect( - AgentDirectoryPresentation.visibleProfiles([.bighelpLinkDefault, canonicalDefault]) - == [canonicalDefault] - ) - } - - @Test func agentRowMenuIncludesCanonicalChatAndAllManagementActions() { - #expect(AgentRowMenuAction.allCases.map(\.title) == [ - "Message", - "Edit", - "Past chats", - "Scheduled tasks", - "Group chats", - "Duplicate", - "Use with Siri", - "Use for new chats", - "Pin", - "Save as template", - "Delete", - ]) - } - @Test func selectedStableIDSurvivesStoreRecreation() async throws { let defaults = isolatedDefaults() let client = AgentDirectoryFixtureClient(profiles: [.defaultFixture, .financeFixture]) diff --git a/BighelpTests/AgentDriveTests.swift b/BighelpTests/AgentDriveTests.swift index fd41f93f..807d665f 100644 --- a/BighelpTests/AgentDriveTests.swift +++ b/BighelpTests/AgentDriveTests.swift @@ -14,30 +14,29 @@ struct AgentDriveTests { let ids = DriveCatalog.places.map(\.id) #expect(Set(ids).count == ids.count) for place in DriveCatalog.places { - #expect(!place.playbooks.isEmpty, "\(place.id) is reachable in no mode") - for (mode, steps) in place.playbooks { - #expect(steps.first?.move != nil, "\(place.id) in \(mode) starts without a move") - #expect(steps.dropLast().allSatisfy { !$0.points }, "\(place.id) points before its last step") - if steps.last?.points == true { #expect(steps.last?.target != nil) } - } + let steps = place.steps + #expect(steps.first?.move != nil, "\(place.id) starts without a move") + #expect(steps.dropLast().allSatisfy { !$0.points }, "\(place.id) points before its last step") + if steps.last?.points == true { #expect(steps.last?.target != nil) } } } @Test func thePersonsOwnWordsFindTheirPlace() { - let feed = DriveCatalog.search("How do I see what my Feed can do?", mode: .bots, nerdMode: false, limit: 3) + let feed = DriveCatalog.search("How do I see what my Feed can do?", nerdMode: false, limit: 3) #expect(feed.first?.id == "bot.dashboard.templates.feed") - let returnKey = DriveCatalog.search("enter key sends", mode: .chat, nerdMode: false, limit: 3) + let returnKey = DriveCatalog.search("enter key sends", nerdMode: false, limit: 3) #expect(returnKey.first?.id == "settings.chat.return-sends") - #expect(DriveCatalog.search("kanban", mode: .bots, nerdMode: false, limit: 5).isEmpty, "Bots mode has no Kanban") + #expect(DriveCatalog.search("kanban", nerdMode: false, limit: 5).first?.id == "kanban", + "One home: a bot's page and Work's pages are found from the same place") } @Test func nerdModePlacesStayHiddenUntilItIsOn() { - #expect(!DriveCatalog.search("logs", mode: .chat, nerdMode: false, limit: 5).contains { $0.id == "hermes.logs" }) - #expect(DriveCatalog.search("logs", mode: .chat, nerdMode: true, limit: 5).contains { $0.id == "hermes.logs" }) + #expect(!DriveCatalog.search("logs", nerdMode: false, limit: 5).contains { $0.id == "hermes.logs" }) + #expect(DriveCatalog.search("logs", nerdMode: true, limit: 5).contains { $0.id == "hermes.logs" }) } @Test func feedTemplatesWalkTheProfileThenPointAtTheDeck() throws { - let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")?.playbooks[.bots]) + let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")).steps #expect(steps.map { $0.label(bot: "Nova") } == ["Nova's profile", "Dashboard", "Templates", "Feed"]) #expect(steps[0].move == .botProfile(BotProfileOpening(tab: .dashboard))) #expect(steps[2].move == .botProfile(BotProfileOpening(sheet: .templates(.feed)))) @@ -60,8 +59,8 @@ struct AgentDriveTests { #expect(permissions.isEnabled(.appearance), "Each light tool has its own switch") } - @Test func placesListsMatchesForThisMode() throws { - let fixture = ToolFixture(mode: .bots) + @Test func placesListsMatches() throws { + let fixture = ToolFixture() let payload = try fixture.tool.execute(operation: "navigation.places", arguments: ["query": .string("feed templates")], context: ToolFixture.context, authorize: {}) guard case .array(let places)? = payload["places"], case .object(let first)? = places.first else { @@ -72,7 +71,7 @@ struct AgentDriveTests { } @Test func openRefusesWhatItCannotShowBeforeMovingAnything() { - let fixture = ToolFixture(mode: .chat) + let fixture = ToolFixture() func failure(_ arguments: [String: BighelpJSONValue]) -> String? { do { _ = try fixture.tool.execute(operation: "navigation.open", arguments: arguments, context: ToolFixture.context, authorize: {}); return nil } @@ -83,18 +82,17 @@ struct AgentDriveTests { #expect(failure(["place": .string("kanban"), "tap": .string("x")]) == "invalid_arguments") #expect(failure(["place": .string("kanban"), "note": .string(String(repeating: "a", count: 161))]) == "invalid_arguments") #expect(failure(["place": .string("nowhere")]) == "unknown_place") - #expect(failure(["place": .string("bot.dashboard")]) == "not_in_this_mode") #expect(failure(["place": .string("hermes.logs")]) == "needs_nerd_mode") #expect(fixture.opened.isEmpty) } @Test func openStartsTheDriveForTheAgentInTheChatWhenNoBotIsNamed() throws { - let fixture = ToolFixture(mode: .bots) + let fixture = ToolFixture() let payload = try fixture.tool.execute(operation: "navigation.open", arguments: ["place": .string("bot.info"), "note": .string("Here it is")], context: ToolFixture.context, authorize: {}) #expect(payload["opened"] == .string("bot.info")) - #expect(payload["mode"] == .string("bots")) + #expect(payload["mode"] == .string("home")) #expect(fixture.opened.map(\.bot) == ["nova"]) #expect(fixture.opened.map(\.note) == ["Here it is"]) #expect(throws: (any Error).self) { @@ -105,7 +103,7 @@ struct AgentDriveTests { } @Test func aClosedChatStopsTheDriveBeforeItStarts() { - let fixture = ToolFixture(mode: .chat) + let fixture = ToolFixture() #expect(throws: (any Error).self) { try fixture.tool.execute(operation: "navigation.open", arguments: ["place": .string("kanban")], context: ToolFixture.context, authorize: { throw CancellationError() }) @@ -119,7 +117,7 @@ struct AgentDriveTests { let router = FakeRouter(path: [.chat(conversationID: "c1")]) let navigator = DriveNavigator() navigator.attach(router, agent: { _ in nil }, chat: { nil }) - let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")?.playbooks[.bots]) + let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")).steps let trail = navigator.start(title: "Feed templates", steps: steps, bot: (id: "nova", name: "Nova"), agent: DriveAgent(id: "nova", name: "Nova", imageURL: nil), note: "Swipe right", chat: nil, reduceMotion: true) @@ -131,7 +129,7 @@ struct AgentDriveTests { #expect(navigator.spotlight == "dashboard.templates.deck") navigator.returnToChat() try await waitUntil { navigator.phase == .idle } - #expect(router.restored == DriveSnapshot(tab: .sessions, path: [.chat(conversationID: "c1")])) + #expect(router.restored == DriveSnapshot(tab: .conversations, view: .chats, path: [.chat(conversationID: "c1")])) } @Test func aStepLightsOnlyWhenTheScreenShowsIt() async throws { @@ -139,7 +137,7 @@ struct AgentDriveTests { router.shows = [] let navigator = DriveNavigator() navigator.attach(router, agent: { _ in nil }, chat: { nil }) - let steps = try #require(DriveCatalog.place("settings.chat.return-sends")?.playbooks[.chat]) + let steps = try #require(DriveCatalog.place("settings.chat.return-sends")).steps navigator.start(title: "Return sends", steps: steps, bot: nil, agent: DriveAgent(id: "a", name: "A", imageURL: nil), note: nil, chat: nil, reduceMotion: true) try await Task.sleep(for: .milliseconds(600)) @@ -156,7 +154,7 @@ struct AgentDriveTests { router.shows = ["settings.menu.chat"] let navigator = DriveNavigator() navigator.attach(router, agent: { _ in nil }, chat: { nil }) - let steps = try #require(DriveCatalog.place("settings.chat.return-sends")?.playbooks[.chat]) + let steps = try #require(DriveCatalog.place("settings.chat.return-sends")).steps navigator.start(title: "Return sends", steps: steps, bot: nil, agent: DriveAgent(id: "a", name: "A", imageURL: nil), note: nil, chat: nil, reduceMotion: true) try await waitUntil { navigator.phase == .arrived } @@ -170,7 +168,7 @@ struct AgentDriveTests { router.shows = ["settings.menu.chat"] let navigator = DriveNavigator() navigator.attach(router, agent: { _ in nil }, chat: { nil }) - let steps = try #require(DriveCatalog.place("settings.chat.return-sends")?.playbooks[.chat]) + let steps = try #require(DriveCatalog.place("settings.chat.return-sends")).steps navigator.start(title: "Return sends", steps: steps, bot: nil, agent: DriveAgent(id: "a", name: "A", imageURL: nil), note: nil, chat: nil, reduceMotion: true) try await waitUntil { navigator.scrollRequest != nil } @@ -187,7 +185,7 @@ struct AgentDriveTests { router.shows = [] let navigator = DriveNavigator() navigator.attach(router, agent: { _ in nil }, chat: { nil }) - let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")?.playbooks[.bots]) + let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")).steps navigator.start(title: "Feed templates", steps: steps, bot: (id: "nova", name: "Nova"), agent: DriveAgent(id: "nova", name: "Nova", imageURL: nil), note: nil, chat: nil, reduceMotion: true) try await waitUntil { router.moves.count == 1 } @@ -204,7 +202,7 @@ struct AgentDriveTests { let first = FakeRouter(path: [.chat(conversationID: "c1")]) let navigator = DriveNavigator() navigator.attach(first, agent: { _ in nil }, chat: { nil }) - let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")?.playbooks[.bots]) + let steps = try #require(DriveCatalog.place("bot.dashboard.templates.feed")).steps navigator.start(title: "Feed templates", steps: steps, bot: (id: "nova", name: "Nova"), agent: DriveAgent(id: "nova", name: "Nova", imageURL: nil), note: nil, chat: nil, reduceMotion: true) try await waitUntil { navigator.phase == .arrived } @@ -229,7 +227,7 @@ struct AgentDriveTests { for case let file as URL in files where file.pathExtension == "swift" { code += (try? String(contentsOf: file, encoding: .utf8)) ?? "" } - let targets = Set(DriveCatalog.places.flatMap { $0.playbooks.values.flatMap { $0.compactMap(\.target) } }) + let targets = Set(DriveCatalog.places.flatMap { $0.steps.compactMap(\.target) }) let accessibility = SettingsMenuSection.allCases.map(\.accessibilityIdentifier) for target in targets { let head = target.split(separator: ".").dropLast().joined(separator: ".") + "." @@ -267,7 +265,7 @@ struct AgentDriveTests { try await settle { navigator.agent("default")?.name == "Alfie" } #expect(navigator.agent("default")?.name == "Alfie") let place = try #require(DriveCatalog.place("settings.chat.return-sends")) - _ = navigator.open(place, steps: try #require(place.playbooks[.chat]), bot: nil, note: nil, agentID: "default") + _ = navigator.open(place, steps: place.steps, bot: nil, note: nil, agentID: "default") #expect(navigator.agent?.name == "Alfie") try await settle { azure.appState.isSettingsPresented } #expect(azure.appState.isSettingsPresented) @@ -290,7 +288,7 @@ private final class FakeRouter: DriveRouting { init(path: [AppRoute]) { self.path = path } - func snapshot() -> DriveSnapshot { DriveSnapshot(tab: .sessions, path: path) } + func snapshot() -> DriveSnapshot { DriveSnapshot(tab: .conversations, view: .chats, path: path) } func restore(_ snapshot: DriveSnapshot) async { restored = snapshot; path = snapshot.path } func perform(_ move: DriveMove, bot: String?) async { moves.append(move) @@ -307,9 +305,9 @@ private final class ToolFixture { var opened: [(place: String, bot: String?, note: String?)] = [] private(set) var tool: DeviceNavigationTool! - init(mode: BighelpMode, nerdMode: Bool = false) { + init(nerdMode: Bool = false) { tool = DeviceNavigationTool(.init( - mode: { mode }, nerdMode: { nerdMode }, + nerdMode: { nerdMode }, botName: { $0 == "nova" ? "Nova" : nil }, open: { [weak self] place, steps, bot, note, _ in self?.opened.append((place.id, bot?.id, note)) @@ -345,11 +343,10 @@ private final class DriveGatewaySource { private struct DriveGatewayHarness: View { let source: DriveGatewaySource let navigator: DriveNavigator - let settings = SettingsStore(defaults: isolatedDefaults()) var body: some View { let gateway = source.gateway Color.clear.modifier(DriveShellHooks(appState: gateway.appState, featureStore: gateway.features, agents: gateway.agents, - settings: settings, usesDemoFixtures: false, navigator: navigator)) + usesDemoFixtures: false, navigator: navigator)) } } diff --git a/BighelpTests/AgentEditorModelTests.swift b/BighelpTests/AgentEditorModelTests.swift index 5223365d..a5c941d0 100644 --- a/BighelpTests/AgentEditorModelTests.swift +++ b/BighelpTests/AgentEditorModelTests.swift @@ -5,20 +5,6 @@ import UIKit @MainActor struct AgentEditorModelTests { - @Test func chatEditorPresentationRequiresExactProfileAndCurrentOwner() async throws { - let store = AgentDirectoryStore(client: AgentDirectoryFixtureClient(profiles: [.financeFixture]), defaults: isolatedDefaults()) - try await store.load() - var current = true - let presentation = ChatAgentEditorPresentation(profileID: AgentProfile.financeFixture.id, - store: store, isCurrent: { current }) - #expect(presentation.isAvailable) - let wrongProfile = ChatAgentEditorPresentation(profileID: "different-profile", store: store, isCurrent: { true }) - #expect(!wrongProfile.isAvailable) - current = false - #expect(!presentation.isAvailable) - #expect(store.profiles == [.financeFixture]) - } - @Test func unchangedDraftCanCloseAndSavedChangesBecomeTheNewBaseline() async throws { let store = AgentDirectoryStore( client: AgentDirectoryFixtureClient(profiles: [.financeFixture]), diff --git a/BighelpTests/AgentHeroHeaderLayoutTests.swift b/BighelpTests/AgentHeroHeaderLayoutTests.swift index afc00974..2947aabb 100644 --- a/BighelpTests/AgentHeroHeaderLayoutTests.swift +++ b/BighelpTests/AgentHeroHeaderLayoutTests.swift @@ -6,26 +6,30 @@ import UIKit @MainActor struct AgentHeroHeaderLayoutTests { /// The shell makes the chrome again on every update; only what it shows may redraw the chat. - @Test func chromeIsTheSameWhenWhatItShowsIsTheSame() { - var opened = 0 - let first = AgentHomeChrome(isEnabled: true, showsTabBar: true, onMenu: { opened += 1 }, - unreadTabs: [.feed], barTabs: [.sessions, .feed]) - let again = AgentHomeChrome(isEnabled: true, showsTabBar: true, onMenu: { opened += 2 }, - unreadTabs: [.feed], barTabs: [.sessions, .feed]) - #expect(first == again) - var read = again - read.unreadTabs = [] - #expect(first != read, "A dot going away still redraws the bar") + @Test func pushedChatChromeIsTheSameWhateverItsAction() { + var opened: [String] = [] + let pushed = AgentHomeChrome.pushedChat(onProfile: { opened.append($0) }) + #expect(pushed == AgentHomeChrome.pushedChat(onProfile: { _ in })) + #expect(pushed != AgentHomeChrome()) + pushed.onProfile("atlas") + #expect(opened == ["atlas"]) } - @Test func chatHomeUsesACompactIdentityPill() { - let controller = UIHostingController(rootView: - AgentHomeChatHeader(agentID: "default", displayName: "Atlas", imageURL: nil, - activity: .idle, groupIdentity: nil, options: AnyView(Color.clear), - chrome: AgentHomeChrome(), screenHeight: 852, beforeAction: {}) - ) - let size = controller.sizeThatFits(in: CGSize(width: 393, height: 852)) - #expect(size.height <= 54, "Chat mode should use Bots mode's single-row pill") + /// Back, the bot and ⋯ are one row, as in Bots mode. A new chat's To row is a row of its own + /// under them: it adds its height and leaves the buttons where they are. + @Test func aNewChatsToRowSitsUnderTheHeadersButtons() { + func height(toRow: AnyView?) -> CGFloat { + let pill = ChatAgentIdentityPill(agentID: "default", name: "Atlas", imageURL: nil) + let controller = UIHostingController(rootView: + ChatPushedHeader(identity: AnyView(pill), toRow: toRow, options: AnyView(Color.clear), onBack: {}) + ) + return controller.sizeThatFits(in: CGSize(width: 393, height: 852)).height + } + let plain = height(toRow: nil) + #expect(plain > 0) + #expect(plain <= 54) + let withToRow = height(toRow: AnyView(Color.clear.frame(height: 48))) + #expect(abs(withToRow - plain - 48) < 1) } /// The chat's top inset is the header's height, so a status line that grew the header diff --git a/BighelpTests/AgentsPresentationTests.swift b/BighelpTests/AgentsPresentationTests.swift index 13799d76..9c108db6 100644 --- a/BighelpTests/AgentsPresentationTests.swift +++ b/BighelpTests/AgentsPresentationTests.swift @@ -13,119 +13,6 @@ struct AgentsPresentationTests { summary: "Sources and careful explanations.", instructions: "", isDefault: false ) - @MainActor @Test func groupPreferencesPersistWithinOwnerAndAreErasedWithAccountData() throws { - let suite = "group-preferences-\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - AgentGroupPreferences(defaults: defaults).set(.init(pinned: true, archived: true), id: "group", scope: "owner-a") - let restored = AgentGroupPreferences(defaults: defaults) - #expect(restored.entry("group", scope: "owner-a").pinned) - #expect(restored.entry("group", scope: "owner-a").archived) - #expect(!restored.entry("group", scope: "owner-b").archived) - AgentDirectoryStore.erasePersistedUserPreferences(defaults: defaults) - #expect(!AgentGroupPreferences(defaults: defaults).entry("group", scope: "owner-a").archived) - } - - @Test func searchPreservesOrderAndMatchesMultiplePublicFields() { - let profiles = [studio, field] - #expect(AgentDirectoryPresentation.visibleProfiles(profiles, query: "planning workshop") == [studio]) - #expect(AgentDirectoryPresentation.visibleProfiles(profiles, query: " ") == profiles) - #expect(AgentDirectoryPresentation.visibleProfiles(profiles, query: "FIELD") == [field]) - } - - @Test func searchNeverExposesInstructionMatchesOrTheInternalPlaceholder() { - #expect(AgentDirectoryPresentation.visibleProfiles([studio], query: "Private instruction").isEmpty) - #expect(AgentDirectoryPresentation.visibleProfiles([.bighelpLinkDefault, studio]) == [studio]) - } - - @Test func memberSearchKeepsTheCompleteGroupRoster() { - let group = room() - let visible = AgentDirectoryPresentation.visibleGroups( - [group], profiles: [studio, field], query: "Field Notes", profileID: nil - ) - #expect(visible.count == 1) - #expect(visible.first?.memberCount == 3) - #expect(visible.first?.participants(profiles: [studio, field]).count == 3) - } - - @Test func unavailableMembersKeepTheirNativeIdentityAndCount() { - let participants = room().participants(profiles: [studio, field]) - #expect(participants.map(\.memberID) == ["member-studio", "member-field", "member-absent"]) - #expect(participants.last?.availability == .profileUnavailable) - #expect(participants.last?.canOpenAgentChat == false) - } - - @Test func groupSelectionPreservesTheCodexFirstMatchingFallback() { - let groups = [room(id: "first"), room(id: "second")] - #expect(AgentDirectoryPresentation.selectedGroup(in: groups, selectedID: nil)?.roomID == "first") - #expect(AgentDirectoryPresentation.selectedGroup(in: groups, selectedID: "second")?.roomID == "second") - #expect(AgentDirectoryPresentation.selectedGroup(in: groups, selectedID: "filtered-out")?.roomID == "first") - #expect(AgentDirectoryPresentation.selectedGroup(in: [], selectedID: "first") == nil) - } - - @Test func groupFilterUsesProfileIdentityRatherThanDisplayName() { - #expect(AgentDirectoryPresentation.visibleGroups( - [room()], profiles: [studio], query: "", profileID: "studio" - ).count == 1) - #expect(AgentDirectoryPresentation.visibleGroups( - [room()], profiles: [studio], query: "", profileID: "Studio" - ).isEmpty) - } - - @Test func groupsAlwaysPrecedeAgentsIncludingWhenFilteredToAnAgent() { - #expect(AgentDirectoryPresentation.sectionOrder == [.groups, .agents]) - #expect(AgentDirectoryPresentation.sectionOrder(filteredToProfileID: "studio") == [.groups, .agents]) - } - - @Test func unknownCapabilitiesDoNotEnableRemoteActions() throws { - let owner = try owner() - let items = actions(owner: owner, capabilities: WorkspaceCapabilities(owner: owner)) - #expect(items.first { $0.action == .openChat }?.isEnabled == false) - #expect(items.first { $0.action == .edit }?.isEnabled == false) - #expect(items.first { $0.action == .togglePin }?.isEnabled == true) - #expect(items.first { $0.action == .setPrimary }?.isEnabled == true) - #expect(!items.contains { $0.action == .shortcuts }) - } - - @Test func profileSpecificPolicyOverridesWorkspaceCapability() throws { - let owner = try owner() - let capabilities = WorkspaceCapabilities( - owner: owner, values: [.profilesEdit: .available], - profileValues: ["studio": [.profilesEdit: .unavailable(.policyRestricted)]] - ) - let item = actions(owner: owner, capabilities: capabilities).first { $0.action == .edit } - #expect(item?.isEnabled == false) - #expect(item?.detail == WorkspaceUnavailableReason.policyRestricted.message) - } - - @Test func staleCapabilitySnapshotCannotEnableNewOwnerActions() throws { - let previous = try owner() - let current = try owner() - let capabilities = WorkspaceCapabilities(owner: previous, values: [.canonicalAgentChat: .available]) - #expect(actions(owner: current, capabilities: capabilities).first { $0.action == .openChat }?.isEnabled == false) - } - - @Test func directNativeRuntimeSolelyOwnsInitialStoreRefreshWhileLinkKeepsViewBootstrap() throws { - let direct = WorkspaceOwner( - authority: try .direct(endpointIdentity: "https://hermes.example", providerID: "provider", userID: "user"), - authenticationGeneration: UUID(), connectionGeneration: UUID() - ) - let link = WorkspaceOwner( - authority: try .link(origin: "https://loopdy.example", deviceID: "device", deviceAuthorizationEpoch: 1, - hostID: "host", hostAuthorizationEpoch: 1), - authenticationGeneration: UUID(), connectionGeneration: UUID() - ) - let fixture = WorkspaceOwner( - authority: try .fixture(id: "agents-presentation-fixture"), - authenticationGeneration: UUID(), connectionGeneration: UUID() - ) - - #expect(!AgentsView.shouldBootstrapStoreRefresh(for: direct)) - #expect(AgentsView.shouldBootstrapStoreRefresh(for: link)) - #expect(AgentsView.shouldBootstrapStoreRefresh(for: fixture)) - #expect(AgentsView.shouldBootstrapStoreRefresh(for: nil)) - } - @MainActor @Test func nativeRefreshFlightOutlivesCancelledViewCallerUntilExplicitSuspension() async { let flight = NativeWorkspaceRefreshFlight() let state = NativeRefreshFlightTestState() @@ -162,45 +49,6 @@ struct AgentsPresentationTests { await second.value } - @Test func pinLimitNeverPreventsUnpinAndPrimaryRemainsSeparate() throws { - let owner = try owner() - let items = actions(owner: owner, capabilities: WorkspaceCapabilities(owner: owner), isPrimary: true, isPinned: true, canPin: false) - #expect(items.first { $0.action == .togglePin }?.title == "Unpin") - #expect(items.first { $0.action == .togglePin }?.isEnabled == true) - #expect(items.first { $0.action == .setPrimary }?.isEnabled == false) - } - - @Test func deleteAndSaveTemplateAppearOnlyWhenOffered() throws { - let owner = try owner() - let capabilities = WorkspaceCapabilities(owner: owner) - let plain = actions(owner: owner, capabilities: capabilities).map(\.action) - #expect(!plain.contains(.delete)) - #expect(!plain.contains(.saveTemplate)) - let offered = actions(owner: owner, capabilities: capabilities, canDelete: true, canSaveTemplate: true) - #expect(offered.map(\.action).suffix(2) == [.saveTemplate, .delete]) - #expect(offered.last?.action.isDestructive == true) - } - - private func actions( - owner: WorkspaceOwner, capabilities: WorkspaceCapabilities, - isPrimary: Bool = false, isPinned: Bool = false, canPin: Bool = true, - canDelete: Bool = false, canSaveTemplate: Bool = false - ) -> [AgentActionItem] { - AgentActionsPresentation.items( - profileID: "studio", owner: owner, capabilities: capabilities, - isPrimary: isPrimary, isPinned: isPinned, canPin: canPin, - canClone: true, shortcutsAvailable: false, hasNavigation: true, - canDelete: canDelete, canSaveTemplate: canSaveTemplate - ) - } - - private func owner() throws -> WorkspaceOwner { - WorkspaceOwner( - authority: try .fixture(id: "agents-presentation"), - authenticationGeneration: UUID(), connectionGeneration: UUID() - ) - } - private func room(id: String = "research-circle") -> HermesBotModeRoomSummary { let members = ["studio", "field", "absent"].map { id in HermesBotModeRoomMember( diff --git a/BighelpTests/AppLayoutTests.swift b/BighelpTests/AppLayoutTests.swift deleted file mode 100644 index eb7bc02b..00000000 --- a/BighelpTests/AppLayoutTests.swift +++ /dev/null @@ -1,127 +0,0 @@ -import Foundation -import Testing -@testable import Bighelp - -/// Settings › Appearance › App layout: the bottom bar after Chat, and ☰'s order. -struct AppLayoutTests { - @Test func theStandardLayoutIsTodaysBarAndMenu() { - let layout = BighelpAppLayout.standard - #expect(layout.barTabs == [.sessions, .feed, .ideas, .goals], "Two either side of New chat") - #expect(layout.menuPlaces == [.agents, .sessions, .projects, .kanban, .workflows, .scheduledTasks, .usage, - .files, .settings]) - } - - @Test func sessionsIsInTheMenuAndCanTakeABottomBarTab() { - var layout = BighelpAppLayout.standard - #expect(layout.menuPlaces[1] == .sessions, "Every chat, right under Agents") - layout.unpin(.goals) - layout.pin(.sessions) - #expect(layout.barTabs == [.sessions, .feed, .ideas, .sessionList], - "Its own tab: Chat stays the agent's chat") - #expect(!layout.menuPlaces.contains(.sessions), "A pinned place isn't listed twice") - #expect(BighelpPlace(tab: .sessionList) == .sessions) - #expect(BighelpAppLayout(saved: layout.saved) == layout) - } - - @Test func aLayoutSavedBeforeSessionsGetsItAtTheEndOfTheMenu() { - let saved = #"{"pinned":["feed","kanban"],"menu":["usage","agents","projects","workflows","scheduledTasks","ideas","goals","files","settings"]}"# - let layout = BighelpAppLayout(saved: saved) - #expect(layout.menuPlaces.last == .sessions, "The person's own order stays; the new place comes after it") - #expect(layout.barTabs == [.sessions, .feed, .kanban]) - } - - @Test func swappingBoardsForPagesPutsTheBoardsInTheMenu() { - var layout = BighelpAppLayout.standard - for place in [BighelpPlace.feed, .ideas, .goals] { layout.unpin(place) } - for place in [BighelpPlace.kanban, .workflows, .scheduledTasks] { layout.pin(place) } - #expect(layout.barTabs == [.sessions, .kanban, .workflows, .scheduledTasks]) - #expect(layout.menuPlaces == [.agents, .sessions, .projects, .usage, .feed, .ideas, .goals, .files, .settings], - "Feed, Ideas and Goals stay one tap away in the menu") - #expect(!layout.menuPlaces.contains(.kanban), "A pinned place isn't listed twice") - } - - @Test func theBarHoldsChatAndThreeMoreAndSettingsStaysInTheMenu() { - var layout = BighelpAppLayout.standard - #expect(!layout.canPinMore) - layout.pin(.kanban) - #expect(!layout.isPinned(.kanban), "Full: remove one first") - layout.unpin(.goals) - layout.pin(.settings) - #expect(!layout.isPinned(.settings), "Settings can't leave the menu") - layout.pin(.kanban) - #expect(layout.barTabs.last == .kanban) - } - - @Test func aFourPlaceBarFromAnOlderBuildKeepsThreeAndTheFourthGoesBackToTheMenu() { - let layout = BighelpAppLayout(saved: #"{"pinned":["feed","ideas","goals","files"],"menu":[]}"#) - #expect(layout.barTabs == [.sessions, .feed, .ideas, .goals]) - #expect(layout.menuPlaces.contains(.files), "Still one tap away in ☰") - } - - @MainActor - @Test func newChatSitsInTheMiddleOfTheBar() { - #expect(FloatingTabBar.slots(tabs: [.sessions, .feed, .ideas, .goals], hasNewChat: true) - == [.tab(.sessions), .tab(.feed), .newChat, .tab(.ideas), .tab(.goals)]) - #expect(FloatingTabBar.slots(tabs: [.sessions], hasNewChat: true) == [.tab(.sessions), .newChat]) - #expect(!FloatingTabBar.slots(tabs: [.sessions, .feed], hasNewChat: false).contains(.newChat), - "All agents has its own New chat") - } - - @Test func agentsAndSettingsStayInTheMenuWhenPinned() { - var layout = BighelpAppLayout.standard - layout.unpin(.goals) - layout.pin(.agents) - #expect(layout.barTabs.last == .agents) - #expect(layout.menuPlaces.first == .agents, "Quick screens hide the bar; ☰ still reaches Agents") - #expect(layout.menuPlaces.last == .settings) - #expect(!layout.menuPlaces.contains(.feed), "Other pinned places aren't listed twice") - layout.moveMenu(from: [0], to: 3) - #expect(layout.menuPlaces.filter { $0 == .agents }.count == 1) - #expect(layout.menuPlaces[2] == .agents) - #expect(BighelpAppLayout(saved: layout.saved) == layout) - } - - @Test func barAndMenuOrdersMove() { - var layout = BighelpAppLayout.standard - layout.movePinned(from: [2], to: 0) - #expect(layout.barTabs == [.sessions, .goals, .feed, .ideas], "Chat stays first") - layout.moveMenu(from: [8], to: 0) - #expect(layout.menuPlaces.first == .settings) - layout.unpin(.goals) - #expect(layout.menuPlaces.last == .goals, "Taken out of the bar, it comes back at the end of the menu") - #expect(layout.menuPlaces.first == .settings) - } - - @Test func savedLayoutsSurviveAndOddOnesFallBack() { - var layout = BighelpAppLayout.standard - layout.unpin(.ideas) - layout.pin(.workflows) - layout.moveMenu(from: [1], to: 0) - let restored = BighelpAppLayout(saved: layout.saved) - #expect(restored == layout) - #expect(BighelpAppLayout(saved: nil) == .standard) - #expect(BighelpAppLayout(saved: "not json") == .standard) - // A place from a newer build is dropped; a missing one comes back in the menu. - let odd = BighelpAppLayout(saved: #"{"pinned":["kanban","teleporter","kanban","settings"],"menu":["usage"]}"#) - #expect(odd.barTabs == [.sessions, .kanban]) - #expect(odd.menuPlaces.first == .usage && Set(odd.menuPlaces + [.kanban]) == Set(BighelpPlace.allCases)) - // A launch argument arrives as a dictionary of names. - let argument = BighelpAppLayout(savedObject: ["pinned": ["agents", "feed"], "menu": [String]()]) - #expect(argument.barTabs == [.sessions, .agents, .feed]) - #expect(BighelpAppLayout(savedObject: 42) == .standard) - } - - @MainActor - @Test func settingsKeepTheLayoutOnThisDevice() throws { - let suite = "bighelp.tests.app-layout.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let settings = SettingsStore(defaults: defaults) - #expect(settings.appLayout == .standard) - settings.appLayout.unpin(.feed) - settings.appLayout.pin(.kanban) - #expect(SettingsStore(defaults: defaults).appLayout.barTabs == [.sessions, .ideas, .goals, .kanban]) - settings.appLayout = .standard - #expect(defaults.string(forKey: "bighelp.app-layout") == nil, "The standard layout saves nothing") - } -} diff --git a/BighelpTests/AppStateTests.swift b/BighelpTests/AppStateTests.swift index b9d5c146..24eed4a1 100644 --- a/BighelpTests/AppStateTests.swift +++ b/BighelpTests/AppStateTests.swift @@ -5,45 +5,73 @@ import Testing struct AppStateTests { @Test @MainActor func hostSwitchKeepsTheConnectionsScreenButClearsChatOwnership() { let state = AppState() - state.selectedTab = .agents + state.selectedTab = .work state.activateConversation(id: "old-host-chat", source: .newChat) state.requestVoiceMode(for: "old-host-chat") state.path = [.workspaceConnections] state.resetForHostBoundary() - #expect(state.selectedTab == .agents) + #expect(state.selectedTab == .work) #expect(state.path == [.workspaceConnections]) #expect(state.activeConversationID == nil) #expect(state.pendingVoiceConversationID == nil) } - - @Test func ordinaryHostSwitchPreservesTheCodexSessionsLanding() { + /// Another computer or account: the old one's pages close, and the person stays on their tab. + @Test func aComputerOrAccountSwitchKeepsTheTabAndClosesItsPages() { let state = AppState() - state.select(.profile) - state.path = [.sessions] - + state.select(.today) + state.path = [.projects, .chat(conversationID: "old")] state.resetForHostBoundary() + #expect(state.selectedTab == .today) + #expect(state.path.isEmpty) - #expect(state.selectedTab == .sessions) + state.path = [.sessions] + state.resetForAccountBoundary() + #expect(state.selectedTab == .today) #expect(state.path.isEmpty) } - /// With every computer showing, its lists stay put when the working computer changes; - /// the old computer's own pages above them go. - @Test func aComputerSwitchInAllHostsKeepsItsLists() { + /// Every computer has its own `AppState`. The tab and the first tab's view are the whole app's, + /// so a chat opened on another computer lands on the place the person was on; each keeps its + /// own pages. + @Test func everyComputersStateSharesTheTabAndTheView() { + let home = HomeSelection() + let first = AppState(home: home), second = AppState(home: home) + first.select(.bots) + first.select(.work) + first.open(.projects) + + #expect(second.selectedTab == .work) + #expect(second.home.view == .bots) + #expect(second.path.isEmpty) + } + + @Test func aLaunchLandsOnThePlaceThePersonPicked() { + let home = HomeSelection() + home.land(on: .bots, view: .chats) + #expect(home.tab == .conversations) + #expect(home.view == .bots) + home.land(on: .chats, view: .bots) + #expect(home.view == .chats) + home.land(on: .today, view: .bots) + #expect(home.tab == .today) + #expect(home.view == .bots, "Today and Work keep the first tab on the person's own view") + home.land(on: .work, view: .chats) + #expect(home.tab == .work) + #expect(home.view == .chats) + } + + /// A page that belongs to another tab (Kanban from a link) opens over that tab, so Back goes there. + @Test func aPageOfAnotherTabOpensOverIt() async { let state = AppState() - state.path = [.allHostsChats, .projects, .chat(conversationID: "old")] - state.resetForHostBoundary(keepsAllHostsScreens: true) - #expect(state.selectedTab == .sessions) - #expect(state.path == [.allHostsChats]) + state.activateConversation(id: "current", source: .sessions) - state.select(.scheduledTasks) - state.resetForHostBoundary(keepsAllHostsScreens: true) - #expect(state.selectedTab == .scheduledTasks, "Every computer's tasks stay up") + state.select(.work, thenOpen: [.kanban]) + // The Mac pushes a moment after the switch. + try? await Task.sleep(for: .milliseconds(400)) - state.path = [.allHostsChats] - state.resetForHostBoundary() - #expect(state.path.isEmpty, "One computer: nothing of the old one stays") + #expect(state.selectedTab == .work) + #expect(state.path == [.kanban]) } @Test func conversationActivationTracksTheCanonicalSessionID() { @@ -55,29 +83,19 @@ struct AppStateTests { #expect(state.path == [.chat(conversationID: "session-1")]) } - @Test func newChatReplacesTrailingChatButSessionsChatPushesFromItsRootTab() { + @Test func newChatReplacesTrailingChatButAChatFromAListIsPushed() { let state = AppState() state.path = [.chat(conversationID: "old")] state.activateConversation(id: "new", source: .newChat) #expect(state.path == [.chat(conversationID: "new")]) - state.openSessions() + state.select(.chats) state.activateConversation(id: "saved", source: .sessions) - #expect(state.selectedTab == .sessions) + #expect(state.selectedTab == .conversations) + #expect(state.home.view == .chats) #expect(state.path == [.chat(conversationID: "saved")]) } - @Test func openingSessionsFromChatReplacesChat() { - let state = AppState() - state.activateConversation(id: "current", source: .newChat) - - state.openSessions() - - #expect(state.selectedTab == .sessions) - #expect(state.path.isEmpty) - #expect(state.activeConversationID == "current") - } - @Test func quickSwitchFromShellAppendsButReplacesTrailingChat() { let state = AppState() state.activateConversation(id: "first", source: .quickSwitch) @@ -120,137 +138,27 @@ struct AppStateTests { @Test func anAlertWithoutAChatAsksForNeedsYouAndLeavesThePlaceAlone() { let state = AppState() - state.select(.agents) + state.select(.work) state.path = [.sessions, .chat(conversationID: "current")] state.openNeedsYou() #expect(state.isNeedsYouRequested) - #expect(state.selectedTab == .agents) + #expect(state.selectedTab == .work) #expect(state.path == [.sessions, .chat(conversationID: "current")]) } - @Test func legacyInboxTabSelectionOpensChat() { - let state = AppState() - state.select(.agents) - state.path = [.sessions] - - state.select(.inbox) - - #expect(state.selectedTab == .sessions) - #expect(state.path.isEmpty) - #expect(AppTab.allCases == [.sessions, .feed, .ideas, .goals, .apps]) - } - - @Test func selectingARootTabClearsAnyStaleNavigationPath() { + /// A tab is a root: picking one (the bar, the sidebar, ⌘1–⌘3) closes whatever was pushed. + @Test func selectingATabClosesWhatWasPushed() { let state = AppState() state.path = [ .sessions, .chat(conversationID: "stale-session") ] - state.select(.agents) + state.select(.today) - #expect(state.selectedTab == .agents) + #expect(state.selectedTab == .today) #expect(state.path.isEmpty) } - - @Test func drawerHighlightsOnlyTheRootDestinationThatIsActuallyVisible() { - let state = AppState() - state.select(.agents) - - #expect(state.drawerSelectedTab == .agents) - - state.activateConversation(id: "session-current", source: .newChat) - - #expect(state.selectedTab == .agents) - #expect(state.drawerSelectedTab == nil) - } - - @Test func rootRouteOpenersReplaceAnyStaleNavigationStack() { - let state = AppState() - - state.path = [ - .scheduledTasks, - .scheduledTask(id: "stale-task") - ] - state.openSessions() - #expect(state.selectedTab == .sessions) - #expect(state.path.isEmpty) - - state.path = [ - .sessions, - .chat(conversationID: "stale-chat") - ] - state.openScheduledTasks() - #expect(state.selectedTab == .scheduledTasks) - #expect(state.path.isEmpty) - } - - /// Leaving a chat for any other place holds it, as it was opened, for the tab it was under. - @Test func leavingAChatForAnotherPlaceHoldsIt() { - for tab in [AppTab.ideas, .feed, .apps, .agents, .kanban, .projects] { - let state = AppState() - state.chatOpenedFromList = true - state.activateConversation(id: "chat-1", source: .sessions) - #expect(state.heldChat == nil) - - state.select(tab) - - #expect(state.path.isEmpty) - #expect(state.heldChat == HeldChat(conversationID: "chat-1", openedFromList: true), "\(tab)") - } - } - - /// Chat and Sessions share a root: moving between them, or opening a chat, holds nothing. - @Test func chatAndSessionsAndOpeningAChatHoldNothing() { - let state = AppState() - state.activateConversation(id: "chat-1", source: .sessions) - state.select(.sessionList) - #expect(state.heldChat == nil) - - state.activateConversation(id: "chat-1", source: .sessions) - state.select(.ideas) - #expect(state.heldChat != nil) - state.select(.feed) - #expect(state.heldChat?.conversationID == "chat-1", "Board to board keeps it") - state.select(.sessions) - state.activateConversation(id: "chat-2", source: .sessions) - #expect(state.heldChat == nil, "The chat on screen is the one held next") - } - - /// The held chat belongs to this computer and this account. - @Test func hostAndAccountBoundariesForgetTheHeldChat() { - let state = AppState() - state.activateConversation(id: "chat-1", source: .sessions) - state.select(.goals) - state.resetForHostBoundary() - #expect(state.heldChat == nil) - - state.select(.sessions) - state.activateConversation(id: "chat-1", source: .sessions) - state.select(.goals) - state.resetForAccountBoundary() - #expect(state.heldChat == nil) - } - - /// Chat opens its own chat and, without Sessions in the bar, a chat from the list too. With - /// Sessions in the bar, a chat from the list is Sessions'. - @Test func theTabAChatWasUnderOpensItAgain() { - let own = HeldChat(conversationID: "own", openedFromList: false) - let listed = HeldChat(conversationID: "listed", openedFromList: true) - #expect(own.tab(sessionsInBar: false) == .sessions) - #expect(own.tab(sessionsInBar: true) == .sessions) - #expect(listed.tab(sessionsInBar: false) == .sessions) - #expect(listed.tab(sessionsInBar: true) == .sessionList) - } - - /// Chat opens a 1:1 chat again only while its agent is the one in use; a group chat always. - @Test func chatHoldsAOneToOneChatOnlyForItsAgent() { - #expect(HeldChat.fitsChat(members: ["finance"], agentInUse: "finance"), - "A board from a 1:1 chat makes its agent the one in use") - #expect(!HeldChat.fitsChat(members: ["finance"], agentInUse: "travel")) - #expect(!HeldChat.fitsChat(members: ["finance"], agentInUse: nil)) - #expect(HeldChat.fitsChat(members: ["finance", "travel"], agentInUse: "home")) - } } diff --git a/BighelpTests/BighelpCardRendererTests.swift b/BighelpTests/BighelpCardRendererTests.swift index 874a7d74..368317cb 100644 --- a/BighelpTests/BighelpCardRendererTests.swift +++ b/BighelpTests/BighelpCardRendererTests.swift @@ -6,7 +6,7 @@ struct BighelpCardRendererTests { #expect(BighelpCardRenderer.supportedTypes == Set([ "card", "vstack", "hstack", "grid", "text", "metric", "badge", "progress", "chart", "table", "list", "divider", "spacer", "image", - "contact", "place", "music", "contact_draft", "event_draft", "html_app", + "contact", "place", "music", "contact_draft", "event_draft", "html_app", "space_draft", ])) #expect(BighelpCardValidator.supportedElementTypes == BighelpCardRenderer.supportedTypes) } diff --git a/BighelpTests/BighelpLandingTests.swift b/BighelpTests/BighelpLandingTests.swift index c59dc358..a9f9ff51 100644 --- a/BighelpTests/BighelpLandingTests.swift +++ b/BighelpTests/BighelpLandingTests.swift @@ -2,206 +2,39 @@ import Foundation import Testing @testable import Bighelp -/// Settings › Chat › Opens on and Start with: the screen and agent a cold -/// launch lands on, with today's start kept until someone picks. +/// Opens on: the home's four places, and how a screen saved before the one home maps to one. @MainActor struct BighelpLandingTests { private func defaults() -> UserDefaults { UserDefaults(suiteName: "landing-\(UUID().uuidString)")! } - // MARK: Which screen each choice opens - - @Test func eachChoiceOpensItsScreen() { - func open(_ screen: BighelpLandingScreen) -> BighelpLandingDestination? { - BighelpLanding.destination(for: .chosen(screen), kanbanAvailable: true, kanbanWaitIsOver: false, - projectsAvailable: true) - } - #expect(open(.agents) == .agents) - #expect(open(.allAgents) == .allAgents) - #expect(open(.lastChat) == .homeChat) - #expect(open(.sessions) == .chatList, "All sessions, to pick a recent one") - #expect(open(.feed) == .board(.feed)) - #expect(open(.ideas) == .board(.ideas)) - #expect(open(.goals) == .board(.goals)) - #expect(open(.kanban) == .kanban) - #expect(open(.projects) == .projects) - } - - @Test func nothingPickedKeepsTodaysStart() { - #expect(BighelpLanding.destination(for: .standard(opensChat: true), kanbanAvailable: nil, - kanbanWaitIsOver: false, projectsAvailable: true) == .homeChat) - // `-loopdy.home.opens-chat NO` (the UI tests' older flows) stays on the chat list. - #expect(BighelpLanding.destination(for: .standard(opensChat: false), kanbanAvailable: nil, - kanbanWaitIsOver: false, projectsAvailable: true) == .chatList) - } - - @Test func kanbanFallsBackQuietlyWhereTheComputerHasNone() { - #expect(BighelpLanding.destination(for: .chosen(.kanban), kanbanAvailable: false, kanbanWaitIsOver: false, - projectsAvailable: true) == .homeChat) - } - - @Test func kanbanWaitsBrieflyForTheFirstAnswer() { - #expect(BighelpLanding.destination(for: .chosen(.kanban), kanbanAvailable: nil, kanbanWaitIsOver: false, - projectsAvailable: true) == nil, "Not known yet: wait") - #expect(BighelpLanding.destination(for: .chosen(.kanban), kanbanAvailable: nil, kanbanWaitIsOver: true, - projectsAvailable: true) == .homeChat, "No answer in time: the default") - } - - @Test func projectsFallBackWhereTheyCantOpen() { - #expect(BighelpLanding.destination(for: .chosen(.projects), kanbanAvailable: nil, kanbanWaitIsOver: false, - projectsAvailable: false) == .homeChat) - } - - // MARK: All hosts at launch - - @Test func onlyAChosenScreenDecidesTheAllHostsView() { - #expect(BighelpLanding.allHostsMode(for: .chosen(.allAgents)) == true) - #expect(BighelpLanding.allHostsMode(for: .chosen(.agents)) == false) - #expect(BighelpLanding.allHostsMode(for: .chosen(.feed)) == false) - #expect(BighelpLanding.allHostsMode(for: .standard(opensChat: true)) == nil, "Untouched until picked") - #expect(BighelpLanding.allHostsMode(for: .standard(opensChat: false)) == nil) + @Test func everyOldScreenMapsToItsPlace() { + #expect(BighelpLandingScreen.allCases.map(\.homeLanding) + == [.bots, .bots, .chats, .chats, .today, .today, .today, .work, .work]) } - @Test func sessionsAndLastChatKeepTheModeYouWereIn() { - // Both exist with one computer and with all of them. - #expect(BighelpLanding.allHostsMode(for: .chosen(.sessions)) == nil) - #expect(BighelpLanding.allHostsMode(for: .chosen(.lastChat)) == nil) + @Test func opensOnReadsTheFourAndMapsTheOldOnes() { + #expect(BighelpLanding.homeLanding(stored: "today") == .today) + #expect(BighelpLanding.homeLanding(stored: "all-agents") == .bots) + #expect(BighelpLanding.homeLanding(stored: "kanban") == .work) + #expect(BighelpLanding.homeLanding(stored: "dashboard") == nil) + #expect(BighelpLanding.homeLanding(stored: nil) == nil) } - @Test func anAlertThatOpensTheAppKeepsTheModeOpenOnChanged() throws { - let suite = "bighelp.landing.alert.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - defaults.set(true, forKey: "bighelp.hosts.all-hosts") - defaults.set(BighelpLandingScreen.feed.rawValue, forKey: BighelpLanding.screenKey) - var now = Date(timeIntervalSince1970: 1_000) - let settings = SettingsStore(defaults: defaults, now: { now }) - settings.applyLaunchLandingToAllHostsMode() - #expect(!settings.allHostsMode, "Opens on Feed starts on one computer") - settings.restoreAllHostsModeForOutsideOpen() - #expect(settings.allHostsMode, "The tapped alert opens in the mode you were in") - - // Later in the same launch, Opens on stands. - settings.applyLaunchLandingToAllHostsMode() - settings.allHostsMode = false - now.addTimeInterval(120) - settings.restoreAllHostsModeForOutsideOpen() - #expect(!settings.allHostsMode) - } - - // MARK: Start with - - @Test func aStartAgentThatStillExistsIsUsed() { - #expect(BighelpLanding.startAgent(stored: "travel", agentIDs: ["finance", "travel"], - choice: .chosen(.feed)) == "travel") - #expect(BighelpLanding.startAgent(stored: "travel", agentIDs: ["finance", "travel"], - choice: .standard(opensChat: true)) == "travel") - } - - @Test func aStartAgentThatsGoneFallsBackToAutomatic() { - #expect(BighelpLanding.startAgent(stored: "deleted", agentIDs: ["finance", "travel"], - choice: .chosen(.lastChat)) == nil) - #expect(BighelpLanding.startAgent(stored: nil, agentIDs: ["finance"], choice: .chosen(.lastChat)) == nil) - } - - @Test func allAgentsStartsWithNoOneAgent() { - #expect(BighelpLanding.startAgent(stored: "travel", agentIDs: ["travel"], choice: .chosen(.allAgents)) == nil) - #expect(!BighelpLandingScreen.allAgents.offersStartAgent) - #expect(!BighelpLandingScreen.sessions.offersStartAgent, "Every agent's sessions") - #expect(BighelpLandingScreen.allCases.filter(\.offersStartAgent).count == BighelpLandingScreen.allCases.count - 2) - } - - // MARK: Saved choices - - @Test func theOldOpensChatValueCarriesOverUntilAScreenIsPicked() { - let unset = defaults() - #expect(SettingsStore(defaults: unset).launchLanding == .standard(opensChat: true)) - - let chatList = defaults() - chatList.set(false, forKey: BighelpLanding.legacyOpensChatKey) - #expect(SettingsStore(defaults: chatList).launchLanding == .standard(opensChat: false)) - - let opensChat = defaults() - opensChat.set(true, forKey: BighelpLanding.legacyOpensChatKey) - #expect(SettingsStore(defaults: opensChat).launchLanding == .standard(opensChat: true)) - - // Picking a screen wins over the old value. - chatList.set("goals", forKey: BighelpLanding.screenKey) - #expect(SettingsStore(defaults: chatList).launchLanding == .chosen(.goals)) - } - - @Test func anUnknownSavedScreenKeepsTodaysStart() { - let saved = defaults() - saved.set("dashboard", forKey: BighelpLanding.screenKey) - let settings = SettingsStore(defaults: saved) - #expect(settings.landingScreen == nil) - #expect(settings.launchLanding == .standard(opensChat: true)) - } - - @Test func aPickedScreenAppliesNextLaunch() { + @Test func aPickedPlaceAppliesNextLaunch() { let saved = defaults() let settings = SettingsStore(defaults: saved) - settings.landingScreen = .projects - #expect(settings.launchLanding == .standard(opensChat: true), "This launch already happened") - let next = SettingsStore(defaults: saved) - #expect(next.landingScreen == .projects) - #expect(next.launchLanding == .chosen(.projects)) - - next.landingScreen = nil - #expect(SettingsStore(defaults: saved).launchLanding == .standard(opensChat: true), "Back to the default") + settings.homeLanding = .today + #expect(settings.launchHomeLanding == .chats, "This launch already happened") + #expect(SettingsStore(defaults: saved).launchHomeLanding == .today) } - @Test func startAgentsAreKeptPerComputer() { + @Test func anOldOrUnknownSavedScreenStillOpensSomewhere() { let saved = defaults() - let settings = SettingsStore(defaults: saved) - settings.setStartAgentID("travel", scope: "computer-a") - settings.setStartAgentID("home", scope: "computer-b") - let next = SettingsStore(defaults: saved) - #expect(next.startAgentID(scope: "computer-a") == "travel") - #expect(next.startAgentID(scope: "computer-b") == "home") - #expect(next.startAgentID(scope: "computer-c") == nil, "Another computer never gets an ID it doesn't have") - #expect(next.startAgentID(scope: nil) == nil) - - next.setStartAgentID(nil, scope: "computer-a") - #expect(SettingsStore(defaults: saved).startAgentID(scope: "computer-a") == nil, "Automatic again") - #expect(SettingsStore(defaults: saved).startAgentID(scope: "computer-b") == "home") - } - - @Test func aChosenScreenSetsTheAllHostsViewAtLaunch() { - let multi = defaults() - multi.set("all-agents", forKey: BighelpLanding.screenKey) - let settings = SettingsStore(defaults: multi) - settings.applyLaunchLandingToAllHostsMode() - #expect(settings.allHostsMode) - - let one = defaults() - one.set(true, forKey: "bighelp.hosts.all-hosts") - one.set("feed", forKey: BighelpLanding.screenKey) - let single = SettingsStore(defaults: one) - single.applyLaunchLandingToAllHostsMode() - #expect(!single.allHostsMode) - - let untouched = defaults() - untouched.set(true, forKey: "bighelp.hosts.all-hosts") - let standard = SettingsStore(defaults: untouched) - standard.applyLaunchLandingToAllHostsMode() - #expect(standard.allHostsMode, "Nothing picked: the all-hosts switch stays as it was") - } - - /// Bots mode opens on its own home: Opens on doesn't turn the all-hosts view on at launch. - @Test func simpleBotModeIgnoresOpenOn() { - let saved = defaults() - saved.set("all-agents", forKey: BighelpLanding.screenKey) - saved.set(true, forKey: "bighelp.settings.simple-bots") - let settings = SettingsStore(defaults: saved) - settings.applyLaunchLandingToAllHostsMode() - #expect(!settings.allHostsMode) - #expect(!SettingsStore(defaults: saved).allHostsMode, "Nothing saved for the next launch either") - } - - @Test func choicesUseThePlainLabels() { - #expect(BighelpLandingScreen.allCases.map(\.title) - == ["Agents", "Agents (multi)", "Last chat", "Sessions", "Feed", "Ideas", "Goals", "Kanban", "Projects"]) + saved.set("goals", forKey: BighelpLanding.screenKey) + #expect(SettingsStore(defaults: saved).launchHomeLanding == .today) + saved.set("dashboard", forKey: BighelpLanding.screenKey) + #expect(SettingsStore(defaults: saved).launchHomeLanding == .chats) } } diff --git a/BighelpTests/BighelpTabGlyphTests.swift b/BighelpTests/BighelpTabGlyphTests.swift deleted file mode 100644 index c193772a..00000000 --- a/BighelpTests/BighelpTabGlyphTests.swift +++ /dev/null @@ -1,52 +0,0 @@ -import SwiftUI -import Testing -@testable import Bighelp - -struct BighelpTabGlyphTests { - /// The design's paths read right: each drawing covers its grid the way the - /// mockup does (outermost points plus half the 1.7-pt stroke, or a dot's edge). - @Test func glyphsSitOnTheirGridLikeTheDesign() { - // minX, minY, maxX, maxY on the 24-pt grid. - func expected(_ glyph: BighelpTabGlyph, _ selected: Bool) -> (CGFloat, CGFloat, CGFloat, CGFloat) { - switch glyph { - case .chat: (3.5 - 0.85, 4 - 0.85, 20.5 + 0.85, 19.9 + 0.85) - case .feed: (3.5 - 0.85, 2.4 - 0.85, 21.6 + 0.85, 20.5 + 0.85) - // The dot (radius 1.6, or 1.9 selected) reaches past the sparkle. - case .ideas: (3 - 0.85, 5.4 - (selected ? 1.9 : 1.6), 18.6 + (selected ? 1.9 : 1.6), 21 + 0.85) - case .goals: (3 - 0.85, 3.5 - 0.85, 21 + 0.85, 19.5 + 0.85) - } - } - for glyph in BighelpTabGlyph.allCases { - for selected in [false, true] { - let bounds = glyph.path(selected: selected).boundingRect - let edges = expected(glyph, selected) - let outline = CGRect(x: edges.0, y: edges.1, width: edges.2 - edges.0, height: edges.3 - edges.1) - #expect(abs(bounds.minX - outline.minX) < 0.2, "\(glyph) \(selected) left") - #expect(abs(bounds.maxX - outline.maxX) < 0.2, "\(glyph) \(selected) right") - #expect(abs(bounds.minY - outline.minY) < 0.2, "\(glyph) \(selected) top") - #expect(abs(bounds.maxY - outline.maxY) < 0.2, "\(glyph) \(selected) bottom") - } - } - } - - /// Selected is the filled variant: its eyes and lines are cut out of a solid - /// shape, so the middle of the bubble is ink only when selected. - @Test func selectedGlyphsAreFilled() { - let middle = CGPoint(x: 12, y: 14.5) - #expect(!BighelpTabGlyph.chat.path(selected: false).contains(middle)) - #expect(BighelpTabGlyph.chat.path(selected: true).contains(middle)) - // The eyes stay open in the filled bubble. - #expect(!BighelpTabGlyph.chat.path(selected: true).contains(CGPoint(x: 9.2, y: 11))) - #expect(BighelpTabGlyph.chat.path(selected: false).contains(CGPoint(x: 9.2, y: 11))) - #expect(BighelpTabGlyph.goals.path(selected: true).contains(CGPoint(x: 11, y: 17))) - #expect(!BighelpTabGlyph.goals.path(selected: false).contains(CGPoint(x: 11, y: 17))) - } - - @Test func barTabsUseTheGlyphs() { - #expect(AppTab.sessions.glyph == .chat) - #expect(AppTab.feed.glyph == .feed) - #expect(AppTab.ideas.glyph == .ideas) - #expect(AppTab.goals.glyph == .goals) - #expect(AppTab.apps.glyph == nil) - } -} diff --git a/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift b/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift index fd581a83..e7f58baa 100644 --- a/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift +++ b/BighelpTests/BoardBlueprintAndGoalCategoryTests.swift @@ -40,15 +40,13 @@ struct BoardBlueprintAndGoalCategoryTests { } /// The root's right-edge strip (New chat by default) sat over the trailing edge of every - /// board row and took right-to-left drags first. On Feed, Ideas and Goals the rows own them. - @Test func boardRowsOwnSwipesFromTheTrailingEdge() { - for tab in [AppTab.feed, .ideas, .goals] { - #expect(!WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: tab, pathIsEmpty: true), "\(tab)") - #expect(WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: tab, pathIsEmpty: false), - "A chat pushed over \(tab) keeps the edge") - } - #expect(WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: .apps, pathIsEmpty: true)) - #expect(WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: .sessions, pathIsEmpty: true)) + /// row that swipes and took right-to-left drags first. On Today's root the rows own them. + @Test func todaysRowsOwnSwipesFromTheTrailingEdge() { + #expect(!WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: .today, pathIsEmpty: true)) + #expect(WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: .today, pathIsEmpty: false), + "A chat pushed over Today keeps the edge") + #expect(WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: .conversations, pathIsEmpty: true)) + #expect(WorkspaceEdgeSwipeResolver.trailingEdgeIsActive(tab: .work, pathIsEmpty: true)) } // MARK: Blueprints diff --git a/BighelpTests/BotChatActivityTests.swift b/BighelpTests/BotChatActivityTests.swift index 56616509..87b703b6 100644 --- a/BighelpTests/BotChatActivityTests.swift +++ b/BighelpTests/BotChatActivityTests.swift @@ -67,13 +67,6 @@ struct BotChatActivityTests { #expect(BotChatActivity.merged(nil, nil) == nil) } - @Test func theAgentsScreenShowsBotChatsAndAGroupApprovalWins() throws { - let states = AgentLiveStatePresentation.agentStates( - rooms: [], pendingApprovals: { _ in [] }, - botChats: ["nova": .working(tool: "web_search"), "pip": .waiting, "rio": .idle]) - #expect(states == ["nova": .thinking, "pip": .nudge], "Idle stays idle: nothing invented") - } - // MARK: Signals without the route @Test func withoutTheRouteOnlyARunningBotChatCounts() { diff --git a/BighelpTests/BotProfileActionsTests.swift b/BighelpTests/BotProfileActionsTests.swift new file mode 100644 index 00000000..3e14378e --- /dev/null +++ b/BighelpTests/BotProfileActionsTests.swift @@ -0,0 +1,105 @@ +import Foundation +import Testing +@testable import Bighelp + +/// A bot page's ⋯ menu (`BotProfileMenu`) and its About rows (`BotProfileAbout`): what each offers, +/// in what order, from what the page's context can do. +struct BotProfileActionsTests { + /// Everything the shell can hand a page for a bot that isn't the primary one. + static let everything = BotProfileMenuCapabilities( + isOnComputerInUse: true, isPrimary: false, offersNewChat: true, offersChats: true, + offersPinning: true, isPinned: false, canPinAnother: true, offersShortcuts: true, + offersDuplicate: true, showsRoutinesToggle: true, + offersManage: true, offersDelete: true, isDefaultBot: false, isDeleting: false) + + @Test func everythingInOrderWithDeleteLast() { + #expect(BotProfileMenu.actions(Self.everything) == [ + .message, .newChat, .chats, .makePrimary, .pin, .shortcuts, .duplicate, .showRoutines, .manageBots, .delete, + ]) + } + + @Test func groupsRunBotThenManageThenDelete() { + let groups = BotProfileMenu.actions(Self.everything).map(\.group) + #expect(groups == groups.sorted()) + #expect(groups.last == .delete) + } + + @Test func thePrimaryBotOffersNoMakePrimary() { + var can = Self.everything + can.isPrimary = true + #expect(!BotProfileMenu.actions(can).contains(.makePrimary)) + } + + @Test func aPinnedBotOffersUnpinAndAFullPinListOffersNoPin() { + var can = Self.everything + can.isPinned = true + let pinned = BotProfileMenu.actions(can) + #expect(pinned.contains(.unpin) && !pinned.contains(.pin)) + + can.isPinned = false + can.canPinAnother = false + let full = BotProfileMenu.actions(can) + #expect(!full.contains(.pin) && !full.contains(.unpin)) + } + + @Test func theDefaultBotCantBeDeletedButCanBeManaged() { + var can = Self.everything + can.isDefaultBot = true + let actions = BotProfileMenu.actions(can) + #expect(!actions.contains(.delete)) + #expect(actions.last == .manageBots) + } + + @Test func aDeletionUnderWayHidesDelete() { + var can = Self.everything + can.isDeleting = true + #expect(!BotProfileMenu.actions(can).contains(.delete)) + } + + @Test func noCloneClientOffersNoDuplicate() { + var can = Self.everything + can.offersDuplicate = false + #expect(!BotProfileMenu.actions(can).contains(.duplicate)) + } + + @Test func anotherComputersBotOffersNothingUntilItsComputerIsInUse() { + var can = Self.everything + can.isOnComputerInUse = false + #expect(BotProfileMenu.actions(can).isEmpty) + } + + @Test func aBareContextOffersMessageAndMakePrimaryOnly() { + #expect(BotProfileMenu.actions(BotProfileMenuCapabilities()) == [.message, .makePrimary]) + } + + @Test func showRoutinesKeepsItsIdentifier() { + #expect(BotProfileAction.showRoutines.identifier == "simple-bots.profile.show-routines") + #expect(BotProfileAction.delete.identifier == "simple-bots.profile.more.delete") + } + + // MARK: About + + @Test func editableRowsShowTheirValues() { + let rows = BotProfileAbout.rows(name: "Mina", role: "Travel planner", summary: " ", handle: "mina", + canEdit: true, unavailableReason: "Not on this computer") + #expect(rows.map(\.kind) == [.field(.name), .field(.role), .field(.summary), .handle]) + #expect(rows.map(\.detail) == ["Mina", "Travel planner", "Not set", "@mina"]) + #expect(rows.map(\.isEditable) == [true, true, true, false]) + } + + @Test func aComputerThatWontTakeEditsSaysWhyOnEachField() { + let reason = "This host doesn't support that." + let rows = BotProfileAbout.rows(name: "Mina", role: "Travel planner", summary: "Plans trips", handle: "mina", + canEdit: false, unavailableReason: reason) + let fields = rows.filter { $0.kind != .handle } + #expect(fields.allSatisfy { !$0.isEditable && $0.detail == reason }) + // The handle is only ever read, so it keeps its value. + #expect(rows.last?.detail == "@mina") + } + + @Test func withoutAReasonTheRowsSayTheComputerWontLetTheAppChangeTheBot() { + let rows = BotProfileAbout.rows(name: "Mina", role: "", summary: "", handle: "mina", + canEdit: false, unavailableReason: nil) + #expect(rows.first?.detail == String(localized: "This computer doesn't let the app change this bot.")) + } +} diff --git a/BighelpTests/ChatComposerRedrawTests.swift b/BighelpTests/ChatComposerRedrawTests.swift index a2084cc6..7c7fcb86 100644 --- a/BighelpTests/ChatComposerRedrawTests.swift +++ b/BighelpTests/ChatComposerRedrawTests.swift @@ -78,6 +78,11 @@ struct ChatComposerRedrawTests { // The box that stays calls the newest one. drawn.actions.voice() #expect(voiceTaps == ["second"]) + // A new chat's Send hook comes and goes the same way. + actions.sendOverride = { _ in true } + let keepsTheBoxWithAHook = drawn == box(model) + #expect(keepsTheBoxWithAHook) + #expect(drawn.actions.sendOverride?(false) == true) let focusRedraws = drawn != box(model, focused: true) let attachmentsRedraw = drawn != box(model, attachments: false) @@ -132,6 +137,86 @@ struct ChatComposerRedrawTests { #expect(restored.draftShape == ChatDraftShape("Ask @ju")) } + /// New chat's Send asks its hook first, once a send. A message the hook takes goes nowhere + /// else and stays in the box for whoever took it; one it leaves is sent here as usual, and + /// from then on the chat is an ordinary one that asks nobody. + @Test func aNewChatsSendAsksItsHookOnceAndATakenMessageIsNotSentHere() async throws { + let client = RecordingFixtureClient() + let model = ChatModel(conversationID: "composer-send-hook", client: client, initialItems: []) + let hook = SendHook() + let mounted = try MountedComposerChat(model: model, newChat: ChatNewChatSlot( + toRow: AnyView(Color.clear.frame(height: 44)), + sendOverride: { _ in + hook.asked += 1 + return hook.takes + })) + defer { mounted.close() } + await mounted.settle { mounted.editor != nil } + let editor = try #require(mounted.editor) + model.draft = "Fix the widget tap" + #expect(model.canSend) + + // Command-Return sends whatever Settings › Chat › Return sends says. + #expect(editor.onReturnKey?(.command) == true) + try await Task.sleep(for: .milliseconds(200)) + #expect(hook.asked == 1) + #expect(client.sent.isEmpty, "A taken message must not also go to this chat") + #expect(model.draft == "Fix the widget tap", "Whoever takes the message empties the box") + #expect(model.transcriptEntries.isEmpty) + + hook.takes = false + #expect(editor.onReturnKey?(.command) == true) + await mounted.settle(tries: 100) { client.sent.count == 1 && !model.isSending } + #expect(hook.asked == 2) + #expect(client.sent.count == 1) + #expect(model.draft.isEmpty) + #expect(!model.transcriptEntries.isEmpty) + + // The chat has a message now: it draws again without the hook. + try await Task.sleep(for: .milliseconds(200)) + mounted.window.layoutIfNeeded() + model.draft = "And the alert tap" + await mounted.settle(tries: 100) { model.canSend } + #expect(model.canSend) + #expect(editor.onReturnKey?(.command) == true) + await mounted.settle(tries: 100) { client.sent.count == 2 } + #expect(client.sent.count == 2) + #expect(hook.asked == 2, "Only a chat with nothing sent asks the hook") + } + + /// New chat's choices are a sibling under the box. When they change and grow, the chat screen + /// makes room and moves the box up, without drawing the box again. + @Test func aChangeInTheChoicesRowDoesNotRedrawTheMessageBox() async throws { + let model = ChatModel(conversationID: "composer-redraw-choices", client: ConversationFixtureClient(), + initialItems: []) + let row = ChoicesRowState() + let mounted = try MountedComposerChat(model: model, newChat: ChatNewChatSlot( + toRow: AnyView(Color.clear.frame(height: 44)), + choicesRow: AnyView(ChoicesRowStandIn(state: row)))) + defer { mounted.close() } + await mounted.settle { mounted.editor != nil } + let editor = try #require(mounted.editor) + // The open draws the box a few times; count only what the row does. + try await Task.sleep(for: .milliseconds(400)) + mounted.window.layoutIfNeeded() + let coordinator = try #require(editor.delegate as? ReferenceComposerTextView.Coordinator) + let before = coordinator.surfaceUpdates + let restingBottom = mounted.bottom(of: editor) + + for step in 1...8 { + row.height = 40 + CGFloat(step) * 10 + try await Task.sleep(for: .milliseconds(30)) + mounted.window.layoutIfNeeded() + } + await mounted.settle { mounted.bottom(of: editor) <= restingBottom - 70 } + + #expect(mounted.bottom(of: editor) <= restingBottom - 70, + "The row grew by 80 points under the box, or this checks nothing") + let redraws = coordinator.surfaceUpdates - before + #expect(redraws <= 2, "A change in the choices row redrew the message box: \(redraws) times") + #expect(mounted.editor === editor) + } + private static func answer(_ id: String, _ text: String, delivery: String = "Delivered") -> TimelineItem { TimelineItem(id: id, role: .assistant, sender: .agent(id: "default", snapshot: .init(name: "Juno")), content: .message(text), metadata: .init(delivery: delivery)) @@ -147,6 +232,38 @@ private final class ComposerRedrawCounter: @unchecked Sendable { func increment() { lock.withLock { count += 1 } } } +/// What a test's Send hook was asked and answers. +@MainActor +private final class SendHook { + var asked = 0 + var takes = true +} + +/// The demo client, keeping what the chat sent through it. +private final class RecordingFixtureClient: ConversationFixtureClient { + private(set) var sent: [String] = [] + + override func send(message: String, conversationID: String) async throws -> ConversationResponse { + sent.append(message) + return try await super.send(message: message, conversationID: conversationID) + } +} + +@MainActor +@Observable +private final class ChoicesRowState { + var height: CGFloat = 40 +} + +/// Stands in for New chat's choices row: its own state changes it, as a chip does the real one. +private struct ChoicesRowStandIn: View { + let state: ChoicesRowState + + var body: some View { + Color.clear.frame(height: state.height) + } +} + @MainActor @Observable private final class ComposerChatState { @@ -157,10 +274,13 @@ private final class ComposerChatState { private struct ComposerChatHarness: View { let model: ChatModel let state: ComposerChatState + /// New chat's parts, with the pushed header they come with. + var newChat: ChatNewChatSlot? = nil var body: some View { - ChatView(model: model, composerFocusRequest: state.focusRequest) + ChatView(model: model, composerFocusRequest: state.focusRequest, newChat: newChat) .environment(\.bighelpUIV3Enabled, true) + .environment(\.agentHomeChrome, newChat == nil ? AgentHomeChrome() : .pushedChat(onProfile: { _ in })) } } @@ -169,15 +289,21 @@ private final class MountedComposerChat { let window: UIWindow let state = ComposerChatState() - init(model: ChatModel) throws { + init(model: ChatModel, newChat: ChatNewChatSlot? = nil) throws { let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) window = UIWindow(windowScene: scene) window.frame = CGRect(x: 0, y: 0, width: 402, height: 874) window.windowLevel = .alert + 1 - window.rootViewController = UIHostingController(rootView: ComposerChatHarness(model: model, state: state)) + window.rootViewController = UIHostingController( + rootView: ComposerChatHarness(model: model, state: state, newChat: newChat)) window.makeKeyAndVisible() } + /// Where the view ends, down the window. + func bottom(of view: UIView) -> CGFloat { + view.convert(view.bounds, to: window).maxY + } + var editor: ClipboardPasteTextView? { func find(in view: UIView) -> ClipboardPasteTextView? { if let editor = view as? ClipboardPasteTextView, editor.accessibilityIdentifier == "chat.composer.text" { diff --git a/BighelpTests/ChatGlassArchitectureTests.swift b/BighelpTests/ChatGlassArchitectureTests.swift index e01f7f51..ec1ca4db 100644 --- a/BighelpTests/ChatGlassArchitectureTests.swift +++ b/BighelpTests/ChatGlassArchitectureTests.swift @@ -3,7 +3,8 @@ import Testing struct ChatGlassArchitectureTests { @Test func chatChromeUsesOnlyBoundedControlGlass() throws { - let source = try load("Bighelp/Chat/ChatView.swift") + // The chat and its header (`ChatPushedHeader`). + let source = try load("Bighelp/Chat/ChatView.swift") + load("Bighelp/Board/AgentHomeChrome.swift") #expect(!source.contains("ChatFloatingChromeBackdropLayer")) #expect(!source.contains("ChatFloatingChromeBackdropSurface")) #expect(source.contains("bighelpNavigationGlass")) diff --git a/BighelpTests/ChatLayoutPreferencesTests.swift b/BighelpTests/ChatLayoutPreferencesTests.swift index 93d93860..935c64e6 100644 --- a/BighelpTests/ChatLayoutPreferencesTests.swift +++ b/BighelpTests/ChatLayoutPreferencesTests.swift @@ -16,11 +16,11 @@ struct ChatLayoutPreferencesTests { } @Test func tabBarDropsIntoTheHomeIndicatorAreaButNeverOffScreen() { - #expect(FloatingTabBar.homeIndicatorSink(forBottomInset: 34) == 20) - #expect(FloatingTabBar.homeIndicatorSink(forBottomInset: 21) == 7) - #expect(FloatingTabBar.homeIndicatorSink(forBottomInset: 0) == 0) + #expect(HomeTabBar.homeIndicatorSink(forBottomInset: 34) == 20) + #expect(HomeTabBar.homeIndicatorSink(forBottomInset: 21) == 7) + #expect(HomeTabBar.homeIndicatorSink(forBottomInset: 0) == 0) // A keyboard's inset is much larger; the bar still moves at most 20 points. - #expect(FloatingTabBar.homeIndicatorSink(forBottomInset: 336) == 20) + #expect(HomeTabBar.homeIndicatorSink(forBottomInset: 336) == 20) } @Test func textSizeStepsAroundTheSystemSize() { diff --git a/BighelpTests/ChatsInboxProjectionTests.swift b/BighelpTests/ChatsInboxProjectionTests.swift new file mode 100644 index 00000000..b1d0a918 --- /dev/null +++ b/BighelpTests/ChatsInboxProjectionTests.swift @@ -0,0 +1,199 @@ +import Foundation +import Testing +@testable import Bighelp + +/// The Chats view's one list: every computer's chats merged, the computer in use live and the +/// others from their all-hosts copies, Pinned first and then the newest. +@MainActor +struct ChatsInboxProjectionTests { + private static let home = UUID() + private static let studio = UUID() + private static let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func session(_ id: String, at minutesAgo: Double, pinned: Bool = false, unread: Bool = false, + title: String? = nil, preview: String = "") -> SessionSummary { + SessionSummary(id: id, kind: .direct, agentIDs: ["mina"], title: title ?? id.capitalized, preview: preview, + updatedAt: Self.now.addingTimeInterval(-minutesAgo * 60), isPinned: pinned, + isUnread: unread, tracksUnread: true) + } + + private func fleetChat(_ id: String, on hostID: UUID, at minutesAgo: Double, title: String? = nil) -> FleetChat { + FleetChat(hostID: hostID, profileID: "otto", storedSessionID: id, title: title ?? id.capitalized, + preview: "", updatedAt: Self.now.addingTimeInterval(-minutesAgo * 60), isActive: false) + } + + private func room(_ id: String) -> HermesBotModeRoomSummary { + let members = ["mina", "otto"].map { profile in + HermesBotModeRoomMember(memberID: "member-\(profile)", profile: profile, handle: profile, + target: ["kind": .string("local"), "profile": .string(profile)]) + } + return HermesBotModeRoomSummary(room: HermesBotModeRoomState( + roomID: id, name: id.capitalized, members: members, authorityGatewayID: "gateway", authorityEpoch: 1, + revision: 1, createdAt: 50, updatedAt: 60, latestSequence: 0, disbandedAt: nil, driverStatus: nil), + capabilities: nil) + } + + private func computers(home: [FleetChat] = [], studio: [FleetChat]) -> [ChatsInboxComputer] { + [ChatsInboxComputer(id: Self.home, name: "Home Mac", chats: home, groups: []), + ChatsInboxComputer(id: Self.studio, name: "Studio Mac", chats: studio, groups: [])] + } + + @Test func pinnedComeFirstThenTheNewest() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("old", at: 300), session("pinned", at: 900, pinned: true), session("new", at: 5)], + selectedHostID: Self.home, + computers: computers(studio: [fleetChat("studio-mid", on: Self.studio, at: 60)]))) + + #expect(rows.map(\.title) == ["Pinned", "New", "Studio-Mid", "Old"]) + } + + @Test func theComputerInUsesCopiesAreDropped() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("live", at: 10)], + selectedHostID: Self.home, + computers: computers(home: [fleetChat("live", on: Self.home, at: 10)], + studio: [fleetChat("away", on: Self.studio, at: 20)]), + showsComputerTags: true)) + + #expect(rows.map(\.title) == ["Live", "Away"], "The live chat once, from its catalog") + #expect(rows[0].isOnComputerInUse && rows[0].computerTag == nil) + #expect(rows[1].computerTag == "Studio Mac") + } + + @Test func oneComputerShowsNoComputerTags() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("live", at: 10)], selectedHostID: Self.home, + computers: computers(studio: [fleetChat("away", on: Self.studio, at: 20)]), showsComputerTags: false)) + + #expect(rows.allSatisfy { $0.computerTag == nil }) + } + + @Test func aComputerChipShowsOnlyThatComputersChats() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("live", at: 10)], selectedHostID: Self.home, + computers: computers(studio: [fleetChat("away", on: Self.studio, at: 20)]), showsComputerTags: true)) + + #expect(ChatsInboxProjection.filter(rows, by: .computer(Self.studio), matching: "").map(\.title) == ["Away"]) + #expect(ChatsInboxProjection.filter(rows, by: .computer(Self.home), matching: "").map(\.title) == ["Live"]) + #expect(ChatsInboxProjection.filter(rows, by: .all, matching: "").count == 2) + } + + /// Another computer's copy has no read state, so only the computer in use's chats can be unread. + @Test func unreadShowsOnlyUnreadChats() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("seen", at: 10), session("fresh", at: 20, unread: true)], selectedHostID: Self.home, + computers: computers(studio: [fleetChat("away", on: Self.studio, at: 5)]))) + + #expect(ChatsInboxProjection.filter(rows, by: .unread, matching: "").map(\.title) == ["Fresh"]) + } + + @Test func searchLooksAtTitlesAndPreviews() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("trip", at: 10, title: "Lisbon trip"), + session("budget", at: 20, title: "Budget", preview: "Dining is capped at $300.")], + selectedHostID: Self.home, + computers: computers(studio: [fleetChat("away", on: Self.studio, at: 5, title: "Widget fix")]))) + + #expect(ChatsInboxProjection.filter(rows, by: .all, matching: " lisbon ").map(\.title) == ["Lisbon trip"]) + #expect(ChatsInboxProjection.filter(rows, by: .all, matching: "dining").map(\.title) == ["Budget"]) + #expect(ChatsInboxProjection.filter(rows, by: .all, matching: "widget").map(\.title) == ["Widget fix"]) + #expect(ChatsInboxProjection.filter(rows, by: .all, matching: "nothing").isEmpty) + } + + /// A group chat just made has no messages, so the catalog doesn't list it yet: Hermes' rooms do. + @Test func aGroupChatWithNoMessageYetShowsOnce() { + let talked = SessionSummary(id: "hermes-room:crew", kind: .botMode, agentIDs: ["mina", "otto"], title: "Crew", + preview: "Hi", updatedAt: Self.now, hostedRoomID: "crew") + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [talked], rooms: [room("crew"), room("fresh")], selectedHostID: Self.home)) + + #expect(rows.map(\.id) == ["here/hermes-room:crew", "here/hermes-room:fresh"]) + #expect(rows.allSatisfy { $0.isGroup }) + #expect(rows[1].memberIDs == ["mina", "otto"]) + #expect(!rows[1].canPin && !rows[1].canRename, "Group chats are managed in their own settings") + } + + @Test func codingSessionsCarryTheCodeTag() { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("fix", at: 10), session("chat", at: 20)], codeSessionIDs: ["fix"], + selectedHostID: Self.home)) + + #expect(rows.map(\.isCode) == [true, false]) + } + + /// Another computer's chat renames and archives through the fleet; it has no pin or read state. + @Test func anotherComputersChatOffersOnlyWhatTheFleetCanDo() throws { + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + selectedHostID: Self.home, computers: computers(studio: [fleetChat("away", on: Self.studio, at: 5)]))) + + let away = try #require(rows.first) + #expect(away.canRename && away.canArchive) + #expect(!away.canPin && !away.canMarkUnread) + } + + @Test func sectionsArePinnedThenByDay() { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC")! + let rows = ChatsInboxProjection.rows(ChatsInboxInput( + sessions: [session("pinned", at: 5 * 24 * 60, pinned: true), session("today", at: 1), + session("yesterday", at: 24 * 60), session("older", at: 4 * 24 * 60)], + selectedHostID: Self.home)) + + let sections = ChatsInboxProjection.sections(rows, now: Self.now, calendar: calendar) + + #expect(sections.map(\.kind) == [.pinned, .today, .yesterday, .earlier]) + #expect(sections.map { $0.rows.map(\.title) } == [["Pinned"], ["Today"], ["Yesterday"], ["Older"]]) + } + + private func key(_ catalog: AnyObject, revision: Int, unsentDrafts: [String: Bool] = [:]) -> ChatsInboxCache.Key { + ChatsInboxCache.Key(catalog: ObjectIdentifier(catalog), revision: revision, rooms: [], codeSessionIDs: [], + selectedHostID: nil, computers: [], showsComputerTags: false, unsentDrafts: unsentDrafts) + } + + @Test func theCacheSortsOnlyWhenAnInputChanges() { + let cache = ChatsInboxCache() + let catalog = NSObject() + var builds = 0 + let build = { builds += 1; return [ChatsInboxRow]() } + + _ = cache.rows(for: key(catalog, revision: 1), build: build) + _ = cache.rows(for: key(catalog, revision: 1), build: build) + #expect(builds == 1) + _ = cache.rows(for: key(catalog, revision: 2), build: build) + #expect(builds == 2) + } + + /// Every computer's catalog counts its revisions from zero, and with Show every computer off + /// nothing else in the key names the computer: after a switch, an equal revision must not + /// bring back the first computer's rows. + @Test func anotherComputersCatalogAtTheSameRevisionBuildsItsOwnRows() { + let cache = ChatsInboxCache() + let home = NSObject(), studio = NSObject() + let homeRows = cache.rows(for: key(home, revision: 3)) { + ChatsInboxProjection.rows(ChatsInboxInput(sessions: [session("one", at: 1, title: "On the home Mac")])) + } + let studioRows = cache.rows(for: key(studio, revision: 3)) { + ChatsInboxProjection.rows(ChatsInboxInput(sessions: [session("one", at: 1, title: "On the studio Mac")])) + } + + #expect(key(home, revision: 3) != key(studio, revision: 3)) + #expect(homeRows.map(\.title) == ["On the home Mac"]) + #expect(studioRows.map(\.title) == ["On the studio Mac"]) + } + + /// A file added in a chat's message box is never saved, so the catalog's revision stays. The + /// Draft mark still has to follow it. + @Test func aDraftOnlyTheOpenChatHoldsBuildsTheRowsAgain() { + let cache = ChatsInboxCache() + let catalog = NSObject() + var builds = 0 + let build = { builds += 1; return [ChatsInboxRow]() } + + _ = cache.rows(for: key(catalog, revision: 1), build: build) + _ = cache.rows(for: key(catalog, revision: 1, unsentDrafts: ["mina-chat": true]), build: build) + _ = cache.rows(for: key(catalog, revision: 1, unsentDrafts: ["mina-chat": true]), build: build) + #expect(builds == 2) + _ = cache.rows(for: key(catalog, revision: 1), build: build) + #expect(builds == 3) + } +} diff --git a/BighelpTests/CodeSessionStatusReaderTests.swift b/BighelpTests/CodeSessionStatusReaderTests.swift new file mode 100644 index 00000000..fe31cead --- /dev/null +++ b/BighelpTests/CodeSessionStatusReaderTests.swift @@ -0,0 +1,41 @@ +import Foundation +import Testing +@testable import Bighelp + +/// A coding session on Work reads "Needs you" from the dashboard's list too, as Today's Needs you +/// does, so a session whose chat isn't open is never shown as Done or Working while it waits. +@MainActor +struct CodeSessionStatusReaderTests { + private func approval(session: String?) -> DashboardAttentionItem { + DashboardAttentionItem( + id: "event-1", title: "Approve session action", detail: "Hermes needs authorization", urgency: .important, + approvalID: "approval-1", sessionID: session, agentID: "coder", + interaction: .approval(DashboardApprovalRequest( + eventID: "event-1", approvalID: "approval-1", allowedDecisions: [.session], + expiresAt: Date(timeIntervalSince1970: 2_000_000_000)))) + } + + private func question(session: String) -> DashboardAttentionItem { + DashboardAttentionItem( + id: "event-2", title: "Hermes needs guidance", detail: "Which branch?", urgency: .needsReview, + sessionID: session, agentID: "coder", + interaction: .clarification(DashboardClarificationRequest( + eventID: "event-2", requestID: "request-2", sessionID: session, question: "Which branch?", + choices: ["main", "next"], allowsCustomResponse: false, isMultiSelect: false, expiresAt: nil))) + } + + @Test func aSessionWithAWaitingApprovalOrQuestionNeedsYou() { + let items = [approval(session: "s-1"), question(session: "s-2")] + #expect(CodeChatStatusReader.waitingAsk(for: "s-1", in: items) == "Approve a command") + #expect(CodeChatStatusReader.waitingAsk(for: "s-2", in: items) == "Answer a question") + } + + @Test func otherSessionsAndPlainNoticesDoNotWait() { + let notice = DashboardAttentionItem(id: "n", title: "Review", detail: "", urgency: .needsReview, + sessionID: "s-3", agentID: "coder") + let items = [approval(session: "s-1"), approval(session: nil), notice] + #expect(CodeChatStatusReader.waitingAsk(for: "s-3", in: items) == nil) + #expect(CodeChatStatusReader.waitingAsk(for: "s-9", in: items) == nil) + #expect(CodeChatStatusReader.waitingAsk(for: "s-1", in: []) == nil) + } +} diff --git a/BighelpTests/DesignSystemTests.swift b/BighelpTests/DesignSystemTests.swift index 13a661b2..b0f895c0 100644 --- a/BighelpTests/DesignSystemTests.swift +++ b/BighelpTests/DesignSystemTests.swift @@ -7,23 +7,8 @@ import UIKit @MainActor struct DesignSystemTests { @Test func newChatTabUsesTheRequiredVisibleAndAccessibilityLabels() { - #expect(FloatingTabBar.newChatVisibleLabel == "New chat") - #expect(FloatingTabBar.newChatAccessibilityLabel == "New chat") - } - - @Test func primaryNavigationUsesRegularUntintedGlassOrSemanticAccessibilityFallbacks() { - #expect(FloatingTabBar.backgroundSurface(supportsLiquidGlass: true, - reduceTransparency: false, increasedContrast: false) == .regularLiquidGlass) - #expect(FloatingTabBar.backgroundSurface(supportsLiquidGlass: true, - reduceTransparency: false, increasedContrast: true) == .regularLiquidGlass) - #expect(FloatingTabBar.backgroundSurface(supportsLiquidGlass: false, - reduceTransparency: false, increasedContrast: false) == .regularMaterial) - #expect(FloatingTabBar.backgroundSurface(supportsLiquidGlass: false, - reduceTransparency: false, increasedContrast: true) == .thickMaterial) - for supportsGlass in [false, true] { - #expect(FloatingTabBar.backgroundSurface(supportsLiquidGlass: supportsGlass, - reduceTransparency: true, increasedContrast: true) == .opaque) - } + #expect(HomeTabBar.newChatVisibleLabel == "New chat") + #expect(HomeTabBar.newChatAccessibilityLabel == "New chat") } @Test func primaryNavigationRowMeasuresFiniteUniformCellsForEveryLayoutProposal() { @@ -39,11 +24,6 @@ struct DesignSystemTests { == CGSize(width: 620, height: 56)) } - @Test func rootNavigationDoesNotDuplicatePushedDestinationBars() { - #expect(FloatingTabBar.isRootBarVisible(for: [])) - #expect(!FloatingTabBar.isRootBarVisible(for: [.chat(conversationID: "current")])) - } - @Test func expandedNavigationRowsRespectTheWidthReservedBesideNewChat() { let items = [CGSize(width: 160, height: 180), CGSize(width: 200, height: 180)] let viewports: [CGFloat] = [320, 375, 402, 430, 620] @@ -361,16 +341,6 @@ struct DesignSystemTests { #expect(presentation.hitTarget == 48) } - @Test func primaryNavigationActionUsesNeutralGlassAndThemeAccentWithoutAnOutline() { - let presentation = FloatingTabBar.newChatPresentation(for: .bighelp) - - #expect(presentation.surface == .neutralGlass) - #expect(presentation.foreground == .themeAccent) - #expect(!presentation.usesGradient) - #expect(!presentation.showsBorder) - #expect(!presentation.usesGlow) - } - @Test func primitiveSpectrumAndStatusColorsMatchTheApprovedPalette() { #expect([ BighelpTokens.Palette.coralHex, diff --git a/BighelpTests/FirstRunModeTests.swift b/BighelpTests/FirstRunModeTests.swift index 8d918eef..038561e8 100644 --- a/BighelpTests/FirstRunModeTests.swift +++ b/BighelpTests/FirstRunModeTests.swift @@ -1,51 +1,30 @@ import Foundation import Testing -import UIKit @testable import Bighelp -/// "Choose your mode" at the end of setup: each card turns on its own home and turns the others off. +/// "How do you want to start?" at the end of setup: each choice sets where the home opens and its view. @MainActor -struct FirstRunModeTests { +struct FirstRunHomeTests { private func settings() -> (SettingsStore, () -> Void) { - let suite = "first-run-mode-\(UUID().uuidString)" + let suite = "first-run-home-\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suite)! return (SettingsStore(defaults: defaults), { defaults.removePersistentDomain(forName: suite) }) } - @Test func botsTurnsOnSimpleBotMode() { + @Test func withABotOpensOnBots() { let (settings, cleanUp) = settings() defer { cleanUp() } - settings.codeModeEnabled = true - FirstRunMode.bots.apply(to: settings) - #expect(settings.simpleBotsEnabled) - #expect(!settings.codeModeEnabled) + FirstRunHome.bots.apply(to: settings) + #expect(settings.homeLanding == .bots) + #expect(settings.homeView == .bots) } - @Test func sessionsKeepsTheAppAsItComes() { + @Test func acrossChatsOpensOnChats() { let (settings, cleanUp) = settings() defer { cleanUp() } - settings.simpleBotsEnabled = true - settings.codeModeEnabled = true - FirstRunMode.sessions.apply(to: settings) - #expect(!settings.simpleBotsEnabled) - #expect(!settings.codeModeEnabled) - #expect(settings.experience == .bighelp) - } - - @Test func codeOpensInBighelpIDE() { - let (settings, cleanUp) = settings() - defer { cleanUp() } - settings.simpleBotsEnabled = true - FirstRunMode.code.apply(to: settings) - #expect(!settings.simpleBotsEnabled) - #expect(settings.codeModeEnabled) - #expect(settings.startExperience == .code) - #expect(settings.experience == .code) - } - - @Test func everyModeHasAPreviewInTheApp() { - for mode in FirstRunMode.allCases { - #expect(UIImage(named: mode.previewImage) != nil, "\(mode.title) needs its preview") - } + settings.homeLanding = .bots + FirstRunHome.chats.apply(to: settings) + #expect(settings.homeLanding == .chats) + #expect(settings.homeView == .chats) } } diff --git a/BighelpTests/Fixtures/CardExamples/static-space-draft.json b/BighelpTests/Fixtures/CardExamples/static-space-draft.json new file mode 100644 index 00000000..ab311dfd --- /dev/null +++ b/BighelpTests/Fixtures/CardExamples/static-space-draft.json @@ -0,0 +1,21 @@ +{ + "schema": "loopdy.card", + "version": 1, + "title": "Commute", + "spoken_summary": "A space to add to Today: Commute. Updates every 15 minutes, without AI.", + "data_sources": [], + "root": "space", + "elements": { + "space": { + "type": "space_draft", + "props": { + "space_id": "s_0123456789abcdef0123456789abcdef", + "description": "Drive time to work, from live traffic.", + "updates": "Every 15 minutes", + "uses_ai": false, + "revision": 1 + }, + "children": [] + } + } +} diff --git a/BighelpTests/FleetStoreTests.swift b/BighelpTests/FleetStoreTests.swift index 46b9ce71..7455eacb 100644 --- a/BighelpTests/FleetStoreTests.swift +++ b/BighelpTests/FleetStoreTests.swift @@ -297,48 +297,6 @@ struct FleetStoreTests { #expect(reader.reads == [studio], "The selected host is live; it is never read") } - /// All sessions' search bar matches a chat's title and its preview text, in any case, on every host. - @Test func chatSearchMatchesTitleAndPreview() { - let fleet = FleetStore(reader: reader(), directory: directory(), saveDelay: .zero) - var trip = chat(home, "travel", "Trip to Lisbon", minutesAgo: 1) - trip.preview = "Booked the train" - var budget = chat(studio, "default", "Budget", minutesAgo: 2) - budget.preview = "The lisbon hotel costs more" - fleet.recordLive(FleetSnapshot(agents: [agent(home, "travel", "Mina")], chats: [trip], refreshedAt: Date()), - hostID: home) - fleet.recordLive(FleetSnapshot(agents: [agent(studio, "default", "Rio")], chats: [budget], - refreshedAt: Date()), hostID: studio) - - #expect(fleet.chats(matching: "lisbon").map(\.title) == ["Trip to Lisbon", "Budget"]) - #expect(fleet.chats(matching: "TRAIN").map(\.title) == ["Trip to Lisbon"]) - #expect(fleet.chats(on: studio, matching: "lisbon").map(\.title) == ["Budget"]) - #expect(fleet.chats(matching: " ").count == 2, "An empty search shows every chat") - #expect(fleet.chats(matching: "paris").isEmpty) - } - - /// All sessions filters like one computer's Sessions: by agent (on its own computer) - /// and by where the chats started. - @Test func chatFiltersMatchAnAgentOnItsComputerAndWhereChatsStarted() { - let fleet = FleetStore(reader: reader(), directory: directory(), saveDelay: .zero) - var telegram = chat(home, "travel", "Hotel", minutesAgo: 1) - telegram.origin = "telegram" - var codex = chat(home, "default", "Menus", minutesAgo: 2) - codex.origin = "codex-cli" - var studioTravel = chat(studio, "travel", "Flights", minutesAgo: 3) - studioTravel.origin = "telegram" - fleet.recordLive(FleetSnapshot(agents: [agent(home, "travel", "Mina"), agent(home, "default", "Rio")], - chats: [telegram, codex], refreshedAt: Date()), hostID: home) - fleet.recordLive(FleetSnapshot(agents: [agent(studio, "travel", "Sage")], chats: [studioTravel], - refreshedAt: Date()), hostID: studio) - - let mina = FleetChatsFilter(agentID: FleetID.make(home, "travel")) - #expect(fleet.chats(matching: "", filter: mina).map(\.title) == ["Hotel"], "Same profile on another computer isn't Mina") - #expect(fleet.chats(matching: "", filter: FleetChatsFilter(origin: "Telegram")).map(\.title) == ["Hotel", "Flights"]) - #expect(fleet.chats(on: studio, matching: "", filter: FleetChatsFilter(origin: "Telegram")).map(\.title) == ["Flights"]) - #expect(fleet.origins() == ["Codex", "Telegram"]) - #expect(fleet.chats(matching: "", filter: FleetChatsFilter()).count == 3) - } - /// Pinned agents from every host stay in the order the person dragged them /// into, after a relaunch too; a newly pinned agent joins at the end. @Test func pinnedAgentsKeepTheArrangedOrderAcrossHosts() async { diff --git a/BighelpTests/HTMLAppNavigationPolicyTests.swift b/BighelpTests/HTMLAppNavigationPolicyTests.swift new file mode 100644 index 00000000..f6c9eec7 --- /dev/null +++ b/BighelpTests/HTMLAppNavigationPolicyTests.swift @@ -0,0 +1,64 @@ +import Foundation +import Testing +import WebKit +@testable import Bighelp + +/// Where an agent's app page may go (`HTMLAppNavigationPolicy`): a page leaves for the outside only +/// as a web link the person tapped. Everything else goes nowhere. +struct HTMLAppNavigationPolicyTests { + static let appID = "a_0123456789abcdef0123456789abcdef" + static let otherID = "a_ffffffffffffffffffffffffffffffff" + + private func decide(_ text: String, mainFrame: Bool = true, + _ type: WKNavigationType = .other) -> HTMLAppNavigationPolicy.Decision { + HTMLAppNavigationPolicy.decide(url: URL(string: text)!, appID: Self.appID, isMainFrame: mainFrame, + navigationType: type) + } + + @Test(arguments: [ + "https://example.com/page", "http://example.com", "HTTPS://Example.com/x", + ]) + func aTappedWebLinkOpensOutside(_ link: String) { + #expect(decide(link, .linkActivated) == .openOutside) + } + + /// A script's own `location` or `window.open`, a form, a reload: no tap, nowhere to go. + @Test(arguments: [WKNavigationType.other, .formSubmitted, .formResubmitted, .reload, .backForward]) + func aWebAddressWithoutATapGoesNowhere(_ type: WKNavigationType) { + #expect(decide("https://example.com/page", type) == .drop) + } + + @Test(arguments: [ + "loopdy://voice?agent=default", "LOOPDY://voice", "app.loopdy.mobile://settings", "tel:5550100", + "sms:5550100", "shortcuts://run-shortcut?name=x", "mailto:a@example.com", "file:///etc/hosts", + "data:text/html,hi", "javascript:alert(1)", "about:blank", "blob:https://example.com/1", + "itms-apps://apps.apple.com/app/id1", "facetime://5550100", "x-apple-reminderkit://", + ]) + func nothingButWebLinksLeavesThePageEvenWithATap(_ link: String) { + #expect(decide(link, .linkActivated) == .drop) + #expect(decide(link, .other) == .drop) + } + + @Test func thePageStaysOnItsOwnOrigin() { + #expect(decide("bighelp-app://\(Self.appID)/") == .allowInPage) + #expect(decide("bighelp-app://\(Self.appID)/index.html#top", .linkActivated) == .allowInPage) + #expect(decide("bighelp-app://\(Self.appID)/", .reload) == .allowInPage) + // Another app's origin, or none, is never reached. + #expect(decide("bighelp-app://\(Self.otherID)/", .linkActivated) == .drop) + #expect(decide("bighelp-app://\(Self.otherID)/") == .drop) + #expect(decide("bighelp-app:///") == .drop) + #expect(decide("BIGHELP-APP://\(Self.otherID)/", .linkActivated) == .drop) + } + + @Test func framesInsideThePageLoadAsTheyAskButNeverReachTheApp() { + #expect(decide("https://example.com/embed", mainFrame: false) == .allowInPage) + #expect(decide("about:blank", mainFrame: false) == .allowInPage) + #expect(decide("data:text/html,hi", mainFrame: false) == .allowInPage) + #expect(decide("blob:https://example.com/1", mainFrame: false) == .allowInPage) + #expect(decide("bighelp-app://\(Self.appID)/frame.html", mainFrame: false) == .allowInPage) + #expect(decide("bighelp-app://\(Self.otherID)/", mainFrame: false) == .drop) + for link in ["loopdy://voice", "app.loopdy.mobile://x", "tel:5550100", "shortcuts://x", "file:///etc/hosts"] { + #expect(decide(link, mainFrame: false, .linkActivated) == .drop) + } + } +} diff --git a/BighelpTests/HomeChromeTests.swift b/BighelpTests/HomeChromeTests.swift new file mode 100644 index 00000000..00091951 --- /dev/null +++ b/BighelpTests/HomeChromeTests.swift @@ -0,0 +1,71 @@ +import Foundation +import SwiftUI +import Testing +@testable import Bighelp + +@MainActor +struct HomeChromeTests { + @Test(arguments: HomeConversationsView.allCases) + func firstTabTakesTheDefaultViewsName(view: HomeConversationsView) { + let items = HomeTabItem.standard(view: view) + #expect(items.map(\.id) == [.conversations, .today, .work]) + #expect(items[0].title == view.title) + #expect(items.map(\.accessibilityIdentifier) == ["home.tab.conversations", "home.tab.today", "home.tab.work"]) + } + + @Test func onlyTodayCarriesTheDot() { + let items = HomeTabItem.standard(view: .chats, todayHasNew: true) + #expect(items.filter(\.showsDot).map(\.id) == [.today]) + #expect(HomeTabItem.standard(view: .chats).allSatisfy { !$0.showsDot }) + } + + @Test func dotHidesOnThePlaceShowing() { + let today = HomeTabItem.standard(view: .bots, todayHasNew: true)[1] + #expect(today.showsDot(selected: false)) + #expect(!today.showsDot(selected: true)) + } + + @Test func selectedPlaceDrawsItsFilledSymbol() { + let work = HomeTabItem.standard(view: .bots)[2] + #expect(work.symbol(selected: false) == "hammer") + #expect(work.symbol(selected: true) == "hammer.fill") + } + + @Test func switchWinsOverTitle() { + var context = header() + #expect(context.center == .empty) + context.title = "Today" + #expect(context.center == .title("Today")) + context.viewSwitch = HomeViewSwitch(current: .chats, select: { _ in }) + #expect(context.center == .viewSwitch(.chats)) + } + + @Test func emptyTitleShowsNothing() { + var context = header() + context.title = "" + #expect(context.center == .empty) + } + + @Test func computerMenuNeedsTwoComputers() { + var context = header() + context.computer = HomeHeaderComputer(name: "Home Mac", hosts: [host("home", selected: true)], select: { _ in }) + #expect(context.shownComputer == nil) + context.computer = HomeHeaderComputer(name: "Home Mac", + hosts: [host("home", selected: true), host("studio")], + select: { _ in }) + #expect(context.shownComputer?.name == "Home Mac") + } + + @Test func centeredRowKeepsTheMiddleClearOfTheWiderSide() { + // 44-point circle on the left, search and + (96) on the right, a 120-point switch. + #expect(HomeHeaderRowLayout.requiredWidth(leading: 44, middle: 120, trailing: 96, spacing: 8) == 328) + } + + private func header() -> HomeHeaderContext { + HomeHeaderContext(personName: "Sam", personImageURL: nil, onOpenSettings: {}) + } + + private func host(_ id: String, selected: Bool = false) -> BighelpMenuHosts.Host { + BighelpMenuHosts.Host(id: id, name: id, isSelected: selected) + } +} diff --git a/BighelpTests/HomeSettingsMigrationTests.swift b/BighelpTests/HomeSettingsMigrationTests.swift new file mode 100644 index 00000000..3d43fcae --- /dev/null +++ b/BighelpTests/HomeSettingsMigrationTests.swift @@ -0,0 +1,227 @@ +import Foundation +import Testing +@testable import Bighelp + +/// One home: where an install that ran the modes lands, and its edge swipes without the mode actions. +@MainActor +struct HomeSettingsMigrationTests { + private typealias Migration = HomeSettingsMigration + + private func existing(_ change: (inout Migration.Stored) -> Void = { _ in }) -> Migration.Stored { + var stored = Migration.Stored(isExistingInstall: true) + change(&stored) + return stored + } + + /// Opens on, the first tab's view, and Show every computer. + private struct Lands: Equatable { + let landing: HomeLanding + let view: HomeConversationsView + let everyComputer: Bool + + init(_ landing: HomeLanding, _ view: HomeConversationsView, _ everyComputer: Bool) { + self.landing = landing + self.view = view + self.everyComputer = everyComputer + } + } + + private func lands(_ stored: Migration.Stored) -> Lands { + let outcome = Migration.outcome(stored) + return Lands(outcome.landing, outcome.view, outcome.showsEveryComputer) + } + + private func defaults() -> (UserDefaults, () -> Void) { + let suite = "home-migration-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + return (defaults, { defaults.removePersistentDomain(forName: suite) }) + } + + // MARK: Where a person lands, first match wins + + @Test func botsModeOpensOnBotsAndShowsEveryComputerOnlyWithMultiGateway() { + #expect(lands(existing { $0.botsMode = true; $0.allHosts = true }) == Lands(.bots, .bots, false)) + #expect(lands(existing { $0.botsMode = true; $0.multiGateway = true }) == Lands(.bots, .bots, true)) + #expect(lands(existing { $0.botsMode = true; $0.codeMode = true; $0.codeOpensAtLaunch = true }).landing == .bots, + "Bots mode wins over Code") + } + + @Test func codeAsTheLaunchHomeOpensOnWork() { + #expect(lands(existing { $0.codeMode = true; $0.codeOpensAtLaunch = true; $0.allHosts = true }) + == Lands(.work, .chats, true)) + #expect(lands(existing { $0.codeMode = true; $0.codeOpensAtLaunch = true; $0.landing = "agents" }).landing == .work, + "Code mode ignored Opens on") + #expect(lands(existing { $0.codeMode = true }).landing == .chats, "Code on beside Chat opened on Chat") + } + + @Test func agentsOpensOnBotsAsItWas() { + #expect(lands(existing { $0.landing = "agents" }) == Lands(.bots, .bots, false)) + #expect(lands(existing { $0.landing = "agents"; $0.allHosts = true }) == Lands(.bots, .bots, true)) + } + + @Test func everyComputersAgentsOpensOnBotsWithEveryComputer() { + #expect(lands(existing { $0.landing = "all-agents"; $0.allHosts = false }) == Lands(.bots, .bots, true)) + } + + @Test func sessionsAndLastChatOpenOnChats() { + #expect(lands(existing { $0.landing = "sessions" }) == Lands(.chats, .chats, false)) + #expect(lands(existing { $0.landing = "last-chat"; $0.allHosts = true }) == Lands(.chats, .chats, true)) + } + + @Test func feedIdeasAndGoalsOpenOnToday() { + for screen in ["feed", "ideas", "goals"] { + #expect(lands(existing { $0.landing = screen }) == Lands(.today, .chats, false), "\(screen)") + } + } + + @Test func kanbanAndProjectsOpenOnWork() { + for screen in ["kanban", "projects"] { + #expect(lands(existing { $0.landing = screen; $0.allHosts = true }) == Lands(.work, .chats, true), "\(screen)") + } + } + + @Test func theAllHostsViewWithNothingPickedOpensOnBots() { + #expect(lands(existing { $0.allHosts = true }) == Lands(.bots, .bots, true)) + } + + @Test func nothingPickedOpensOnChatsWithOneComputer() { + #expect(lands(existing()) == Lands(.chats, .chats, false)) + #expect(lands(existing { $0.landing = "dashboard" }) == Lands(.chats, .chats, false), "An unknown screen") + } + + @Test func aNewInstallIsAskedAndShowsEveryComputer() { + #expect(lands(Migration.Stored()) == Lands(.chats, .chats, true)) + } + + // MARK: Edge swipes + + @Test func modeSwipesBecomePlaces() { + #expect(Migration.remapped("botsMode", edgeDefault: .sessions) == .agents) + for mode in ["nextMode", "chatMode", "codeMode"] { + #expect(Migration.remapped(mode, edgeDefault: .sessions) == .sessions, "\(mode) on the left") + #expect(Migration.remapped(mode, edgeDefault: .newChat) == .newChat, "\(mode) on the right") + } + #expect(Migration.remapped("inbox", edgeDefault: .sessions) == .home) + #expect(Migration.remapped("quickWorkspace", edgeDefault: .sessions) == .quickWorkspace) + #expect(Migration.remapped("none", edgeDefault: .newChat) == WorkspaceSwipeAction.none) + #expect(Migration.remapped(nil, edgeDefault: .newChat) == .newChat) + #expect(Migration.remapped("teleport", edgeDefault: .sessions) == .sessions) + } + + @Test func botsModeKeepsTheSwipesItHad() { + let outcome = Migration.outcome(existing { $0.botsMode = true; $0.leftEdge = "nextMode"; $0.rightEdge = "none" }) + #expect(outcome.leftEdge == .agents) + #expect(outcome.rightEdge == .profile) + } + + // MARK: Writing it down + + /// Someone who finished first run under the modes and changed no setting has only that key. They + /// had one computer's view, so Show every computer must not turn on for them as for a new install. + @Test func anInstallThatOnlyFinishedFirstRunIsAnExistingOne() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + defaults.set(true, forKey: "loopdy.onboarding.first-run-v1.completed") + + #expect(Migration.Stored(reading: defaults).isExistingInstall) + Migration.runIfNeeded(defaults: defaults) + + #expect(defaults.object(forKey: "bighelp.hosts.all-hosts") as? Bool == false) + #expect(defaults.string(forKey: "bighelp.home.view") == "chats") + } + + @Test func runsOnceAndWritesOnlyTheNewTruth() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + defaults.set(true, forKey: "bighelp.settings.simple-bots") + defaults.set(true, forKey: "bighelp.simple-bots.multi-gateway") + defaults.set("chatMode", forKey: "loopdy.workspace.leftEdgeSwipeAction") + defaults.set("feed", forKey: BighelpLanding.screenKey) + + Migration.runIfNeeded(defaults: defaults) + + #expect(defaults.string(forKey: BighelpLanding.screenKey) == "bots") + #expect(defaults.string(forKey: "bighelp.home.view") == "bots") + #expect(defaults.object(forKey: "bighelp.hosts.all-hosts") as? Bool == true) + #expect(defaults.string(forKey: "loopdy.workspace.leftEdgeSwipeAction") == "agents") + #expect(defaults.string(forKey: "loopdy.workspace.rightEdgeSwipeAction") == "profile") + #expect(defaults.bool(forKey: "bighelp.settings.simple-bots"), "Old keys stay") + #expect(defaults.bool(forKey: Migration.markerKey)) + + defaults.set(false, forKey: "bighelp.settings.simple-bots") + defaults.set("sessions", forKey: BighelpLanding.screenKey) + Migration.runIfNeeded(defaults: defaults) + #expect(defaults.string(forKey: "bighelp.home.view") == "bots", "The marker stops a second run") + #expect(defaults.string(forKey: BighelpLanding.screenKey) == "sessions") + } + + @Test func anOldScreenThatMapsByItselfStaysAsSaved() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + defaults.set("goals", forKey: BighelpLanding.screenKey) + + Migration.runIfNeeded(defaults: defaults) + + #expect(defaults.string(forKey: BighelpLanding.screenKey) == "goals", "The old shell still reads it") + #expect(defaults.string(forKey: "bighelp.home.view") == "chats") + #expect(defaults.object(forKey: "bighelp.hosts.all-hosts") as? Bool == false, "One computer, as it was") + #expect(defaults.object(forKey: "loopdy.workspace.leftEdgeSwipeAction") == nil, "Unchanged swipes stay unset") + } + + @Test func aNewInstallGetsOnlyTheMarker() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + + Migration.runIfNeeded(defaults: defaults) + + #expect(defaults.bool(forKey: Migration.markerKey)) + #expect(defaults.object(forKey: BighelpLanding.screenKey) == nil, "First run asks") + #expect(defaults.object(forKey: "bighelp.home.view") == nil) + #expect(defaults.object(forKey: "bighelp.hosts.all-hosts") == nil) + } + + // MARK: What the store reads after + + @Test func theStoreReadsTheMigratedHome() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + defaults.set(true, forKey: "bighelp.settings.simple-bots") + + let settings = SettingsStore(defaults: defaults) + + #expect(settings.homeLanding == .bots) + #expect(settings.launchHomeLanding == .bots) + #expect(settings.homeView == .bots) + #expect(!settings.showsEveryComputer) + } + + @Test func aNewInstallOpensOnChatsWithEveryComputerUntilFirstRunAsks() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + + let settings = SettingsStore(defaults: defaults) + + #expect(settings.homeLanding == .chats) + #expect(settings.homeView == .chats) + #expect(settings.showsEveryComputer) + } + + @Test func opensOnSetsTheViewForBotsAndChatsAndKeepsItForTodayAndWork() { + let (defaults, cleanUp) = defaults() + defer { cleanUp() } + let settings = SettingsStore(defaults: defaults) + + settings.homeLanding = .bots + #expect(settings.homeView == .bots) + settings.homeLanding = .today + #expect(settings.homeView == .bots, "The last view picked") + settings.homeView = .chats + settings.homeLanding = .work + #expect(settings.homeView == .chats) + + let next = SettingsStore(defaults: defaults) + #expect(next.launchHomeLanding == .work) + #expect(next.homeView == .chats) + #expect(settings.launchHomeLanding == .chats, "This launch already happened") + } +} diff --git a/BighelpTests/LiquidOrbPresentationTests.swift b/BighelpTests/LiquidOrbPresentationTests.swift index 683921fc..d616b049 100644 --- a/BighelpTests/LiquidOrbPresentationTests.swift +++ b/BighelpTests/LiquidOrbPresentationTests.swift @@ -8,12 +8,6 @@ struct LiquidOrbPresentationTests { #expect(VoiceViewPresentation.controlMinimumHeight == 64) } - @Test func agentRowsGiveLongRoleAndSummaryCopyRoomToWrap() { - #expect(AgentRowPresentation.roleLineLimit == 2) - #expect(AgentRowPresentation.summaryLineLimit == 2) - #expect(AgentRowPresentation.textColumnCanShrink) - } - @Test func voiceStatusesMapToTheirPurposeBuiltThinkingOrbAnimations() { #expect(VoiceOrbPresentation.scenario(for: .listening) == .listening) #expect(VoiceOrbPresentation.scenario(for: .working) == .reasoning) diff --git a/BighelpTests/LocalizationTests.swift b/BighelpTests/LocalizationTests.swift index e01b8bfe..10c2eada 100644 --- a/BighelpTests/LocalizationTests.swift +++ b/BighelpTests/LocalizationTests.swift @@ -46,16 +46,16 @@ struct LocalizationTests { } } - @Test func simpleBotModeTeamworkAndTheirSettingsHaveChinese() throws { + @Test func botsTeamworkTheHomeAndTheirSettingsHaveChinese() throws { let chinese = try bundle("zh-Hans") let english = try bundle("en") let expected = [ ("Search bots", "搜索机器人"), ("Mark Unread", "标为未读"), ("Make Primary Bot", "设为主机器人"), ("Rearrange", "重新排列"), ("Instructions", "指令"), ("Default Model", "默认模型"), ("Routines", "例行任务"), ("Teamwork", "团队协作"), ("Bots messaging each other", "机器人之间的消息"), - ("Quiet hours", "勿扰时段"), ("Chat layout", "聊天布局"), ("Multi-gateway", "多网关"), - ("Bots", "机器人"), ("Chat", "聊天"), ("Code", "代码"), ("Bots mode", "机器人模式"), - ("Code mode", "代码模式"), ("Header mode switcher", "顶部模式切换"), + ("Quiet hours", "勿扰时段"), ("Chat layout", "聊天布局"), ("Show every computer", "显示所有电脑"), + ("Bots", "机器人"), ("Chats", "聊天"), ("Today", "今天"), ("Work", "工作"), + ("Make a space", "创建空间"), ("How do you want to start?", "你想怎么开始?"), ] for (key, value) in expected { #expect(chinese.localizedString(forKey: key, value: nil, table: nil) == value) @@ -84,11 +84,9 @@ struct LocalizationTests { } @Test func localizedDisplayNamesDoNotChangeSavedNavigationOrSendBehavior() throws { - let layout = BighelpAppLayout(pinned: [.agents, .feed], menuOrder: [.settings]) - let saved = try #require(layout.saved) - #expect(saved.contains("agents") && saved.contains("feed") && saved.contains("settings")) - #expect(BighelpAppLayout(saved: saved) == layout) + #expect(HomeLanding.allCases.map(\.rawValue) == ["bots", "chats", "today", "work"]) + #expect(HomeConversationsView.bots.rawValue == "bots") #expect(MidSessionChatBehavior.steer.rawValue == "steer") - #expect(FirstRunMode.bots.rawValue == "bots") + #expect(FirstRunHome.bots.rawValue == "bots") } } diff --git a/BighelpTests/NativeAgentCreationVisualTests.swift b/BighelpTests/NativeAgentCreationVisualTests.swift deleted file mode 100644 index 084d90aa..00000000 --- a/BighelpTests/NativeAgentCreationVisualTests.swift +++ /dev/null @@ -1,95 +0,0 @@ -import XCTest -import SwiftUI -@testable import Bighelp - -final class NativeAgentCreationVisualTests: XCTestCase { - @MainActor - func testNativeCreationShowsOnlySupportedOptionsAndSeparateName() async throws { - let suite = "NativeAgentCreationVisualTests.\(UUID().uuidString)" - let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let store = AgentDirectoryStore( - client: AgentDirectoryFixtureClient(profiles: [.defaultFixture, .financeFixture]), - defaults: defaults - ) - try await store.load() - let model = AgentEditorModel.creating(store: store, processor: AvatarImageProcessor(), - profileCloneSupport: .nativeBundleOnly) - model.setSkipBundledSkills(true) - model.selectCloneSource(AgentProfile.financeFixture.id) - XCTAssertFalse(model.draft.skipBundledSkills) - XCTAssertTrue(model.draft.name.isEmpty) - XCTAssertTrue(model.cloneSources.contains { $0.id == AgentProfile.financeFixture.id }) - let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) - let window = UIWindow(windowScene: scene) - window.frame = CGRect(x: 0, y: 0, width: 402, height: 874) - func content() -> some View { - AgentEditorView( - model: model, - onCompleted: { _ in } - ) - .environment(\.bighelpUIV3Enabled, true) - .environment(\.nerdModeEnabled, true) - .environment(\.appAppearance, BighelpAppearanceContext(appearance: .light)) - .environment(\.colorScheme, .light) - } - let host = UIHostingController(rootView: content()) - host.safeAreaRegions = [] - window.rootViewController = host - window.isHidden = false - defer { window.isHidden = true; window.rootViewController = nil } - host.view.frame = window.bounds - host.view.layoutIfNeeded() - try await Task.sleep(for: .milliseconds(250)) - capture(window, name: "native-creation-required-name-and-avatar") - let basicForm = try XCTUnwrap(viewHierarchy(in: host.view).compactMap { $0 as? UICollectionView }.first) - XCTAssertEqual(basicForm.numberOfSections, 3) - let advancedIndexPath = IndexPath(item: 0, section: 2) - basicForm.scrollToItem(at: advancedIndexPath, at: .bottom, animated: false) - basicForm.layoutIfNeeded() - try await Task.sleep(for: .milliseconds(150)) - XCTAssertNotNil(basicForm.cellForItem(at: advancedIndexPath), "The Advanced route must be reachable in the mounted editor form.") - basicForm.delegate?.collectionView?(basicForm, didSelectItemAt: advancedIndexPath) - for _ in 0..<20 where advancedNavigationTitle(in: host) != "Advanced" { - try await Task.sleep(for: .milliseconds(50)) - host.view.layoutIfNeeded() - } - XCTAssertEqual(advancedNavigationTitle(in: host), "Advanced") - let advancedForm = try XCTUnwrap( - viewHierarchy(in: host.view).compactMap { $0 as? UICollectionView }.first { - $0.numberOfSections == 2 - && $0.numberOfItems(inSection: 0) == 4 - && $0.numberOfItems(inSection: 1) == 1 - } - ) - XCTAssertTrue(viewHierarchy(in: advancedForm).contains { $0 is UISwitch }) - capture(window, name: "native-creation-clone-and-skip-bundled-skills") - XCTAssertTrue(model.draft.name.isEmpty) - XCTAssertEqual(store.profiles.first { $0.id == AgentProfile.financeFixture.id }, .financeFixture) - } - - @MainActor - private func viewHierarchy(in root: UIView) -> [UIView] { - [root] + root.subviews.flatMap { viewHierarchy(in: $0) } - } - - @MainActor - private func advancedNavigationTitle(in root: UIViewController) -> String? { - func navigationController(in controller: UIViewController) -> UINavigationController? { - if let navigation = controller as? UINavigationController { return navigation } - return controller.children.lazy.compactMap(navigationController).first - } - return navigationController(in: root)?.topViewController?.navigationItem.title - } - - @MainActor - private func capture(_ window: UIWindow, name: String) { - let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in - window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) - } - let attachment = XCTAttachment(image: image) - attachment.name = name - attachment.lifetime = .keepAlways - add(attachment) - } -} diff --git a/BighelpTests/NeedsYouBlueprintsModesTests.swift b/BighelpTests/NeedsYouBlueprintsModesTests.swift index 0df15184..17ee9268 100644 --- a/BighelpTests/NeedsYouBlueprintsModesTests.swift +++ b/BighelpTests/NeedsYouBlueprintsModesTests.swift @@ -2,66 +2,9 @@ import Foundation import Testing @testable import Bighelp -/// Settings › Modes' picker, blueprints in the message box, and what the Needs you deck lists. +/// Blueprints in the message box, and what the Needs you deck lists. @MainActor struct NeedsYouBlueprintsModesTests { - private func settings() throws -> (SettingsStore, () -> Void) { - let suite = "bighelp.modes.\(UUID().uuidString)" - let defaults = try #require(UserDefaults(suiteName: suite)) - return (SettingsStore(defaults: defaults), { defaults.removePersistentDomain(forName: suite) }) - } - - // MARK: Modes - - @Test func pickingAHomeSwitchesToItNowAndAtLaunch() throws { - let (settings, cleanup) = try settings() - defer { cleanup() } - #expect(settings.homeMode == .chat) - - settings.selectHomeMode(.bots) - #expect(settings.homeMode == .bots) - #expect(settings.currentMode == .bots) - - settings.selectHomeMode(.code) - #expect(settings.homeMode == .code) - #expect(settings.currentMode == .code) - #expect(!settings.simpleBotsEnabled) - #expect(settings.codeModeEnabled, "Picking Code turns Code mode on") - #expect(settings.startExperience == .code) - - settings.selectHomeMode(.chat) - #expect(settings.homeMode == .chat) - #expect(settings.currentMode == .chat) - #expect(settings.startExperience == .bighelp) - #expect(settings.availableModes == [.bots, .chat, .code], "Code stays reachable from a Chat home") - } - - /// The picker shows the home a launch opens in, not the mode ☰ or the pill switched to for now. - @Test func theHomeStaysWhenAModeIsSwitchedForNow() throws { - let (settings, cleanup) = try settings() - defer { cleanup() } - settings.selectHomeMode(.code) - settings.switchMode(.chat) - #expect(settings.currentMode == .chat) - #expect(settings.homeMode == .code) - } - - /// Picking Code once left it on for good: no switch turned it off again. - @Test func codeModeTurnsOffAgain() throws { - let (settings, cleanup) = try settings() - defer { cleanup() } - settings.selectHomeMode(.code) - - settings.setCodeMode(false) - #expect(!settings.codeModeEnabled) - #expect(settings.currentMode == .chat) - #expect(settings.homeMode == .chat) - #expect(settings.availableModes == [.bots, .chat]) - - settings.setCodeMode(true) - #expect(settings.homeMode == .chat, "Turning it back on doesn't make it the home again") - } - // MARK: Blueprints @Test func startersHaveBlanksAndCoverMoreThanOneTopic() throws { diff --git a/BighelpTests/NewChatCoordinatorTests.swift b/BighelpTests/NewChatCoordinatorTests.swift index 1a4a84d3..5f65f502 100644 --- a/BighelpTests/NewChatCoordinatorTests.swift +++ b/BighelpTests/NewChatCoordinatorTests.swift @@ -187,7 +187,7 @@ struct NewChatCoordinatorTests { _ = try await start.value return } - state.select(.sessions) + state.select(.conversations) client.finishCreation() let outcome = try await start.value @@ -197,6 +197,33 @@ struct NewChatCoordinatorTests { #expect(catalog.session(id: "session-shared") != nil) } + /// New chat's blank chat is on top and another bot is picked for it: the chat the computer makes + /// takes its place in one step. No second canvas goes between them. + @Test func aPickForTheBlankChatOnTopReplacesItOnce() async throws { + let client = DeferredNewChatSessionCatalogClient() + let agents = AgentDirectoryStore( + client: AgentDirectoryFixtureClient(profiles: [.defaultFixture]), + profiles: [.defaultFixture] + ) + let state = AppState() + state.path = [.chat(conversationID: "blank")] + let catalog = SessionCatalogStore(client: client) + let coordinator = NewChatCoordinator(appState: state, agents: agents, catalog: catalog, prepare: { _ in true }) + var presented: [String] = [] + + let start = Task { + try await coordinator.start(replacingBlankChat: true, beforePresentation: { next, _ in presented.append(next) }) + } + await client.waitUntilCreateStarts() + #expect(state.path == [.chat(conversationID: "blank")], "The blank chat stays while the computer makes the next") + client.finishCreation() + + let outcome = try await start.value + #expect(outcome == .opened(sessionID: "session-shared", agentID: "default")) + #expect(presented == ["session-shared"]) + #expect(state.path == [.chat(conversationID: "session-shared")]) + } + @Test func creatingAnotherLocalCanvasKeepsEarlierDraftForRecovery() { let catalog = SessionCatalogStore(client: SessionCatalogFixtureClient()) let first = catalog.createLocalPresentationDraft(agentID: "default") @@ -221,14 +248,6 @@ struct NewChatCoordinatorTests { #expect(model.isComposerAttachmentInputDisabled) } - @Test func newChatActionExpandsItsHitAreaWithoutGrowingTheVisibleControl() { - let presentation = SpectrumAction.hitTargetPresentation - - #expect(presentation.visualSize == BighelpTokens.primaryActionSize) - #expect(presentation.minimumHeight == BighelpTokens.primaryActionSize) - #expect(presentation.expandsHorizontally) - } - @Test func repeatedNewChatTapsShareOneSessionCreation() async throws { let client = DeferredNewChatSessionCatalogClient() let agents = AgentDirectoryStore( diff --git a/BighelpTests/NewChatPickTests.swift b/BighelpTests/NewChatPickTests.swift new file mode 100644 index 00000000..98059782 --- /dev/null +++ b/BighelpTests/NewChatPickTests.swift @@ -0,0 +1,199 @@ +import Foundation +import Testing +@testable import Bighelp + +/// New chat's To row and the blank chat under it must agree, and what the person typed goes where +/// the pick goes or stays where it is. +@MainActor +struct NewChatPickTests { + private static let home = UUID() + private static let studio = UUID() + + private func bot(_ id: String, on hostID: UUID? = nil) -> SimpleBotsBot { + SimpleBotsBot(id: hostID.map { "\($0)/\(id)" } ?? id, profileID: id, hostID: hostID, + name: id.capitalized, role: "") + } + + private func pick(_ recipients: [SimpleBotsBot], blank: [String]?, hasFleet: Bool = false, + hostInUse: UUID? = nil) -> NewChatPick { + NewChatPick.decide(recipients: recipients, blankMembers: blank, hasFleet: hasFleet, hostInUse: hostInUse) + } + + @Test func oneBotMakesTheBlankChatThatBots() { + #expect(pick([], blank: ["primary"]) == .keep, "Nobody picked: the blank chat stays the primary bot's") + #expect(pick([bot("mina")], blank: ["primary"]) == .start(profileID: "mina")) + #expect(pick([bot("mina")], blank: ["mina"]) == .keep) + #expect(pick([bot("mina"), bot("otto")], blank: ["primary"]) == .keep, "A group chat is made at Send") + #expect(pick([bot("mina")], blank: nil) == .start(profileID: "mina")) + } + + @Test func aBotOnAnotherComputerSwitchesThereFirst() { + let onStudio = bot("mina", on: Self.studio) + #expect(pick([onStudio], blank: ["mina"], hasFleet: true, hostInUse: Self.home) + == .switchComputer(Self.studio, profileID: "mina"), "The same profile name there is another bot") + #expect(pick([onStudio], blank: ["primary"], hasFleet: true, hostInUse: Self.studio) == .start(profileID: "mina")) + #expect(pick([onStudio], blank: ["primary"], hasFleet: false, hostInUse: nil) == .start(profileID: "mina"), + "Without other computers to switch to, every bot is on this one") + } + + /// One chat starts at a time, and the first start runs from the blank canvas until the computer + /// has made the chat. A pick in that time was dropped: the To row said Otto and the chat was + /// Mina's. It waits, and when the start ends the To row as it is then gets the chat. + @Test func thePickMadeWhileAChatStartsIsTheOneThatGetsTheChat() { + let session = NewChatSession() + session.start(conversationID: "canvas") + var gate = NewChatPickGate() + let rules = NewChatGroupRules() + + session.toggle(bot("mina"), rules: rules) + #expect(pick(session.recipients, blank: ["primary"]) == .start(profileID: "mina")) + // Mina's chat is starting. The person changes their mind twice. + session.remove(bot("mina")) + session.toggle(bot("otto"), rules: rules) + gate.hold() + session.remove(bot("otto")) + session.toggle(bot("juno"), rules: rules) + gate.hold() + + // Mina's chat arrived: the To row is read again, once. + let readsAgain = gate.release() + #expect(readsAgain) + #expect(pick(session.recipients, blank: ["mina"]) == .start(profileID: "juno")) + let readsOnceMore = gate.release() + #expect(!readsOnceMore, "A start with no pick behind it starts nothing more") + } + + @Test func aStartWithNoPickBehindItStartsNothingMore() { + var gate = NewChatPickGate() + let readsAgain = gate.release() + #expect(!readsAgain) + } + + // MARK: A pick on another computer + + private func model(_ draft: String) -> ChatModel { + let model = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), initialItems: []) + model.draft = draft + return model + } + + /// New chat's text and To row go with the switch. A switch that doesn't open must leave none + /// of it behind: a later New chat on that computer started with the old message and To row. + @Test(arguments: [FleetOpenEnd.refused, .cancelled, .unanswered]) + func aSwitchThatDoesNotOpenDropsWhatNewChatHandedOver(_ end: FleetOpenEnd) { + let home = HomeSelection() + let blank = model("hello") + home.newChat.start(with: [bot("mina", on: Self.studio), bot("otto", on: Self.studio)]) + home.newChat.ask(.startGroup) + home.handOffNewChat(NewChatHandoff(text: "hello", followsPick: true, source: blank)) + + #expect(home.takeNewChatHandoff(after: end) == nil) + + #expect(home.newChatHandoff == nil) + #expect(home.takeNewChatHandoff(after: .opened) == nil, "Nothing is left for the next switch") + #expect(blank.draft == "hello", "The box still has the text") + #expect(!home.newChat.isStartingGroup, "Send is free again") + } + + @Test func aSwitchThatOpensTakesTheTextAndTheBoxLetsItGoOnceItArrives() throws { + let home = HomeSelection() + let blank = model("hello") + home.handOffNewChat(NewChatHandoff(text: "hello", followsPick: true, source: blank)) + + let handoff = try #require(home.takeNewChatHandoff(after: .opened)) + #expect(handoff.text == "hello") + #expect(handoff.followsPick) + #expect(home.newChatHandoff == nil) + #expect(blank.draft == "hello", "Not before the other computer has it") + + handoff.delivered() + #expect(blank.draft.isEmpty) + } + + @Test func textChangedSinceTheSwitchStaysInItsBox() { + let blank = model("hello") + let handoff = NewChatHandoff(text: "hello", followsPick: false, source: blank) + blank.draft = "hello again" + + handoff.delivered() + + #expect(blank.draft == "hello again") + } + + // MARK: The blank chat under a chat that takes its place + + /// New chat's blank chat goes when a group chat takes its place. A chat that was New chat's and + /// has a message is an ordinary chat: a group chat opened over it later (an alert, a link) must + /// leave it for Back. + @Test func aChatWithAMessageStaysUnderTheChatThatOpensOverIt() { + let state = AppState() + state.activateConversation(id: "mina-chat", source: .newChat) + state.activateConversation(id: "group", source: .sessions) + + state.dropBlankChat("mina-chat", under: "group", isBlank: false) + #expect(state.path == [.chat(conversationID: "mina-chat"), .chat(conversationID: "group")]) + + state.dropBlankChat("mina-chat", under: "group", isBlank: true) + #expect(state.path == [.chat(conversationID: "group")]) + } + + @Test func theBlankChatStaysUntilTheChatThatTakesItsPlaceIsOpen() { + let state = AppState() + state.activateConversation(id: "blank", source: .newChat) + + state.dropBlankChat("blank", under: "group", isBlank: true) + #expect(state.path == [.chat(conversationID: "blank")], "The group chat didn't open") + state.dropBlankChat("blank", under: "blank", isBlank: true) + #expect(state.path == [.chat(conversationID: "blank")]) + } + + @Test func aChatIsBlankForNewChatOnlyUntilSomethingIsSentOrFails() { + let blank = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), initialItems: []) + #expect(blank.isBlankForNewChat) + blank.draft = "Typing doesn't count" + #expect(blank.isBlankForNewChat) + + let sent = ChatModel(conversationID: "sent", client: ConversationFixtureClient(), initialItems: [ + TimelineItem(id: "first", role: .human, sender: .user(snapshot: .init(name: "You")), + content: .message("Hello"), metadata: .init(delivery: "Sent")), + ]) + #expect(!sent.isBlankForNewChat) + + blank.failureMessage = "This chat couldn't start." + #expect(!blank.isBlankForNewChat) + } + + // MARK: The chat that is open + + /// Back, a tab or a computer's pages closing take a chat off the stack: it isn't the open chat + /// any more, whatever was opened last. + @Test func aChatThatLeftTheStackIsNotTheOpenChat() { + let state = AppState() + state.activateConversation(id: "mina-chat", source: .sessions) + #expect(state.activeConversationID == "mina-chat") + + state.open(.simpleBotProfile(agentID: "mina")) + #expect(state.activeConversationID == "mina-chat", "A page over the chat leaves it open") + + state.path.removeLast(2) + #expect(state.activeConversationID == nil) + #expect(state.chatOnScreen == nil) + + state.activateConversation(id: "otto-chat", source: .sessions) + state.select(.today) + #expect(state.activeConversationID == nil) + } + + /// Every computer has its own `AppState`. The alert's tap reaches the app's first one; the shell + /// on screen reads the computer in use's. + @Test func anAlertWithoutAChatReachesWhicheverStateTheShellReads() { + let home = HomeSelection() + let first = AppState(home: home), computers = AppState(home: home) + + first.openNeedsYou() + #expect(computers.isNeedsYouRequested) + + computers.isNeedsYouRequested = false + #expect(!first.isNeedsYouRequested) + } +} diff --git a/BighelpTests/NewChatRecipientsTests.swift b/BighelpTests/NewChatRecipientsTests.swift new file mode 100644 index 00000000..aaa3d8c5 --- /dev/null +++ b/BighelpTests/NewChatRecipientsTests.swift @@ -0,0 +1,138 @@ +import Foundation +import Testing +@testable import Bighelp + +@MainActor +struct NewChatRecipientsTests { + private let here = UUID(uuidString: "00000000-0000-4000-8000-0000000000A1")! + private let there = UUID(uuidString: "00000000-0000-4000-8000-0000000000B2")! + + private func bot(_ id: String, on host: UUID? = nil) -> SimpleBotsBot { + SimpleBotsBot(id: host.map { FleetID.make($0, id) } ?? id, profileID: id, hostID: host, + name: id.capitalized, role: "") + } + + private var groups: NewChatGroupRules { NewChatGroupRules(hostInUse: here, canMakeGroups: true) } + + @Test func oneBotIsAChatAndTwoToSixAGroup() { + let session = NewChatSession() + #expect(session.kind == .nobody) + #expect(session.toggle(bot("avery"), rules: groups)) + #expect(session.kind == .chat) + for id in ["mina", "jordan", "sam", "kai", "rio"] { + #expect(session.toggle(bot(id), rules: groups)) + #expect(session.kind == .group) + } + #expect(session.recipients.map(\.profileID) == ["avery", "mina", "jordan", "sam", "kai", "rio"]) + #expect(session.refusal == nil) + } + + @Test func aSeventhBotIsRefused() { + let six = ["a", "b", "c", "d", "e", "f"].map { bot($0) } + let change = NewChatRecipients.toggling(bot("g"), in: six, rules: groups) + #expect(change.picked == six) + #expect(change.refusal == .full) + #expect(!NewChatRecipients.canJoin(bot("g"), picked: six, rules: groups)) + // A picked bot can still be taken out. + #expect(NewChatRecipients.toggling(six[2], in: six, rules: groups).picked.count == 5) + } + + /// Until the computer's Hermes has said whether it makes group chats, nobody is marked as unable. + @Test func aSecondPickIsTakenWhileTheComputerHasNotAnswered() { + let rules = NewChatGroupRules(hostInUse: here, canMakeGroups: nil) + let avery = bot("avery", on: here), mina = bot("mina", on: here) + #expect(NewChatRecipients.canJoin(mina, picked: [avery], rules: rules)) + let session = NewChatSession() + #expect(session.toggle(avery, rules: rules)) + #expect(session.toggle(mina, rules: rules)) + #expect(session.kind == .group) + #expect(session.refusal == nil) + } + + @Test func aSecondPickIsRefusedWhereGroupChatsCantBeMade() { + let rules = NewChatGroupRules(hostInUse: here, canMakeGroups: false) + let session = NewChatSession() + #expect(session.toggle(bot("avery"), rules: rules)) + #expect(!session.toggle(bot("mina"), rules: rules)) + #expect(session.recipients.map(\.profileID) == ["avery"]) + #expect(session.refusal == .noGroups) + #expect(session.refusal?.message == "Group chats need a newer Hermes on this computer.") + // The next change clears the line. + session.remove(bot("avery")) + #expect(session.refusal == nil) + } + + @Test func onlyBotsHermesSeatsCanJoinAGroupOnItsComputer() { + let rules = NewChatGroupRules(hostInUse: here, canMakeGroups: true, seatableProfiles: ["avery", "mina"]) + #expect(NewChatRecipients.refusal(adding: bot("mina"), to: [bot("avery")], rules: rules) == nil) + #expect(NewChatRecipients.refusal(adding: bot("jordan"), to: [bot("avery")], rules: rules) + == .cannotSeat(names: ["Jordan"])) + // A chat with one bot never needs a seat. + #expect(NewChatRecipients.refusal(adding: bot("jordan"), to: [], rules: rules) == nil) + // A first pick Hermes can't seat holds back the group it would start. + #expect(NewChatRecipients.refusal(adding: bot("avery"), to: [bot("jordan")], rules: rules) + == .cannotSeat(names: ["Jordan"])) + } + + @Test func botsOnAnotherComputerJoinAsPeers() { + let rules = NewChatGroupRules(hostInUse: here, canMakeGroups: true, seatableProfiles: ["avery"]) + let avery = bot("avery", on: here) + let juno = bot("juno", on: there) + // Hermes on this computer seats only its own bots; Juno joins through its own computer. + #expect(NewChatRecipients.refusal(adding: juno, to: [avery], rules: rules) == nil) + let split = NewChatRecipients.split([avery, juno], rules: rules) + #expect(split.home == [avery]) + #expect(split.peers == [juno]) + let peers = NewChatRecipients.peerCandidates([avery, juno], rules: rules) { _ in "Studio" } + #expect(peers == [HermesBotModePeerCandidate(hostID: there.uuidString, hostName: "Studio", + profileID: "juno", name: "Juno")]) + } + + @Test func aGroupStartedOnAnotherComputerIsCheckedThere() { + // This computer can't make groups, but the group lives on the first bot's computer. + let rules = NewChatGroupRules(hostInUse: here, canMakeGroups: false, seatableProfiles: []) + let juno = bot("juno", on: there) + #expect(NewChatRecipients.refusal(adding: bot("kai", on: there), to: [juno], rules: rules) == nil) + #expect(NewChatRecipients.refusal(adding: bot("avery", on: here), to: [juno], rules: rules) == nil) + // Started here, it is refused. + #expect(NewChatRecipients.refusal(adding: juno, to: [bot("avery", on: here)], rules: rules) == .noGroups) + } + + @Test func anotherBotOrASecondOneDropsTheProject() { + let session = NewChatSession() + let project = CodeProject(id: "p", name: "Sample", folder: "/tmp/sample") + session.toggle(bot("avery"), rules: groups) + session.project = project + session.toggle(bot("mina"), rules: groups) + #expect(session.project == nil) + session.remove(bot("mina")) + #expect(session.recipients.map(\.profileID) == ["avery"]) + session.project = project + // A refused pick changes nobody, so the project stays. + session.toggle(bot("mina"), rules: NewChatGroupRules(hostInUse: here, canMakeGroups: false)) + #expect(session.project == project) + session.remove(bot("avery")) + session.toggle(bot("mina"), rules: groups) + #expect(session.project == nil) + } + + @Test func listGroupsBotsByComputerInOrder() { + let hosts = [FleetHost(id: here, name: "Home", isSelected: true), + FleetHost(id: there, name: "Studio", isSelected: false)] + let bots = [bot("juno", on: there), bot("avery", on: here), bot("mina")] + let sections = NewChatRecipients.sections(bots, hosts: hosts, rules: groups) + #expect(sections.map(\.host?.name) == ["Home", "Studio"]) + // A bot with no computer is on the one in use. + #expect(sections[0].bots.map(\.profileID) == ["avery", "mina"]) + #expect(sections[1].bots.map(\.profileID) == ["juno"]) + // One computer: one section, no header. + #expect(NewChatRecipients.sections([bot("avery"), bot("mina")], hosts: [], rules: groups).count == 1) + } + + @Test func searchMatchesNamesAndRoles() { + let travel = SimpleBotsBot(id: "mina", profileID: "mina", name: "Mina", role: "Travel") + #expect(NewChatRecipients.matches(travel, query: "trav")) + #expect(NewChatRecipients.matches(travel, query: " ")) + #expect(!NewChatRecipients.matches(travel, query: "money")) + } +} diff --git a/BighelpTests/NewChatSendTests.swift b/BighelpTests/NewChatSendTests.swift new file mode 100644 index 00000000..b5ad2dda --- /dev/null +++ b/BighelpTests/NewChatSendTests.swift @@ -0,0 +1,191 @@ +import Foundation +import Testing +@testable import Bighelp + +@MainActor +struct NewChatSendTests { + @Test func sendFollowsWhoAndWhere() { + #expect(NewChatSend.decide(recipients: 0, hasProject: false, stagedJobs: 0) == nil) + #expect(NewChatSend.decide(recipients: 1, hasProject: false, stagedJobs: 0) == .chat) + // Staged jobs belong to a project: without one, Send is the chat's own. + #expect(NewChatSend.decide(recipients: 1, hasProject: false, stagedJobs: 2) == .chat) + #expect(NewChatSend.decide(recipients: 1, hasProject: true, stagedJobs: 0) == .coding) + #expect(NewChatSend.decide(recipients: 1, hasProject: true, stagedJobs: 2) == .staged) + #expect(NewChatSend.decide(recipients: 2, hasProject: false, stagedJobs: 0) == .group) + #expect(NewChatSend.decide(recipients: 6, hasProject: true, stagedJobs: 1) == .group) + #expect(NewChatSend.decide(recipients: 7, hasProject: false, stagedJobs: 0) == nil) + } + + @Test func contextLineSaysWhatSendDoes() { + #expect(NewChatSend.contextLine(.chat, names: ["Mina"], projectName: nil) == "New chat with Mina") + #expect(NewChatSend.contextLine(.group, names: ["Avery", "Mina", "Jordan"], projectName: nil) + == "Group chat · 3 bots") + #expect(NewChatSend.contextLine(.coding, names: ["Mina"], projectName: "sample-app") + == "Coding session in sample-app") + #expect(NewChatSend.contextLine(.staged, names: ["Mina"], projectName: "sample-app", jobs: 3) + == "3 coding sessions in sample-app") + #expect(NewChatSend.contextLine(.staged, names: ["Mina"], projectName: "sample-app", jobs: 1) + == "Coding session in sample-app") + } + + @Test func sessionLineCountsTheBoxAsAJob() { + let session = NewChatSession() + #expect(NewChatSend.contextLine(session, stagedJobs: 0, hasText: true) == nil) + session.start(with: [SimpleBotsBot(id: "mina", profileID: "mina", name: "Mina", role: "")]) + #expect(NewChatSend.contextLine(session, stagedJobs: 0, hasText: true) == "New chat with Mina") + session.project = CodeProject(id: "p", name: "sample-app", folder: "/tmp/sample-app") + #expect(NewChatSend.decide(session, stagedJobs: 0) == .coding) + #expect(NewChatSend.contextLine(session, stagedJobs: 2, hasText: true) == "3 coding sessions in sample-app") + #expect(NewChatSend.contextLine(session, stagedJobs: 2, hasText: false) == "2 coding sessions in sample-app") + } + + // MARK: Send sends everything in the box, or nothing + + private func bot(_ id: String, on hostID: UUID? = nil) -> SimpleBotsBot { + SimpleBotsBot(id: id, profileID: id, hostID: hostID, name: id.capitalized, role: "") + } + + private func relay(_ session: NewChatSession, _ model: ChatModel, hostInUse: UUID? = nil, + shown: @escaping @MainActor (String) -> Void = { _ in }) -> NewChatSendRelay { + NewChatSendRelay(session: session, model: model, store: nil, hostInUse: { hostInUse }, showProject: shown) + } + + @Test func aStepThatCannotCarryTheBoxIsRefusedNeverRunWithoutIt() { + func step(_ send: NewChatSend?, own: Bool = false, files: Bool = false, starting: Bool = false) -> NewChatSend.Step { + NewChatSend.step(send, isPickedBotsChat: own, holdsAttachments: files, isStartingGroup: starting) + } + #expect(step(nil) == .refuse(.nobody)) + #expect(step(.chat, own: true, files: true) == .sendHere, "The chat's own send carries attachments") + #expect(step(.chat) == .followPick) + #expect(step(.chat, files: true) == .refuse(.pickKeepsAttachments)) + #expect(step(.group) == .startGroup) + #expect(step(.group, files: true) == .refuse(.groupTextOnly)) + #expect(step(.group, starting: true) == .refuse(.starting), "A second Send would make a second group chat") + #expect(step(.coding) == .startCoding) + #expect(step(.coding, files: true) == .refuse(.codingTextOnly)) + #expect(step(.staged) == .startStaged) + #expect(step(.staged, files: true) == .refuse(.codingTextOnly)) + } + + /// The group chat is made by the shell, after Send returns, and making it can fail. The box + /// keeps the text until the group chat has it. + @Test func aGroupSendKeepsTheTextUntilTheGroupChatHasIt() { + let session = NewChatSession() + session.start(with: [bot("mina"), bot("otto")], conversationID: "blank") + let model = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "mina", + initialItems: []) + model.draft = "Plan the trip together" + let send = relay(session, model) + + #expect(send.send(holdsReferences: false), "The message isn't this chat's to send") + #expect(session.takeRequest() == .startGroup) + #expect(session.isStartingGroup) + #expect(model.draft == "Plan the trip together") + + // A second press while it is being made asks for nothing more. + #expect(send.send(holdsReferences: false)) + #expect(session.takeRequest() == nil) + #expect(session.note == .starting) + + // It couldn't be made: Send is free again and the text is still there. + session.groupEnded() + #expect(!session.isStartingGroup) + #expect(session.note == nil) + #expect(model.draft == "Plan the trip together") + #expect(send.send(holdsReferences: false)) + #expect(session.takeRequest() == .startGroup) + } + + @Test func aGroupSendWithReferencesAsksForNothingAndSaysWhy() { + let session = NewChatSession() + session.start(with: [bot("mina"), bot("otto")], conversationID: "blank") + let model = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "mina", + initialItems: []) + model.draft = "Use the trip notes" + + #expect(relay(session, model).send(holdsReferences: true)) + #expect(session.takeRequest() == nil) + #expect(!session.isStartingGroup) + #expect(session.note == .groupTextOnly) + #expect(model.draft == "Use the trip notes") + } + + /// A picture pasted or dropped into the box before the second bot was picked stays there: the + /// group chat would have started without it. + @Test func aGroupSendWithAnAttachmentAsksForNothingAndKeepsIt() throws { + let session = NewChatSession() + session.start(with: [bot("mina"), bot("otto")], conversationID: "blank") + let model = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "mina", + initialItems: []) + model.draft = "Where is this?" + try model.addDraftAttachment(ChatAttachment(id: "attachment_image_new_chat_0001", fileName: "map.png", + mimeType: "image/png", data: Data([0x89, 0x50, 0x4E, 0x47]))) + + #expect(relay(session, model).send(holdsReferences: false)) + #expect(session.takeRequest() == nil) + #expect(session.note == .groupTextOnly) + #expect(model.draft == "Where is this?") + #expect(model.orderedDraftAttachments.count == 1) + } + + @Test func sendWithNobodyPickedSaysSoAndPutsTheCursorInTheToField() { + let session = NewChatSession() + session.start(conversationID: "blank") + let model = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "mina", + initialItems: []) + model.draft = "Hello" + + #expect(relay(session, model).send(holdsReferences: false)) + #expect(session.note == .nobody) + #expect(session.fieldFocusRequests == 1) + #expect(session.noteCount == 1) + #expect(model.draft == "Hello") + // Each press says it again, for VoiceOver. + #expect(relay(session, model).send(holdsReferences: false)) + #expect(session.noteCount == 2) + + // A pick takes the line away. + session.toggle(bot("mina"), rules: NewChatGroupRules()) + #expect(session.note == nil) + } + + @Test func oneBotsOwnChatSendsHereAndAnotherBotsChatFollowsThePickFirst() { + let studio = UUID() + let session = NewChatSession() + session.start(with: [bot("mina")], conversationID: "blank") + let minas = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "mina", + initialItems: []) + minas.draft = "Hello" + #expect(!relay(session, minas).send(holdsReferences: true), "Its own send carries references too") + #expect(session.takeRequest() == nil) + + // The blank chat is still the primary bot's: nothing is sent to the wrong bot. + let primarys = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "otto", + initialItems: []) + primarys.draft = "Hello" + #expect(relay(session, primarys).send(holdsReferences: false)) + #expect(session.takeRequest() == .followPick) + #expect(primarys.draft == "Hello") + + // The same profile name on another computer isn't this chat's bot. + session.start(with: [bot("mina", on: studio)], conversationID: "blank") + #expect(relay(session, minas, hostInUse: UUID()).send(holdsReferences: false)) + #expect(session.takeRequest() == .followPick) + } + + /// No coding store on the computer in use: nothing starts, the text stays and a line says so. + @Test func aCodingSendThatCannotStartKeepsTheText() { + let session = NewChatSession() + session.start(with: [bot("mina")], conversationID: "blank") + session.project = CodeProject(id: "p", name: "sample-app", folder: "/tmp/sample-app") + let model = ChatModel(conversationID: "blank", client: ConversationFixtureClient(), agentID: "mina", + initialItems: []) + model.draft = "Fix the widget tap" + var shown: [String] = [] + + #expect(relay(session, model, shown: { shown.append($0) }).send(holdsReferences: false)) + #expect(session.note == .codingUnavailable) + #expect(model.draft == "Fix the widget tap") + #expect(shown.isEmpty) + } +} diff --git a/BighelpTests/PrimaryNavigationSelectionTests.swift b/BighelpTests/PrimaryNavigationSelectionTests.swift deleted file mode 100644 index fe4621e0..00000000 --- a/BighelpTests/PrimaryNavigationSelectionTests.swift +++ /dev/null @@ -1,44 +0,0 @@ -import XCTest -import SwiftUI -@testable import Bighelp - -final class PrimaryNavigationSelectionTests: XCTestCase { - @MainActor - func testSelectedSurfaceIsRoundedSquareRatherThanCapsule() { - let bounds = CGRect(x: 0, y: 0, width: 74, height: 74) - let selected = FloatingTabBar.selectionShape.path(in: bounds) - XCTAssertTrue(selected.contains(CGPoint(x: 10, y: 10))) - XCTAssertFalse(Capsule().path(in: bounds).contains(CGPoint(x: 10, y: 10))) - XCTAssertFalse(selected.contains(CGPoint(x: 0, y: 0))) - } - - @MainActor - func testAllRootSelectionsRenderThroughTheSameSurface() async throws { - let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) - let tabs: [(AppTab, String)] = [(.agents, "agents"), (.sessions, "sessions"), (.scheduledTasks, "tasks")] - for (tab, name) in tabs { - let content = FloatingTabBar(selection: .constant(tab), onNewChat: {}) - .frame(width: 402, height: 110) - .background(Color.white) - .environment(\.appAppearance, BighelpAppearanceContext(appearance: .light)) - .environment(\.colorScheme, .light) - let host = UIHostingController(rootView: content) - host.safeAreaRegions = [] - let window = UIWindow(windowScene: scene) - window.frame = CGRect(x: 0, y: 0, width: 402, height: 110) - window.rootViewController = host - window.isHidden = false - defer { window.isHidden = true; window.rootViewController = nil } - host.view.frame = window.bounds - host.view.layoutIfNeeded() - await Task.yield() - let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in - window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) - } - let attachment = XCTAttachment(image: image) - attachment.name = "rounded-square-navigation-" + name - attachment.lifetime = .keepAlways - add(attachment) - } - } -} diff --git a/BighelpTests/SettingsComputersTests.swift b/BighelpTests/SettingsComputersTests.swift index a2bb56bf..5e456614 100644 --- a/BighelpTests/SettingsComputersTests.swift +++ b/BighelpTests/SettingsComputersTests.swift @@ -1,17 +1,21 @@ +import Foundation import Testing @testable import Bighelp -/// Settings › Your computers: which setting Show every computer changes, and the time zone row's value. +/// Settings › Your computers: the one Show every computer setting, and the time zone row's value. @MainActor struct SettingsComputersTests { - @Test func showEveryComputerIsBotsModesMultiGatewayWhileBotsModeIsOn() { - #expect(SettingsEveryComputer.choice(botsModeOn: true, canSetAllHosts: true) == .botsMultiGateway) - #expect(SettingsEveryComputer.choice(botsModeOn: true, canSetAllHosts: false) == .botsMultiGateway) - } + @Test func showEveryComputerKeepsTheOldAllHostsKey() { + let suite = "settings-computers-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let settings = SettingsStore(defaults: defaults) - @Test func showEveryComputerIsTheAllHostsViewElsewhereWhenTheShellCanSetIt() { - #expect(SettingsEveryComputer.choice(botsModeOn: false, canSetAllHosts: true) == .allHosts) - #expect(SettingsEveryComputer.choice(botsModeOn: false, canSetAllHosts: false) == nil) + settings.showsEveryComputer = false + #expect(defaults.object(forKey: "bighelp.hosts.all-hosts") as? Bool == false) + settings.showsEveryComputer = true + #expect(SettingsStore(defaults: defaults).showsEveryComputer) + #expect(defaults.object(forKey: "bighelp.hosts.all-hosts") as? Bool == true, "The all-hosts key, kept") } @Test func timeZoneSaysNothingUntilTheComputerAnswers() { diff --git a/BighelpTests/SettingsDestinationTests.swift b/BighelpTests/SettingsDestinationTests.swift index 77eb8af3..ee764de2 100644 --- a/BighelpTests/SettingsDestinationTests.swift +++ b/BighelpTests/SettingsDestinationTests.swift @@ -6,7 +6,7 @@ struct SettingsDestinationTests { @Test func openingSettingsAtPagesPresentsThemInOrder() { let state = AppState() - state.openSettings(at: [.section(.appearance), .appLayout]) + state.openSettings(at: [.section(.appearance), .thinking]) #expect(state.isSettingsPresented) #expect(state.settingsPath.count == 2) @@ -23,7 +23,7 @@ struct SettingsDestinationTests { @Test func openingAgainReplacesThePagesOfTheOpenSettings() { let state = AppState() - state.openSettings(at: [.section(.appearance), .appLayout]) + state.openSettings(at: [.section(.appearance), .thinking]) state.openSettings(at: [.section(.chat)]) diff --git a/BighelpTests/SettingsStoreTests.swift b/BighelpTests/SettingsStoreTests.swift index 4316dfe8..7ec9eac7 100644 --- a/BighelpTests/SettingsStoreTests.swift +++ b/BighelpTests/SettingsStoreTests.swift @@ -362,29 +362,6 @@ struct SettingsStoreTests { #expect(BotChatExperience.allCases == [.botChat, .lastChat, .newChat]) } - /// Chat is the out-of-box home. Code mode opens a launch only once it's - /// on and chosen, and turning it off brings Chat back at once. - @Test func codeModeIsOffByDefaultAndOpensOnlyWhenChosen() { - let suiteName = #function - let defaults = UserDefaults(suiteName: suiteName)! - defaults.removePersistentDomain(forName: suiteName) - defer { defaults.removePersistentDomain(forName: suiteName) } - - let fresh = SettingsStore(defaults: defaults) - #expect(!fresh.codeModeEnabled) - #expect(fresh.experience == .bighelp) - - fresh.startExperience = .code - #expect(SettingsStore(defaults: defaults).experience == .bighelp) - - fresh.codeModeEnabled = true - let relaunched = SettingsStore(defaults: defaults) - #expect(relaunched.experience == .code) - - relaunched.codeModeEnabled = false - #expect(relaunched.experience == .bighelp) - } - @Test func midSessionChatBehaviorDefaultsToSteerAndOffersEveryHermesMode() { let suiteName = #function let defaults = UserDefaults(suiteName: suiteName)! @@ -523,7 +500,6 @@ struct SettingsStoreTests { @Test func settingsMenuUsesFocusedSubsectionsInsteadOfOneLongForm() { #expect(SettingsMenuSection.allCases == [ - .modes, .appearance, .chat, .voice, @@ -532,12 +508,8 @@ struct SettingsStoreTests { .companion, .help, ]) - #expect(Set(SettingsMenuSection.allCases.map(\.title)).count == 8) - #expect(Set(SettingsMenuSection.allCases.map(\.accessibilityIdentifier)).count == 8) - } - - @Test func currentEdgeGestureChoicesExcludeTheLegacyInboxDestination() { - #expect(!WorkspaceSwipeAction.allCases.contains(.inbox)) + #expect(Set(SettingsMenuSection.allCases.map(\.title)).count == 7) + #expect(Set(SettingsMenuSection.allCases.map(\.accessibilityIdentifier)).count == 7) } @Test func persistedLegacyInboxEdgeGesturesMigrateToVisibleHomeRouting() { diff --git a/BighelpTests/ShellFeatureStoreTests.swift b/BighelpTests/ShellFeatureStoreTests.swift index cb7364ea..347a4411 100644 --- a/BighelpTests/ShellFeatureStoreTests.swift +++ b/BighelpTests/ShellFeatureStoreTests.swift @@ -577,42 +577,42 @@ struct ShellFeatureStoreTests { )) let originPath: [AppRoute] = [] #expect(SessionRestorePresentationPolicy.canComplete( - originTab: .sessions, + originTab: .conversations, originPath: originPath, - currentTab: .sessions, + currentTab: .conversations, currentPath: originPath )) #expect(!SessionRestorePresentationPolicy.canComplete( - originTab: .sessions, + originTab: .conversations, originPath: originPath, - currentTab: .home, + currentTab: .today, currentPath: originPath )) #expect(!SessionRestorePresentationPolicy.canComplete( - originTab: .sessions, + originTab: .conversations, originPath: originPath, - currentTab: .sessions, + currentTab: .conversations, currentPath: [.scheduledTasks] )) #expect(SessionRestorePresentationPolicy.ownsRestore( route: route, - originTab: .sessions, + originTab: .conversations, originPath: originPath, - currentTab: .sessions, + currentTab: .conversations, currentPath: [route] )) #expect(!SessionRestorePresentationPolicy.ownsRestore( route: route, - originTab: .sessions, + originTab: .conversations, originPath: originPath, - currentTab: .home, + currentTab: .today, currentPath: [] )) #expect(!SessionRestorePresentationPolicy.ownsRestore( route: route, - originTab: .sessions, + originTab: .conversations, originPath: originPath, - currentTab: .sessions, + currentTab: .conversations, currentPath: [.scheduledTasks] )) } diff --git a/BighelpTests/SimpleBotsTests.swift b/BighelpTests/SimpleBotsTests.swift index f878e810..fb63bf7b 100644 --- a/BighelpTests/SimpleBotsTests.swift +++ b/BighelpTests/SimpleBotsTests.swift @@ -5,34 +5,14 @@ import Testing @MainActor struct SimpleBotsTests { - @Test func simpleBotModeIsOffByDefaultAndChangesTheLook() { - let suiteName = #function - let defaults = UserDefaults(suiteName: suiteName)! - defaults.removePersistentDomain(forName: suiteName) - defer { defaults.removePersistentDomain(forName: suiteName) } - - let fresh = SettingsStore(defaults: defaults) - #expect(!fresh.simpleBotsEnabled) - #expect(!fresh.appearanceContext.simpleBots) - - fresh.simpleBotsEnabled = true - let relaunched = SettingsStore(defaults: defaults) - #expect(relaunched.simpleBotsEnabled) - let context = relaunched.appearanceContext - #expect(context.simpleBots) - #expect(context.lightBackground == .paper) - #expect(context.darkBackground == .black) - } - - /// Bots mode's dark page is the one picked in Appearance, like the rest of the app (#718). - @Test func botsModeFollowsTheDarkBackgroundChoice() { + /// The dark page is the one picked in Appearance (#718). + @Test func thePageFollowsTheDarkBackgroundChoice() { let suiteName = #function let defaults = UserDefaults(suiteName: suiteName)! defaults.removePersistentDomain(forName: suiteName) defer { defaults.removePersistentDomain(forName: suiteName) } let settings = SettingsStore(defaults: defaults) - settings.simpleBotsEnabled = true settings.darkBackground = .graphite #expect(settings.appearanceContext.darkBackground == .graphite) let graphite = BighelpTheme.resolve(appearance: settings.appearanceContext, colorScheme: .dark, @@ -44,15 +24,14 @@ struct SimpleBotsTests { #expect(black.canvasHex == BighelpTheme.blackDark.canvasHex) } - /// Bots mode's light page is the theme picked in Appearance too (#719); it used to be Paper always. - @Test func botsModeFollowsTheLightThemeChoice() { + /// The light page is the theme picked in Appearance too (#719). + @Test func thePageFollowsTheLightThemeChoice() { let suiteName = #function let defaults = UserDefaults(suiteName: suiteName)! defaults.removePersistentDomain(forName: suiteName) defer { defaults.removePersistentDomain(forName: suiteName) } let settings = SettingsStore(defaults: defaults) - settings.simpleBotsEnabled = true settings.pickTheme(.moss, dark: false) settings.pickTheme(.violet, dark: true) let context = settings.appearanceContext @@ -68,23 +47,8 @@ struct SimpleBotsTests { contrast: .standard).canvasHex == BighelpTheme.light.canvasHex) } - @Test func edgeSwipesGoToYourBotsAndThisBotsProfile() { - let suiteName = #function - let defaults = UserDefaults(suiteName: suiteName)! - defaults.removePersistentDomain(forName: suiteName) - defer { defaults.removePersistentDomain(forName: suiteName) } - let settings = SettingsStore(defaults: defaults) - settings.leftEdgeSwipeAction = .newChat - settings.rightEdgeSwipeAction = .none - #expect(settings.effectiveLeftEdgeSwipeAction == .newChat, "Your choices everywhere else") - settings.simpleBotsEnabled = true - #expect(settings.effectiveLeftEdgeSwipeAction == .agents) - #expect(settings.effectiveRightEdgeSwipeAction == .profile) - } - @Test func simpleLookHasBlackBubblesByDayAndInkAfterDark() { - var context = BighelpAppearanceContext(appearance: .light, lightBackground: .paper, darkBackground: .black) - context.simpleBots = true + let context = BighelpAppearanceContext(appearance: .light, lightBackground: .paper, darkBackground: .black) let day = BighelpTheme.resolve(appearance: context, colorScheme: .light, contrast: .standard) #expect(day.chosenBubbleHex == "111111") let night = BighelpTheme.resolve(appearance: BighelpAppearanceContext(appearance: .dark), colorScheme: .dark, @@ -96,33 +60,29 @@ struct SimpleBotsTests { let savedInk = BighelpTheme.resolve(appearance: BighelpAppearanceContext(appearance: .light, bubbleColor: .graphite), colorScheme: .light, contrast: .standard) #expect(savedInk.chosenBubbleHex == "111111", "Ink saved by an older build is the same Ink") - var dark = context - dark = BighelpAppearanceContext(appearance: .dark, lightBackground: .paper, darkBackground: .black) - dark.simpleBots = true + let dark = BighelpAppearanceContext(appearance: .dark, lightBackground: .paper, darkBackground: .black) #expect(BighelpTheme.resolve(appearance: dark, colorScheme: .dark, contrast: .standard).chosenBubbleHex == "3A3A3F") } - /// Buttons, links and tinted Settings text use the page's ink in Bots mode. The accent used + /// Buttons, links and tinted Settings text use the page's ink. The accent used /// to follow the bubble color, which is a dark gray after dark, so tinted text in Settings read as /// grayed out ("Hermes restart", Check Host Status). @Test func simpleLookTintsWithThePagesInk() { for (scheme, ink) in [(ColorScheme.light, "111111"), (.dark, "FFFFFF")] { - var context = BighelpAppearanceContext(appearance: scheme == .dark ? .dark : .light, + let context = BighelpAppearanceContext(appearance: scheme == .dark ? .dark : .light, lightBackground: .paper, darkBackground: .black) - context.simpleBots = true let theme = BighelpTheme.resolve(appearance: context, colorScheme: scheme, contrast: .standard) #expect(theme.actionHex.uppercased() == ink, "\(scheme): \(theme.actionHex)") #expect(theme.chosenBubbleHex == (scheme == .dark ? "3A3A3F" : "111111"), "Bubbles keep their color") } } - /// A bubble color picked in Appearance wins in Bots mode too; black and ink are only its default. + /// A bubble color picked in Appearance wins; black and ink are only the default. @Test func simpleLookKeepsThePickedBubbleColor() { for scheme in [ColorScheme.light, .dark] { var context = BighelpAppearanceContext(appearance: scheme == .dark ? .dark : .light, lightBackground: .paper, darkBackground: .black, bubbleColor: .teal) - context.simpleBots = true let theme = BighelpTheme.resolve(appearance: context, colorScheme: scheme, contrast: .standard) #expect(theme.chosenBubbleHex == BighelpBubbleColor.teal.hex, "\(scheme)") context.bubbleColor = nil diff --git a/BighelpTests/SpaceDraftCardStateTests.swift b/BighelpTests/SpaceDraftCardStateTests.swift new file mode 100644 index 00000000..1168fc70 --- /dev/null +++ b/BighelpTests/SpaceDraftCardStateTests.swift @@ -0,0 +1,268 @@ +import Foundation +import Testing +@testable import Bighelp + +/// The chat's draft card: read the draft, Add to Today, then On Today, and every way that can go +/// otherwise. Answers count only for the request the card waits on. +@MainActor +struct SpaceDraftCardStateTests { + static let draft = SpaceDraftCard(spaceID: SpacesWireTests.spaceID, title: "Commute", + description: "Drive time to work.", updates: "Every 15 minutes", + usesAI: false, revision: 1) + + static func routine(state: String, usesAI: Bool = false, pendingChange: Bool = false) -> BighelpJSONValue { + .object(["kind": .string(usesAI ? "ai" : "script"), "usesAI": .boolean(usesAI), + "updates": .string(usesAI ? "Every day at 7:00" : "Every 15 minutes"), "state": .string(state), + "pendingChange": .boolean(pendingChange)]) + } + + static func draftSpace(revision: Int = 1, size: String = "small", usesAI: Bool = false, + description: String = "Drive time to work.") throws -> Space { + try #require(Space(json: SpacesWireTests.spaceJSON([ + "state": .string("draft"), "status": .string("draft"), "revision": .integer(revision), + "size": .string(size), "description": .string(description), + "routine": routine(state: "draft", usesAI: usesAI), + ]))) + } + + static func liveSpace(revision: Int = 1, pendingChange: Bool = false) throws -> Space { + try #require(Space(json: SpacesWireTests.spaceJSON([ + "revision": .integer(revision), "routine": routine(state: "running", pendingChange: pendingChange), + ]))) + } + + /// A flow that has read the draft. + static func ready() throws -> SpaceDraftFlow { + var flow = SpaceDraftFlow(draft: draft) + let read = flow.beginLoad() + flow.loaded(.success(try draftSpace()), ticket: read) + return flow + } + + @Test func aDraftIsAddedAndThenOnToday() throws { + var flow = SpaceDraftFlow(draft: Self.draft) + #expect(flow.phase == .loading) + #expect(!flow.canAdd) + let read = flow.beginLoad() + flow.loaded(.success(try Self.draftSpace(size: "small")), ticket: read) + #expect(flow.phase == .ready) + #expect(flow.size == .small) + #expect(flow.canAdd) + + let addTicket = flow.beginAdd() + let add = try #require(addTicket) + #expect(add.revision == 1) + #expect(flow.phase == .adding) + #expect(flow.beginAdd() == nil) + #expect(!flow.added(.success(try Self.liveSpace()), ticket: add)) + #expect(flow.phase == .onToday) + #expect(!flow.showsSizes) + } + + @Test func aSpaceAlreadyLiveIsOnToday() throws { + var flow = SpaceDraftFlow(draft: Self.draft) + let read = flow.beginLoad() + flow.loaded(.success(try Self.liveSpace()), ticket: read) + #expect(flow.phase == .onToday) + #expect(!flow.wantsRead) + } + + @Test func aLiveSpaceWithAChangedRoutineWaitsForAdd() throws { + var flow = SpaceDraftFlow(draft: Self.draft) + let read = flow.beginLoad() + flow.loaded(.success(try Self.liveSpace(pendingChange: true)), ticket: read) + #expect(flow.phase == .ready) + #expect(flow.canAdd) + } + + @Test func aDeletedDraftIsRemoved() { + var flow = SpaceDraftFlow(draft: Self.draft) + let read = flow.beginLoad() + flow.loaded(.failure(.notFound), ticket: read) + #expect(flow.phase == .removed) + #expect(!flow.canAdd) + } + + @Test func aDraftThatCanNotBeReadStillAdds() { + var flow = SpaceDraftFlow(draft: Self.draft) + let read = flow.beginLoad() + flow.loaded(.failure(.unreachable), ticket: read) + #expect(flow.phase == .ready) + #expect(flow.preview == nil) + #expect(flow.canAdd) + // Shown again later, it asks again. + #expect(flow.wantsRead) + } + + @Test func aNewerDraftOnTheComputerIsWhatAddSends() throws { + var flow = SpaceDraftFlow(draft: Self.draft) + let read = flow.beginLoad() + flow.loaded(.success(try Self.draftSpace(revision: 2, usesAI: true, description: "Drive and train times.")), + ticket: read) + #expect(flow.notice == .changed) + #expect(flow.revision == 2) + #expect(flow.details.description == "Drive and train times.") + #expect(flow.details.usesAI) + #expect(flow.details.updates == "Every day at 7:00") + #expect(flow.beginAdd()?.revision == 2) + } + + @Test func theBotChangingTheDraftReadsItAgain() throws { + var flow = try Self.ready() + let addTicket = flow.beginAdd() + let add = try #require(addTicket) + let addReread = flow.added(.failure(.draftChanged(revision: 3)), ticket: add) + #expect(addReread) + #expect(flow.phase == .loading) + #expect(flow.notice == .changed) + #expect(flow.revision == 3) + #expect(!flow.canAdd) + + let read = flow.beginLoad() + flow.loaded(.success(try Self.draftSpace(revision: 3)), ticket: read) + #expect(flow.phase == .ready) + #expect(flow.notice == .changed) + #expect(flow.beginAdd()?.revision == 3) + } + + @Test func anOlderPluginSaysToUpdateIt() throws { + var loading = SpaceDraftFlow(draft: Self.draft) + let read = loading.beginLoad() + loading.loaded(.failure(.needsPluginUpdate), ticket: read) + #expect(loading.phase == .needsPluginUpdate) + + var adding = try Self.ready() + let addTicket = adding.beginAdd() + let add = try #require(addTicket) + adding.added(.failure(.needsPluginUpdate), ticket: add) + #expect(adding.phase == .needsPluginUpdate) + #expect(!adding.canAdd) + } + + @Test func noAnswerKeepsAddAndSaysSo() throws { + var flow = try Self.ready() + let addTicket = flow.beginAdd() + let add = try #require(addTicket) + flow.added(.failure(.unreachable), ticket: add) + #expect(flow.phase == .ready) + #expect(flow.notice == .unreachable) + #expect(flow.canAdd) + // Trying again clears the line until the next answer. + _ = flow.beginAdd() + #expect(flow.notice == nil) + } + + @Test func aMissingScriptSaysToAskTheBot() throws { + var flow = try Self.ready() + let addTicket = flow.beginAdd() + let add = try #require(addTicket) + flow.added(.failure(.scriptMissing), ticket: add) + #expect(flow.phase == .ready) + #expect(flow.notice == .scriptMissing) + } + + @Test func alreadyLiveAtAddIsOnToday() throws { + var flow = try Self.ready() + let addTicket = flow.beginAdd() + let add = try #require(addTicket) + flow.added(.failure(.notDraft), ticket: add) + #expect(flow.phase == .onToday) + } + + @Test func aLateAnswerForAnOlderRevisionIsIgnored() throws { + var flow = try Self.ready() + let firstTicket = flow.beginAdd() + let first = try #require(firstTicket) + // The same Add answered twice: first "the bot changed it", then, late, a success for revision 1. + let firstReread = flow.added(.failure(.draftChanged(revision: 2)), ticket: first) + #expect(firstReread) + let read = flow.beginLoad() + #expect(!flow.added(.success(try Self.liveSpace(revision: 1)), ticket: first)) + #expect(flow.phase == .loading) + #expect(flow.revision == 2) + + flow.loaded(.success(try Self.draftSpace(revision: 2)), ticket: read) + #expect(flow.phase == .ready) + } + + @Test func aReadTheCardGaveUpOnChangesNothing() throws { + var flow = SpaceDraftFlow(draft: Self.draft) + let first = flow.beginLoad() + let second = flow.beginLoad() + flow.loaded(.failure(.notFound), ticket: first) + #expect(flow.phase == .loading) + flow.loaded(.success(try Self.draftSpace()), ticket: second) + #expect(flow.phase == .ready) + } + + @Test func theCardNeverSaysNoAIByGuess() throws { + // The card's props say no AI, but the computer's routine for the same revision says AI. + var flow = SpaceDraftFlow(draft: Self.draft) + #expect(!flow.details.usesAI) + let read = flow.beginLoad() + flow.loaded(.success(try Self.draftSpace(usesAI: true)), ticket: read) + #expect(flow.details.usesAI) + + let props = SpaceDraftCard(spaceID: SpacesWireTests.spaceID, title: "Commute", description: "Drive time.", + updates: "Every hour", usesAI: true, revision: 1) + var aiFlow = SpaceDraftFlow(draft: props) + let aiRead = aiFlow.beginLoad() + aiFlow.loaded(.success(try Self.draftSpace(usesAI: false)), ticket: aiRead) + #expect(aiFlow.details.usesAI) + } + + @Test func aSizeThePersonPickedStays() throws { + var flow = SpaceDraftFlow(draft: Self.draft) + flow.choose(.tall) + let read = flow.beginLoad() + flow.loaded(.success(try Self.draftSpace(size: "small")), ticket: read) + #expect(flow.size == .tall) + let addTicket = flow.beginAdd() + let add = try #require(addTicket) + #expect(add.revision == 1) + flow.choose(.small) + #expect(flow.size == .tall) + } + + // MARK: The card's model + + /// What the fake computer was asked. + @MainActor + final class Calls { + var reads = 0 + var sent: [(revision: Int, size: SpaceSize, hasPreview: Bool)] = [] + } + + @Test func addSendsTheRevisionAndSizeShownAndReadsAgainWhenTheBotChangedIt() async throws { + let calls = Calls() + let drafts = [try Self.draftSpace(revision: 1), try Self.draftSpace(revision: 2)] + let live = try Self.liveSpace(revision: 2) + let model = SpaceDraftCardModel( + draft: Self.draft, + read: { (_: String, _: String) async throws(SpacesError) -> Space in + calls.reads += 1 + return drafts[min(calls.reads, 2) - 1] + }, + add: { (_: String, _: String, revision: Int, size: SpaceSize, preview: Space?) async throws(SpacesError) -> Space in + calls.sent.append((revision, size, preview != nil)) + // The bot drafted revision 2 while the card still showed 1. + if revision == 1 { throw .draftChanged(revision: nil) } + return live + }) + await model.load(agentID: "research") + model.choose(.wide) + model.add(agentID: "research") + while model.flow.phase == .adding { await Task.yield() } + #expect(model.flow.notice == .changed) + #expect(model.reloads == 1) + + await model.load(agentID: "research") + #expect(model.flow.revision == 2) + model.add(agentID: "research") + while model.flow.phase == .adding { await Task.yield() } + #expect(model.flow.phase == .onToday) + #expect(calls.sent.map(\.revision) == [1, 2]) + #expect(calls.sent.map(\.size) == [.wide, .wide]) + #expect(calls.sent.allSatisfy { $0.hasPreview }) + } +} diff --git a/BighelpTests/SpacePanelStateTests.swift b/BighelpTests/SpacePanelStateTests.swift new file mode 100644 index 00000000..1c29fe11 --- /dev/null +++ b/BighelpTests/SpacePanelStateTests.swift @@ -0,0 +1,138 @@ +import Foundation +import Testing +@testable import Bighelp + +/// A space panel's one footer line, picked from what the computer said (never the time it was +/// drawn), and how its time reads. +@MainActor +struct SpacePanelStateTests { + static func space(_ changes: [String: BighelpJSONValue?] = [:]) throws -> Space { + try #require(Space(json: SpacesWireTests.spaceJSON(changes))) + } + + static func item(_ space: Space, isConnected: Bool = true) -> TodaySpace { + TodaySpace(id: TodaySpace.id(scope: "scope", key: space.key), space: space, scope: "scope", hostKey: "demo", + computerName: "Demo computer", botName: "Research", isConnected: isConnected) + } + + static func routine(state: String, usesAI: Bool = false) -> BighelpJSONValue { + .object(["kind": .string(usesAI ? "ai" : "script"), "usesAI": .boolean(usesAI), + "updates": .string("Every 15 minutes"), "state": .string(state)]) + } + + @Test func aFreshSpaceSaysWhenItUpdated() throws { + let space = try Self.space() + let footer = SpacePanelFooter.state(for: Self.item(space), size: .small) + #expect(footer == .updated(space.updatedAt, usesAI: false)) + #expect(space.updatedAt != nil) + } + + @Test func anAIRoutineCarriesTheBadge() throws { + let space = try Self.space(["routine": Self.routine(state: "running", usesAI: true)]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small) == .updated(space.updatedAt, usesAI: true)) + } + + @Test(arguments: ["missing", "failed", "late", "something-new"]) + func aRoutineThatIsNotRunningStopsThePanel(state: String) throws { + let space = try Self.space(["routine": Self.routine(state: state), "status": .string("stale")]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small) == .stopped(.idle)) + } + + /// Paused in Scheduled tasks: only the person resumes it there, so no Try again and no error. + @Test func aPausedRoutineSaysWhereToResumeIt() throws { + let space = try Self.space(["routine": Self.routine(state: "paused"), "status": .string("stopped")]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small) == .paused) + } + + /// The bot changed its script after the space was added: no Try again, which can't fix it. + @Test func aChangedScriptStopsThePanelWithoutTryAgain() throws { + let routine: BighelpJSONValue = .object(["kind": .string("script"), "usesAI": .boolean(false), + "updates": .string("Every 15 minutes"), "state": .string("failed"), + "problem": .string("script_changed")]) + let space = try Self.space(["routine": routine, "status": .string("stopped")]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small) == .scriptChanged) + // Another problem is an ordinary stop, with Try again. + let failed: BighelpJSONValue = .object(["kind": .string("script"), "state": .string("failed"), + "problem": .string("script_failed")]) + let other = try Self.space(["routine": failed, "status": .string("stopped")]) + #expect(SpacePanelFooter.state(for: Self.item(other), size: .small) == .stopped(.idle)) + } + + @Test func theComputerSayingStoppedStopsARunningRoutine() throws { + let space = try Self.space(["status": .string("stopped")]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small, retry: .running) == .stopped(.running)) + } + + @Test func aComputerThatIsNotConnectedSaysSoAndKeepsItsCard() throws { + let stopped = try Self.space(["routine": Self.routine(state: "late")]) + #expect(SpacePanelFooter.state(for: Self.item(stopped, isConnected: false), size: .small) == .notConnected) + let noCard = try Self.space(["card": nil, "sizes": nil]) + #expect(SpacePanelFooter.state(for: Self.item(noCard, isConnected: false), size: .small) == .notConnected) + } + + @Test func aCardThatCanNotBeDrawnSaysSo() throws { + let space = try Self.space(["card": .object(["schema": .string("other")]), "sizes": nil]) + #expect(space.cardUnreadable) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .wide) == .unreadable) + } + + @Test func aCardNotReadYetIsAStillPlaceholder() throws { + let space = try Self.space(["card": nil, "sizes": nil, "cardOmitted": .boolean(true)]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small) == .loading) + } + + @Test func eachSizeDrawsItsOwnCardOrTheSpaceCard() throws { + // Only a Tall card: Tall draws it, the other sizes wait for theirs. + let space = try Self.space(["card": nil]) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .tall) == .updated(space.updatedAt, usesAI: false)) + #expect(SpacePanelFooter.state(for: Self.item(space), size: .small) == .loading) + } + + @Test func aDraftPreviewHasNoFooter() throws { + let space = try Self.space(["state": .string("draft"), "status": .string("draft"), + "routine": Self.routine(state: "draft")]) + #expect(SpacePanelFooter.state(space: space, size: .wide, isConnected: true) == .none) + } + + @Test func tryAgainNamesOnlyTheAnswersThePersonCanActOn() { + #expect(SpacePanelRetry.after(.tooSoon(retryAfter: 40)) == .tooSoon) + #expect(SpacePanelRetry.after(.routineFailed(nil)) == .failed) + #expect(SpacePanelRetry.after(.unreachable) == .idle) + #expect(SpacePanelRetry.after(.notFound) == .idle) + } + + @Test func tryAgainKeepsTheComputersAnswer() async { + let retry = SpacePanelRetryModel() + retry.run { () async throws(SpacesError) -> SpaceRefreshRun in throw .tooSoon(retryAfter: nil) } + #expect(retry.state == .running) + while retry.state == .running { await Task.yield() } + #expect(retry.state == .tooSoon) + } + + // MARK: Time + + static var calendar: Calendar { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC") ?? .gmt + return calendar + } + + static let locale = Locale(identifier: "en_US") + + /// iOS writes a narrow space before AM and PM. + static func plain(_ text: String) -> String { text.replacingOccurrences(of: "\u{202F}", with: " ") } + + @Test func todayIsATime() throws { + let now = try #require(SpacesWire.date(.string("2026-11-12T18:00:00Z"))) + let updated = try #require(SpacesWire.date(.string("2026-11-12T14:14:00Z"))) + #expect(Self.plain(SpacePanelTime.text(updated, now: now, calendar: Self.calendar, locale: Self.locale)) == "2:14 PM") + } + + @Test func anotherDayIsADate() throws { + let now = try #require(SpacesWire.date(.string("2026-11-12T08:00:00Z"))) + let yesterday = try #require(SpacesWire.date(.string("2026-11-10T23:30:00Z"))) + #expect(SpacePanelTime.text(yesterday, now: now, calendar: Self.calendar, locale: Self.locale) == "Nov 10") + let lastYear = try #require(SpacesWire.date(.string("2025-12-31T09:00:00Z"))) + #expect(SpacePanelTime.text(lastYear, now: now, calendar: Self.calendar, locale: Self.locale) == "Dec 31, 2025") + } +} diff --git a/BighelpTests/SpacesStoreTests.swift b/BighelpTests/SpacesStoreTests.swift new file mode 100644 index 00000000..9c1ee71f --- /dev/null +++ b/BighelpTests/SpacesStoreTests.swift @@ -0,0 +1,568 @@ +import Foundation +import Testing +@testable import Bighelp + +/// Shared by the Spaces tests: a computer, a folder for the phone's copy, and a client that can +/// hold or refuse answers. +@MainActor +enum SpacesTestKit { + static let now = Date(timeIntervalSince1970: 1_794_500_000) + static let bots = ["travel", "home", "finance"].map { SpacesBot(id: $0, name: $0.capitalized) } + static let commute = Space.key(agentID: "travel", spaceID: DemoSpacesClient.commuteID) + static let garden = Space.key(agentID: "home", spaceID: DemoSpacesClient.gardenID) + static let workouts = Space.key(agentID: "home", spaceID: DemoSpacesClient.workoutsID) + + static func folder() -> URL { + FileManager.default.temporaryDirectory.appendingPathComponent("spaces-tests-\(UUID().uuidString)", isDirectory: true) + } + + static func demo() -> DemoSpacesClient { DemoSpacesClient(clock: { now }) } + + static func computer(_ scope: String = "scope-home", name: String = "Home", client: (any SpacesClient)?, + bots: [SpacesBot] = bots, isCurrent: Bool = true) -> SpacesComputer { + SpacesComputer(hostKey: "host-" + scope, scope: scope, name: name, api: client.map { SpacesAPI(client: $0) }, + bots: bots, isCurrent: isCurrent) + } + + static func store(_ folder: URL, scope: String = "scope-home") -> SpacesStore { + SpacesStore(scope: scope, hostKey: "host-" + scope, cacheFolder: folder, clock: { now }) + } +} + +/// The connection a computer has now; tests swap it for a reconnect. +@MainActor +final class SpacesTestConnection { + var client: any SpacesClient + + init(_ client: any SpacesClient) { + self.client = client + } +} + +/// Answers through another client, and can hold an answer after it's made (a read that comes back +/// late) or refuse instead. +@MainActor +final class HeldSpacesClient: SpacesClient { + let inner: any SpacesClient + var holds: Set = [] + var failure: (any Error)? + private var waiting: [CheckedContinuation] = [] + private(set) var payloads: [(operation: SpacesOperation, payload: [String: BighelpJSONValue])] = [] + + init(_ inner: any SpacesClient) { + self.inner = inner + } + + var isHolding: Bool { !waiting.isEmpty } + + func perform(_ operation: SpacesOperation, + payload: [String: BighelpJSONValue]) async throws -> [String: BighelpJSONValue] { + payloads.append((operation, payload)) + if let failure { throw failure } + let answer = try await inner.perform(operation, payload: payload) + if holds.contains(operation) { await withCheckedContinuation { waiting.append($0) } } + return answer + } + + func release() { + let held = waiting + waiting = [] + for continuation in held { continuation.resume() } + } + + func untilHolding() async { + while !isHolding { await Task.yield() } + } +} + +/// The plugin when a bot is gone from the computer: its `list` answer has no spaces for it and +/// says `profile_not_found` for it. +@MainActor +final class GoneBotSpacesClient: SpacesClient { + let inner: any SpacesClient + let gone: Set + + init(_ inner: any SpacesClient, gone: Set) { + self.inner = inner + self.gone = gone + } + + func perform(_ operation: SpacesOperation, + payload: [String: BighelpJSONValue]) async throws -> [String: BighelpJSONValue] { + var answer = try await inner.perform(operation, payload: payload) + guard operation == .list else { return answer } + answer["spaces"] = .array((answer["spaces"]?.array ?? []).filter { !gone.contains($0.object?["agentId"]?.string ?? "") }) + var agents = answer["agents"]?.object ?? [:] + for id in gone { agents[id] = .string("profile_not_found") } + answer["agents"] = .object(agents) + return answer + } +} + +/// A connection as `DirectHermesSpacesClient` sees it: the plugin's context, and answers or errors. +@MainActor +private final class SpacesPerformer: WorkspaceOperationPerforming { + var owner: WorkspaceOwner? + var capabilities: WorkspaceCapabilities { .init(owner: owner, values: [:]) } + var features = ["native-context-v1"] + var failures: [any Error] = [] + var contextFailure: (any Error)? + private(set) var calls: [(operation: WorkspaceOperation, payload: [String: BighelpJSONValue])] = [] + + init() throws { + owner = WorkspaceOwner(authority: try .fixture(id: UUID().uuidString), + authenticationGeneration: UUID(), connectionGeneration: UUID()) + } + + func perform(_ operation: WorkspaceOperation, payload: [String: BighelpJSONValue], + owner: WorkspaceOwner) async throws -> [String: BighelpJSONValue] { + guard owner == self.owner else { throw WorkspaceClientError.ownerChanged } + calls.append((operation, payload)) + if operation == .nativeContext { + if let contextFailure { throw contextFailure } + return ["features": .array(features.map(BighelpJSONValue.string))] + } + if !failures.isEmpty { throw failures.removeFirst() } + return ["spaces": .array([]), "agents": .object([:])] + } +} + +@MainActor +struct SpacesStoreTests { + typealias Kit = SpacesTestKit + + // MARK: Keeping the data + + @Test func theCacheScopeSurvivesANewOwner() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let connection = SpacesTestConnection(Kit.demo()) + let model = TodaySpacesModel(computers: { [Kit.computer(client: connection.client)] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let store = try #require(model.stores["scope-home"]) + #expect(store.spaces.count == 3) + // A reconnect: a new connection to the same computer, which doesn't answer yet. + let refusing = HeldSpacesClient(Kit.demo()) + refusing.failure = WorkspaceClientError.transportUnavailable + connection.client = refusing + await model.refresh() + #expect(model.stores["scope-home"] === store) + #expect(store.spaces.count == 3) + #expect(store.phase == .unreachable) + } + + @Test func aRelaunchDrawsTheLastPanelsAtOnce() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let store = Kit.store(folder) + await store.load(Kit.computer(client: Kit.demo())) + await store.savedToDisk() + let again = Kit.store(folder) + #expect(again.spaces == store.spaces) + #expect(again.spaces.allSatisfy { $0.card != nil }) + #expect(again.lastLoaded == Kit.now) + #expect(again.phase == .loading) + // Another computer's copy isn't this one's. + #expect(Kit.store(folder, scope: "scope-other").spaces.isEmpty) + } + + @Test func aNilOwnerKeepsTheData() async { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let store = Kit.store(folder) + await store.load(Kit.computer(client: Kit.demo())) + let read = store.spaces + await store.load(Kit.computer(client: nil)) + #expect(store.spaces == read) + #expect(store.phase == .unreachable) + } + + @Test func nothingIsReadBeforeTheBotsAreKnown() async { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client, bots: [])) + #expect(client.payloads.isEmpty) + #expect(store.phase == .loading) + } + + // MARK: Changes the computer hasn't confirmed + + @Test func anUnconfirmedChangeIsReplayedWhenTheComputerAnswersAgain() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let client = HeldSpacesClient(demo) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + // Not connected: it shows at once and waits. + try await store.change(Kit.garden, SpaceChanges(size: .small), api: nil) + #expect(store.spaces.first { $0.key == Kit.garden }?.size == .small) + let waiting = try #require(store.pending[Kit.garden]) + // It survives a relaunch too. + await store.savedToDisk() + let relaunched = Kit.store(folder) + #expect(relaunched.pending[Kit.garden] == waiting) + #expect(relaunched.spaces.first { $0.key == Kit.garden }?.size == .small) + + await relaunched.load(Kit.computer(client: client)) + let sent = try #require(client.payloads.last(where: { $0.operation == .update })) + #expect(sent.payload["operationId"] == .string(waiting.operationID)) + #expect(sent.payload["changes"] == .object(["size": .string("small")])) + #expect(relaunched.pending.isEmpty) + let onComputer = try await SpacesAPI(client: demo).space(agentID: "home", spaceID: DemoSpacesClient.gardenID) + #expect(onComputer.size == .small) + } + + @Test func anUnconfirmedChangeGoesOnceTheComputersValueCatchesUp() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let client = HeldSpacesClient(demo) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + try await store.change(Kit.garden, SpaceChanges(hidden: true), api: nil) + // Another device hid it meanwhile. + _ = try await SpacesAPI(client: demo).update(agentID: "home", spaceID: DemoSpacesClient.gardenID, + changes: SpaceChanges(hidden: true)) + await store.load(Kit.computer(client: client)) + #expect(store.pending.isEmpty) + #expect(!client.payloads.contains { $0.operation == .update }) + #expect(store.spaces.first { $0.key == Kit.garden }?.hidden == true) + } + + @Test func aRefusalUndoesTheChangeAndNoAnswerKeepsIt() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + let api = SpacesAPI(client: client) + + client.failure = WorkspaceClientError.transportUnavailable + try await store.change(Kit.commute, SpaceChanges(size: .tall), api: api) + #expect(store.spaces.first { $0.key == Kit.commute }?.size == .tall) + #expect(store.pending[Kit.commute] != nil) + + client.failure = WorkspaceClientError.rejected(code: "invalid_request") + do throws(SpacesError) { + try await store.change(Kit.commute, SpaceChanges(size: .wide), api: api) + Issue.record("The refusal didn't reach the caller.") + } catch { + #expect(error == .other(code: "invalid_request")) + } + #expect(store.pending[Kit.commute] == nil) + #expect(store.spaces.first { $0.key == Kit.commute }?.size == .small) + } + + /// An `operationId` goes again only with its own request: a change on top of one the computer + /// hasn't confirmed is a new request, with a new id. + @Test func aChangeOnTopOfAnUnconfirmedOneIsANewRequest() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + let api = SpacesAPI(client: client) + client.failure = WorkspaceClientError.transportUnavailable + try await store.change(Kit.garden, SpaceChanges(size: .tall), api: api) + let first = try #require(store.pending[Kit.garden]) + client.failure = nil + try await store.change(Kit.garden, SpaceChanges(hidden: true), api: api) + let updates = client.payloads.filter { $0.operation == .update } + #expect(updates.count == 2) + #expect(updates.last?.payload["operationId"] != .string(first.operationID)) + #expect(updates.last?.payload["changes"] == .object(["size": .string("tall"), "hidden": .boolean(true)])) + #expect(store.pending.isEmpty) + #expect(store.confirmedSpace(Kit.garden)?.size == .tall) + } + + @Test func aMutationsAnswerIsNotUndoneByAReadThatBeganBefore() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + client.holds = [.list] + let read = Task { await store.load(Kit.computer(client: client)) } + await client.untilHolding() + // The read holds the computer's answer from before this change. + client.holds = [] + try await store.change(Kit.garden, SpaceChanges(size: .tall), api: SpacesAPI(client: client)) + client.release() + await read.value + #expect(store.spaces.first { $0.key == Kit.garden }?.size == .tall) + #expect(store.confirmedSpace(Kit.garden)?.size == .tall) + } + + + // MARK: One request at a time + + /// Hide, then show, before the computer answers the first: the second request waits, so the + /// computer never takes them in the wrong order, and the space ends as the person last chose. + @Test func overlappingChangesToOneSpaceGoOneAtATimeAndEndOnTheLastChoice() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let client = HeldSpacesClient(demo) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + let api = SpacesAPI(client: client) + client.holds = [.update] + + let hide = Task { try? await store.change(Kit.garden, SpaceChanges(hidden: true), api: api) } + await client.untilHolding() + let show = Task { try? await store.change(Kit.garden, SpaceChanges(hidden: false), api: api) } + for _ in 0..<20 { await Task.yield() } + // The first answer is still out: only one request has gone. + #expect(client.payloads.filter { $0.operation == .update }.count == 1) + #expect(store.spaces.first { $0.key == Kit.garden }?.hidden == false) + + client.release() + await client.untilHolding() + client.release() + await hide.value + await show.value + + let updates = client.payloads.filter { $0.operation == .update } + #expect(updates.count == 2) + #expect(updates[0].payload["changes"] == .object(["hidden": .boolean(true)])) + #expect(updates[1].payload["changes"] == .object(["hidden": .boolean(false)])) + #expect(updates[0].payload["operationId"] != updates[1].payload["operationId"]) + #expect(store.pending.isEmpty) + #expect(store.spaces.first { $0.key == Kit.garden }?.hidden == false) + let onComputer = try await SpacesAPI(client: demo).space(agentID: "home", spaceID: DemoSpacesClient.gardenID) + #expect(!onComputer.hidden) + } + + // MARK: A partial list of bots + + /// The phone's list of bots can lag or be partial while a computer reconnects or the selection + /// moves. A read asks about the bots the phone holds spaces for too, so a short list takes + /// nothing off Today and a waiting change still gets to the computer. + @Test func aPartialListOfBotsKeepsTheOtherBotsSpacesAndTheirChanges() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + #expect(store.spaces.count == 3) + try await store.change(Kit.garden, SpaceChanges(size: .tall), api: nil) + + await store.load(Kit.computer(client: client, bots: [SpacesBot(id: "travel", name: "Travel")])) + #expect(store.spaces.map(\.key).sorted() == [Kit.commute, Kit.garden, Kit.workouts].sorted()) + #expect(store.spaces.first { $0.key == Kit.garden }?.size == .tall) + + // A list with only a bot this computer has no spaces for is a partial list too. + await store.load(Kit.computer(client: client, bots: [SpacesBot(id: "finance", name: "Finance")])) + #expect(store.spaces.count == 3) + await store.savedToDisk() + #expect(Kit.store(folder).spaces.count == 3) + } + + @Test func onlyTheComputerSayingABotIsGoneRemovesItsSpaces() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let store = Kit.store(folder) + await store.load(Kit.computer(client: demo)) + try await store.change(Kit.garden, SpaceChanges(size: .tall), api: nil) + try await store.change(Kit.commute, SpaceChanges(size: .tall), api: nil) + + await store.load(Kit.computer(client: GoneBotSpacesClient(demo, gone: ["home"]))) + #expect(store.spaces.map(\.key) == [Kit.commute]) + #expect(store.pending.keys.contains(Kit.garden) == false) + } + + // MARK: Deleting + + /// `schedules_unavailable` from delete: the space is off Today on the computer, and Hermes still + /// has its task. It never shows again here, and the same request goes at each read until done. + @Test func aDeleteTheComputerHasntFinishedStaysOffAndGoesAgainAsTheSameRequest() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let client = HeldSpacesClient(demo) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + demo.stuckTasks = [DemoSpacesClient.commuteID] + try await store.delete(Kit.commute, api: SpacesAPI(client: client)) + #expect(!store.spaces.contains { $0.key == Kit.commute }) + let waiting = try #require(store.deleting[Kit.commute]) + + await store.load(Kit.computer(client: client)) + #expect(!store.spaces.contains { $0.key == Kit.commute }) + #expect(store.deleting[Kit.commute] == waiting) + + demo.stuckTasks = [] + await store.load(Kit.computer(client: client)) + #expect(store.deleting.isEmpty) + let deletes = client.payloads.filter { $0.operation == .delete } + #expect(deletes.count == 3) + #expect(deletes.allSatisfy { $0.payload["operationId"] == .string(waiting.operationID) }) + await #expect(throws: SpacesError.notFound) { + try await SpacesAPI(client: demo).space(agentID: "travel", spaceID: DemoSpacesClient.commuteID) + } + } + + @Test func aDeleteWithoutAConnectionWaitsAndSurvivesARelaunch() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + try await store.delete(Kit.garden, api: nil) + #expect(!store.spaces.contains { $0.key == Kit.garden }) + await store.savedToDisk() + + let relaunched = Kit.store(folder) + #expect(!relaunched.spaces.contains { $0.key == Kit.garden }) + #expect(relaunched.deleting[Kit.garden] == store.deleting[Kit.garden]) + await relaunched.load(Kit.computer(client: client)) + #expect(relaunched.deleting.isEmpty) + #expect(!relaunched.spaces.contains { $0.key == Kit.garden }) + #expect(relaunched.spaces.count == 2) + } + + @Test func aRefusedDeleteBringsTheSpaceBack() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + client.failure = WorkspaceClientError.rejected(code: "invalid_request") + await #expect(throws: SpacesError.other(code: "invalid_request")) { + try await store.delete(Kit.commute, api: SpacesAPI(client: client)) + } + #expect(store.spaces.contains { $0.key == Kit.commute }) + #expect(store.deleting.isEmpty) + } + + // MARK: Stale and cancelled reads + + @Test func aStaleReadDoesNotWrite() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let older = Kit.demo() + _ = try await SpacesAPI(client: older).update(agentID: "home", spaceID: DemoSpacesClient.gardenID, + changes: SpaceChanges(hidden: true)) + let late = HeldSpacesClient(older) + late.holds = [.list] + let store = Kit.store(folder) + let first = Task { await store.load(Kit.computer(client: late)) } + await late.untilHolding() + await store.load(Kit.computer(client: Kit.demo())) + late.release() + await first.value + // The newer read's answer stands. + #expect(store.spaces.first { $0.key == Kit.garden }?.hidden == false) + } + + @Test func aCancelledReadDoesNotWrite() async { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let late = HeldSpacesClient(Kit.demo()) + late.holds = [.list] + let store = Kit.store(folder) + let read = Task { await store.load(Kit.computer(client: late)) } + await late.untilHolding() + read.cancel() + late.release() + await read.value + #expect(store.spaces.isEmpty) + #expect(store.lastLoaded == nil) + #expect(store.phase == .loading) + } + + // MARK: Cards the phone has + + @Test func knownCardsAreSentAndLeftOut() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let store = Kit.store(folder) + await store.load(Kit.computer(client: client)) + let hashes = Dictionary(uniqueKeysWithValues: store.spaces.compactMap { space in + space.cardsSHA256.map { (space.key, $0) } + }) + #expect(hashes.count == 3) + await store.load(Kit.computer(client: client)) + let lists = client.payloads.filter { $0.operation == .list } + #expect(lists.first?.payload["known"] == .object([:])) + #expect(lists.last?.payload["known"] == .object(hashes.mapValues(BighelpJSONValue.string))) + #expect(!client.payloads.contains { $0.operation == .get }) + // The answer left the cards out; the phone's own stay. + #expect(store.spaces.count == 3) + #expect(store.spaces.allSatisfy { $0.card != nil }) + } + + // MARK: needsPluginUpdate comes only from the context + + @Test func needsPluginUpdateOnlyFromAContextWithoutTheFeature() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let store = Kit.store(folder) + await store.load(Kit.computer(client: Kit.demo())) + let performer = try SpacesPerformer() + let client = DirectHermesSpacesClient(workspace: { performer }) + + // The route is refused while the context lists the feature (a reconnect): the data stays. + performer.features = ["native-context-v1", SpacesWire.feature] + performer.failures = [WorkspaceClientError.unavailable(.unsupportedOperation)] + await store.load(Kit.computer(client: client)) + #expect(store.phase == .unreachable) + #expect(store.spaces.count == 3) + + // The context didn't load: still not "update the plugin". + performer.contextFailure = WorkspaceClientError.transportUnavailable + performer.failures = [WorkspaceClientError.unavailable(.unsupportedOperation)] + await store.load(Kit.computer(client: client)) + #expect(store.phase == .unreachable) + + // The computer's plugin says it has no spaces. + performer.contextFailure = nil + performer.features = ["native-context-v1"] + performer.failures = [WorkspaceClientError.unavailable(.unsupportedOperation)] + await store.load(Kit.computer(client: client)) + #expect(store.phase == .needsPluginUpdate) + #expect(store.spaces.count == 3) + + // A later failed read doesn't turn that into "not connected". + performer.failures = [WorkspaceClientError.transportUnavailable] + await store.load(Kit.computer(client: client)) + #expect(store.phase == .needsPluginUpdate) + } + + // MARK: The client's retries + + @Test func aLostAnswerIsAskedAgainOnceWithTheSameOperationID() async throws { + let performer = try SpacesPerformer() + let client = DirectHermesSpacesClient(workspace: { performer }) + let payload: [String: BighelpJSONValue] = [ + "agentId": .string("home"), "spaceId": .string(DemoSpacesClient.gardenID), + "operationId": .string(SpacesWire.newOperationID()), "changes": .object(["hidden": .boolean(true)]), + ] + performer.failures = [WorkspaceClientError.outcomeUnknown] + _ = try await client.perform(.update, payload: payload) + #expect(performer.calls.map { $0.operation } == [.spacesUpdate, .spacesUpdate]) + #expect(performer.calls.allSatisfy { $0.payload == payload }) + + performer.failures = [WorkspaceClientError.outcomeUnknown, WorkspaceClientError.outcomeUnknown] + await #expect(throws: WorkspaceClientError.outcomeUnknown) { try await client.perform(.update, payload: payload) } + #expect(performer.calls.count == 4) + } + + @Test func aChangedContextIsLoadedAgainOnce() async throws { + let performer = try SpacesPerformer() + let client = DirectHermesSpacesClient(workspace: { performer }) + performer.failures = [WorkspaceClientError.conflict] + _ = try await client.perform(.list, payload: ["agentIds": .array([.string("home")]), "known": .object([:])]) + #expect(performer.calls.count == 2) + performer.failures = [WorkspaceClientError.conflict, WorkspaceClientError.conflict] + await #expect(throws: WorkspaceClientError.conflict) { + try await client.perform(.list, payload: ["agentIds": .array([.string("home")]), "known": .object([:])]) + } + } +} diff --git a/BighelpTests/SpacesWireTests.swift b/BighelpTests/SpacesWireTests.swift new file mode 100644 index 00000000..a410d72b --- /dev/null +++ b/BighelpTests/SpacesWireTests.swift @@ -0,0 +1,429 @@ +import Foundation +import Testing +@testable import Bighelp + +/// A space as the plugin's routes describe it (docs/SPACES.md › Routes), read leniently, and the +/// chat's `space_draft` card, read exactly. +@MainActor +struct SpacesWireTests { + static let spaceID = "s_0123456789abcdef0123456789abcdef" + static let appID = "a_0123456789abcdef0123456789abcdef" + static let at = Date(timeIntervalSince1970: 1_794_500_000) + + /// The plan's sample space, with a card the app can draw. + static func spaceJSON(_ changes: [String: BighelpJSONValue?] = [:]) -> [String: BighelpJSONValue] { + var json: [String: BighelpJSONValue] = [ + "spaceId": .string(spaceID), "agentId": .string("research"), "state": .string("live"), + "title": .string("Commute"), "description": .string("Drive time to work."), + "size": .string("small"), "hidden": .boolean(false), "position": .integer(3_072), "revision": .integer(2), + "cardsSha256": .string(String(repeating: "c", count: 64)), + "card": .object(DemoSpaceCards.commute(at).card), + "sizes": .object(["tall": .object(DemoSpaceCards.workouts(at).card)]), + "cardOmitted": .boolean(false), + "updatedAt": .string("2026-11-12T14:02:00Z"), "checkedAt": .string("2026-11-12T14:15:01.250Z"), + "page": .object(["appId": .string(appID), "htmlSha256": .string(String(repeating: "d", count: 64)), + "live": .boolean(true)]), + "routine": .object([ + "kind": .string("script"), "usesAI": .boolean(false), "updates": .string("Every 15 minutes"), + "cadenceMinutes": .integer(15), "state": .string("running"), "nextRunAt": .string("2026-11-12T14:30:00Z"), + "lastRunAt": .string("2026-11-12T14:15:00Z"), "problem": .null, "pendingChange": .boolean(false), + ]), + "status": .string("fresh"), + ] + for (key, value) in changes { json[key] = value } + return json + } + + /// A bot wrote the title and the words; native UI never draws more than the plugin accepts. + @Test func aBotsTitleAndDescriptionAreCappedAtTheWireMaximums() throws { + let long = String(repeating: "w", count: 10_000) + let space = try #require(Space(json: Self.spaceJSON(["title": .string(long), "description": .string(long)]))) + #expect(space.title.count == SpacesWire.maximumTitleLength) + #expect(space.description.count == SpacesWire.maximumDescriptionLength) + // A blank title falls back to the card's. + let untitled = try #require(Space(json: Self.spaceJSON(["title": .string(" ")]))) + #expect(untitled.title == "Commute") + // And the copy on the phone's disk reads back as it was kept. + #expect(Space(json: space.json)?.title == space.title) + } + + @Test func theDraftCardsWordsAreCappedToo() { + let long = String(repeating: "w", count: 10_000) + let details = SpaceDraftDetails(title: long, description: long, updates: long, usesAI: false) + #expect(details.title.count == SpacesWire.maximumTitleLength) + #expect(details.description.count == SpacesWire.maximumDescriptionLength) + #expect(details.updates.count == SpacesWire.maximumUpdatesLength) + #expect(SpaceDraftDetails(title: "Commute", description: "Drive time.", updates: "Every hour", usesAI: true).title + == "Commute") + } + + // MARK: Space + + @Test func aFullSpaceReadsEveryField() throws { + let space = try #require(Space(json: Self.spaceJSON())) + #expect(space.key == "research/" + Self.spaceID) + #expect(space.state == .live) + #expect(space.title == "Commute") + #expect(space.size == .small) + #expect(!space.hidden) + #expect(space.position == 3_072) + #expect(space.revision == 2) + #expect(space.cardsSHA256 == String(repeating: "c", count: 64)) + #expect(space.card?.title == "Commute") + #expect(space.card(for: .tall)?.title == "Workouts") + #expect(space.card(for: .wide)?.title == "Commute") + #expect(!space.cardUnreadable) + #expect(space.updatedAt == ISO8601DateFormatter().date(from: "2026-11-12T14:02:00Z")) + #expect(space.checkedAt != nil) + #expect(space.page == SpacePage(appID: Self.appID, htmlSHA256: String(repeating: "d", count: 64), isLive: true)) + #expect(space.page?.card(title: space.title, description: space.description).sendsAnswers == false) + #expect(space.routine.kind == .script) + #expect(!space.routine.usesAI) + #expect(space.routine.updates == "Every 15 minutes") + #expect(space.routine.cadenceMinutes == 15) + #expect(space.routine.state == .running) + #expect(space.routine.problem == nil) + #expect(space.status == .fresh) + #expect(!space.isStopped) + } + + @Test func unknownValuesFallBackAndUnknownKeysAreIgnored() throws { + let space = try #require(Space(json: Self.spaceJSON([ + "size": .string("huge"), "status": .string("glowing"), "position": .string("first"), + "updatedAt": .string("yesterday"), "checkedAt": .integer(12), "card": nil, "sizes": nil, + "routine": .object(["kind": .string("ai"), "state": .string("sleeping"), "problem": .string("Bad output!")]), + "somethingNew": .object(["x": .integer(1)]), "page": .object(["appId": .string("not-an-app")]), + ]))) + #expect(space.size == .wide) + #expect(space.status == .unknown) + #expect(space.position == SpacesWire.maximumPositionMagnitude) + #expect(space.updatedAt == nil) + #expect(space.checkedAt == nil) + #expect(space.card == nil) + #expect(!space.cardUnreadable) + #expect(space.page == nil) + #expect(space.routine.state == .unknown) + // Not running, as far as this app can tell: drawn as stopped. + #expect(space.isStopped) + // Never "no AI" by guess. + #expect(space.routine.usesAI) + // Only the plugin's fixed codes, never text. + #expect(space.routine.problem == nil) + } + + @Test func aMissingRoutineSaysUsesAIAndStopped() throws { + let space = try #require(Space(json: Self.spaceJSON(["routine": nil, "status": nil]))) + #expect(space.routine.kind == .unknown) + #expect(space.routine.usesAI) + #expect(space.isStopped) + } + + @Test func aCardThatCantBeDrawnMarksOnlyItsSpace() throws { + var card = DemoSpaceCards.commute(Self.at).card + card["data_sources"] = .array([.object(["id": .string("live")])]) + let space = try #require(Space(json: Self.spaceJSON(["card": .object(card), "title": .string(" ")]))) + #expect(space.card == nil) + #expect(space.cardUnreadable) + #expect(space.holdsCards) + // No title of its own and no card to borrow one from. + #expect(space.title.isEmpty) + } + + @Test func aBrokenSpaceIsLeftOutAndTheRestRead() { + let list = SpacesList(json: [ + "spaces": .array([ + .object(Self.spaceJSON()), + .object(Self.spaceJSON(["spaceId": nil])), + .object(Self.spaceJSON(["agentId": .string("Not An Id")])), + .string("garbage"), + .object(Self.spaceJSON(["title": .string("Second copy")])), + .object(Self.spaceJSON(["spaceId": .string("s_ffffffffffffffffffffffffffffffff"), "size": .integer(3)])), + ]), + "agents": .object(["research": .string("ok"), "nova": .string("profile_not_found"), + "atlas": .string("busy"), "BAD": .string("ok")]), + ]) + #expect(list.spaces.map(\.spaceID) == [Self.spaceID, "s_ffffffffffffffffffffffffffffffff"]) + // The first of two with one key wins. + #expect(list.spaces.first?.title == "Commute") + #expect(list.spaces.last?.size == .wide) + #expect(list.agents == ["research": .ok, "nova": .notFound, "atlas": .other("busy")]) + #expect(SpacesList(json: [:]).spaces.isEmpty) + } + + @Test func thePhonesCopyReadsBackAsTheSameSpace() throws { + let space = try #require(Space(json: Self.spaceJSON())) + #expect(Space(json: space.json) == space) + var unreadable = Self.spaceJSON() + unreadable["card"] = .object(["schema": .string("other")]) + let marked = try #require(Space(json: unreadable)) + let copy = try #require(Space(json: marked.json)) + #expect(copy.cardUnreadable) + #expect(copy == marked) + } + + @Test func cardsLeftOutAreTakenFromThePhoneOnlyWhenUnchanged() throws { + let cached = try #require(Space(json: Self.spaceJSON())) + let omitted = try #require(Space(json: Self.spaceJSON(["card": nil, "sizes": nil]))) + #expect(omitted.needsCards) + #expect(omitted.takingCards(from: cached).card == cached.card) + let changed = try #require(Space(json: Self.spaceJSON([ + "card": nil, "sizes": nil, "cardsSha256": .string(String(repeating: "e", count: 64)), + ]))) + #expect(changed.takingCards(from: cached).card == nil) + let tooBig = try #require(Space(json: Self.spaceJSON(["card": nil, "sizes": nil, "cardOmitted": .boolean(true)]))) + #expect(tooBig.needsCards) + } + + @Test func changesMergeApplyAndCatchUp() throws { + let space = try #require(Space(json: Self.spaceJSON())) + let changes = SpaceChanges(size: .tall).merging(SpaceChanges(hidden: true)).merging(SpaceChanges(size: .wide)) + #expect(changes == SpaceChanges(size: .wide, hidden: true)) + #expect(changes.payload == ["size": .string("wide"), "hidden": .boolean(true)]) + let changed = changes.applied(to: space) + #expect(changed.size == .wide && changed.hidden) + #expect(!changes.isSatisfied(by: space)) + #expect(changes.isSatisfied(by: changed)) + } + + @Test func idsAreThePluginsPatterns() { + #expect(SpacesWire.isSpaceID(Self.spaceID)) + #expect(!SpacesWire.isSpaceID("s_0123456789ABCDEF0123456789abcdef")) + #expect(!SpacesWire.isSpaceID("a_0123456789abcdef0123456789abcdef")) + #expect(SpacesWire.isAgentID("research")) + #expect(SpacesWire.isAgentID("9-lives_bot")) + #expect(!SpacesWire.isAgentID("-research")) + #expect(!SpacesWire.isAgentID("Research")) + #expect(!SpacesWire.isAgentID(String(repeating: "a", count: 65))) + let operation = SpacesWire.newOperationID() + #expect(operation == operation.lowercased() && UUID(uuidString: operation) != nil) + } + + @Test func refusalsBecomeWhatTheScreensActOn() { + let cases: [(WorkspaceClientError, SpacesError)] = [ + (.rejected(code: "space_not_found"), .notFound), + (.rejected(code: "profile_not_found"), .notFound), + (.rejected(code: "draft_changed"), .draftChanged(revision: nil)), + (.rejected(code: "space_not_draft"), .notDraft), + (.rejected(code: "spaces_full"), .full), + (.rejected(code: "refresh_too_soon"), .tooSoon(retryAfter: nil)), + (.rejected(code: "schedules_unavailable"), .schedulesUnavailable), + (.rejected(code: "routine_failed"), .routineFailed(nil)), + (.rejected(code: "invalid_request"), .other(code: "invalid_request")), + (.outcomeUnknown, .unreachable), + (.ownerChanged, .unreachable), + // Only the client's own context check says "update the plugin". + (.unavailable(.unsupportedOperation), .unreachable), + (.unavailable(.pluginRequired), .unreachable), + ] + for (error, expected) in cases { + #expect(SpacesError(error) == expected, "\(error)") + } + #expect(!SpacesError.unreachable.isDefinite) + #expect(SpacesError.notFound.isDefinite) + #expect(SpaceRefreshRun(rawValue: "paused") == .paused) + } + + @Test func aScriptThatChangedAfterAddIsNamed() throws { + let space = try #require(Space(json: Self.spaceJSON([ + "routine": .object(["kind": .string("script"), "state": .string("failed"), + "problem": .string("script_changed")]), + "status": .string("stopped"), + ]))) + #expect(space.isScriptChanged) + #expect(space.isStopped) + #expect(!space.isPaused) + } + + // MARK: Known answers from the spaces routes + + /// The plugin sends these 5xx only once it knows what happened: a refresh that ran and failed, + /// and a delete that took the space off Today but couldn't remove its task yet. Other routes' + /// `schedules_unavailable` (Workflows' triggers) keep their meaning. + @Test func theSpacesRoutesKnownFailuresAreRefusalsNotUnknown() async throws { + let http = SpacesNativeHTTP() + let owner = try SpacesNativeHTTP.owner() + let client = DirectHermesNativePluginClient(http: http, owner: owner, currentOwner: { owner }) + let delete: [String: BighelpJSONValue] = [ + "agentId": .string("home"), "spaceId": .string(Self.spaceID), "operationId": .string(SpacesWire.newOperationID()), + ] + http.answer = (503, "schedules_unavailable") + await #expect(throws: WorkspaceClientError.rejected(code: "schedules_unavailable")) { + try await client.perform(.spacesDelete, payload: delete) + } + http.answer = (502, "routine_failed") + await #expect(throws: WorkspaceClientError.rejected(code: "routine_failed")) { + try await client.perform(.spacesRefresh, payload: delete) + } + http.answer = (503, "spaces_unavailable") + await #expect(throws: WorkspaceClientError.rejected(code: "spaces_unavailable")) { + try await client.perform(.spacesAdd, payload: delete) + } + // Any other 5xx to a change may have run: still unknown. + http.answer = (503, "busy") + await #expect(throws: WorkspaceClientError.outcomeUnknown) { + try await client.perform(.spacesDelete, payload: delete) + } + http.answer = (503, "schedules_unavailable") + await #expect(throws: WorkspaceClientError.outcomeUnknown) { + try await client.perform(.cardsTemplatesInstall, payload: ["agentId": .string("default")]) + } + } + + // MARK: The routes + + /// Demo mode skips HTTP, so only this catches a route the transport would refuse before + /// sending, or one the plugin client doesn't route at all. + @Test func everySpacesRouteIsRoutedAndItsAnswerFitsTheHTTPSizeFence() throws { + for operation in SpacesOperation.allCases { + let budget = try #require(DirectHermesNativePluginClient.responseBudget(operation.workspaceOperation)) + #expect(budget.path == "/api/plugins/loopdy/native/spaces/" + operation.rawValue) + #expect(budget.maximumResponseBytes <= DirectHermesHTTP.responseLimit(route: budget.path, method: "POST", query: []), + "\(budget.path)") + } + // A list of every bot's spaces can come near 4 MiB before the plugin leaves cards out. + let list = try #require(DirectHermesNativePluginClient.responseBudget(.spacesList)) + #expect(list.maximumResponseBytes > 4 * 1_024 * 1_024) + } + + // MARK: The draft card + + static func draftProps(_ changes: [String: BighelpJSONValue?] = [:]) -> [String: BighelpJSONValue] { + var props: [String: BighelpJSONValue] = [ + "space_id": .string(spaceID), "description": .string("Drive time to work, from live traffic."), + "updates": .string("Every 15 minutes"), "uses_ai": .boolean(false), "revision": .integer(1), + ] + for (key, value) in changes { props[key] = value } + return props + } + + /// The card `bighelp_draft_space` renders, as `render_card` leaves it. + static func draftDocument(props: [String: BighelpJSONValue] = draftProps(), + extraElements: [String: BighelpJSONValue] = [:]) -> [String: BighelpJSONValue] { + var elements: [String: BighelpJSONValue] = [ + "space": .object(["type": .string("space_draft"), "props": .object(props), "children": .array([])]), + ] + elements.merge(extraElements) { $1 } + return [ + "schema": .string("loopdy.card"), "version": .integer(1), "title": .string("Commute"), + "spoken_summary": .string("A space to add to Today: Commute. Updates every 15 minutes, without AI."), + "data_sources": .array([]), "root": .string("space"), "elements": .object(elements), + "content_hash": .string(String(repeating: "a", count: 64)), "card_id": .string(String(repeating: "b", count: 32)), + "origin": .string("live"), "created_at": .string("2026-11-12T12:00:00Z"), + ] + } + + @Test func theDraftCardReadsBackExactly() throws { + let card = try BighelpCardDocument(document: Self.draftDocument()) + let draft = try #require(SpaceDraftCard.draft(in: card)) + #expect(draft == SpaceDraftCard(spaceID: Self.spaceID, title: "Commute", + description: "Drive time to work, from live traffic.", + updates: "Every 15 minutes", usesAI: false, revision: 1)) + } + + @Test func draftPropsAreExactlyTheFiveKeys() { + let wrong: [[String: BighelpJSONValue?]] = [ + ["size": .string("wide")], + ["uses_ai": nil], + ["uses_ai": .string("no")], + ["revision": .integer(0)], + ["revision": .number(1.5)], + ["space_id": .string("s_0123")], + ["space_id": .string(Self.appID)], + ["description": .string(" ")], + ["description": .string(String(repeating: "x", count: 241))], + ["updates": .string("")], + ["updates": .string(String(repeating: "x", count: 61))], + ] + for change in wrong { + #expect(throws: (any Error).self, "\(change)") { + try SpaceDraftCard(props: Self.draftProps(change), title: "Commute") + } + } + #expect((try? SpaceDraftCard(props: Self.draftProps(["uses_ai": .boolean(true)]), title: "Workouts"))?.usesAI == true) + } + + /// The speaker note says the app draws drafts only to a plugin that knows them, and the whole + /// list stays within the plugin's eight names. + @Test func theSpeakerNoteOffersDraftsOnlyToAPluginThatKnowsThem() { + let every: Set = [BighelpCardObjects.feature, ImageDraftWire.feature, HTMLAppWire.feature, SpacesWire.feature] + let renders = DirectHermesChatSpeakerNote.payload(agentID: "default", storedSessionID: "s1", personID: "p", + name: "Sam", pluginFeatures: every)["renders"]?.array + #expect(renders?.last == .string("space_draft")) + #expect((renders?.count ?? 0) <= 8) + let older = DirectHermesChatSpeakerNote.payload(agentID: "default", storedSessionID: "s1", personID: "p", name: "Sam", + pluginFeatures: [BighelpCardObjects.feature, HTMLAppWire.feature])["renders"] + #expect(older?.array?.contains(.string("space_draft")) == false) + } + + /// The plugin's own example (`fixtures/loopdy_card_v1/static-space-draft.json`, same bytes). + @Test func thePluginFixtureDraftValidatesAndReadsBack() throws { + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .appendingPathComponent("Fixtures/CardExamples/static-space-draft.json") + var document = try JSONDecoder().decode([String: BighelpJSONValue].self, from: Data(contentsOf: url)) + // What `render_card` adds to every card. + for (key, value) in Self.draftDocument() where ["content_hash", "card_id", "origin", "created_at"].contains(key) { + document[key] = value + } + let card = try BighelpCardValidator.validate(BighelpCardDocument(document: document)) + let draft = try #require(SpaceDraftCard.draft(in: card)) + #expect(draft == SpaceDraftCard(spaceID: Self.spaceID, title: "Commute", + description: "Drive time to work, from live traffic.", + updates: "Every 15 minutes", usesAI: false, revision: 1)) + } + + @Test func aDraftIsItsCardsOnlyElement() throws { + let alone = try BighelpCardDocument(document: Self.draftDocument()) + #expect(throws: Never.self) { try SpaceDraftCard.validateComposition(alone.elements) } + let crowded = try BighelpCardDocument(document: Self.draftDocument(extraElements: [ + "note": .object(["type": .string("text"), "props": .object(["value": .object(["literal": .string("Hi")])]), + "children": .array([])]), + ])) + #expect(throws: BighelpCardValidationError.self) { try SpaceDraftCard.validateComposition(crowded.elements) } + } + + // MARK: The demo computer's cards + + @Test func everyDemoCardDraws() throws { + for cards in [DemoSpaceCards.commute(Self.at), DemoSpaceCards.garden(Self.at), + DemoSpaceCards.workouts(Self.at), DemoSpaceCards.spending(Self.at)] { + _ = try BighelpCardValidator.validateForStaticRelease(BighelpCardDocument(document: cards.card)) + for (_, size) in cards.sizes { + _ = try BighelpCardValidator.validateForStaticRelease(BighelpCardDocument(document: try #require(size.object))) + } + } + } +} + +/// The plugin's HTTP for `DirectHermesNativePluginClient`: its context lists Spaces, and every +/// route answers with one error. +@MainActor +private final class SpacesNativeHTTP: DirectHermesNativeHTTP { + var answer: (status: Int, code: String) = (503, "busy") + private static let etag = "\"sha256:" + String(repeating: "a", count: 64) + "\"" + + static func owner() throws -> WorkspaceOwner { + WorkspaceOwner(authority: try .direct(endpointIdentity: "https://host.example", providerID: "basic", userID: "person"), + authenticationGeneration: UUID(), connectionGeneration: UUID()) + } + + func nativeResponse(_ request: DirectHermesHTTPRequest, + requestGuard: DirectHermesNativeRequestGuard?) async throws -> DirectHermesHTTP.Response { + let url = try #require(URL(string: "https://host.example" + request.path)) + guard requestGuard != nil else { + let context: [String: BighelpJSONValue] = [ + "schemaVersion": .integer(1), "pluginVersion": .string("test"), "runtimeId": .string("runtime-test"), + "servingProfileId": .string("default"), + "principal": .object(["provider": .string("basic"), "userId": .string("person"), "displayName": .null]), + "features": .array(["native-context-v1", "serving-profile-v1", "native-card-templates-v1", + SpacesWire.feature].map(BighelpJSONValue.string)), + ] + let http = try #require(HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["ETag": Self.etag, "Cache-Control": "no-store"])) + return .init(http: http, body: try JSONEncoder().encode(BighelpJSONValue.object(context))) + } + let http = try #require(HTTPURLResponse(url: url, statusCode: answer.status, httpVersion: "HTTP/1.1", + headerFields: ["Cache-Control": "no-store"])) + let body: [String: BighelpJSONValue] = ["error": .object(["code": .string(answer.code), "message": .string("details")])] + return .init(http: http, body: try JSONEncoder().encode(BighelpJSONValue.object(body))) + } +} diff --git a/BighelpTests/TodayBoardsStoreTests.swift b/BighelpTests/TodayBoardsStoreTests.swift new file mode 100644 index 00000000..ac01a00f --- /dev/null +++ b/BighelpTests/TodayBoardsStoreTests.swift @@ -0,0 +1,154 @@ +import Foundation +import Testing +@testable import Bighelp + +/// Today's Feed, Ideas and Goals across bots: which bots are read, how often, and what stays. +@MainActor +struct TodayBoardsStoreTests { + /// A board client like the plugin's: one bot's board per call, or an error for that bot. + @MainActor + private final class Client: AgentBoardClient { + var boards: [String: [AgentBoardItem]] + var failing: Set = [] + private(set) var reads: [String] = [] + let supportsFeedback = true + + init(_ boards: [String: [AgentBoardItem]] = [:]) { self.boards = boards } + + func items(agentID: String) async throws -> [AgentBoardItem] { + reads.append(agentID) + if failing.contains(agentID) { throw WorkspaceClientError.invalidRequest } + return boards[agentID] ?? [] + } + + func update(agentID: String, itemID: String, change: AgentBoardChange) async throws -> AgentBoardItem { + throw WorkspaceClientError.invalidRequest + } + func markRead(agentID: String, itemIDs: [String]) async throws {} + func promote(agentID: String, itemID: String) async throws -> AgentBoardItem { throw WorkspaceClientError.invalidRequest } + func picture(agentID: String, itemID: String, index: Int) async throws -> Data { Data() } + func activity(agentID: String) async throws -> [AgentActivityEntry] { [] } + func approvals(agentID: String) async throws -> [AgentApprovalEntry] { [] } + func identity(agentID: String) async throws -> AgentIdentityDocuments { + AgentIdentityDocuments(soul: .init(), memory: .init(), user: .init()) + } + } + + /// A clock the test moves. + @MainActor + private final class Clock { + var now = Date(timeIntervalSince1970: 1_800_000_000) + } + + private func post(_ id: String, minutesAgo: Double, clock: Clock, kind: AgentBoardItem.Kind = .feed) -> AgentBoardItem { + AgentBoardItem(id: id, kind: kind, title: id, read: false, createdAt: clock.now.addingTimeInterval(-minutesAgo * 60)) + } + + @Test func shownBotsAreReadFirstAndAtMostTwentyFour() { + let ids = (1...30).map { "bot\($0)" } + let order = TodayBoardsStore.readOrder(botIDs: ids + ["bot2"], hiddenIDs: ["bot1", "bot3"]) + #expect(order.count == TodayBoardsStore.maximumBots) + #expect(Array(order.prefix(3)) == ["bot2", "bot4", "bot5"]) + #expect(!order.contains("bot1")) + #expect(Set(order).count == order.count) + #expect(TodayBoardsStore.readOrder(botIDs: ["a", "b", "c"], hiddenIDs: ["a"]) == ["b", "c", "a"]) + } + + @Test func itReadsOneBotAfterAnotherAndMergesNewestFirst() async { + let clock = Clock() + let client = Client(["mina": [post("m1", minutesAgo: 30, clock: clock)], + "avery": [post("a1", minutesAgo: 5, clock: clock), + post("a2", minutesAgo: 1, clock: clock, kind: .idea)]]) + let store = TodayBoardsStore(now: { clock.now }) + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"], hiddenIDs: ["mina"]) + #expect(client.reads == ["avery", "mina"]) + #expect(store.hasRead) + #expect(store.tracksUnread) + #expect(store.entries(.feed).map(\.id) == ["avery/a1", "mina/m1"]) + #expect(store.entries(.idea).map(\.id) == ["avery/a2"]) + #expect(store.entries(.feed, agentIDs: ["mina"]).map(\.id) == ["mina/m1"]) + } + + @Test func itReadsAtMostOnceAMinuteUnlessForced() async { + let clock = Clock() + let client = Client(["mina": []]) + let store = TodayBoardsStore(now: { clock.now }) + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina"]) + clock.now += 30 + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina"]) + #expect(client.reads.count == 1) + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina"], force: true) + #expect(client.reads.count == 2) + clock.now += 61 + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina"]) + #expect(client.reads.count == 3) + } + + @Test func aFailedReadKeepsWhatItHadAndDoesNotHoldOffTheNext() async { + let clock = Clock() + let client = Client(["mina": [post("m1", minutesAgo: 1, clock: clock)], "avery": []]) + let store = TodayBoardsStore(now: { clock.now }) + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"]) + client.failing = ["mina"] + client.boards["avery"] = [post("a1", minutesAgo: 0, clock: clock)] + clock.now += 61 + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"]) + #expect(store.entries(.feed).map(\.id) == ["avery/a1", "mina/m1"]) + // Only a read where every bot answered counts toward the minute. + let before = client.reads.count + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"]) + #expect(client.reads.count == before + 2) + } + + @Test func eachComputerKeepsItsOwnBoards() async { + let clock = Clock() + let first = Client(["mina": [post("m1", minutesAgo: 1, clock: clock)]]) + let second = Client(["river": [post("r1", minutesAgo: 1, clock: clock)]]) + let store = TodayBoardsStore(now: { clock.now }) + await store.refresh(client: first, scope: "computer-1", botIDs: ["mina"]) + await store.refresh(client: second, scope: "computer-2", botIDs: ["river"]) + #expect(store.scope == "computer-2") + #expect(store.entries(.feed).map(\.id) == ["river/r1"]) + // Back on the first computer within the minute: its last read shows, and it isn't read again. + await store.refresh(client: first, scope: "computer-1", botIDs: ["mina"]) + #expect(store.entries(.feed).map(\.id) == ["mina/m1"]) + #expect(first.reads == ["mina"]) + // A new connection to the same computer is the same scope: the minute still holds. + let reconnected = Client(["mina": []]) + await store.refresh(client: reconnected, scope: "computer-1", botIDs: ["mina"]) + #expect(reconnected.reads.isEmpty) + } + + @Test func aReadWhereEveryBotFailedIsNotARead() async { + let clock = Clock() + let client = Client(["mina": [post("m1", minutesAgo: 1, clock: clock)], "avery": []]) + client.failing = ["mina", "avery"] + let store = TodayBoardsStore(now: { clock.now }) + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"]) + // Today keeps its offline state instead of "Nothing yet". + #expect(!store.hasRead) + // Away and back to the same computer: still nothing was read. + await store.refresh(client: client, scope: "computer-2", botIDs: ["mina"]) + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"]) + #expect(!store.hasRead) + // The next read that works counts, and a later failure keeps it. + client.failing = [] + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"], force: true) + #expect(store.hasRead) + client.failing = ["mina", "avery"] + await store.refresh(client: client, scope: "computer-1", botIDs: ["mina", "avery"], force: true) + #expect(store.hasRead) + #expect(store.entries(.feed).map(\.id) == ["mina/m1"]) + } + + @Test func answeredAndDismissedItemsStayOffToday() { + let clock = Clock() + var done = post("i1", minutesAgo: 1, clock: clock, kind: .idea) + done.answer = "yes" + var gone = post("i2", minutesAgo: 2, clock: clock, kind: .idea) + gone.dismissed = true + let open = post("i3", minutesAgo: 3, clock: clock, kind: .idea) + let entries = TodayBoardsStore.entries(.idea, boards: ["mina": [done, gone, open]]) + #expect(entries.map(\.id) == ["mina/i3"]) + } +} diff --git a/BighelpTests/TodayPanelLayoutTests.swift b/BighelpTests/TodayPanelLayoutTests.swift new file mode 100644 index 00000000..c486d687 --- /dev/null +++ b/BighelpTests/TodayPanelLayoutTests.swift @@ -0,0 +1,150 @@ +import Foundation +import Testing +@testable import Bighelp + +/// Today's panel grid: how panels pack into rows, and the layout the person chose. +@MainActor +struct TodayPanelLayoutTests { + private func panel(_ id: String, _ size: TodayPanelSize = .small, canDelete: Bool = false) -> TodayPanelDescriptor { + TodayPanelDescriptor(id: id, kind: "space", title: id, size: size, canDelete: canDelete) + } + + private func freshDefaults() throws -> UserDefaults { + try #require(UserDefaults(suiteName: "today-panels-\(UUID().uuidString)")) + } + + // MARK: Packing + + @Test func twoSmallPanelsShareARowAndWideAndTallTakeOne() { + let rows = TodayPanelPacking.rows([panel("a"), panel("b"), panel("c", .wide), panel("d", .tall)]) + #expect(rows.map { $0.panels.map(\.id) } == [["a", "b"], ["c"], ["d"]]) + #expect(rows.map(\.takesRow) == [false, true, true]) + } + + @Test func aLoneSmallPanelKeepsItsOrderAndLeavesTheRestOfItsRowEmpty() { + let rows = TodayPanelPacking.rows([panel("a"), panel("b", .wide), panel("c"), panel("d"), panel("e")]) + #expect(rows.map { $0.panels.map(\.id) } == [["a"], ["b"], ["c", "d"], ["e"]]) + #expect(rows[0].takesRow == false) + } + + @Test func wideColumnsHoldMoreSmallPanelsAndOneColumnHoldsOne() { + let panels = ["a", "b", "c", "d"].map { panel($0) } + #expect(TodayPanelPacking.rows(panels, columns: 3).map(\.panels.count) == [3, 1]) + #expect(TodayPanelPacking.rows(panels, columns: 1).map(\.panels.count) == [1, 1, 1, 1]) + #expect(TodayPanelPacking.columns(width: 358, isAccessibilitySize: false) == 2) + #expect(TodayPanelPacking.columns(width: 1_060, isAccessibilitySize: false) == 4) + #expect(TodayPanelPacking.columns(width: 1_060, isAccessibilitySize: true) == 1) + } + + // MARK: Layout + + @Test func aPanelTheLayoutDoesNotKnowGoesLastAtItsOwnSize() throws { + let store = TodayPanelLayoutStore(defaults: try freshDefaults()) + let first = [panel("boards", .tall), panel("commute")] + store.move(fromOffsets: [1], toOffset: 0, among: first) + let shown = store.shown(first + [panel("workouts", .wide)]) + #expect(shown.map(\.id) == ["commute", "boards", "workouts"]) + #expect(shown.map(\.size) == [.small, .tall, .wide]) + } + + @Test func hideAndShowMoveAPanelBetweenTodayAndHidden() throws { + let store = TodayPanelLayoutStore(defaults: try freshDefaults()) + let panels = [panel("boards", .tall), panel("commute")] + store.setHidden("commute", true) + #expect(store.shown(panels).map(\.id) == ["boards"]) + #expect(store.hiddenPanels(panels).map(\.id) == ["commute"]) + store.setHidden("commute", false) + #expect(store.shown(panels).map(\.id) == ["boards", "commute"]) + #expect(store.hiddenPanels(panels).isEmpty) + } + + @Test func theSizeThePersonPicksSticksAcrossLaunches() throws { + let defaults = try freshDefaults() + let panels = [panel("boards", .tall), panel("commute")] + TodayPanelLayoutStore(defaults: defaults).setSize(.wide, for: "boards") + let relaunched = TodayPanelLayoutStore(defaults: defaults) + #expect(relaunched.shown(panels).map(\.size) == [.wide, .small]) + #expect(relaunched.size(of: panels[0]) == .wide) + } + + @Test func reorderingMovesAmongShownPanelsAndKeepsHiddenOnes() throws { + let store = TodayPanelLayoutStore(defaults: try freshDefaults()) + let panels = [panel("a"), panel("b"), panel("c"), panel("d")] + store.setHidden("b", true) + // Shown: a, c, d. Drag a below d. + store.move(fromOffsets: [0], toOffset: 3, among: panels) + #expect(store.shown(panels).map(\.id) == ["c", "d", "a"]) + #expect(store.hiddenPanels(panels).map(\.id) == ["b"]) + } + + @Test func aPanelNotListedKeepsItsChoicesUntilItIsDeleted() throws { + let store = TodayPanelLayoutStore(defaults: try freshDefaults()) + let space = panel("commute", canDelete: true) + let panels = [panel("boards", .tall), space] + store.move(fromOffsets: [1], toOffset: 0, among: panels) + store.setSize(.tall, for: "commute") + // Its computer hasn't answered yet: the panel isn't listed, and nothing about it is lost. + #expect(store.shown([panel("boards", .tall)]).map(\.id) == ["boards"]) + #expect(store.shown(panels).map(\.id) == ["commute", "boards"]) + #expect(store.size(of: space) == .tall) + store.forget("commute") + #expect(store.layout.order == ["boards"]) + #expect(store.size(of: space) == .small) + #expect(store.shown(panels).map(\.id) == ["boards", "commute"]) + } + + // MARK: Panels that keep their own layout (Spaces) + + private func owned(_ id: String, _ size: TodayPanelSize = .small, hidden: Bool = false) -> TodayPanelDescriptor { + TodayPanelDescriptor(id: id, kind: "space", title: id, size: size, canDelete: true, + keepsOwnLayout: true, isHidden: hidden) + } + + /// What the store sent to the panels' owner. + @MainActor + final class OwnerCalls { + var sizes: [(String, TodayPanelSize)] = [] + var hidden: [(String, Bool)] = [] + var orders: [[String]] = [] + + func changes() -> TodayOwnedPanelChanges { + TodayOwnedPanelChanges(resize: { self.sizes.append(($0.id, $1)) }, + setHidden: { self.hidden.append(($0.id, $1)) }, + reorder: { self.orders.append($0.map(\.id)) }) + } + } + + @Test func anOwnedPanelsSizeAndHiddenAreItsOwners() throws { + let store = TodayPanelLayoutStore(defaults: try freshDefaults()) + let calls = OwnerCalls() + store.ownedChanges = calls.changes() + let panels = [panel("boards", .tall), owned("a"), owned("b", .wide, hidden: true)] + #expect(store.shown(panels).map(\.id) == ["boards", "a"]) + #expect(store.hiddenPanels(panels).map(\.id) == ["b"]) + + store.setSize(.tall, for: panels[1]) + store.setHidden(panels[1], true) + #expect(calls.sizes.map { $0.0 } == ["a"] && calls.sizes.map { $0.1 } == [.tall]) + #expect(calls.hidden.map { $0.0 } == ["a"] && calls.hidden.map { $0.1 } == [true]) + // Nothing about it is kept on this device: the owner's answer is what shows. + #expect(store.layout.sizes.isEmpty && store.layout.hidden.isEmpty) + #expect(store.size(of: panels[1]) == .small) + // A panel of the device's own still keeps its choices here. + store.setSize(.wide, for: panels[0]) + #expect(store.layout.sizes == ["boards": .wide]) + } + + @Test func aDragTellsTheOwnerItsOrderAndFollowsIt() throws { + let store = TodayPanelLayoutStore(defaults: try freshDefaults()) + let calls = OwnerCalls() + store.ownedChanges = calls.changes() + let before = [panel("boards", .tall), owned("a"), owned("c")] + // Drag c to the top. + store.move(fromOffsets: [2], toOffset: 0, among: before) + #expect(calls.orders == [["c", "boards", "a"]]) + // Until the owner moves them, its order fills the places the drag left. + #expect(store.shown(before).map(\.id) == ["a", "boards", "c"]) + let after = [panel("boards", .tall), owned("c"), owned("a")] + #expect(store.shown(after).map(\.id) == ["c", "boards", "a"]) + } +} diff --git a/BighelpTests/TodaySpacesModelTests.swift b/BighelpTests/TodaySpacesModelTests.swift new file mode 100644 index 00000000..c6e6a996 --- /dev/null +++ b/BighelpTests/TodaySpacesModelTests.swift @@ -0,0 +1,346 @@ +import Foundation +import Testing +@testable import Bighelp + +/// Today's spaces from several computers in one order, and what each action sends where. +@MainActor +struct TodaySpacesModelTests { + typealias Kit = SpacesTestKit + + /// Two computers with the demo's spaces, the one in use first. + private static func twoComputers(folder: URL) -> (model: TodaySpacesModel, home: HeldSpacesClient, studio: HeldSpacesClient) { + let home = HeldSpacesClient(Kit.demo()) + let studio = HeldSpacesClient(Kit.demo()) + let model = TodaySpacesModel( + computers: { + [Kit.computer("scope-home", name: "Home", client: home), + Kit.computer("scope-studio", name: "Studio", client: studio, isCurrent: false)] + }, + current: { Kit.computer("scope-home", name: "Home", client: home) }, + cacheFolder: folder, clock: { Kit.now }) + return (model, home, studio) + } + + private static func id(_ scope: String, _ key: String) -> String { TodaySpace.id(scope: scope, key: key) } + + @Test func spacesFromEveryComputerAreInOneOrder() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let (model, _, studio) = Self.twoComputers(folder: folder) + await model.refresh() + #expect(model.items.map(\.space.title) == ["Commute", "Commute", "Garden", "Garden", "Workouts", "Workouts"]) + // Same place: the computer in use first. + #expect(model.items.prefix(2).map(\.computerName) == ["Home", "Studio"]) + #expect(model.showsComputerNames) + #expect(model.items.first?.botName == "Travel") + + // Same place on one computer: by title. + _ = try await SpacesAPI(client: studio).update(agentID: "home", spaceID: DemoSpacesClient.gardenID, + changes: SpaceChanges(position: 1_024)) + await model.refresh() + #expect(model.items.prefix(3).map(\.id) == [ + Self.id("scope-home", Kit.commute), Self.id("scope-studio", Kit.commute), Self.id("scope-studio", Kit.garden), + ]) + } + + @Test func oneComputerShowsNoComputerNames() async { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let model = TodaySpacesModel(computers: { [Kit.computer(client: Kit.demo())] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + #expect(model.items.count == 3) + #expect(!model.showsComputerNames) + // Drafts never show on Today. + #expect(!model.items.contains { $0.space.spaceID == DemoSpacesClient.spendingDraftID }) + } + + @Test func aReorderSendsOnlyTheSpacesWhosePlaceChanged() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let (model, home, studio) = Self.twoComputers(folder: folder) + await model.refresh() + let order = [ + Self.id("scope-home", Kit.commute), Self.id("scope-home", Kit.workouts), Self.id("scope-studio", Kit.commute), + Self.id("scope-home", Kit.garden), Self.id("scope-studio", Kit.garden), Self.id("scope-studio", Kit.workouts), + ] + let sending = model.reorder(order) + // The new order shows before any computer answers: a drag never jumps back for a frame. + #expect(model.items.map(\.id) == order) + await sending.value + #expect(model.items.map(\.id) == order) + #expect(model.items.map(\.space.position) == [1_024, 2_048, 3_072, 4_096, 5_120, 6_144]) + + func sent(_ client: HeldSpacesClient) -> [String: BighelpJSONValue] { + var sent: [String: BighelpJSONValue] = [:] + for call in client.payloads where call.operation == .update { + if let space = call.payload["spaceId"]?.string { sent[space] = call.payload["changes"]?.object?["position"] } + } + return sent + } + // Home's commute stays at 1,024 and isn't sent; each change goes to its own computer. + #expect(sent(home) == [DemoSpacesClient.workoutsID: .number(2_048), DemoSpacesClient.gardenID: .number(4_096)]) + #expect(sent(studio) == [DemoSpacesClient.commuteID: .number(3_072), DemoSpacesClient.gardenID: .number(5_120), + DemoSpacesClient.workoutsID: .number(6_144)]) + #expect(model.stores.values.allSatisfy { $0.pending.isEmpty }) + } + + @Test func aHiddenSpaceLeavesTodayButStaysInTheList() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let garden = Self.id("scope-home", Kit.garden) + try await model.setHidden(garden, true) + #expect(!model.shown.contains { $0.id == garden }) + #expect(model.items.contains { $0.id == garden }) + #expect(model.hiddenCount == 1) + let onComputer = try await SpacesAPI(client: demo).space(agentID: "home", spaceID: DemoSpacesClient.gardenID) + #expect(onComputer.hidden) + try await model.setHidden(garden, false) + #expect(model.hiddenCount == 0) + } + + @Test func aComputerThatIsntConnectedKeepsItsPanels() async { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let connection = SpacesTestConnection(Kit.demo()) + let isConnected = SpacesTestFlag(true) + let model = TodaySpacesModel( + computers: { [Kit.computer(client: isConnected.value ? connection.client : nil)] }, + current: { nil }, cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + isConnected.value = false + await model.refresh() + #expect(model.items.count == 3) + #expect(model.items.allSatisfy { !$0.isConnected }) + #expect(model.statuses.map(\.phase) == [.unreachable]) + } + + /// No scope for a computer for a moment (it reconnects, the selection moves) is a gap in the + /// list, not a removed computer: its store and waiting changes stay. + @Test func aComputerMissingFromTheListForAMomentKeepsItsStoreAndWaitingChanges() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let listed = SpacesTestFlag(true) + let model = TodaySpacesModel( + computers: { listed.value ? [Kit.computer(client: client)] : [] }, current: { nil }, + hostKeys: { ["host-scope-home"] }, cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let store = try #require(model.stores["scope-home"]) + try await store.change(Kit.garden, SpaceChanges(size: .tall), api: nil) + + listed.value = false + await model.refresh() + #expect(model.stores["scope-home"] === store) + #expect(store.pending[Kit.garden] != nil) + + listed.value = true + await model.refresh() + #expect(model.stores["scope-home"] === store) + #expect(store.pending.isEmpty) + } + + @Test func aRemovedComputerLeavesNoSpacesInMemoryOrOnDisk() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let client = HeldSpacesClient(Kit.demo()) + let model = TodaySpacesModel( + computers: { [Kit.computer(client: client), Kit.computer("scope-studio", name: "Studio", client: client, + isCurrent: false)] }, + current: { nil }, cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let store = try #require(model.stores["scope-home"]) + await store.savedToDisk() + await model.stores["scope-studio"]?.savedToDisk() + #expect(SpacesCacheFile.read(scope: "scope-home", folder: folder) != nil) + + model.forget(hostKey: "host-scope-home", scope: "scope-home") + #expect(model.stores["scope-home"] == nil) + #expect(!model.items.contains { $0.scope == "scope-home" }) + // The erase waits for a write under way, so nothing brings the file back. + try await store.change(Kit.garden, SpaceChanges(size: .tall), api: nil) + for _ in 0..<50 { await Task.yield() } + await store.savedToDisk() + #expect(SpacesCacheFile.read(scope: "scope-home", folder: folder) == nil) + // The other computer keeps its panels and its copy. + #expect(model.stores["scope-studio"] != nil) + #expect(SpacesCacheFile.read(scope: "scope-studio", folder: folder) != nil) + } + + @Test func aStoppedSpaceRunsAgainButNotTwiceInAMinute() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + // One computer for the whole test: the model asks for its connection again at each call. + let demo = Kit.demo() + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let garden = Self.id("scope-home", Kit.garden) + #expect(model.items.first { $0.id == garden }?.space.isStopped == true) + #expect(try await model.runNow(garden) == .now) + let space = try #require(model.items.first { $0.id == garden }?.space) + #expect(!space.isStopped) + #expect(space.updatedAt == Kit.now) + do throws(SpacesError) { + _ = try await model.runNow(garden) + Issue.record("A second run within a minute went through.") + } catch { + #expect(error == .tooSoon(retryAfter: nil)) + } + } + + @Test func aDeletedSpaceIsGoneFromTodayAndTheComputer() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + try await model.delete(Self.id("scope-home", Kit.commute)) + #expect(!model.items.contains { $0.space.key == Kit.commute }) + do throws(SpacesError) { + _ = try await SpacesAPI(client: demo).space(agentID: "travel", spaceID: DemoSpacesClient.commuteID) + Issue.record("The deleted space still reads.") + } catch { + #expect(error == .notFound) + } + } + + @Test func aDraftIsAddedAfterEverythingOnToday() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let (model, home, _) = Self.twoComputers(folder: folder) + await model.refresh() + let api = SpacesAPI(client: home) + let draft = try await api.space(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID) + #expect(draft.state == .draft) + let added = try await model.add(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID, + draftRevision: draft.revision, size: .small, preview: draft) + #expect(added.state == .live) + #expect(added.size == .small) + #expect(model.items.last?.space.key == added.key) + #expect(added.position == 3_072 + SpacesWire.positionStep) + } + + /// A chat's Add before Today ever showed this run: the space is on Today at once, after what the + /// computer has. + @Test func aDraftAddedBeforeTodayShowsIsOnTodayAtOnce() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let (model, home, _) = Self.twoComputers(folder: folder) + let draft = try await SpacesAPI(client: home).space(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID) + let added = try await model.add(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID, + draftRevision: draft.revision, size: nil, preview: draft) + #expect(model.items.contains { $0.space.key == added.key }) + #expect(added.position == 3_072 + SpacesWire.positionStep) + } + + @Test func aDraftWhoseScriptIsGoneSaysSo() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + demo.missingScripts = [DemoSpacesClient.spendingDraftID] + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, + current: { Kit.computer(client: demo) }, cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let draft = try await SpacesAPI(client: demo).space(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID) + await #expect(throws: SpacesError.scriptMissing) { + try await model.add(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID, + draftRevision: draft.revision, size: nil, preview: draft) + } + #expect(!model.items.contains { $0.space.spaceID == DemoSpacesClient.spendingDraftID }) + } + + /// An AI routine the person paused in Scheduled tasks: Update now runs nothing, says so, and the + /// next one isn't held off. + @Test func aPausedAIRoutineRunsNothing() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + demo.setRoutine(DemoSpacesClient.workoutsID, agentID: "home", state: .paused) + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let workouts = Self.id("scope-home", Kit.workouts) + let item = try #require(model.items.first { $0.id == workouts }) + #expect(SpacePanelFooter.state(for: item, size: .tall) == .paused) + #expect(try await model.runNow(workouts) == .paused) + #expect(try await model.runNow(workouts) == .paused) + #expect(model.items.first { $0.id == workouts }?.space.isPaused == true) + } + + /// The bot changed the script after Add: stopped until it's drafted and added again; Update now + /// can't run it. + @Test func aScriptThatChangedStopsTheSpace() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + demo.setRoutine(DemoSpacesClient.commuteID, agentID: "travel", state: .failed, + problem: SpacesWire.scriptChangedProblem) + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, current: { nil }, + cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let commute = Self.id("scope-home", Kit.commute) + let item = try #require(model.items.first { $0.id == commute }) + #expect(SpacePanelFooter.state(for: item, size: .small) == .scriptChanged) + do throws(SpacesError) { + _ = try await model.runNow(commute) + Issue.record("A changed script ran.") + } catch { + guard case .routineFailed(let space) = error else { Issue.record("\(error)"); return } + #expect(space?.isScriptChanged == true) + } + } + + @Test func aDraftTheBotChangedIsRefusedWithItsNewRevision() async throws { + let folder = Kit.folder() + defer { try? FileManager.default.removeItem(at: folder) } + let demo = Kit.demo() + let model = TodaySpacesModel(computers: { [Kit.computer(client: demo)] }, + current: { Kit.computer(client: demo) }, cacheFolder: folder, clock: { Kit.now }) + await model.refresh() + let draft = try await SpacesAPI(client: demo).space(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID) + demo.reviseDraft(DemoSpacesClient.spendingDraftID, agentID: "finance") + do throws(SpacesError) { + _ = try await model.add(agentID: "finance", spaceID: DemoSpacesClient.spendingDraftID, + draftRevision: draft.revision, size: nil, preview: draft) + Issue.record("An old revision was added.") + } catch { + #expect(error == .draftChanged(revision: 2)) + } + // The preview went again: the computer didn't add it. + #expect(!model.items.contains { $0.space.spaceID == DemoSpacesClient.spendingDraftID }) + } + + /// The same request again gets the first answer; the same `operationId` with another body is + /// refused, and nothing is done (the plugin's `invalid_request`). + @Test func aRepeatedOperationGetsTheFirstAnswerOnlyForTheSameRequest() async throws { + let demo = Kit.demo() + let api = SpacesAPI(client: demo) + let operation = SpacesWire.newOperationID() + let first = try await api.update(agentID: "home", spaceID: DemoSpacesClient.gardenID, + changes: SpaceChanges(size: .tall), operationID: operation) + let again = try await api.update(agentID: "home", spaceID: DemoSpacesClient.gardenID, + changes: SpaceChanges(size: .tall), operationID: operation) + #expect(again == first) + await #expect(throws: SpacesError.other(code: "invalid_request")) { + try await api.update(agentID: "home", spaceID: DemoSpacesClient.gardenID, + changes: SpaceChanges(size: .small), operationID: operation) + } + #expect(try await api.space(agentID: "home", spaceID: DemoSpacesClient.gardenID).size == .tall) + } +} + +/// A switch the computers closure reads; tests flip it. +@MainActor +final class SpacesTestFlag { + var value: Bool + + init(_ value: Bool) { + self.value = value + } +} diff --git a/BighelpTests/UnifiedModeToggleTests.swift b/BighelpTests/UnifiedModeToggleTests.swift deleted file mode 100644 index c4e1d2f7..00000000 --- a/BighelpTests/UnifiedModeToggleTests.swift +++ /dev/null @@ -1,100 +0,0 @@ -import Foundation -import Testing -@testable import Bighelp - -/// Bots, Chat and Code: the Header mode switcher, the mode swipes and ⌃⌘1–⌃⌘3 all switch through -/// `SettingsStore.switchMode`, so these check the modes it offers and where each choice lands. -@MainActor -struct UnifiedModeToggleTests { - private func store(_ setup: (UserDefaults) -> Void = { _ in }) -> (SettingsStore, () -> Void) { - let suite = "unified-mode-\(UUID().uuidString)" - let defaults = UserDefaults(suiteName: suite)! - setup(defaults) - return (SettingsStore(defaults: defaults), { defaults.removePersistentDomain(forName: suite) }) - } - - @Test func theToggleIsOffOutOfTheBoxAndRemembered() { - let suite = "unified-mode-\(UUID().uuidString)" - let defaults = UserDefaults(suiteName: suite)! - defer { defaults.removePersistentDomain(forName: suite) } - let settings = SettingsStore(defaults: defaults) - #expect(!settings.unifiedModeToggleEnabled) - settings.unifiedModeToggleEnabled = true - #expect(SettingsStore(defaults: defaults).unifiedModeToggleEnabled) - } - - @Test func codeIsOfferedOnlyWhileCodeModeIsOn() { - let (settings, cleanup) = store() - defer { cleanup() } - #expect(settings.availableModes == [.bots, .chat]) - settings.codeModeEnabled = true - #expect(settings.availableModes == [.bots, .chat, .code]) - } - - @Test func eachModeLandsOnItsHome() { - let (settings, cleanup) = store() - defer { cleanup() } - settings.codeModeEnabled = true - #expect(settings.currentMode == .chat) - - settings.switchMode(.code) - #expect(settings.currentMode == .code) - #expect(settings.experience == .code) - #expect(!settings.simpleBotsEnabled) - - settings.switchMode(.bots) - #expect(settings.currentMode == .bots) - #expect(settings.simpleBotsEnabled) - - settings.switchMode(.chat) - #expect(settings.currentMode == .chat) - #expect(settings.experience == .bighelp) - #expect(!settings.simpleBotsEnabled) - } - - @Test func codeCanNotBePickedWhileCodeModeIsOff() { - let (settings, cleanup) = store() - defer { cleanup() } - settings.switchMode(.code) - #expect(settings.currentMode == .chat) - #expect(settings.experience == .bighelp) - } - - @Test func nextModeCyclesThroughWhatIsOffered() { - let (settings, cleanup) = store() - defer { cleanup() } - #expect(settings.nextMode == .bots) - settings.switchMode(settings.nextMode) - #expect(settings.currentMode == .bots) - #expect(settings.nextMode == .chat) - - settings.codeModeEnabled = true - settings.switchMode(.chat) - #expect(settings.nextMode == .code) - settings.switchMode(settings.nextMode) - #expect(settings.nextMode == .bots) - } - - @Test func modeSwipesStayModeSwipesInBotsMode() { - let (settings, cleanup) = store() - defer { cleanup() } - settings.leftEdgeSwipeAction = .chatMode - settings.rightEdgeSwipeAction = .newChat - settings.simpleBotsEnabled = true - // Bots mode keeps its own swipes for places, but a mode swipe still brings you back out. - #expect(settings.effectiveLeftEdgeSwipeAction == .chatMode) - #expect(settings.effectiveRightEdgeSwipeAction == .profile) - settings.simpleBotsEnabled = false - #expect(settings.effectiveRightEdgeSwipeAction == .newChat) - } - - @Test func aCodeSwipeDoesNothingOnceCodeModeIsOff() { - let (settings, cleanup) = store() - defer { cleanup() } - settings.codeModeEnabled = true - settings.leftEdgeSwipeAction = .codeMode - #expect(settings.effectiveLeftEdgeSwipeAction == .codeMode) - settings.codeModeEnabled = false - #expect(settings.effectiveLeftEdgeSwipeAction == WorkspaceSwipeAction.none) - } -} diff --git a/BighelpTests/WorkProjectionTests.swift b/BighelpTests/WorkProjectionTests.swift new file mode 100644 index 00000000..ef72abfc --- /dev/null +++ b/BighelpTests/WorkProjectionTests.swift @@ -0,0 +1,171 @@ +import Foundation +import Testing +@testable import Bighelp + +@MainActor +struct WorkProjectionTests { + private let now = Date(timeIntervalSince1970: 2_000_000_000) + + private func session(_ id: String, project: String = "app", startedAt: TimeInterval = -60, + batchID: UUID? = nil) -> CodeSessionRecord { + CodeSessionRecord(id: id, agentID: "a", projectID: project, projectName: project, title: "Session \(id)", + folder: "/work/\(project)", branch: "b-\(id)", placement: .newWorktree, + startedAt: now.addingTimeInterval(startedAt), batchID: batchID) + } + + private func run(_ id: String, state: WorkflowRunState, updated: TimeInterval = -60) -> WorkflowRunSummary { + WorkflowRunSummary(id: id, number: 1, workflowID: "w", workflowName: "Run \(id)", revision: nil, + state: state, stageKey: nil, stageTitle: nil, stageState: nil, stagesDone: 1, + stageCount: 3, startedAt: nil, updatedAt: now.addingTimeInterval(updated), version: 1) + } + + private func task(_ id: String, _ status: HermesKanbanTaskStatus, project: String? = nil) -> HermesKanbanTask { + let base = DemoKanbanService.task(id, "Task \(id)", status: status, assignee: "a", priority: 0, + createdAt: now.addingTimeInterval(-120)) + guard let project else { return base } + return HermesKanbanTask( + id: base.id, title: base.title, body: nil, assignee: base.assignee, status: status, priority: 0, + createdBy: nil, createdAt: base.createdAt, startedAt: nil, completedAt: nil, tenant: nil, + workspaceKind: "scratch", workspacePath: nil, branchName: nil, projectID: project, result: nil, + idempotencyKey: nil, latestSummary: nil, currentRunID: nil, workerPID: nil, lastHeartbeatAt: nil, + maxRuntimeSeconds: nil, modelOverride: nil, providerOverride: nil, reasoningEffort: nil, + workflowTemplateID: nil, currentStepKey: nil, skills: nil, maximumRetries: nil, consecutiveFailures: 0, + goalMode: false, goalMaximumTurns: nil, completionContract: nil, blockKind: nil, blockRecurrences: 0, + childCount: 0, parentCount: 0, commentCount: 0) + } + + private func schedule(_ id: String, status: ScheduledTaskStatus = .active, lastError: String? = nil, + nextRun: TimeInterval? = 3_600) -> ScheduledTask { + ScheduledTask(id: id, agentID: "a", name: "Schedule \(id)", instructions: "", + schedule: .naturalLanguage("daily", timeZoneID: "UTC"), scheduleDescription: "Every day", + nextRun: nextRun.map { now.addingTimeInterval($0) }, status: status, lastResult: nil, + lastError: lastError) + } + + private func bucket(_ items: [WorkItem], _ id: String) -> WorkBucket? { + items.first { $0.id == id }?.bucket + } + + @Test func eachKindLandsInItsBucket() { + var sources = WorkSources(now: now) + sources.codeSessions = [ + WorkCodeSession(record: session("ask"), status: .needsYou("Approve a command")), + WorkCodeSession(record: session("run"), status: .running(nil)), + WorkCodeSession(record: session("start"), status: .starting("Setting up")), + WorkCodeSession(record: session("ready"), status: .ready), + WorkCodeSession(record: session("fail"), status: .failed("Stopped")), + ] + sources.chatWork = [DashboardWorkItem(sessionID: "chat", title: "Plan a trip", subtitle: "Making tool calls")] + sources.background = ["a": BotBackgroundWork(count: 2, title: "Reconcile statements")] + sources.workflowsWaiting = [run("wait", state: .waitingForYou)] + sources.workflowsActive = [run("active", state: .running)] + sources.workflowsRecent = [run("ok", state: .succeeded), run("still", state: .running)] + sources.tasks = [task("blocked", .blocked), task("running", .running), task("done", .done), + task("ready", .ready), task("todo", .todo)] + sources.schedules = [schedule("upcoming"), schedule("broken", lastError: "Timed out")] + + let items = WorkProjection.items(sources) + #expect(bucket(items, "coding:ask") == .needsYou) + #expect(bucket(items, "coding:run") == .working) + #expect(bucket(items, "coding:start") == .working) + #expect(bucket(items, "coding:ready") == .done) + #expect(bucket(items, "coding:fail") == .done) + #expect(bucket(items, "chat:chat") == .working) + #expect(bucket(items, "background:a") == .working) + #expect(bucket(items, "workflow:wait") == .needsYou) + #expect(bucket(items, "workflow:active") == .working) + #expect(bucket(items, "workflow:ok") == .done) + #expect(bucket(items, "workflow:still") == nil, "A recent run that hasn't finished isn't done") + #expect(bucket(items, "task:blocked") == .needsYou) + #expect(bucket(items, "task:running") == .working) + #expect(bucket(items, "task:done") == .done) + #expect(bucket(items, "task:ready") == nil, "Cards waiting to be picked up stay on the board") + #expect(bucket(items, "task:todo") == nil) + #expect(items.first { $0.kind == .schedule && $0.title == "Schedule broken" }?.bucket == .needsYou) + } + + @Test func aScheduledTaskIsNeverWorking() { + var sources = WorkSources(now: now) + sources.schedules = ScheduledTaskStatus.allCases.map { schedule($0.rawValue, status: $0) } + + [schedule("soon", nextRun: 60), schedule("none", nextRun: nil)] + let items = WorkProjection.items(sources) + #expect(items.count == sources.schedules.count) + #expect(items.allSatisfy { $0.bucket != .working }) + #expect(items.filter { $0.bucket == .needsYou }.map(\.title) == ["Schedule failed"]) + #expect(WorkProjection.visible(items, filter: .working, projectID: nil).isEmpty) + } + + @Test func chipsCountAndFilterTheirBuckets() { + var sources = WorkSources(now: now) + sources.codeSessions = [ + WorkCodeSession(record: session("ask"), status: .needsYou("Answer a question")), + WorkCodeSession(record: session("run"), status: .running("Editing")), + WorkCodeSession(record: session("ready"), status: .ready), + ] + sources.schedules = [schedule("upcoming")] + let items = WorkProjection.items(sources) + let counts = WorkProjection.counts(items, projectID: nil) + #expect(counts == [.all: 4, .needsYou: 1, .working: 1, .done: 1]) + #expect(WorkProjection.visible(items, filter: .needsYou, projectID: nil).map(\.id) == ["coding:ask"]) + #expect(WorkProjection.visible(items, filter: .done, projectID: nil).map(\.id) == ["coding:ready"]) + #expect(WorkProjection.visible(items, filter: .all, projectID: nil).contains { $0.bucket == .upcoming }, + "Upcoming scheduled tasks show under All only") + } + + @Test func aProjectShowsOnlyItsOwnWork() { + var sources = WorkSources(now: now) + sources.codeSessions = [ + WorkCodeSession(record: session("mine", project: "app"), status: .running(nil)), + WorkCodeSession(record: session("other", project: "site"), status: .running(nil)), + ] + sources.tasks = [task("card", .running, project: "app"), task("loose", .running)] + sources.schedules = [schedule("daily")] + sources.chatWork = [DashboardWorkItem(sessionID: "chat", title: "Chat", subtitle: "Working")] + let items = WorkProjection.items(sources) + let shown = WorkProjection.visible(items, filter: .all, projectID: "app") + #expect(Set(shown.map(\.id)) == ["coding:mine", "task:card"]) + #expect(WorkProjection.counts(items, projectID: "app")[.all] == 2) + #expect(WorkProjection.visible(items, filter: .all, projectID: nil).count == 6) + } + + @Test func newestActivityComesFirstAndUpcomingGoesLast() { + var sources = WorkSources(now: now) + sources.codeSessions = [ + WorkCodeSession(record: session("old", startedAt: -7_200), status: .ready), + WorkCodeSession(record: session("new", startedAt: -60), status: .ready), + ] + sources.workflowsWaiting = [run("mid", state: .waitingForYou, updated: -600)] + // Running now, with no time from its store: counts as now. + sources.chatWork = [DashboardWorkItem(sessionID: "live", title: "Live", subtitle: "Working")] + sources.schedules = [schedule("later", nextRun: 7_200), schedule("sooner", nextRun: 600)] + let ids = WorkProjection.items(sources).map(\.id) + let scheduleIDs = WorkProjection.items(sources).filter { $0.kind == .schedule }.map(\.title) + #expect(Array(ids.prefix(4)) == ["chat:live", "coding:new", "workflow:mid", "coding:old"]) + #expect(scheduleIDs == ["Schedule sooner", "Schedule later"]) + #expect(ids.count == 6) + } + + @Test func aCodeSessionIsNotListedTwiceAsChatWork() { + var sources = WorkSources(now: now) + sources.codeSessions = [WorkCodeSession(record: session("s1"), status: .running(nil))] + sources.chatWork = [DashboardWorkItem(sessionID: "s1", title: "Session s1", subtitle: "Working")] + #expect(WorkProjection.items(sources).map(\.id) == ["coding:s1"]) + } + + @Test func aBatchNeedsYouWhenAnyOfItsSessionsDoes() { + let batch = CodeBatch(id: UUID(), projectID: "app", title: "Batch", createdAt: now, jobCount: 2, + sessionIDs: ["x", "y"], messages: []) + var sources = WorkSources(now: now) + sources.codeBatches = [WorkCodeBatch(batch: batch, lines: [ + WorkBatchLine(id: "x", title: "X", index: 0, status: .running(nil)), + WorkBatchLine(id: "y", title: "Y", index: 1, status: .needsYou("Approve a command")), + ], startedCount: 2)] + #expect(WorkProjection.items(sources).first?.bucket == .needsYou) + } + + @Test func storesThatAreNilGiveNoRows() { + let context = WorkContext(header: nil, onOpen: { _ in }, onRefresh: {}) + let sources = WorkSources(context: context, now: now) + #expect(WorkProjection.items(sources).isEmpty) + } +} diff --git a/BighelpUITests/AIDataConsentGateUITests.swift b/BighelpUITests/AIDataConsentGateUITests.swift index 0017b7ec..210edcd2 100644 --- a/BighelpUITests/AIDataConsentGateUITests.swift +++ b/BighelpUITests/AIDataConsentGateUITests.swift @@ -13,7 +13,7 @@ final class AIDataConsentGateUITests: BighelpUITestCase { let app = makeApp() app.launch() try onboardOpenHost(app, address: address) - XCTAssertTrue(app.buttons["tab.sessions"].waitForExistence(timeout: 20), "Setup is finished") + XCTAssertTrue(app.buttons["home.new-chat"].waitForExistence(timeout: 20), "Setup is finished") app.terminate() // The same bighelp, as if it was set up before the agreement existed. @@ -32,7 +32,7 @@ final class AIDataConsentGateUITests: BighelpUITestCase { let again = makeApp() again.launch() - XCTAssertTrue(again.buttons["tab.sessions"].waitForExistence(timeout: 20)) + XCTAssertTrue(again.buttons["home.new-chat"].waitForExistence(timeout: 20)) XCTAssertFalse(again.descendants(matching: .any)["onboarding.ai-consent"].firstMatch.waitForExistence(timeout: 5), "Never asked again after agreeing") } diff --git a/BighelpUITests/AgentAppearanceUITests.swift b/BighelpUITests/AgentAppearanceUITests.swift index deed0b50..7d2dc277 100644 --- a/BighelpUITests/AgentAppearanceUITests.swift +++ b/BighelpUITests/AgentAppearanceUITests.swift @@ -10,6 +10,7 @@ final class AgentAppearanceUITests: BighelpUITestCase { expectAppearance(mode: "Dark", color: "rose", in: app) capture("agent-appearance-studio-dark-rose", in: app) closeSettings(in: app) + openDemoChat(in: app) capture("agent-appearance-chat-dark-rose", in: app) } @@ -20,6 +21,7 @@ final class AgentAppearanceUITests: BighelpUITestCase { expectAppearance(mode: "Light", color: "ocean", in: app) capture("agent-appearance-studio-light-ocean", in: app) closeSettings(in: app) + openDemoChat(in: app) capture("agent-appearance-chat-light-ocean", in: app) } @@ -77,13 +79,14 @@ final class AgentAppearanceUITests: BighelpUITestCase { @MainActor private func openDemoChat(in app: XCUIApplication) { - let chat = app.buttons["session.row.demo-finance"].firstMatch + let chat = chatRow("demo-finance", in: app) XCTAssertTrue(chat.waitForExistence(timeout: 15)) chat.tap() - XCTAssertTrue(app.buttons["chat.menu"].firstMatch.waitForExistence(timeout: 10), "The chat opened") + XCTAssertTrue(app.buttons["chat.back"].firstMatch.waitForExistence(timeout: 10), "The chat opened") } - /// Settings › Appearance shows the agent's change like one made there. + /// Settings › Appearance shows the agent's change like one made there. Settings opens from the + /// home, so this leaves the chat. @MainActor private func expectAppearance(mode: String, color: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { diff --git a/BighelpUITests/AgentDeletionUITests.swift b/BighelpUITests/AgentDeletionUITests.swift index 04ad212a..2b386033 100644 --- a/BighelpUITests/AgentDeletionUITests.swift +++ b/BighelpUITests/AgentDeletionUITests.swift @@ -1,14 +1,14 @@ import XCTest -/// Delete Agent from a bot's profile in Bots mode, on the demo's agents (#949): the agent goes, -/// its editor and profile close, and the person is back on the Bots home, never on a page that -/// says "This bot isn't here anymore". +/// Delete bot from a bot's profile on Bots, on the demo's agents (#949): the agent goes, its +/// profile closes, and the person is back on the Bots home, never on a page that says "This bot +/// isn't here anymore". final class AgentDeletionUITests: BighelpUITestCase { @MainActor func testDeletingABotFromItsProfileGoesBackToTheBotsHome() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES"] + "-loopdy.home.landing", "bots"] app.launch() let home = app.descendants(matching: .any)["simple-bots.home"] XCTAssertTrue(home.waitForExistence(timeout: 15)) @@ -23,23 +23,17 @@ final class AgentDeletionUITests: BighelpUITestCase { let profile = app.descendants(matching: .any)["simple-bots.profile"] XCTAssertTrue(profile.waitForExistence(timeout: 10)) + // ⋯ › Delete bot, then the confirmation's Delete bot. app.buttons["simple-bots.profile.more"].tap() - let edit = app.buttons["Edit Name and Role"].firstMatch - XCTAssertTrue(edit.waitForExistence(timeout: 5)) - edit.tap() - // Delete Agent is the editor's last row, which the form builds once it scrolls there. - XCTAssertTrue(app.buttons["agent.editor.save-template"].firstMatch.waitForExistence(timeout: 10) - || app.navigationBars.firstMatch.waitForExistence(timeout: 5), "The editor opens") - let delete = app.buttons["agent.editor.delete"] - for _ in 0..<8 where !(delete.exists && delete.isHittable) { app.swipeUp() } + let delete = app.buttons.matching(NSPredicate(format: "identifier == %@ OR label == %@", + "simple-bots.profile.more.delete", "Delete bot")).firstMatch XCTAssertTrue(delete.waitForExistence(timeout: 5)) delete.tap() - let confirm = app.buttons["agent.editor.delete.confirm"].firstMatch + let confirm = app.buttons["simple-bots.profile.delete.confirm"].firstMatch XCTAssertTrue(confirm.waitForExistence(timeout: 5)) confirm.tap() // Back where the profile opened from, with the bot gone. - XCTAssertTrue(delete.waitForNonExistence(timeout: 10), "The editor closes") XCTAssertTrue(profile.waitForNonExistence(timeout: 10), "The profile closes") XCTAssertTrue(home.waitForExistence(timeout: 5), "The Bots home is back") XCTAssertFalse(app.staticTexts["This bot isn't here anymore"].exists) diff --git a/BighelpUITests/AgentDriveUITests.swift b/BighelpUITests/AgentDriveUITests.swift index c70e3067..784c3b7b 100644 --- a/BighelpUITests/AgentDriveUITests.swift +++ b/BighelpUITests/AgentDriveUITests.swift @@ -8,11 +8,11 @@ final class AgentDriveUITests: BighelpUITestCase { func testFeedTemplatesDriveOpensTheDeckAndReturnsToTheChat() { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "light", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "light", "-test-agent-drive", "bot.dashboard.templates.feed", "-test-agent-drive-note", "Each card is something your Feed can do. Swipe right to use one."] app.launch() - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 15)) primary.tap() XCTAssertTrue(app.buttons["chat.identity"].waitForExistence(timeout: 5)) diff --git a/BighelpUITests/AgentFilesUITests.swift b/BighelpUITests/AgentFilesUITests.swift index f3e4aeb7..903d1850 100644 --- a/BighelpUITests/AgentFilesUITests.swift +++ b/BighelpUITests/AgentFilesUITests.swift @@ -1,28 +1,22 @@ import XCTest -/// Files in the agent home is the selected agent's own folder (#518). On the demo data each agent has -/// its own; switching agents on Files shows the next agent's, and a file opens from it. Nerd Mode's -/// Artifacts stays the serving agent's. BIGHELP_AGENT_FILES_EVIDENCE (TEST_RUNNER_…) saves screenshots. +/// Each bot's Files tab on its page is that bot's own folder (#518). On the demo data each bot has +/// its own; the next bot's page shows the next bot's files, and a file opens from it. +/// BIGHELP_AGENT_FILES_EVIDENCE (TEST_RUNNER_…) saves screenshots. final class AgentFilesUITests: BighelpUITestCase { @MainActor func testSwitchingAgentsShowsEachAgentsOwnFiles() throws { for appearance in ["light", "dark"] { let app = makeApp() - // Files lives in ☰ by default; pinned here so the bar holds it. - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-bighelp.hosts.all-hosts", "NO", "-loopdy.demo.appearance", appearance, - "-bighelp.app-layout", "{pinned=(feed,ideas,files);menu=();}"] + app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "bots", + "-loopdy.demo.appearance", appearance] app.launch() - let files = app.buttons["tab.apps"] - XCTAssertTrue(files.waitForExistence(timeout: 30), "The bottom bar holds Files") - files.tap() - XCTAssertTrue(app.descendants(matching: .any)["board.apps"].waitForExistence(timeout: 10)) - switchAgent(to: "finance", in: app) + openFiles(of: "finance", in: app) XCTAssertTrue(row("Notes.md", in: app).waitForExistence(timeout: 10), "Avery's own files") save("finance-\(appearance)", app) - switchAgent(to: "travel", in: app) + openFiles(of: "travel", in: app) let itinerary = row("Itinerary.md", in: app) XCTAssertTrue(itinerary.waitForExistence(timeout: 10), "Mina's own files") XCTAssertTrue(row("Notes.md", in: app).waitForNonExistence(timeout: 5), "Not Avery's") @@ -32,7 +26,7 @@ final class AgentFilesUITests: BighelpUITestCase { save("travel-open-\(appearance)", app) app.buttons["Done"].firstMatch.tap() - switchAgent(to: "home", in: app) + openFiles(of: "home", in: app) XCTAssertTrue(row("Grocery list.txt", in: app).waitForExistence(timeout: 10), "Jordan's own files") XCTAssertTrue(row("Itinerary.md", in: app).waitForNonExistence(timeout: 5), "Not Mina's") save("home-\(appearance)", app) @@ -44,13 +38,10 @@ final class AgentFilesUITests: BighelpUITestCase { func testWorkspaceFileSearchFilterAndSort() throws { for appearance in ["light", "dark"] { let app = makeApp() - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-bighelp.hosts.all-hosts", "NO", "-loopdy.demo.appearance", appearance, - "-bighelp.app-layout", "{pinned=(feed,ideas,files);menu=();}"] + app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "bots", + "-loopdy.demo.appearance", appearance] app.launch() - XCTAssertTrue(app.buttons["tab.apps"].waitForExistence(timeout: 30)) - app.buttons["tab.apps"].tap() - switchAgent(to: "finance", in: app) + openFiles(of: "finance", in: app) let search = app.descendants(matching: .any)["files.search"].firstMatch XCTAssertTrue(search.waitForExistence(timeout: 10)) app.buttons["files.sort"].tap() @@ -68,7 +59,7 @@ final class AgentFilesUITests: BighelpUITestCase { } } - /// The same on a real Hermes with two agents or more, read only: no chats, no settings changed. + /// The same on a real Hermes with two agents or more, read only: no chats sent, no settings changed. /// Set BIGHELP_AGENT_FILES_HOST (as TEST_RUNNER_…) to an open host, e.g. 127.0.0.1:9121. @MainActor func testARealHostShowsEachAgentsOwnFiles() throws { @@ -76,43 +67,57 @@ final class AgentFilesUITests: BighelpUITestCase { throw XCTSkip("Set BIGHELP_AGENT_FILES_HOST") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES", "-bighelp.app-layout", "{pinned=(feed,ideas,files);menu=();}"] app.launch() try onboardOpenHost(app, address: host) - let files = app.buttons["tab.apps"] - XCTAssertTrue(files.waitForExistence(timeout: 30), "The bottom bar holds Files") - files.tap() - app.buttons["agent.hero.name"].firstMatch.tap() - let listed = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "agent.switcher.agent.")) - XCTAssertTrue(listed.firstMatch.waitForExistence(timeout: 10)) - let agents = listed.allElementsBoundByIndex.prefix(3) - .map { $0.identifier.replacingOccurrences(of: "agent.switcher.agent.", with: "") } - XCTAssertGreaterThanOrEqual(agents.count, 2, "The host has two agents or more") + showBots(in: app) + let listed = app.buttons.matching(NSPredicate( + format: "identifier BEGINSWITH %@ OR identifier BEGINSWITH %@ OR identifier BEGINSWITH %@", + "simple-bots.primary.", "simple-bots.bot.", "simple-bots.pinned.")) + XCTAssertTrue(listed.firstMatch.waitForExistence(timeout: 30)) + let agents = listed.allElementsBoundByIndex.prefix(3).map { + $0.identifier.replacingOccurrences(of: "simple-bots.primary.", with: "") + .replacingOccurrences(of: "simple-bots.bot.", with: "") + .replacingOccurrences(of: "simple-bots.pinned.", with: "") + } + XCTAssertGreaterThanOrEqual(agents.count, 1, "The host has two agents or more: the primary and another") for agent in agents + [agents[0]] { - switchAgent(to: agent, in: app) - XCTAssertTrue(app.staticTexts["Finding the workspace…"].waitForNonExistence(timeout: 30), agent) - XCTAssertFalse(app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", "Plugin version")) - .firstMatch.exists, "\(agent): the plugin reads every agent's folder") - let rows = app.buttons.matching(NSPredicate(format: "label MATCHES %@", ".+, .+, Changed .+")) + openFiles(of: agent, in: app) + XCTAssertTrue(app.staticTexts.containing(NSPredicate(format: "label BEGINSWITH %@", "Opening")) + .firstMatch.waitForNonExistence(timeout: 30), agent) + XCTAssertFalse(app.staticTexts["Update the bighelp plugin to see files"].exists, + "\(agent): the plugin reads every agent's folder") + let rows = app.buttons.matching(identifier: "simple-bots.files.item") .allElementsBoundByIndex.prefix(5).map(\.label) add(XCTAttachment(string: "\(agent): \(rows)")) save("real-host-\(agent)", app) } } + /// Bots › the bot (its chat opens) › its pill › Files. @MainActor - private func switchAgent(to agentID: String, in app: XCUIApplication) { - let agent = app.buttons["agent.switcher.agent.\(agentID)"] - if !agent.exists { app.buttons["agent.hero.name"].firstMatch.tap() } - XCTAssertTrue(agent.waitForExistence(timeout: 5), "The switcher lists \(agentID)") - agent.tap() - XCTAssertTrue(agent.waitForNonExistence(timeout: 5)) + private func openFiles(of botID: String, in app: XCUIApplication) { + showBots(in: app) + let bot = app.buttons.matching(NSPredicate(format: "identifier IN %@", [ + "simple-bots.bot.\(botID)", "simple-bots.pinned.\(botID)", "simple-bots.primary.\(botID)", + ])).firstMatch + let home = app.descendants(matching: .any)["simple-bots.home"].firstMatch + _ = bot.waitForExistence(timeout: 10) + for _ in 0..<6 where !(bot.exists && bot.isHittable) { home.swipeUp() } + XCTAssertTrue(bot.exists, "Bots lists \(botID)") + guard bot.exists else { return } + bot.tap() + openBotPage(fromChatIn: app) + let tab = app.buttons["simple-bots.profile.tab.files"].firstMatch + XCTAssertTrue(tab.waitForExistence(timeout: 5), "The bot's page has Files") + tab.tap() + XCTAssertTrue(app.descendants(matching: .any)["simple-bots.profile.files"].firstMatch.waitForExistence(timeout: 10)) } - /// A file's row reads "name, path in the folder, when it changed". + /// A file's row on the bot's Files tab, by the name it starts with. @MainActor private func row(_ name: String, in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", name + ",")).firstMatch + app.buttons.matching(NSPredicate(format: "identifier == %@ AND label BEGINSWITH %@", + "simple-bots.files.item", name)).firstMatch } @MainActor diff --git a/BighelpUITests/AgentOpenRealHostUITests.swift b/BighelpUITests/AgentOpenRealHostUITests.swift deleted file mode 100644 index 600c3cb6..00000000 --- a/BighelpUITests/AgentOpenRealHostUITests.swift +++ /dev/null @@ -1,198 +0,0 @@ -import XCTest - -/// Tapping an agent opens its chat on the first tap, against two real hosts -/// (`BIGHELP_AGENT_OPEN_PROBE`: JSON with `address_a`, `address_b`, `agent`). -/// It only opens chats; it never sends a message. Skipped without the probe. -final class AgentOpenRealHostUITests: BighelpUITestCase { - private var probe: [String: String] = [:] - - @MainActor func testAgentsOpenOnTheFirstTap() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_AGENT_OPEN_PROBE"] else { - throw XCTSkip("Needs BIGHELP_AGENT_OPEN_PROBE") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - addUIInterruptionMonitor(withDescription: "Password prompts") { dialog in - for label in ["Continue", "Not Now"] where dialog.buttons[label].exists { - dialog.buttons[label].tap() - return true - } - return false - } - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - - // Lab Hermes is selected; Desk Hermes' agent is on the other computer. - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 10)) - let agentName = try XCTUnwrap(probe["agent"]) - _ = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'fleet.agent.'")).firstMatch - .waitForExistence(timeout: 45) - Thread.sleep(forTimeInterval: 5) - save("agent-open-0-list", app) - for row in app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'fleet.'")).allElementsBoundByIndex { - print("FLEET-ROW \(row.identifier) | \(row.label)") - } - var results: [String] = [] - for (step, host) in [("1-other-host", "Desk Hermes"), ("2-switch-back", "Lab Hermes"), - ("3-other-host-again", "Desk Hermes"), ("4-same-host", "Desk Hermes")] { - let agent = fleetAgent(agentName, on: host, in: app) - XCTAssertTrue(agent.waitForExistence(timeout: 45), "\(agentName) on \(host) is listed") - agent.tap() - let outcome = waitForOutcome(in: app) - save("agent-open-\(step)", app) - results.append("\(step): \(outcome)") - if outcome == "error" { app.alerts.buttons["OK"].firstMatch.tap() } - if outcome == "chat" { swipeBackFromLeadingEdge(in: app) } - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 15), "Back on All agents") - } - - // One computer: Agents › an agent that isn't the one the app opens on. - menu.tap() - app.buttons["menu.all-hosts"].tap() - openRootTab("tab.agents", in: app) - let other = app.buttons["agent.\(probe["other_agent"] ?? "nova")"].firstMatch - if other.waitForExistence(timeout: 20) { - other.tap() - let outcome = waitForOutcome(in: app) - save("agent-open-5-single-host-other-agent", app) - results.append("5-single-host-other-agent: \(outcome)") - } else { - save("agent-open-5-missing", app) - results.append("5-single-host-other-agent: not found") - } - // New chat with any agent, including one whose Bot Chat the host can't give. - for agentID in [probe["other_agent"] ?? "nova", "default"] { - openRootTab("tab.agents", in: app) - let row = app.buttons["agent.\(agentID)"].firstMatch - guard row.waitForExistence(timeout: 20) else { results.append("new-chat-\(agentID): not found"); continue } - row.tap() - guard waitForOutcome(in: app) == "chat" else { results.append("new-chat-\(agentID): no chat"); continue } - let newChat = chatNewChatButton(in: app) - guard newChat.waitForExistence(timeout: 10) else { results.append("new-chat-\(agentID): no button"); continue } - newChat.tap() - confirmNewChatPicker(in: app) - let alert = app.alerts.firstMatch - let deadline = Date().addingTimeInterval(15) - while Date() < deadline, !alert.exists { Thread.sleep(forTimeInterval: 0.3) } - save("agent-open-6-new-chat-\(agentID)", app) - let ok = !alert.exists && app.textViews["chat.composer.text"].exists - results.append("new-chat-\(agentID): \(ok ? "chat" : "error \(alert.label)")") - if alert.exists { alert.buttons.firstMatch.tap() } - } - let report = results.joined(separator: "\n") - print("AGENT-OPEN-RESULTS\n\(report)") - XCTAssertEqual(results.filter { !$0.hasSuffix(": chat") }, [], report) - } - - /// Leaving the agent's chat and coming back, also after the app was away long - /// enough for its connections to close, reopens it on the first tap. - @MainActor func testAgentChatReopensAfterLeavingAndReturning() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_AGENT_OPEN_PROBE"] else { - throw XCTSkip("Needs BIGHELP_AGENT_OPEN_PROBE") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 10)) - let agentName = try XCTUnwrap(probe["agent"]) - var results: [String] = [] - func open(_ step: String, on host: String) { - let agent = fleetAgent(agentName, on: host, in: app) - guard agent.waitForExistence(timeout: 45) else { results.append("\(step): not listed"); return } - print("BHSTEP \(step)") - agent.tap() - let outcome = waitForOutcome(in: app) - save("reopen-\(step)", app) - results.append("\(step): \(outcome)") - if outcome == "error" { app.alerts.buttons["OK"].firstMatch.tap() } - if outcome == "chat" { swipeBackFromLeadingEdge(in: app) } - _ = app.navigationBars["All agents"].waitForExistence(timeout: 15) - } - open("1-first", on: "Lab Hermes") - open("2-again", on: "Lab Hermes") - XCUIDevice.shared.press(.home) - XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10)) - sleep(40) - app.activate() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 30)) - open("3-after-away", on: "Lab Hermes") - open("4-other-host", on: "Desk Hermes") - open("5-other-host-again", on: "Desk Hermes") - open("6-back-to-first", on: "Lab Hermes") - let report = results.joined(separator: "\n") - print("AGENT-REOPEN-RESULTS\n\(report)") - XCTAssertEqual(results.filter { !$0.hasSuffix(": chat") }, [], report) - } - - /// "chat" when the composer shows, "error" for the Unable to open alert, "nothing" otherwise. - @MainActor private func waitForOutcome(in app: XCUIApplication) -> String { - let composer = app.textViews["chat.composer.text"] - let alert = app.alerts.matching(NSPredicate(format: "label CONTAINS %@", "Unable to open")).firstMatch - let deadline = Date().addingTimeInterval(30) - while Date() < deadline { - if alert.exists { return "error" } - if composer.exists { return "chat" } - Thread.sleep(forTimeInterval: 0.3) - } - return "nothing" - } - - @MainActor private func fleetAgent(_ name: String, on host: String, in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "(identifier BEGINSWITH 'fleet.agent.' OR identifier BEGINSWITH " - + "'fleet.pinned.') AND label BEGINSWITH %@ AND label CONTAINS %@", name, host)).firstMatch - } - - @MainActor private func addHost(_ app: XCUIApplication, address: String, name: String) throws { - let field = app.textFields["host-setup.address"] - XCTAssertTrue(field.waitForExistence(timeout: 15)) - field.tap() - field.typeText(address) - app.buttons["More options"].firstMatch.tap() - let nameField = app.textFields["host-setup.name"] - if nameField.waitForExistence(timeout: 3) { - nameField.tap() - nameField.typeText(name + "\n") - } - let connect = app.buttons["host-setup.connect-host"] - for _ in 0..<5 where !(connect.exists && connect.isHittable) { app.swipeUp() } - XCTAssertTrue(connect.waitForExistence(timeout: 8)) - connect.tap() - let next = app.buttons["host-setup.continue"] - XCTAssertTrue(next.waitForExistence(timeout: 45), "Connected to \(name)") - next.tap() - } - - @MainActor private func save(_ name: String, _ app: XCUIApplication) { - let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) - shot.name = name - shot.lifetime = .keepAlways - add(shot) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_AGENT_OPEN_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? XCUIScreen.main.screenshot().pngRepresentation - .write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } -} diff --git a/BighelpUITests/AgentsUITests.swift b/BighelpUITests/AgentsUITests.swift index 0195df24..4784e0a9 100644 --- a/BighelpUITests/AgentsUITests.swift +++ b/BighelpUITests/AgentsUITests.swift @@ -1,82 +1,21 @@ import XCTest import UIKit +/// Group chats opened from Bots on the demo data: who is typing, and Stop again after a lost Stop. final class AgentsUITests: BighelpUITestCase { - @MainActor - private func launch(appearance: String = "light", accessibility: Bool = false) -> XCUIApplication { - XCUIDevice.shared.orientation = .portrait - let app = makeApp() - app.launchArguments = [ - "-use-demo-fixtures", "-disable-demo-delays", "-test-agents-directory", - "-loopdy.demo.appearance", appearance - ] - if accessibility { - app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"] - } - app.launch() - openAgents(in: app) - XCTAssertTrue(revealSearchField(agentSearch(in: app), in: app)) - return app - } - - @MainActor - private func agentSearch(in app: XCUIApplication) -> XCUIElement { - app.searchFields["Search agents and groups"].firstMatch - } - - @MainActor - func testAgentTapOpensChatRatherThanManagement() { - let app = launch() - let agent = app.buttons["agent.studio"] - XCTAssertTrue(agent.waitForExistence(timeout: 5)) - agent.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 10)) - XCTAssertFalse(app.descendants(matching: .any)["agent.actions"].exists) - } - - @MainActor - func testNativeSwipePinAndEditHaveVisibleManagementEquivalent() { - let app = launch() - let search = agentSearch(in: app) - search.tap() - search.typeText("Build\n") - let row = app.buttons["agent.build"] - XCTAssertTrue(row.waitForExistence(timeout: 5)) - row.swipeRight() - let pin = app.buttons["Pin"].firstMatch - XCTAssertTrue(pin.waitForExistence(timeout: 3)) - pin.tap() - - app.buttons["agent.build.more"].tap() - let unpin = app.buttons["agent.build.pin"] - for _ in 0..<6 where !unpin.exists || !unpin.isHittable { - app.descendants(matching: .any)["agent.actions.list"].firstMatch.swipeUp() - } - XCTAssertTrue(unpin.waitForExistence(timeout: 3)) - XCTAssertEqual(unpin.label, "Unpin") - unpin.tap() - XCTAssertTrue(unpin.waitForNonExistence(timeout: 3)) - - row.swipeLeft() - let edit = app.buttons["Edit"].firstMatch - XCTAssertTrue(edit.waitForExistence(timeout: 3)) - edit.tap() - XCTAssertTrue(app.textFields["agent.editor.name"].waitForExistence(timeout: 5)) - app.buttons["agent.editor.cancel"].tap() - XCTAssertTrue(app.textFields["agent.editor.name"].waitForNonExistence(timeout: 3)) - } - - @MainActor - func testGroupTapOpensChatAndSearchMatchesMembers() { - let app = launch() - let search = agentSearch(in: app) - search.tap() - search.typeText("Field Notes\n") - let group = app.buttons["agents.group.research-circle"] - XCTAssertTrue(group.waitForExistence(timeout: 5)) - XCTAssertTrue(group.label.contains("3 agents")) + /// Bots › the group chat whose row names `title`. + @MainActor + private func openGroupFromBots(titled title: String, in app: XCUIApplication, + file: StaticString = #filePath, line: UInt = #line) { + showBots(in: app) + let home = app.descendants(matching: .any)["simple-bots.home"].firstMatch + let group = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS %@", + "simple-bots.group.", title)).firstMatch + _ = group.waitForExistence(timeout: 8) + for _ in 0..<8 where !(group.exists && group.isHittable) { home.swipeUp() } + XCTAssertTrue(group.exists && group.isHittable, "Bots lists \(title)", file: file, line: line) + guard group.exists else { return } group.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 10)) } /// Each member Hermes reports writing gets its own "is typing" row; the @@ -91,16 +30,10 @@ final class AgentsUITests: BighelpUITestCase { XCUIDevice.shared.orientation = .portrait let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-agents-directory", - "-preview-group-typing", "-loopdy.demo.appearance", appearance] + "-preview-group-typing", "-loopdy.home.landing", "bots", + "-loopdy.demo.appearance", appearance] app.launch() - openAgents(in: app) - XCTAssertTrue(revealSearchField(agentSearch(in: app), in: app)) - let search = agentSearch(in: app) - search.tap() - search.typeText("Field Notes\n") - let group = app.buttons["agents.group.research-circle"] - XCTAssertTrue(group.waitForExistence(timeout: 5)) - group.tap() + openGroupFromBots(titled: "Research circle", in: app) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 10)) let typing = app.descendants(matching: .any).matching(identifier: "chat.bot-typing") let two = NSPredicate(format: "count == 2") @@ -115,6 +48,7 @@ final class AgentsUITests: BighelpUITestCase { shot.name = "group-typing-\(appearance)" shot.lifetime = .keepAlways add(shot) + app.terminate() } /// A Stop whose answer is lost leaves the group chat one way back, Stop @@ -129,16 +63,10 @@ final class AgentsUITests: BighelpUITestCase { XCUIDevice.shared.orientation = .portrait let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-team-call", - "-preview-group-stop-lost", "-loopdy.demo.appearance", appearance] + "-preview-group-stop-lost", "-loopdy.home.landing", "bots", + "-loopdy.demo.appearance", appearance] app.launch() - openAgents(in: app) - XCTAssertTrue(revealSearchField(agentSearch(in: app), in: app)) - let search = agentSearch(in: app) - search.tap() - search.typeText("Weekend\n") - let group = app.buttons["agents.group.team-call-demo"] - XCTAssertTrue(group.waitForExistence(timeout: 8)) - group.tap() + openGroupFromBots(titled: "Weekend planners", in: app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 10)) @@ -174,282 +102,4 @@ final class AgentsUITests: BighelpUITestCase { add(recovered) app.terminate() } - - /// On one computer every chat keeps the bottom bar, however Agents opened - /// it: the pinned avatar, a new chat from the agent's row, or one of its - /// existing chats. Every chat has ☰ (which goes back to Agents). Tapping an - /// agent makes its chat the Chat tab's own; a chat picked from its list - /// goes back to the list with an edge swipe. - @MainActor - func testChatsOpenedFromAgentsKeepTheTabBar() { - XCUIDevice.shared.orientation = .portrait - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] - app.launch() - let directory = app.descendants(matching: .any)["agents.screen"].firstMatch - - openAgents(in: app) - let avatar = app.descendants(matching: .any)["agents.featured.finance"].firstMatch - XCTAssertTrue(avatar.waitForExistence(timeout: 8)) - avatar.tap() - assertChatKeepsTabBar("The avatar's chat", isTabHome: true, in: app) - - openAgents(in: app) - let row = app.buttons["agent.travel"] - for _ in 0..<6 where !(row.exists && row.isHittable) { directory.swipeUp() } - XCTAssertTrue(row.isHittable) - row.tap() - assertChatKeepsTabBar("A new chat", isTabHome: true, in: app) - - // ☰ is the way back to Agents. - openAgents(in: app) - XCTAssertTrue(directory.waitForExistence(timeout: 8), "☰ › Agents goes back to Agents") - let more = app.buttons["agent.finance.more"] - for _ in 0..<6 where !(more.exists && more.isHittable) { directory.swipeUp() } - more.tap() - let chats = app.buttons["agent.finance.sessions"] - for _ in 0..<6 where !(chats.exists && chats.isHittable) { - app.descendants(matching: .any)["agent.actions.list"].firstMatch.swipeUp() - } - chats.tap() - let session = app.buttons["session.row.demo-finance"] - XCTAssertTrue(session.waitForExistence(timeout: 8)) - session.tap() - assertChatKeepsTabBar("An existing chat", isTabHome: false, in: app) - - // An edge swipe still goes back to the agent's chat list. - swipeBackFromLeadingEdge(in: app) - XCTAssertTrue(session.waitForExistence(timeout: 5), "Swiping from the edge goes back to the list") - session.tap() - XCTAssertTrue(app.buttons["chat.menu"].waitForExistence(timeout: 5)) - - // The bar works from there: Feed leaves the chat. - app.buttons["tab.feed"].tap() - XCTAssertTrue(app.descendants(matching: .any)["board.feed"].firstMatch.waitForExistence(timeout: 8)) - } - - @MainActor - private func assertChatKeepsTabBar(_ chat: String, isTabHome: Bool, in app: XCUIApplication, - file: StaticString = #filePath, line: UInt = #line) { - let composer = app.descendants(matching: .any)["chat.composer-shell"].firstMatch - XCTAssertTrue(composer.waitForExistence(timeout: 10), "\(chat) didn't open", file: file, line: line) - XCTAssertTrue(app.buttons["chat.menu"].waitForExistence(timeout: 5), "\(chat) has ☰", file: file, line: line) - XCTAssertFalse(app.buttons["chat.back"].exists, "\(chat) has no Back", file: file, line: line) - // A new chat can focus the message box; the bar hides under the keyboard. - if app.keyboards.firstMatch.exists { - app.tables["chat.timeline"].swipeDown() - _ = app.keyboards.firstMatch.waitForNonExistence(timeout: 3) - } - let feed = app.buttons["tab.feed"], chatTab = app.buttons["tab.sessions"] - XCTAssertTrue(feed.waitForExistence(timeout: 5) && feed.isHittable, - "\(chat) is missing the tab bar", file: file, line: line) - if chatTab.exists { - XCTAssertLessThanOrEqual(composer.frame.maxY, chatTab.frame.minY + 1, - "\(chat): the message box sits above the tab bar", file: file, line: line) - } - if isTabHome { - // That agent's chat is the Chat tab's own: Chat is the lit tab. - XCTAssertTrue(chatTab.exists && chatTab.isSelected, "\(chat) lights the Chat tab", file: file, line: line) - } - // Evidence: BIGHELP_TABBAR_EVIDENCE (TEST_RUNNER_BIGHELP_TABBAR_EVIDENCE) names a folder. - if let folder = ProcessInfo.processInfo.environment["BIGHELP_TABBAR_EVIDENCE"] { - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - let name = chat.lowercased().replacingOccurrences(of: " ", with: "-").replacingOccurrences(of: "'", with: "") - try? app.screenshot().pngRepresentation - .write(to: URL(fileURLWithPath: folder).appendingPathComponent("agents-\(name).png")) - } - } - - @MainActor - func testGroupGesturesAndRenameMenu() { - let app = launch() - let search = agentSearch(in: app) - search.tap(); search.typeText("Field Notes\n") - let row = app.buttons["agents.group.research-circle"] - XCTAssertTrue(row.waitForExistence(timeout: 5)) - row.swipeRight() - let pin = app.buttons["Pin"].firstMatch - XCTAssertTrue(pin.waitForExistence(timeout: 3)); pin.tap() - row.press(forDuration: 1) - XCTAssertTrue(app.buttons["Unpin"].waitForExistence(timeout: 3)) - app.buttons["Unpin"].tap() - row.press(forDuration: 1) - app.buttons["Rename"].tap() - XCTAssertTrue(app.alerts["Rename group"].waitForExistence(timeout: 3)) - let name = app.alerts.textFields.firstMatch - name.tap(); name.typeText(" Renamed") - app.alerts.buttons["Rename"].tap() - XCTAssertTrue(row.waitForExistence(timeout: 3)) - let renamed = NSPredicate(format: "label CONTAINS %@", "Renamed") - expectation(for: renamed, evaluatedWith: row) - waitForExpectations(timeout: 5) - row.swipeLeft() - let archive = app.buttons["Archive"].firstMatch - XCTAssertTrue(archive.waitForExistence(timeout: 3)); archive.tap() - XCTAssertTrue(row.waitForNonExistence(timeout: 3)) - app.buttons["agents.groups.archived-toggle"].tap() - XCTAssertTrue(row.waitForExistence(timeout: 3)) - row.swipeLeft() - app.buttons["Unarchive"].firstMatch.tap() - XCTAssertTrue(row.waitForNonExistence(timeout: 3)) - } - - /// A new agent starts from scratch, one of the built-in personalities (the - /// typed name goes into it), or a template saved from an existing agent. - @MainActor - func testNewAgentStartsFromScratchATemplateOrASavedTemplate() { - for appearance in ["light", "dark"] { - let app = launch(appearance: appearance) - if appearance == "light" { - // Save an agent as a template first, so My templates has one. - app.buttons["agent.studio.more"].tap() - app.buttons["agent.studio.edit"].tap() - let saveTemplate = app.buttons["agent.editor.save-template"] - XCTAssertTrue(app.textFields["agent.editor.name"].waitForExistence(timeout: 5)) - for _ in 0..<8 where !saveTemplate.isHittable { app.swipeUp() } - saveTemplate.tap() - let saved = app.alerts["Template saved"] - XCTAssertTrue(saved.waitForExistence(timeout: 3)) - XCTAssertTrue(saved.staticTexts.element(boundBy: 1).label.contains("choose My templates")) - saved.buttons.firstMatch.tap() - app.buttons["agent.editor.cancel"].tap() - XCTAssertTrue(app.textFields["agent.editor.name"].waitForNonExistence(timeout: 3)) - } - - app.buttons["agents.create"].tap() - let name = app.textFields["agent.editor.name"] - XCTAssertTrue(name.waitForExistence(timeout: 5)) - let start = app.segmentedControls["agent.editor.start"] - XCTAssertTrue(start.exists) - XCTAssertTrue(start.buttons["Scratch"].isSelected, "A new agent starts from scratch") - if appearance == "light" { evidence("scratch", app) } - - start.buttons["Templates"].tap() - let anchor = app.buttons["agent.editor.template.anchor"] - XCTAssertTrue(anchor.waitForExistence(timeout: 3)) - XCTAssertTrue(app.buttons["agent.editor.template.fable"].exists, "All fifteen are offered") - anchor.tap() - XCTAssertEqual(editorRole(app).value as? String, "Everyday generalist") - name.tap() - name.typeText("Kai") - let instructions = app.textViews["agent.editor.instructions"] - XCTAssertTrue((instructions.value as? String)?.contains("You are Kai, a practical, warm AI assistant") == true, - "The name goes into the personality") - XCTAssertFalse((instructions.value as? String)?.contains("{{agent_name}}") == true) - evidence("templates-\(appearance)", app) - // Dragging down into the keyboard puts it away (its Done bar isn't reachable from UI tests). - app.swipeDown(velocity: .fast) - XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 3)) - app.swipeUp() - app.swipeUp() - evidence("instructions-\(appearance)", app) - for _ in 0..<4 { app.swipeDown() } - - if appearance == "light" { - start.buttons["My templates"].tap() - let savedCard = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'agent.editor.saved-template.'")) - .firstMatch - XCTAssertTrue(savedCard.waitForExistence(timeout: 3)) - savedCard.tap() - // Two rails of saved templates can leave Name below the fold. - for _ in 0..<3 where !name.exists { app.swipeUp() } - XCTAssertEqual(name.value as? String, "Kai", "A typed name is kept") - evidence("my-templates", app) - app.swipeUp() - app.swipeUp() - XCTAssertTrue(instructions.waitForExistence(timeout: 3)) - XCTAssertFalse((instructions.value as? String)?.contains("a practical, warm AI assistant") == true, - "The saved template's instructions replace the personality") - for _ in 0..<4 { app.swipeDown() } - - start.buttons["Scratch"].tap() - XCTAssertEqual(editorRole(app).value as? String, "e.g. Travel planner", - "Scratch clears what the template filled in") - } - app.buttons["agent.editor.cancel"].tap() - let discard = app.buttons["Discard changes"] - if discard.waitForExistence(timeout: 3) { discard.tap() } - XCTAssertTrue(name.waitForNonExistence(timeout: 3)) - app.terminate() - } - } - - /// The editor's Role field. The form builds its rows as they scroll in, and the template - /// rail with its topic chips can leave Role just below the fold. - @MainActor - private func editorRole(_ app: XCUIApplication) -> XCUIElement { - let role = app.textFields["agent.editor.role"] - for _ in 0..<3 where !role.exists || !role.isHittable { app.swipeUp() } - return role - } - - @MainActor - private func evidence(_ label: String, _ app: XCUIApplication) { - let shot = XCUIScreen.main.screenshot() - let attachment = XCTAttachment(screenshot: shot) - attachment.name = "agent-start-\(label)" - attachment.lifetime = .keepAlways - add(attachment) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_UI_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? shot.pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("agent-start-\(label).png")) - } - - @MainActor - func testEditorCancellationRequiresConfirmationOnlyForUnsavedChanges() { - let app = launch() - app.buttons["agent.studio.more"].tap() - app.buttons["agent.studio.edit"].tap() - let name = app.textFields["agent.editor.name"] - XCTAssertTrue(name.waitForExistence(timeout: 5)) - name.tap() - name.typeText(" Updated") - app.buttons["agent.editor.cancel"].tap() - let keep = app.buttons["Keep editing"] - XCTAssertTrue(keep.waitForExistence(timeout: 3)) - keep.tap() - XCTAssertTrue(name.exists) - XCTAssertTrue((name.value as? String)?.contains("Updated") == true) - app.buttons["agent.editor.cancel"].tap() - app.buttons["Discard changes"].tap() - XCTAssertTrue(name.waitForNonExistence(timeout: 3)) - } - - @MainActor - func testLastRowClearsSearchAndNavigationInPortraitAndLandscape() { - verifyClearance(accessibility: false, appearance: "light") - } - - @MainActor - func testAccessibilityTextClearsSearchInDarkMode() { - verifyClearance(accessibility: true, appearance: "dark") - } - - @MainActor - private func verifyClearance(accessibility: Bool, appearance: String) { - defer { XCUIDevice.shared.orientation = .portrait } - let app = launch(appearance: appearance, accessibility: accessibility) - for orientation in [UIDeviceOrientation.portrait, .landscapeLeft] { - XCUIDevice.shared.orientation = orientation - let list = app.descendants(matching: .any)["agents.screen"].firstMatch - let lastRow = app.buttons["agent.long-name"] - let search = agentSearch(in: app) - XCTAssertTrue(revealSearchField(search, in: app)) - for _ in 0..<24 { - if lastRow.exists, lastRow.isHittable { break } - list.swipeUp() - } - XCTAssertTrue(lastRow.exists) - XCTAssertTrue(lastRow.isHittable) - let manage = app.buttons["agent.long-name.more"] - XCTAssertGreaterThanOrEqual(manage.frame.width, 44) - XCTAssertGreaterThanOrEqual(manage.frame.height, 44) - XCTAssertTrue(app.frame.intersects(lastRow.frame)) - let evidence = XCTAttachment(screenshot: app.screenshot()) - evidence.name = "agents-clearance-\(appearance)-\(orientation.rawValue)-ax-\(accessibility)" - evidence.lifetime = .keepAlways - add(evidence) - } - XCUIDevice.shared.orientation = .portrait - } } diff --git a/BighelpUITests/AllHostsHostUITests.swift b/BighelpUITests/AllHostsHostUITests.swift deleted file mode 100644 index d6950519..00000000 --- a/BighelpUITests/AllHostsHostUITests.swift +++ /dev/null @@ -1,470 +0,0 @@ -import XCTest - -/// The all-hosts view against two real, isolated Hermes hosts started by -/// `Scripts/HostSignInMatrixProbe.py --modes fleet` (BIGHELP_SIGNIN_PROBE). -/// The host that isn't selected is read in the background, and opening one of -/// its agents switches to it. Skipped without the probe. -final class AllHostsHostUITests: BighelpUITestCase { - private var probe: [String: String] = [:] - - @MainActor func testAllHostsListsBothHostsAndOpensTheOther() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { - throw XCTSkip("Run through Scripts/HostSignInMatrixProbe.py --modes fleet") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - guard probe["mode"] == "fleet" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } - addUIInterruptionMonitor(withDescription: "Password prompts") { dialog in - for label in ["Continue", "Not Now"] where dialog.buttons[label].exists { - dialog.buttons[label].tap() - return true - } - return false - } - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - - // Lab Hermes is selected now; Desk Hermes is read in the background. - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 10)) - let desk = agent(on: "Desk Hermes", in: app) - XCTAssertTrue(desk.waitForExistence(timeout: 45), "The other host's agents are listed") - XCTAssertTrue(agent(on: "Lab Hermes", in: app).waitForExistence(timeout: 20)) - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS[c] %@", "researcher")).firstMatch - .waitForExistence(timeout: 20), "Every agent on the host, not just its default") - save("fleet-1-both-hosts", app) - - // Opening Desk Hermes' agent switches to that host and opens its chat. - // Give each agent a chat first, so later taps reopen it. - desk.tap() - try say("Hello desk", in: app) - save("fleet-2-other-host-chat", app) - swipeBackFromLeadingEdge(in: app) - - // Back on the list, Lab Hermes is now the one read in the background. - XCTAssertTrue(agent(on: "Lab Hermes", in: app).waitForExistence(timeout: 45)) - XCTAssertTrue(agent(on: "Desk Hermes", in: app).exists) - named("Lab agent", in: app).tap() - try say("Hello lab", in: app) - swipeBackFromLeadingEdge(in: app) - - // Each switch is timed from the tap to that agent's own chat on screen. - var timings: [String: Double] = [:] - timings["1-to-desk"] = try timeToOpen(named("Desk agent", in: app), showing: "Hello desk", in: app) - swipeBackFromLeadingEdge(in: app) - timings["2-to-lab"] = try timeToOpen(named("Lab agent", in: app), showing: "Hello lab", in: app) - swipeBackFromLeadingEdge(in: app) - timings["3-to-desk-again"] = try timeToOpen(named("Desk agent", in: app), showing: "Hello desk", in: app) - swipeBackFromLeadingEdge(in: app) - // The floor: the same host's agent again, with no switch at all. - timings["4-same-host"] = try timeToOpen(named("Desk agent", in: app), showing: "Hello desk", in: app) - swipeBackFromLeadingEdge(in: app) - report(timings) - menu.tap() - app.buttons["menu.all-hosts"].tap() - menu.tap() - let hosts = app.buttons["menu.hosts"] - XCTAssertTrue(hosts.waitForExistence(timeout: 5)) - XCTAssertTrue(hosts.label.contains("Desk Hermes"), "Desk Hermes became the selected host: \(hosts.label)") - save("fleet-3-desk-selected", app) - } - - /// Provider usage opened from a chat on the host the all-hosts list just - /// switched to. The usage panel used to keep the first host's connection and - /// said "Usage couldn't be loaded" until the chat closed. - /// A group chat with an agent from each host (Hermes RoomLink), against - /// `Scripts/RoomLinkProbe.py --simulator-id …`: Lab Hermes, the selected - /// host, is the home and links Desk Hermes' agent; one message gets both - /// agents' answers. Skipped without that probe. - @MainActor func testGroupChatWithAnAgentFromEachHostAnswers() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { - throw XCTSkip("Run through Scripts/RoomLinkProbe.py --simulator-id") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - guard probe["mode"] == "roomlink" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } - addUIInterruptionMonitor(withDescription: "Password prompts") { dialog in - for label in ["Continue", "Not Now"] where dialog.buttons[label].exists { - dialog.buttons[label].tap() - return true - } - return false - } - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(agent(on: "Desk Hermes", in: app).waitForExistence(timeout: 45)) - XCTAssertTrue(agent(on: "Lab Hermes", in: app).waitForExistence(timeout: 20)) - let newChat = app.buttons["fleet.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 10)) - newChat.tap() - let group = app.buttons["fleet.new-chat.group"] - XCTAssertTrue(group.waitForExistence(timeout: 20), "Group chat is offered on a host that can run them") - group.tap() - // The first pick's host is the group's home. - app.buttons["fleet.new-chat.Lab agent"].tap() - app.buttons["fleet.new-chat.Desk agent"].tap() - save("roomlink-1-picked", app) - app.buttons["fleet.new-chat.create-group"].tap() - XCTAssertTrue(app.buttons["chat.people"].waitForExistence(timeout: 60), "The group chat opens") - let status = app.descendants(matching: .any)["chat.bot-mode-status"] - XCTAssertFalse(status.exists && status.label.contains("isn't linked"), status.label) - - let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 20)) - composer.tap() - composer.typeText("Everyone, say hello") - let send = app.buttons["chat.send"] - let deadline = Date().addingTimeInterval(30) - while !send.isEnabled, Date() < deadline { Thread.sleep(forTimeInterval: 0.3) } - send.tap() - if probe["plugin"] == "yes" { - // Desk agent writes on its own computer; that computer's plugin says so. - let typing = app.descendants(matching: .any).matching(NSPredicate( - format: "identifier == 'chat.bot-typing' AND label == %@", "Desk agent is typing")) - XCTAssertTrue(typing.firstMatch.waitForExistence(timeout: 120), "The other computer's agent shows typing") - save("roomlink-1b-typing", app) - } - let replies = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "Hello from this agent.")) - expectation(for: NSPredicate(format: "count >= 2"), evaluatedWith: replies) - waitForExpectations(timeout: 240) - // Both agents are each host's "default" profile; each reply keeps its own name. - for name in ["Lab agent", "Desk agent"] { - let row = app.descendants(matching: .any) - .matching(NSPredicate(format: "label == %@", "\(name): Hello from this agent.")).firstMatch - XCTAssertTrue(row.exists, "\(name)'s reply carries its own name") - } - save("roomlink-2-both-answered", app) - } - - @MainActor func testProviderUsageLoadsInAChatOnTheOtherHost() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { - throw XCTSkip("Run through Scripts/HostSignInMatrixProbe.py --modes fleet") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - guard probe["mode"] == "fleet" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - let desk = agent(on: "Desk Hermes", in: app) - XCTAssertTrue(desk.waitForExistence(timeout: 45)) - desk.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 45), "Desk Hermes' chat opens") - let options = app.buttons["chat.options"].firstMatch - XCTAssertTrue(options.waitForExistence(timeout: 10)) - let usage = chatMenuItem("chat.provider-usage", in: app) - XCTAssertTrue(usage.waitForExistence(timeout: 10), "Usage is in the chat's ⋯ menu") - usage.tap() - XCTAssertTrue(app.descendants(matching: .any)["usage"].waitForExistence(timeout: 10)) - XCTAssertTrue(app.descendants(matching: .any)["provider-usage"].waitForExistence(timeout: 10)) - let failed = app.descendants(matching: .any).matching( - NSPredicate(format: "label CONTAINS %@", "couldn't be loaded")).firstMatch - let loaded = app.descendants(matching: .any).matching( - NSPredicate(format: "identifier BEGINSWITH %@", "provider-usage.")).matching( - NSPredicate(format: "NOT identifier IN %@", ["provider-usage.message"])).firstMatch - let deadline = Date().addingTimeInterval(30) - while Date() < deadline, !failed.exists, !loaded.exists { Thread.sleep(forTimeInterval: 0.5) } - save("fleet-4-usage-in-other-host-chat", app) - XCTAssertFalse(failed.exists, "Usage loads in the other host's chat") - } - - /// ☰ › Usage with All hosts on, before and after the list switches hosts. It did - /// nothing on a real host: the page opened on the host runtime the shell had - /// before the selected host's own one arrived (#99). - @MainActor func testUsageOpensFromTheMenuWithAllHosts() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { - throw XCTSkip("Run through Scripts/HostSignInMatrixProbe.py --modes fleet") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - guard probe["mode"] == "fleet" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 10)) - XCTAssertTrue(agent(on: "Desk Hermes", in: app).waitForExistence(timeout: 45)) - - func openUsage(_ step: String) { - XCTAssertTrue(menu.waitForExistence(timeout: 20), "☰ \(step)") - menu.tap() - let usage = app.buttons["menu.usage"] - XCTAssertTrue(usage.waitForExistence(timeout: 10), "Usage is in ☰ \(step)") - usage.tap() - let page = app.descendants(matching: .any)["usage"].firstMatch - let opened = page.waitForExistence(timeout: 10) - save("fleet-usage-\(step.replacingOccurrences(of: " ", with: "-"))", app) - XCTAssertTrue(opened, "Usage opens \(step)") - guard opened else { return } - XCTAssertTrue(app.descendants(matching: .any)["usage.hosts.row.Desk Hermes"].waitForExistence(timeout: 45) - || app.descendants(matching: .any)["usage.hero"].exists, "Usage reads every computer \(step)") - app.navigationBars.buttons.element(boundBy: 0).tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 10), "Back to All agents") - } - - openUsage("on the list") - // Opening Desk Hermes' agent switches hosts; back on the list, Usage still opens. - named("Desk agent", in: app).tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 45), "Desk Hermes' chat opens") - swipeBackFromLeadingEdge(in: app) - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 10)) - openUsage("after switching hosts") - - // Away long enough for the connections to close, then back. - XCUIDevice.shared.press(.home) - XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10)) - sleep(35) - app.activate() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 20)) - XCTAssertTrue(agent(on: "Lab Hermes", in: app).waitForExistence(timeout: 45)) - openUsage("after coming back") - - // The way people usually get here: the app opens with All hosts already on. - app.terminate() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts"] - app.launch() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 30), "Opens on All agents") - XCTAssertTrue(agent(on: "Lab Hermes", in: app).waitForExistence(timeout: 45)) - openUsage("after opening the app") - } - - /// Secure input and a question in a chat on the host the all-hosts list switched to. - /// They were refused at once there, so the agent heard "declined" without the person - /// ever seeing the pop-up. - @MainActor func testSecureInputAndQuestionsWorkInAChatOnTheOtherHost() throws { - guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { - throw XCTSkip("Run through Scripts/HostSignInMatrixProbe.py --modes fleet") - } - probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) - guard probe["mode"] == "fleet" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - try addHost(app, address: try XCTUnwrap(probe["address_a"]), name: "Desk Hermes") - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.hosts"].tap() - app.buttons["menu.host.add"].tap() - try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - XCTAssertTrue(menu.waitForExistence(timeout: 20)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - let desk = named("Desk agent", in: app) - XCTAssertTrue(desk.waitForExistence(timeout: 45)) - desk.tap() - - let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 45), "Desk Hermes' chat opens") - send("secure input test", composer: composer, in: app) - let field = app.secureTextFields["direct-hermes.secure-input"] - XCTAssertTrue(field.waitForExistence(timeout: 30), "The secure pop-up appears on the other host's chat") - save("fleet-5-secure-pop-up", app) - field.tap() - field.typeText("fixture-value-not-a-secret") - app.buttons["direct-hermes.secure-submit"].tap() - let saved = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "Secure input fixture: saved.")).firstMatch - XCTAssertTrue(saved.waitForExistence(timeout: 30), "The agent got the value, not a refusal") - save("fleet-6-secure-saved", app) - - send("question test", composer: composer, in: app) - let attention = app.descendants(matching: .any)["needs-you.deck"].firstMatch - XCTAssertTrue(attention.waitForExistence(timeout: 30), "The agent's question pops up on the other host's chat") - save("fleet-7-question", app) - // Answer it, so the turn ends before the next round. - // The question is both in the pop-up and in the chat behind it; answer the one on top. - func tapVisible(_ query: XCUIElementQuery, required: Bool = true, wait: TimeInterval = 10) { - let deadline = Date().addingTimeInterval(wait) - while Date() < deadline { - if let visible = query.allElementsBoundByIndex.last(where: { $0.isHittable && $0.isEnabled }) { - return visible.tap() - } - Thread.sleep(forTimeInterval: 0.3) - } - if required { XCTFail("Nothing to tap for \(query)") } - } - tapVisible(app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Alpha"))) - // One tap on a choice answers a single question; Done shows only when more is needed. - tapVisible(app.buttons.matching(NSPredicate(format: "label == %@", "Done")), required: false, wait: 3) - let answered = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "Question fixture answered")).firstMatch - XCTAssertTrue(answered.waitForExistence(timeout: 30), "The agent got the answer") - if attention.exists { app.buttons["needs-you.later"].tap() } - - // Over to the other host's agent and back, then ask again. - swipeBackFromLeadingEdge(in: app) - let lab = named("Lab agent", in: app) - XCTAssertTrue(lab.waitForExistence(timeout: 30)) - lab.tap() - XCTAssertTrue(composer.waitForExistence(timeout: 45), "Lab Hermes' chat opens") - swipeBackFromLeadingEdge(in: app) - XCTAssertTrue(desk.waitForExistence(timeout: 30)) - desk.tap() - XCTAssertTrue(composer.waitForExistence(timeout: 45), "Back on Desk Hermes' chat") - try secureInput(round: "after switching back", number: 2, composer: composer, in: app) - - // Away from the app long enough for its connections to close, then back to the same chat. - XCUIDevice.shared.press(.home) - XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10)) - sleep(35) - app.activate() - XCTAssertTrue(composer.waitForExistence(timeout: 45)) - try secureInput(round: "after coming back to the app", number: 3, composer: composer, in: app) - } - - /// Asks for secure input and answers it; each round must reach the agent as saved. - @MainActor private func secureInput(round: String, number: Int, composer: XCUIElement, - in app: XCUIApplication) throws { - let saved = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "Secure input fixture: saved.")) - let before = saved.count - let declined = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "Secure input fixture: not saved")) - let declinedBefore = declined.count - // Its own value each round: one already saved on the host isn't asked for again. - send("secure input test \(number)", composer: composer, in: app) - let field = app.secureTextFields["direct-hermes.secure-input"] - let shown = field.waitForExistence(timeout: 30) - save("fleet-secure-\(round.replacingOccurrences(of: " ", with: "-"))", app) - XCTAssertTrue(shown, "The secure pop-up appears \(round)") - XCTAssertEqual(declined.count, declinedBefore, "Not declined without asking \(round)") - guard shown else { return } - field.tap() - field.typeText("fixture-value-not-a-secret") - app.buttons["direct-hermes.secure-submit"].tap() - let more = expectation(for: NSPredicate(format: "count > %d", before), evaluatedWith: saved) - wait(for: [more], timeout: 30) - } - - @MainActor private func send(_ message: String, composer: XCUIElement, in app: XCUIApplication) { - composer.tap() - composer.typeText(message) - let send = app.buttons["chat.send"] - let deadline = Date().addingTimeInterval(30) - while !send.isEnabled, Date() < deadline { Thread.sleep(forTimeInterval: 0.3) } - send.tap() - } - - /// Seconds from tapping an agent to its chat, with the given message, on screen. - @MainActor private func timeToOpen(_ agent: XCUIElement, showing message: String, - in app: XCUIApplication) throws -> Double { - XCTAssertTrue(agent.waitForExistence(timeout: 30)) - let text = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", message)).firstMatch - let start = Date() - agent.tap() - XCTAssertTrue(text.waitForExistence(timeout: 60), "The agent's own chat opens on its host") - return (Date().timeIntervalSince(start) * 100).rounded() / 100 - } - - /// Sends a message and waits for the agent's reply, so the chat is saved on the host. - @MainActor private func say(_ message: String, in app: XCUIApplication) throws { - let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 45), "The agent's chat opens on its own host") - composer.tap() - composer.typeText(message) - let send = app.buttons["chat.send"] - let deadline = Date().addingTimeInterval(30) - while !send.isEnabled, Date() < deadline { Thread.sleep(forTimeInterval: 0.3) } - send.tap() - let reply = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "fixture complete")).firstMatch - XCTAssertTrue(reply.waitForExistence(timeout: 45), "The agent replies") - } - - @MainActor private func named(_ name: String, in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "(identifier BEGINSWITH 'fleet.agent.' OR identifier BEGINSWITH " - + "'fleet.pinned.') AND label BEGINSWITH %@", name)).firstMatch - } - - @MainActor private func report(_ timings: [String: Double]) { - let json = (try? JSONSerialization.data(withJSONObject: timings, options: [.sortedKeys])) ?? Data() - let attachment = XCTAttachment(data: json, uniformTypeIdentifier: "public.json") - attachment.name = "fleet-timings" - attachment.lifetime = .keepAlways - add(attachment) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? json.write(to: URL(fileURLWithPath: folder).appendingPathComponent("fleet-timings.json")) - } - - @MainActor private func agent(on host: String, in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "(identifier BEGINSWITH 'fleet.agent.' OR identifier BEGINSWITH " - + "'fleet.pinned.') AND label CONTAINS %@", host)).firstMatch - } - - @MainActor private func addHost(_ app: XCUIApplication, address: String, name: String) throws { - let field = app.textFields["host-setup.address"] - XCTAssertTrue(field.waitForExistence(timeout: 15)) - field.tap() - field.typeText(address) - app.buttons["More options"].firstMatch.tap() - let nameField = app.textFields["host-setup.name"] - if nameField.waitForExistence(timeout: 3) { - nameField.tap() - // Return closes the keyboard, which otherwise covers Continue. - nameField.typeText(name + "\n") - } - // An open host connects straight from the address. - tapConnect(app) - let next = app.buttons["host-setup.continue"] - XCTAssertTrue(next.waitForExistence(timeout: 45), "Connected to \(name)") - next.tap() - } - - @MainActor private func tapConnect(_ app: XCUIApplication) { - let connect = app.buttons["host-setup.connect-host"] - for _ in 0..<5 where !(connect.exists && connect.isHittable) { app.swipeUp() } - XCTAssertTrue(connect.waitForExistence(timeout: 8)) - connect.tap() - } - - @MainActor private func save(_ name: String, _ app: XCUIApplication) { - let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) - shot.name = name - shot.lifetime = .keepAlways - add(shot) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? XCUIScreen.main.screenshot().pngRepresentation - .write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } -} diff --git a/BighelpUITests/AllHostsUITests.swift b/BighelpUITests/AllHostsUITests.swift deleted file mode 100644 index dc1160d1..00000000 --- a/BighelpUITests/AllHostsUITests.swift +++ /dev/null @@ -1,381 +0,0 @@ -import XCTest - -/// The all-hosts view: ☰'s switch lists every agent on every host with its -/// host tagged, a tap opens that agent's chat, and a one-host screen like -/// Settings asks which host first. Demo hosts: Home Hermes (the demo's own -/// agents), Studio Mac (sample agents) and Office Linux (out of reach). -/// Set BIGHELP_FLEET_EVIDENCE (TEST_RUNNER_…) to save screenshots. -final class AllHostsUITests: BighelpUITestCase { - @MainActor - func testAllHostsListOpensAgentsAndAsksWhichHostForSettings() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO"] - app.launch() - - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let toggle = app.buttons["menu.all-hosts"] - XCTAssertTrue(toggle.waitForExistence(timeout: 5)) - XCTAssertEqual(toggle.label, "Show all hosts", "Several bots: a tap shows every host") - toggle.tap() - - XCTAssertTrue(app.descendants(matching: .any)["fleet.home"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 5)) - let mina = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(mina.waitForExistence(timeout: 5)) - XCTAssertTrue(mina.label.contains("Home Hermes"), mina.label) - let sage = app.buttons["fleet.agent.Sage Ortiz"] - XCTAssertTrue(sage.waitForExistence(timeout: 5), "Another host's agents are listed too") - XCTAssertTrue(sage.label.contains("Studio Mac"), sage.label) - XCTAssertTrue(app.descendants(matching: .any)["fleet.host-note.Office Linux"].exists, - "A host out of reach says so") - XCTAssertTrue(mina.label.contains("Travel agent"), "Each agent's role shows under its name: \(mina.label)") - XCTAssertTrue(app.buttons["fleet.new-chat"].isHittable, "One big New chat, bottom right") - - // Touch and hold a pinned agent and drag it: the new order stays. - let pinned = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fleet.pinned.'")) - XCTAssertGreaterThanOrEqual(pinned.count, 2) - let before = pinned.allElementsBoundByIndex.map(\.identifier) - pinned.element(boundBy: 0).press(forDuration: 0.8, thenDragTo: pinned.element(boundBy: 1), - withVelocity: .slow, thenHoldForDuration: 0.6) - let after = pinned.allElementsBoundByIndex.map(\.identifier) - XCTAssertEqual(after, [before[1], before[0]] + before.dropFirst(2), "Dragged into a new place") - XCTAssertFalse(pinned.element(boundBy: 0).label.contains("Home Hermes"), "Pinned agents skip the host name") - save("list", app) - - // A tap opens that agent's own chat. ☰ is top left, and an edge swipe goes back to the list. - mina.tap() - let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 5)) - XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label == %@", "Mina Shah")) - .firstMatch.exists, "It's Mina's chat") - XCTAssertTrue(app.buttons["chat.menu"].firstMatch.exists, "The chat has ☰") - XCTAssertFalse(app.buttons["chat.back"].firstMatch.exists, "The chat has no Back button") - swipeBackFromLeadingEdge(in: app) - XCTAssertTrue(mina.waitForExistence(timeout: 5)) - - // Settings belongs to one host: pick which. - menu.tap() - XCTAssertEqual(app.buttons["menu.all-hosts"].label, "Show one host", "One bot: a tap goes back to one host") - app.buttons["menu.settings"].tap() - let pickHome = app.buttons["fleet.gate.host.Home Hermes"] - XCTAssertTrue(pickHome.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["fleet.gate.host.Studio Mac"].exists) - save("which-host", app) - pickHome.tap() - XCTAssertTrue(app.navigationBars["Settings"].waitForExistence(timeout: 5)) - closeSettings(in: app) - - // ☰ › Agents is All agents here, right under New chat. One-computer places (Projects, - // Kanban) ask which computer; the one-host Agents row isn't in this menu. - menu.tap() - let agentsRow = app.buttons["menu.all-agents"] - XCTAssertTrue(agentsRow.waitForExistence(timeout: 5)) - XCTAssertEqual(agentsRow.label, "Agents") - XCTAssertLessThan(app.buttons["menu.new-chat"].frame.minY, agentsRow.frame.minY, "New chat comes first") - for hidden in ["menu.agents", "menu.new-group"] { - XCTAssertFalse(app.buttons[hidden].exists, "\(hidden) isn't in the all-hosts menu") - } - XCTAssertTrue(app.buttons["menu.projects"].exists, "Projects asks which computer, like Settings") - save("menu-all-hosts", app) - agentsRow.tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 5)) - - // Top right is All agents' options now; ☰'s switch goes back to one host, its own chat list. - XCTAssertFalse(app.buttons["fleet.toggle"].exists) - XCTAssertTrue(app.buttons["fleet.organize"].exists) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(app.navigationBars["Sessions"].waitForExistence(timeout: 5)) - XCTAssertFalse(app.descendants(matching: .any)["fleet.home"].exists) - } - - /// Switching agents from a chat's header keeps the all-hosts view: the new - /// agent's chat has ☰, an edge swipe goes back to All agents, and no one-host tab bar (Feed, - /// Ideas, Goals), so nothing strands you on one host's screens. - @MainActor - func testSwitchingAgentFromChatStaysInAllHosts() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO"] - app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - XCTAssertTrue(app.buttons["menu.all-hosts"].waitForExistence(timeout: 5)) - save("menu-one-host", app) - app.buttons["menu.all-hosts"].tap() - let mina = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(mina.waitForExistence(timeout: 5)) - save("list-with-one-bot-switch", app) - mina.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["tab.feed"].exists, "An all-hosts chat has the bottom menu, for this agent") - - app.buttons["agent.hero.name"].tap() - let other = app.buttons["agent.switcher.agent.finance"] - XCTAssertTrue(other.waitForExistence(timeout: 5)) - other.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["chat.menu"].firstMatch.waitForExistence(timeout: 5), - "The switched-to chat has ☰") - XCTAssertTrue(app.buttons["tab.feed"].waitForExistence(timeout: 2), - "The switched-to agent's chat has its Feed, Ideas and Goals too") - save("switched-agent", app) - - swipeBackFromLeadingEdge(in: app) - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 5), "An edge swipe returns to All agents") - XCTAssertTrue(mina.waitForExistence(timeout: 5)) - menu.tap() - XCTAssertTrue(app.buttons["menu.all-hosts"].waitForExistence(timeout: 5)) - save("menu-all-hosts", app) - } - - /// Hold a pinned agent and let go to unpin it; long-press any agent's row to pin it. - @MainActor - func testPinnedAgentsCanBeUnpinnedAndPinnedAgain() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO"] - app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - for name in ["Rio Tanaka", "Avery Park"] { // another host's agent, then the selected host's - let tile = app.descendants(matching: .any)["fleet.pinned.\(name)"] - XCTAssertTrue(tile.waitForExistence(timeout: 5), "\(name) is pinned") - tile.press(forDuration: 1.0) - let unpin = app.buttons["Unpin"].firstMatch - XCTAssertTrue(unpin.waitForExistence(timeout: 3), "Holding a pinned agent offers Unpin") - unpin.tap() - XCTAssertFalse(tile.waitForExistence(timeout: 2), "\(name) left the pinned agents") - let row = app.buttons["fleet.agent.\(name)"] - XCTAssertTrue(row.waitForExistence(timeout: 3), "\(name) is in the list now") - } - let row = app.buttons["fleet.agent.Rio Tanaka"] - row.press(forDuration: 1.0) - let pin = app.buttons["Pin"].firstMatch - XCTAssertTrue(pin.waitForExistence(timeout: 3), "A row's menu offers Pin") - pin.tap() - XCTAssertTrue(app.descendants(matching: .any)["fleet.pinned.Rio Tanaka"].waitForExistence(timeout: 3), - "Pinned again") - } - - /// A swipe that starts on the pinned agents scrolls the list like anywhere - /// else; only touch and hold picks an agent up. - @MainActor - func testSwipingOnPinnedAgentsScrollsTheList() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO", - "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXL"] - app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - let pinned = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH 'fleet.pinned.'")) - XCTAssertTrue(pinned.firstMatch.waitForExistence(timeout: 5)) - let order = pinned.allElementsBoundByIndex.map(\.identifier) - let tile = pinned.firstMatch - - // Control: a swipe on an agent row scrolls. - let row = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(row.waitForExistence(timeout: 5)) - let rowTop = row.frame.minY - swipeUp(from: row, in: app) - XCTAssertLessThan(row.frame.minY, rowTop - 40, "The list scrolls (control)") - swipeDown(in: app) - let tileTop = tile.frame.minY - - swipeUp(from: tile, in: app) - // A list long enough scrolls the tiles out of view altogether. - XCTAssertTrue(!tile.exists || tile.frame.minY < tileTop - 40, - "A swipe that starts on a pinned agent scrolls the list") - swipeDown(in: app) - XCTAssertTrue(tile.waitForExistence(timeout: 5)) - XCTAssertEqual(pinned.allElementsBoundByIndex.map(\.identifier), order, "A swipe doesn't rearrange them") - } - - /// Hide an agent and show it again; file it into a new section; delete - /// the section (the agent stays) and Undo. Demo hosts keep it on screen. - @MainActor - func testAgentsHideAndFileIntoSections() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "YES"] - app.launch() - - let mina = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(mina.waitForExistence(timeout: 10)) - XCTAssertTrue(app.descendants(matching: .any)["fleet.group.Launch crew"].exists, - "Group chats list beside agents") - shot("list", app) - - mina.press(forDuration: 1.0) - XCTAssertTrue(app.buttons["Hide from list"].waitForExistence(timeout: 5)) - shot("agent-menu", app) - app.buttons["Hide from list"].tap() - XCTAssertTrue(mina.waitForNonExistence(timeout: 5), "A hidden agent leaves the list") - - app.buttons["fleet.organize"].tap() - let showHidden = app.descendants(matching: .any) - .matching(NSPredicate(format: "label CONTAINS %@", "Show hidden agents (1)")).firstMatch - XCTAssertTrue(showHidden.waitForExistence(timeout: 5)) - shot("organize-menu", app) - showHidden.tap() - XCTAssertTrue(mina.waitForExistence(timeout: 5), "Shown again, dimmed, to unhide") - XCTAssertEqual(mina.value as? String, "Hidden") - shot("hidden-shown", app) - mina.press(forDuration: 1.0) - app.buttons["Show in list"].tap() - - mina.press(forDuration: 1.0) - app.buttons["Move to section"].tap() - app.buttons["New section"].tap() - let field = app.alerts.textFields.firstMatch - XCTAssertTrue(field.waitForExistence(timeout: 5)) - shot("new-section", app) - field.typeText("Trips") - app.alerts.buttons["Create"].firstMatch.tap() - let trips = app.descendants(matching: .any)["fleet.section.Trips"] - XCTAssertTrue(trips.waitForExistence(timeout: 5)) - shot("filed", app) - - app.buttons["fleet.section.menu.Trips"].tap() - app.buttons["Delete section"].tap() - XCTAssertTrue(trips.waitForNonExistence(timeout: 5)) - XCTAssertTrue(mina.exists, "Deleting a section never deletes its agents") - let undo = app.buttons["fleet.section.undo"] - XCTAssertTrue(undo.waitForExistence(timeout: 5)) - shot("undo", app) - undo.tap() - XCTAssertTrue(trips.waitForExistence(timeout: 5)) - } - - /// Holding a pinned agent and holding an agent's row show the same kind - /// of menu, readable in light and dark. - @MainActor - func testHoldingPinnedAgentShowsItsMenu() throws { - for appearance in ["light", "dark"] { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "YES", - "-loopdy.demo.appearance", appearance] - app.launch() - let tile = app.descendants(matching: .any)["fleet.pinned.Avery Park"] - XCTAssertTrue(tile.waitForExistence(timeout: 10)) - tile.press(forDuration: 1.0) - XCTAssertTrue(app.buttons["Unpin"].firstMatch.waitForExistence(timeout: 3), "Holding a pinned agent offers Unpin") - XCTAssertTrue(app.buttons["Hide from list"].firstMatch.exists, "The same menu as the agent's row") - XCTAssertTrue(app.buttons["Move to section"].firstMatch.exists) - sleep(1) - shot("pinned-menu-\(appearance)", app) - app.terminate() - - app.launch() - let row = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(row.waitForExistence(timeout: 10)) - row.press(forDuration: 1.0) - XCTAssertTrue(app.buttons["Pin"].firstMatch.waitForExistence(timeout: 3)) - sleep(1) - shot("row-menu-\(appearance)", app) - app.terminate() - } - } - - /// New chat picks one agent and opens its chat. Its Group chat button - /// picks several agents, from any hosts, and Create chat makes the group - /// on the first one's host and opens it. Organize no longer starts group chats. - @MainActor - func testNewChatPicksOneAgentOrSeveralForAGroup() throws { - for appearance in ["light", "dark"] { newChatPicksOneAgentOrSeveralForAGroup(appearance) } - } - - @MainActor - private func newChatPicksOneAgentOrSeveralForAGroup(_ appearance: String) { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "YES", - "-preview-group-create", // demo group chats can be created - "-loopdy.demo.appearance", appearance] - app.launch() - - let organize = app.buttons["fleet.organize"] - XCTAssertTrue(organize.waitForExistence(timeout: 10)) - organize.tap() - XCTAssertTrue(app.buttons["fleet.organize.new-section"].waitForExistence(timeout: 5)) - XCTAssertFalse(app.buttons["fleet.organize.new-group"].exists, "Group chats start from New chat now") - XCTAssertFalse(app.buttons["New group chat"].exists) - // Outside the menu, which opens down from the top right. - app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.6)).tap() - - // One agent: its chat opens, as before. - let newChat = app.buttons["fleet.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - let avery = app.buttons["fleet.new-chat.Avery Park"] - XCTAssertTrue(avery.waitForExistence(timeout: 5)) - shot("new-chat-\(appearance)", app) - avery.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 10), "Avery's new chat opens") - swipeBackFromLeadingEdge(in: app) - - // Several agents: Group chat, pick, Create chat. - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - let group = app.buttons["fleet.new-chat.group"] - XCTAssertTrue(group.waitForExistence(timeout: 5)) - group.tap() - let create = app.buttons["fleet.new-chat.create-group"] - XCTAssertTrue(create.waitForExistence(timeout: 5)) - XCTAssertFalse(create.isEnabled, "Nobody picked yet") - let mina = app.buttons["fleet.new-chat.Mina Shah"] - mina.tap() - XCTAssertEqual(mina.value as? String, "Selected") - XCTAssertFalse(create.isEnabled, "One agent isn't a group") - app.buttons["fleet.new-chat.Avery Park"].tap() - XCTAssertTrue(create.isEnabled) - let sage = app.buttons["fleet.new-chat.Sage Ortiz"] - XCTAssertTrue(sage.isEnabled, "Another host's agents can join too") - sage.tap() - XCTAssertEqual(sage.value as? String, "Selected") - XCTAssertTrue(app.descendants(matching: .any)["fleet.new-chat.group-note"].label.contains("The group lives on")) - shot("new-group-picked-\(appearance)", app) - create.tap() - XCTAssertTrue(app.buttons["chat.people"].waitForExistence(timeout: 10), "The new group chat opens") - XCTAssertTrue(app.descendants(matching: .any) - .matching(NSPredicate(format: "label CONTAINS %@", "Mina Shah, Avery Park")).firstMatch.exists, - "It's named after its agents, wherever they live") - shot("new-group-chat-\(appearance)", app) - app.terminate() - } - - /// Saves a screenshot into TEST_RUNNER_BIGHELP_FLEET_SHOTS when set. - @MainActor - private func shot(_ name: String, _ app: XCUIApplication) { - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_FLEET_SHOTS"] else { return } - try? app.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } - - @MainActor - private func swipeUp(from element: XCUIElement, in app: XCUIApplication) { - let start = element.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - start.press(forDuration: 0.01, thenDragTo: start.withOffset(CGVector(dx: 0, dy: -260)), - withVelocity: .fast, thenHoldForDuration: 0) - sleep(1) - } - - @MainActor - private func swipeDown(in app: XCUIApplication) { - let start = app.windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.75)) - start.press(forDuration: 0.01, thenDragTo: start.withOffset(CGVector(dx: 0, dy: 500)), - withVelocity: .fast, thenHoldForDuration: 0) - sleep(1) - } - - @MainActor - private func save(_ name: String, _ app: XCUIApplication) { - guard ProcessInfo.processInfo.environment["BIGHELP_FLEET_EVIDENCE"] != nil else { return } - let attachment = XCTAttachment(screenshot: app.screenshot()) - attachment.name = "all-hosts-\(name)" - attachment.lifetime = .keepAlways - add(attachment) - } -} diff --git a/BighelpUITests/AppLayoutUITests.swift b/BighelpUITests/AppLayoutUITests.swift deleted file mode 100644 index 08c43cd1..00000000 --- a/BighelpUITests/AppLayoutUITests.swift +++ /dev/null @@ -1,172 +0,0 @@ -import XCTest - -/// Settings › Appearance › App layout on demo data: Feed, Ideas and Goals leave the bottom -/// bar for Kanban, Workflows and Scheduled tasks, and stay one tap away in ☰. -/// Set BIGHELP_APP_LAYOUT_EVIDENCE (TEST_RUNNER_…) to save screenshots. -final class AppLayoutUITests: BighelpUITestCase { - @MainActor - func testSwappingBoardsForPagesKeepsBoardsInTheMenu() throws { - let app = makeApp() - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays"] - app.launch() - XCTAssertTrue(app.buttons["tab.feed"].waitForExistence(timeout: 20), "Feed starts in the bottom bar") - - openAppLayout(in: app) - save("app-layout-standard", app) - for place in ["feed", "ideas", "goals"] { - let remove = app.buttons["app-layout.remove.\(place)"] - XCTAssertTrue(remove.waitForExistence(timeout: 5), place) - remove.tap() - } - for place in ["kanban", "workflows", "scheduledTasks"] { - let add = app.buttons["app-layout.add.\(place)"] - XCTAssertTrue(scrollTo(add, in: app), place) - add.tap() - } - XCTAssertTrue(scrollTo(app.descendants(matching: .any)["app-layout.menu.feed"], in: app), - "Feed moved to the menu") - save("app-layout-custom", app) - for _ in 0..<4 { app.swipeDown() } - XCTAssertTrue(app.descendants(matching: .any)["app-layout.bar.kanban"].waitForExistence(timeout: 5)) - - // Back to the app: the bar holds the pages now. - closeSettings(in: app) - let kanban = app.buttons["tab.kanban"] - XCTAssertTrue(kanban.waitForExistence(timeout: 10), "Kanban is in the bottom bar") - XCTAssertTrue(app.buttons["tab.workflows"].exists && app.buttons["tab.scheduled-tasks"].exists) - XCTAssertFalse(app.buttons["tab.feed"].exists, "Feed left the bar") - kanban.tap() - XCTAssertTrue(app.buttons["tab.kanban"].waitForExistence(timeout: 5), "The bar stays on its tab") - XCTAssertTrue(app.buttons["tab.kanban"].isSelected) - save("app-layout-kanban-tab", app) - - // Feed is still one tap away in ☰. - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - menu.tap() - let feed = app.buttons["menu.feed"] - XCTAssertTrue(scrollTo(feed, in: app), "Feed is in the menu") - XCTAssertFalse(app.buttons["menu.kanban"].exists, "Kanban isn't listed twice") - save("app-layout-menu", app) - feed.tap() - XCTAssertTrue(app.descendants(matching: .any)["board.feed"].waitForExistence(timeout: 10), "Feed opens") - save("app-layout-feed", app) - } - - /// ☰ › Sessions opens every chat, easier to find than Recent sessions' See all. Pinned, it's - /// a tab of its own while Chat stays the agent's chat. - @MainActor - func testSessionsOpensEveryChatFromTheMenuAndItsOwnTab() throws { - for appearance in ["light", "dark"] { - let app = makeApp() - // Each pass starts from the standard layout: saved settings reset once per run ID. - app.launchEnvironment["BIGHELP_UI_TEST_RUN_ID"] = UUID().uuidString - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-bighelp.hosts.all-hosts", "NO", "-loopdy.demo.appearance", appearance] - app.launch() - XCTAssertTrue(chatIdentity(in: app).waitForExistence(timeout: 30), "Chat opens the agent's chat") - - // The chat's ☰ has its own name. - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["chat.menu", "home.drawer.open"])) - .firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - menu.tap() - let sessions = app.buttons["menu.sessions"] - XCTAssertTrue(sessions.waitForExistence(timeout: 5), "Sessions has its own row in the menu") - save("sessions-menu-\(appearance)", app) - sessions.tap() - let list = app.descendants(matching: .any)["sessions.screen"] - XCTAssertTrue(list.waitForExistence(timeout: 10), "The menu's Sessions opens every chat") - save("sessions-list-from-menu-\(appearance)", app) - - openAppLayout(in: app) - let add = app.buttons["app-layout.add.sessions"] - // The bar is full (Feed, Ideas, Goals): one place makes room. - app.buttons["app-layout.remove.goals"].tap() - XCTAssertTrue(scrollTo(add, in: app), "Sessions can go in the bottom bar") - add.tap() - for _ in 0..<4 { app.swipeDown() } - XCTAssertTrue(app.descendants(matching: .any)["app-layout.bar.sessions"].waitForExistence(timeout: 5)) - save("sessions-app-layout-\(appearance)", app) - closeSettings(in: app) - - let tab = app.buttons["tab.session-list"] - XCTAssertTrue(tab.waitForExistence(timeout: 10), "Sessions is in the bottom bar") - XCTAssertTrue(list.exists && tab.isSelected, "The list is Sessions' tab") - XCTAssertFalse(app.buttons["tab.sessions"].isSelected) - app.buttons["tab.sessions"].tap() - XCTAssertTrue(chatIdentity(in: app).waitForExistence(timeout: 10), "Chat still opens the agent's chat") - app.buttons["tab.session-list"].firstMatch.tap() - XCTAssertTrue(list.waitForExistence(timeout: 10), "The Sessions tab opens every chat") - XCTAssertTrue(app.buttons["tab.session-list"].firstMatch.isSelected) - save("sessions-tab-\(appearance)", app) - app.terminate() - } - } - - @MainActor - func testResetAsksFirstThenRestoresTheDefaultLayout() throws { - let app = makeApp() - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays"] - app.launch() - openAppLayout(in: app) - let reset = app.buttons["app-layout.reset"] - XCTAssertTrue(scrollTo(reset, in: app)) - XCTAssertFalse(reset.isEnabled, "Nothing to reset yet") - - app.swipeDown(); app.swipeDown() - app.buttons["app-layout.remove.goals"].tap() - XCTAssertTrue(scrollTo(reset, in: app)) - XCTAssertTrue(reset.isEnabled) - reset.tap() - let confirm = app.alerts.buttons["Reset"].firstMatch - XCTAssertTrue(confirm.waitForExistence(timeout: 5), "It asks first") - save("app-layout-reset-confirm", app) - app.alerts.buttons["Cancel"].firstMatch.tap() - XCTAssertTrue(reset.isEnabled, "Cancel keeps the change") - - reset.tap() - XCTAssertTrue(confirm.waitForExistence(timeout: 5)) - confirm.tap() - for _ in 0..<4 { app.swipeDown() } - XCTAssertTrue(app.descendants(matching: .any)["app-layout.bar.goals"].waitForExistence(timeout: 5), - "Goals is back in the bottom bar") - XCTAssertTrue(scrollTo(reset, in: app)) - XCTAssertFalse(reset.isEnabled, "Back to the default") - } - - @MainActor private func openAppLayout(in app: XCUIApplication) { - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let settings = app.buttons["menu.settings"] - XCTAssertTrue(scrollTo(settings, in: app)) - settings.tap() - let appearance = settingsRow("settings.themes", in: app) - XCTAssertTrue(appearance.waitForExistence(timeout: 5)) - appearance.tap() - let layout = app.buttons["settings.appearance.app-layout"] - XCTAssertTrue(scrollTo(layout, in: app), "App layout is under Appearance") - layout.tap() - XCTAssertTrue(app.descendants(matching: .any)["app-layout"].waitForExistence(timeout: 5)) - } - - @MainActor private func scrollTo(_ element: XCUIElement, in app: XCUIApplication) -> Bool { - for _ in 0..<8 { - if element.waitForExistence(timeout: 1), element.isHittable { return true } - app.swipeUp() - } - return element.exists && element.isHittable - } - - @MainActor private func save(_ name: String, _ app: XCUIApplication) { - let screenshot = XCUIScreen.main.screenshot() - let shot = XCTAttachment(screenshot: screenshot) - shot.name = name - shot.lifetime = .keepAlways - add(shot) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_APP_LAYOUT_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? screenshot.pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } -} diff --git a/BighelpUITests/AppReviewHostUITests.swift b/BighelpUITests/AppReviewHostUITests.swift index f1f3f80e..11bca818 100644 --- a/BighelpUITests/AppReviewHostUITests.swift +++ b/BighelpUITests/AppReviewHostUITests.swift @@ -12,9 +12,13 @@ final class AppReviewHostUITests: BighelpUITestCase { throw XCTSkip("Set BIGHELP_REVIEW_HOST to the App Review host's address") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: address) + // Bots › the primary bot opens its chat. + showBots(in: app) + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 30), "Bots has the primary bot") + primary.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 30), "The agent's chat opens") save("1-chat", app) diff --git a/BighelpUITests/AppStoreScreenshotUITests.swift b/BighelpUITests/AppStoreScreenshotUITests.swift index 0165389f..a5808b15 100644 --- a/BighelpUITests/AppStoreScreenshotUITests.swift +++ b/BighelpUITests/AppStoreScreenshotUITests.swift @@ -43,7 +43,8 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { ["host-setup.connect-host", "host-setup.screen"], ["Continue", "Connect"])).firstMatch.tap() XCTAssertTrue(continueAfterConnecting(app), "Connected") - // Juno, the everyday agent, opens first. + // Juno, the everyday agent (`default`), opens first. + try openAgent("default", in: app) try ask("Put this week's highlights on my Feed, and keep track of my goals.", until: "two ideas waiting", in: app) try newChat(in: app) @@ -74,13 +75,13 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { revealCardTop("Lisbon packing list", in: app) save("02-packing", app) - // Bots mode's home on the same host, after the agents' chats above. The same app + // Bots on the same host, after the agents' chats above. The same app // (and run ID) relaunched, so it stays connected. app.terminate() - app.launchArguments += ["-bighelp.settings.simple-bots", "YES"] + app.launchArguments += ["-loopdy.home.landing", "bots"] app.launch() let home = app.descendants(matching: .any)["simple-bots.home"] - XCTAssertTrue(home.waitForExistence(timeout: 60), "Bots mode opens on its home") + XCTAssertTrue(home.waitForExistence(timeout: 60), "The app opens on Bots") for id in ["penny", "atlas"] { let bot = app.descendants(matching: .any).matching(NSPredicate(format: "identifier IN %@", ["simple-bots.bot.\(id)", "simple-bots.pinned.\(id)"])).firstMatch @@ -104,17 +105,12 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { app.terminate() app.launchArguments.removeLast(2) app.launch() - // The home chat opens over the launch screen: let it settle before reaching for ☰. - sleep(4) - openMenu(in: app) - save("06-menu", app) - tapMenuRow("menu.kanban", in: app) + // Work › Tasks (Kanban) and Work › Schedules. + openWorkDoor("tasks", in: app) sleep(3) save("07-kanban", app) - goBack(app) - openMenu(in: app) - tapMenuRow("menu.scheduled-tasks", in: app) + openWorkDoor("schedules", in: app) sleep(3) save("09-scheduled", app) } @@ -136,7 +132,6 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { return false } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] if let zone = environment("BIGHELP_STORE_TZ") { app.launchEnvironment["TZ"] = zone } app.launch() return app @@ -159,59 +154,29 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { BighelpKeyboardDismissal.dismiss(in: app) } + /// New chat with Juno (`default`). @MainActor private func newChat(in app: XCUIApplication) throws { - let new = app.buttons.matching(NSPredicate(format: "identifier IN %@", - ["chat.new-chat", "chat.home.new-chat", "root.new-chat"])).firstMatch - XCTAssertTrue(new.waitForExistence(timeout: 10)) - new.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "default", in: app) sleep(2) } + /// Bots › the agent's row (in the list, pinned or the primary bot) opens its chat. @MainActor private func openAgent(_ id: String, in app: XCUIApplication) throws { - openMenu(in: app) - tapMenuRow("menu.agents", in: app) - let row = app.buttons["agent.\(id)"].firstMatch + showBots(in: app, timeout: 30) + let row = app.buttons.matching(NSPredicate(format: "identifier IN %@", [ + "simple-bots.bot.\(id)", "simple-bots.pinned.\(id)", "simple-bots.primary.\(id)", + ])).firstMatch // A short screen (the Duo's cover) draws the rows below the fold once scrolled to. - let list = app.descendants(matching: .any)["agents.screen"].firstMatch + let list = app.descendants(matching: .any)["simple-bots.home"].firstMatch for _ in 0..<4 where !row.waitForExistence(timeout: 3) || !row.isHittable { list.swipeUp() } - XCTAssertTrue(row.waitForExistence(timeout: 15), "\(id) is in Agents") + XCTAssertTrue(row.waitForExistence(timeout: 15), "\(id) is on Bots") row.tap() sleep(2) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 20), "\(id)'s chat opens") } - @MainActor - private func openMenu(in app: XCUIApplication) { - let menu = [app.buttons["home.drawer.open"].firstMatch, app.buttons["chat.menu"].firstMatch] - let deadline = Date().addingTimeInterval(15) - while Date() < deadline { - // A button that's in the tree but not laid out yet has no frame to hit-test. - if let button = menu.first(where: { $0.exists && $0.frame.minX.isFinite && !$0.frame.isEmpty && $0.isHittable }) { - button.tap() - break - } - // The board tabs have no ☰; it's on the chat tab and pushed screens. - let chatTab = app.buttons["tab.sessions"].firstMatch - if chatTab.exists, chatTab.isHittable { chatTab.tap() } else { goBack(app) } - sleep(1) - } - _ = app.descendants(matching: .any)["navigation.menu"].waitForExistence(timeout: 10) - sleep(1) - } - - @MainActor - private func tapMenuRow(_ identifier: String, in app: XCUIApplication) { - let row = app.buttons[identifier].firstMatch - let list = app.descendants(matching: .any)["navigation.menu"].firstMatch - for _ in 0..<6 where !(row.exists && row.isHittable) { list.swipeUp() } - XCTAssertTrue(row.waitForExistence(timeout: 10), identifier) - row.tap() - sleep(2) - } - @MainActor private func openTab(_ identifier: String, in app: XCUIApplication) { openRootTab(identifier, in: app, timeout: 15) @@ -233,14 +198,15 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { XCTAssertTrue(post.exists, "\(text) is on the page") } - /// The reply's card, reopening the chat from ☰ once if the card hasn't drawn. + /// The reply's card, reopening the chat from Chats once if the card hasn't drawn. @MainActor private func expectCard(_ title: String, chat: String, in app: XCUIApplication) throws { let card = app.staticTexts[title].firstMatch if card.waitForExistence(timeout: 10) { return } - openMenu(in: app) - let row = app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", chat)).firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 10), "\(chat) is in Recent chats") + showChats(in: app) + let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS %@", + "chats.row.", chat)).firstMatch + XCTAssertTrue(row.waitForExistence(timeout: 10), "\(chat) is in Chats") row.tap() XCTAssertTrue(card.waitForExistence(timeout: 20), "The \(title) card shows") } @@ -274,16 +240,6 @@ final class AppStoreScreenshotUITests: BighelpUITestCase { sleep(2) } - @MainActor - private func goBack(_ app: XCUIApplication) { - // Chats have ☰, not Back: leave them with an edge swipe. - if app.buttons["chat.menu"].firstMatch.exists { - swipeBackFromLeadingEdge(in: app); sleep(1); return - } - let back = app.navigationBars.buttons.firstMatch - if back.exists, back.frame.minX.isFinite, !back.frame.isEmpty, back.isHittable { back.tap(); sleep(1) } - } - private func environment(_ name: String) -> String? { ProcessInfo.processInfo.environment[name].flatMap { $0.isEmpty ? nil : $0 } } diff --git a/BighelpUITests/ArchivedChatsUITests.swift b/BighelpUITests/ArchivedChatsUITests.swift index eb8d6d64..234708ef 100644 --- a/BighelpUITests/ArchivedChatsUITests.swift +++ b/BighelpUITests/ArchivedChatsUITests.swift @@ -8,12 +8,16 @@ final class ArchivedChatsUITests: BighelpUITestCase { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3"] app.launch() - openRootTab("tab.sessions", in: app) - let filters = app.buttons["sessions.filters"].firstMatch - XCTAssertTrue(filters.waitForExistence(timeout: 15)) - filters.tap() - let archived = app.buttons["Archived Chats"].firstMatch - XCTAssertTrue(archived.waitForExistence(timeout: 5)) + // Chats › More › Archived opens Settings › Chat, which lists Archived chats. + showChats(in: app) + let more = app.buttons["chats.more.archived"].firstMatch + let inbox = app.descendants(matching: .any)["chats.inbox"].firstMatch + for _ in 0..<20 where !(more.exists && more.isHittable) { inbox.swipeUp(velocity: .fast) } + XCTAssertTrue(more.exists && more.isHittable, "Archived is at the end of Chats") + more.tap() + let archived = app.buttons["simple-bots.settings.archived"].firstMatch + XCTAssertTrue(archived.waitForExistence(timeout: 10)) + for _ in 0..<6 where !archived.isHittable { app.swipeUp() } archived.tap() let deletedChat = "travel/demo-archived-lisbon" diff --git a/BighelpUITests/AvatarCreatorUITests.swift b/BighelpUITests/AvatarCreatorUITests.swift index 0b3ce4f1..2c9c9bc0 100644 --- a/BighelpUITests/AvatarCreatorUITests.swift +++ b/BighelpUITests/AvatarCreatorUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Agents › an agent › Edit avatar: the chooser (Bot Studio, PetDex or a photo), Bot Studio's +/// A bot's page › Info › Character: the chooser (Bot Studio, PetDex or a photo), Bot Studio's /// drawer with every tab, Undo and Surprise me, and PetDex with only pets. /// BIGHELP_AVATAR_EVIDENCE (TEST_RUNNER_…) saves the screenshots; BIGHELP_AVATAR_APPEARANCE /// (light, dark) sets how they're drawn. @@ -60,13 +60,10 @@ final class AvatarCreatorUITests: BighelpUITestCase { app.buttons["bot.studio.undo"].firstMatch.tap() XCTAssertTrue(stage.label.hasSuffix("Peak"), "Undo takes back the surprise") + // The bot's page saves the avatar from the studio's own Save. app.buttons["bot.studio.save"].firstMatch.tap() - let saveAgent = app.buttons["agent.editor.save"].firstMatch - let ready = XCTNSPredicateExpectation(predicate: NSPredicate(format: "isEnabled == true"), object: saveAgent) - XCTAssertEqual(XCTWaiter.wait(for: [ready], timeout: 10), .completed) - save("editor-with-studio-avatar-\(appearance)", app) - saveAgent.tap() - XCTAssertTrue(saveAgent.waitForNonExistence(timeout: 10)) + XCTAssertTrue(stage.waitForNonExistence(timeout: 10), "Save closes the studio") + save("profile-with-studio-avatar-\(appearance)", app) openChooser(of: "finance", in: app) any["avatar.chooser.studio"].firstMatch.tap() @@ -160,20 +157,24 @@ final class AvatarCreatorUITests: BighelpUITestCase { save("petdex", app) } + /// Bots › the bot (its chat opens) › its pill › Info › Character. @MainActor private func openChooser(of agentID: String, in app: XCUIApplication) { - openAgents(in: app) - let more = app.buttons["agent.\(agentID).more"].firstMatch - XCTAssertTrue(more.waitForExistence(timeout: 10)) - for _ in 0..<6 where !more.isHittable { app.swipeUp() } - // The last row's button sits partly under the floating New chat button: tap its top. - more.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.2)).tap() - let edit = app.buttons["agent.\(agentID).edit"].firstMatch - XCTAssertTrue(edit.waitForExistence(timeout: 5)) - edit.tap() - let design = app.buttons["agent.editor.design-avatar"].firstMatch - XCTAssertTrue(design.waitForExistence(timeout: 10)) - design.tap() + showBots(in: app) + let bot = app.buttons.matching(NSPredicate(format: "identifier IN %@", [ + "simple-bots.bot.\(agentID)", "simple-bots.pinned.\(agentID)", "simple-bots.primary.\(agentID)", + ])).firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "Bots lists \(agentID)") + for _ in 0..<6 where !bot.isHittable { app.descendants(matching: .any)["simple-bots.home"].firstMatch.swipeUp() } + bot.tap() + openBotPage(fromChatIn: app) + let info = app.buttons["simple-bots.profile.tab.info"].firstMatch + XCTAssertTrue(info.waitForExistence(timeout: 5)) + info.tap() + let character = app.buttons["simple-bots.profile.character"].firstMatch + XCTAssertTrue(character.waitForExistence(timeout: 10)) + for _ in 0..<6 where !character.isHittable { app.swipeUp() } + character.tap() XCTAssertTrue(app.descendants(matching: .any)["avatar.chooser.studio"].firstMatch.waitForExistence(timeout: 10)) } diff --git a/BighelpUITests/BackgroundWorkHostUITests.swift b/BighelpUITests/BackgroundWorkHostUITests.swift index b86affc8..48fa533a 100644 --- a/BighelpUITests/BackgroundWorkHostUITests.swift +++ b/BighelpUITests/BackgroundWorkHostUITests.swift @@ -12,13 +12,14 @@ final class BackgroundWorkHostUITests: BighelpUITestCase { let environment = ProcessInfo.processInfo.environment guard let host = environment["BIGHELP_BACKGROUND_HOST"] else { throw XCTSkip("Set BIGHELP_BACKGROUND_HOST") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES", "-bighelp.chat.work-style", "card"] + app.launchArguments = ["-bighelp.chat.work-style", "card"] app.launch() try onboardOpenHost(app, address: host) let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 30), "The agent's chat opens") - // A new chat: the home chat is the person's own, and /model pins the chat it runs in. - chatNewChatButton(in: app).tap() + // A new chat: the Bot Chat is the person's own, and /model pins the chat it runs in. + let newChat = chatNewChatButton(in: app) + XCTAssertTrue(newChat.waitForExistence(timeout: 30), "Setup lands on the home") + newChat.tap() confirmNewChatPicker(in: app) XCTAssertTrue(composer.waitForExistence(timeout: 30), "A new chat opens") sleep(3) diff --git a/BighelpUITests/BigFileChatUITests.swift b/BighelpUITests/BigFileChatUITests.swift index b8613943..02ad77d5 100644 --- a/BighelpUITests/BigFileChatUITests.swift +++ b/BighelpUITests/BigFileChatUITests.swift @@ -65,7 +65,7 @@ final class BigFileChatUITests: BighelpUITestCase { @MainActor private func launch(_ hold: String, appearance: String) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-loopdy.demo.appearance", appearance, "-test-draft-attachments", hold] app.launch() return app diff --git a/BighelpUITests/BigFileHostUITests.swift b/BighelpUITests/BigFileHostUITests.swift index 7a4b51b2..c2408b3c 100644 --- a/BighelpUITests/BigFileHostUITests.swift +++ b/BighelpUITests/BigFileHostUITests.swift @@ -77,8 +77,7 @@ final class BigFileHostUITests: BighelpUITestCase { let next = app.buttons["host-setup.continue"] XCTAssertTrue(next.waitForExistence(timeout: 45), "Connected") next.tap() - let newChat = app.buttons.matching(NSPredicate(format: "identifier IN %@", - ["sessions.empty.new-chat", "chat.home.new-chat", "chat.new-chat", "root.new-chat"])).firstMatch + let newChat = app.buttons["home.new-chat"].firstMatch if newChat.waitForExistence(timeout: 10) { newChat.tap() confirmNewChatPicker(in: app) diff --git a/BighelpUITests/BighelpMenuUITests.swift b/BighelpUITests/BighelpMenuUITests.swift deleted file mode 100644 index 1931a7b1..00000000 --- a/BighelpUITests/BighelpMenuUITests.swift +++ /dev/null @@ -1,91 +0,0 @@ -import XCTest - -/// One menu (☰) with hosts, chats and everywhere else; the bighelp logo switches -/// hosts on touch and hold; Settings holds this app's settings and, in Nerd Mode, -/// the host's tools. Set BIGHELP_MENU_EVIDENCE (TEST_RUNNER_BIGHELP_MENU_EVIDENCE) to -/// save screenshots. -final class BighelpMenuUITests: BighelpUITestCase { - @MainActor - func testOneMenuHostsChatsAndSettings() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-use-multi-host-fixtures", - "-loopdy.demo.appearance", "dark"] - app.launch() - openSettings(in: app) - XCTAssertFalse(app.buttons["quick-workspace.menu"].exists, "The grid button is gone.") - save("01-settings", app) - closeSettings(in: app) - - // ☰: the host on top as one row, then the places you go, then recent chats. - tap(app.buttons["home.drawer.open"]) - let menu = app.descendants(matching: .any)["navigation.menu"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - let hostSwitcher = app.buttons["menu.hosts"].firstMatch - XCTAssertTrue(hostSwitcher.waitForExistence(timeout: 3), "One row switches hosts.") - XCTAssertTrue(app.buttons["menu.new-chat"].waitForExistence(timeout: 3)) - let newChat = app.buttons["menu.new-chat"] - XCTAssertGreaterThan(newChat.frame.minX, hostSwitcher.frame.maxX, "Its own button, right of the host") - XCTAssertLessThan(abs(newChat.frame.midY - hostSwitcher.frame.midY), 12, "On the host's row") - save("02-menu", app) - // Everything on the first screen is reachable without scrolling. - for id in ["menu.new-chat", "menu.agents", "menu.projects", "menu.scheduled-tasks", "menu.settings", "menu.chats"] { - XCTAssertTrue(app.buttons[id].isHittable, "\(id) shows without scrolling") - } - XCTAssertLessThan(app.buttons["menu.agents"].frame.minY, app.buttons["menu.settings"].frame.minY) - XCTAssertLessThan(app.buttons["menu.new-chat"].frame.minY, app.buttons["menu.agents"].frame.minY, - "New chat first, then Agents") - XCTAssertFalse(app.buttons["menu.new-group"].exists, "Group chats start from New chat's own picker") - XCTAssertFalse(app.buttons["menu.all-agents"].exists, "One host: Agents is this host's") - XCTAssertLessThan(app.buttons["menu.settings"].frame.maxY, app.buttons["menu.chats"].frame.minY, - "Recent chats come after the places you go") - hostSwitcher.tap() - let hosts = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "menu.host.")).allElementsBoundByIndex - XCTAssertFalse(hosts.isEmpty, "The switcher lists hosts.") - save("02b-host-switcher", app) - app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.95)).tap() - XCTAssertFalse(app.buttons["menu.hermes-tools"].exists, "The menu has no Hermes tools row.") - tap(app.buttons["menu.settings"]) - - // Settings has no Hermes tools list either: each tool is on the page it belongs to. - XCTAssertTrue(app.descendants(matching: .any)["settings.screen"].firstMatch.waitForExistence(timeout: 5)) - XCTAssertFalse(app.buttons["settings.hermes-tools"].exists) - save("03-settings", app) - closeSettings(in: app) - - // Touch and hold the logo to switch hosts. - let logo = app.buttons["brand.host-switcher"].firstMatch - XCTAssertTrue(logo.waitForExistence(timeout: 5)) - logo.press(forDuration: 1.0) - XCTAssertTrue(app.buttons["brand.host.add"].waitForExistence(timeout: 5)) - save("04-logo-host-switcher", app) - app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.9)).tap() - - // Settings: help and the computers live here; Apple Watch is a row on Help & feedback. - openSettings(in: app) - let help = app.buttons["settings.menu.help"].firstMatch - for _ in 0..<8 where !(help.exists && help.isHittable) { app.swipeUp() } - XCTAssertTrue(help.exists, "Settings has Help & feedback.") - save("05-settings-help", app) - tap(help) - XCTAssertTrue(app.staticTexts["Version"].waitForExistence(timeout: 5)) - } - - @MainActor - private func tap(_ element: XCUIElement) { - XCTAssertTrue(element.waitForExistence(timeout: 8), "Missing \(element)") - guard element.exists else { return } - element.tap() - sleep(1) - } - - @MainActor - private func save(_ name: String, _ app: XCUIApplication) { - let shot = XCTAttachment(screenshot: app.screenshot()) - shot.name = name - shot.lifetime = .keepAlways - add(shot) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_MENU_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? app.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } -} diff --git a/BighelpUITests/BoardSwipeBlueprintsUITests.swift b/BighelpUITests/BoardSwipeBlueprintsUITests.swift index 677b7417..352cd5dc 100644 --- a/BighelpUITests/BoardSwipeBlueprintsUITests.swift +++ b/BighelpUITests/BoardSwipeBlueprintsUITests.swift @@ -1,7 +1,7 @@ import XCTest -/// Swipe left to dismiss on Feed, Ideas and Goals, the Blueprints on each, and Goals by -/// category, in demo mode. BIGHELP_BOARD_EVIDENCE (a folder) also saves light and dark +/// Swipe left to dismiss on Feed, Ideas and Goals (Today › See all › one bot's board), the +/// Blueprints on each, and Goals by category, in demo mode. BIGHELP_BOARD_EVIDENCE (a folder) also saves light and dark /// screenshots for review. final class BoardSwipeBlueprintsUITests: BighelpUITestCase { /// Each board's rows reveal their own dismiss action, including a swipe that starts at @@ -16,7 +16,7 @@ final class BoardSwipeBlueprintsUITests: BighelpUITestCase { ("tab.goals", app.descendants(matching: .any)["board.goal.goal-4"], "Remove", true, false), ] for (tab, row, action, fromEdge, holds) in cases { - openRootTab(tab, in: app) + openBoard(tab, in: app) // Boards are Lists: rows below the fold don't exist until scrolled to. _ = app.buttons["board.blueprints"].waitForExistence(timeout: 10) scroll(app, until: row) @@ -41,7 +41,7 @@ final class BoardSwipeBlueprintsUITests: BighelpUITestCase { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) for (tab, pick) in [("tab.feed", "feed-marketing-1"), ("tab.ideas", "ideas-productivity-1")] { - openRootTab(tab, in: app) + openBoard(tab, in: app) let entry = app.buttons["board.blueprints"].firstMatch XCTAssertTrue(entry.waitForExistence(timeout: 10), "Blueprints on \(tab)") entry.tap() @@ -95,7 +95,7 @@ final class BoardSwipeBlueprintsUITests: BighelpUITestCase { func testGoalsGroupByCategoryAndStartOneFromTheList() throws { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) - openRootTab("tab.goals", in: app) + openBoard("tab.goals", in: app) let health = app.descendants(matching: .any)["board.goals.category.health"] XCTAssertTrue(health.waitForExistence(timeout: 10), "Goals are grouped by category") XCTAssertTrue(app.descendants(matching: .any)["board.goals.category.finance"].exists) @@ -125,7 +125,7 @@ final class BoardSwipeBlueprintsUITests: BighelpUITestCase { func testLetsDoItOpensAChatWithTheIdeaTitleOnly() throws { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) - openRootTab("tab.ideas", in: app) + openBoard("tab.ideas", in: app) let idea = app.buttons["board.idea.idea-1"] XCTAssertTrue(idea.waitForExistence(timeout: 10)) idea.tap() @@ -168,12 +168,21 @@ final class BoardSwipeBlueprintsUITests: BighelpUITestCase { @MainActor private func launch(appearance: String) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance, - "-loopdy.home.opens-chat", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() return app } + /// Today › the panel's board (`tab.feed|ideas|goals`) › See all › the demo's Avery (`finance`): + /// that bot's whole board. + @MainActor private func openBoard(_ tab: String, in app: XCUIApplication, + file: StaticString = #filePath, line: UInt = #line) { + openTodayBoard(tab.replacingOccurrences(of: "tab.", with: ""), in: app, file: file, line: line) + let bot = app.buttons["today.board-page.chip.finance"].firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "See all has the bot's chip", file: file, line: line) + bot.tap() + } + @MainActor private func save(_ name: String, _ app: XCUIApplication) { let shot = XCTAttachment(screenshot: app.screenshot()) shot.name = name diff --git a/BighelpUITests/BotActivityHostUITests.swift b/BighelpUITests/BotActivityHostUITests.swift index d91ebe11..0c8d2b13 100644 --- a/BighelpUITests/BotActivityHostUITests.swift +++ b/BighelpUITests/BotActivityHostUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// #504 on a real host with the bighelp plugin: Bots mode's home shows a bot working while +/// #504 on a real host with the bighelp plugin: Bots shows a bot working while /// another Hermes process runs its turn (`hermes -p chat -q`, started from a terminal on that /// computer), within a few seconds, and clears when the run ends. The test only watches the home: /// it opens no chat and sends nothing. @@ -25,7 +25,7 @@ final class BotActivityHostUITests: BighelpUITestCase { let (address, profile) = (parts[0], parts[1]) let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.settings.simple-bots", "YES"] + "-loopdy.home.landing", "bots"] app.launch() try addHost(app, address: address) XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 30)) @@ -56,7 +56,7 @@ final class BotActivityHostUITests: BighelpUITestCase { if pinned.exists { return pinned } RunLoop.current.run(until: Date().addingTimeInterval(0.5)) } - return app.buttons["simple-bots.primary"] + return app.primaryBot } /// The state is the row's or tile's value; its label holds the latest message, which can say anything. diff --git a/BighelpUITests/BotChatUITests.swift b/BighelpUITests/BotChatUITests.swift index f6b5cdbc..f44649be 100644 --- a/BighelpUITests/BotChatUITests.swift +++ b/BighelpUITests/BotChatUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Settings › Chat › A bot opens decides what tapping an agent on Agents opens, +/// Settings › Chat › A bot opens decides what tapping a bot on Bots opens, /// and an agent's Bot Chat offers This chat › New Bot Chat. On the demo data, whose /// finance agent has a Bot Chat. Set BIGHELP_BOT_CHAT_EVIDENCE (TEST_RUNNER_…) to save /// screenshots. @@ -71,84 +71,24 @@ final class BotChatUITests: BighelpUITestCase { } } - /// A tab keeps its place: a chat left for Ideas opens again from Chat, not the agent's Bot Chat. - /// The chat is another agent's, so Ideas makes that agent the one in use; once the board - /// switches back, Chat opens that agent's Bot Chat. - @MainActor - func testChatOpensTheChatYouLeftForABoard() { - let app = launchOnTheAgentsChat() - let left = message("Here's the plan for Saturday.", in: app) - openListedChat("demo-session-1", in: app) - XCTAssertTrue(left.waitForExistence(timeout: 10)) - - app.buttons["tab.ideas"].tap() - XCTAssertTrue(left.waitForNonExistence(timeout: 5)) - app.buttons["tab.sessions"].tap() - XCTAssertTrue(left.waitForExistence(timeout: 10), "Chat opens the chat you left") - XCTAssertFalse(message(botChatText, in: app).exists) - save("tab-keeps-chat", app) - - app.buttons["tab.ideas"].tap() - let name = app.buttons["agent.hero.name"].firstMatch - XCTAssertTrue(name.waitForExistence(timeout: 5)) - name.tap() - let finance = app.buttons["agent.switcher.agent.finance"] - XCTAssertTrue(finance.waitForExistence(timeout: 5)) - finance.tap() - XCTAssertTrue(finance.waitForNonExistence(timeout: 5)) - app.buttons["tab.sessions"].tap() - XCTAssertTrue(message(botChatText, in: app).waitForExistence(timeout: 10), - "Chat opens the chat of the agent in use") - XCTAssertFalse(left.exists) - } - - /// With Sessions in the bar, a chat picked from its list is Sessions': Sessions opens it again, - /// a second tap shows the list, and Chat opens the agent's own chat. - @MainActor - func testSessionsOpensTheChatYouLeftFromItsList() { - let app = launchOnTheAgentsChat(layout: "{pinned=(sessions,ideas,feed);menu=();}") - let sessions = app.buttons["tab.session-list"].firstMatch - XCTAssertTrue(sessions.waitForExistence(timeout: 10)) - sessions.tap() - let left = message(listedChatText, in: app) - openListedChat(in: app) - XCTAssertTrue(left.waitForExistence(timeout: 10)) - - app.buttons["tab.ideas"].tap() - XCTAssertTrue(left.waitForNonExistence(timeout: 5)) - sessions.tap() - XCTAssertTrue(left.waitForExistence(timeout: 10), "Sessions opens the chat you left") - save("sessions-keeps-chat", app) - sessions.tap() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].waitForExistence(timeout: 5), - "Sessions again shows the list") - - openListedChat(in: app) - XCTAssertTrue(left.waitForExistence(timeout: 10)) - app.buttons["tab.ideas"].tap() - app.buttons["tab.sessions"].tap() - XCTAssertTrue(message(botChatText, in: app).waitForExistence(timeout: 10), "Chat is the agent's own chat") - } - - /// With several gateways, All sessions' rows have the long-press menu too. + /// With several gateways, Chats lists every computer's chats, and their rows have the long-press menu too. @MainActor func testAllSessionsRowsHaveALongPressMenu() { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "YES"] app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let chats = app.buttons["menu.chats"].firstMatch - XCTAssertTrue(chats.waitForExistence(timeout: 5)) - chats.tap() - let row = app.buttons["fleet.chat.Market scan"].firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 10), "Another computer's chat is listed") + showChats(in: app) + let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS %@", + "chats.row.", "Market scan")).firstMatch + let inbox = app.descendants(matching: .any)["chats.inbox"].firstMatch + _ = row.waitForExistence(timeout: 10) + for _ in 0..<8 where !(row.exists && row.isHittable) { inbox.swipeUp() } + XCTAssertTrue(row.exists, "Another computer's chat is listed") row.press(forDuration: 1.0) - let rename = app.buttons.matching(NSPredicate(format: "identifier == %@ OR label == %@", - "fleet.chat.rename", "Rename")).firstMatch - let archive = app.buttons.matching(NSPredicate(format: "identifier == %@ OR label == %@", - "fleet.chat.archive", "Archive")).firstMatch + let rename = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ OR label == %@", + "chats.action.rename.", "Rename")).firstMatch + let archive = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ OR label == %@", + "chats.action.archive.", "Archive")).firstMatch XCTAssertTrue(rename.waitForExistence(timeout: 5), "Rename on long press") XCTAssertTrue(archive.exists, "Archive on long press") save("all-sessions-menu", app) @@ -164,49 +104,14 @@ final class BotChatUITests: BighelpUITestCase { return app } - /// A finance chat in the list that isn't its Bot Chat. - private let listedChatText = "Booked! The details are in your email." - - /// Chat opening the agent's own chat, as people have it, and one computer. - @MainActor - private func launchOnTheAgentsChat(layout: String? = nil) -> XCUIApplication { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-canonical-agent-chat", - "-loopdy.home.opens-chat", "YES", "-bighelp.hosts.all-hosts", "NO"] - if let layout { app.launchArguments += ["-bighelp.app-layout", layout] } - app.launch() - XCTAssertTrue(chatIdentity(in: app).waitForExistence(timeout: 30)) - return app - } - - /// A chat from the full list: ☰ › Sessions, or the Sessions tab when it's open. `demo-session-3` - /// is the finance agent's, `demo-session-1` the travel agent's. - @MainActor - private func openListedChat(_ id: String = "demo-session-3", in app: XCUIApplication) { - let row = app.buttons["session.row.\(id)"].firstMatch - let list = app.descendants(matching: .any)["sessions.screen"] - if !list.waitForExistence(timeout: 3) { - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["chat.menu", "home.drawer.open"])) - .firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - menu.tap() - app.buttons["menu.sessions"].tap() - } - XCTAssertTrue(list.waitForExistence(timeout: 10)) - for _ in 0..<6 where !(row.exists && row.isHittable) { list.swipeUp() } - row.tap() - } - - @MainActor - private func message(_ text: String, in app: XCUIApplication) -> XCUIElement { - app.textViews.matching(NSPredicate(format: "value CONTAINS %@", text)).firstMatch - } - + /// Bots › the bot's row, wherever it is: in the list, pinned or the primary bot. @MainActor private func tapAgent(_ id: String, in app: XCUIApplication) { - openRootTab("tab.agents", in: app) - let agent = app.buttons["agent.\(id)"].firstMatch - XCTAssertTrue(agent.waitForExistence(timeout: 10), "agent.\(id) on Agents") + showBots(in: app) + let agent = app.buttons.matching(NSPredicate(format: "identifier IN %@", [ + "simple-bots.bot.\(id)", "simple-bots.pinned.\(id)", "simple-bots.primary.\(id)", + ])).firstMatch + XCTAssertTrue(agent.waitForExistence(timeout: 10), "\(id) on Bots") agent.tap() } diff --git a/BighelpUITests/BotDashboardUITests.swift b/BighelpUITests/BotDashboardUITests.swift index ac775360..1c23f55e 100644 --- a/BighelpUITests/BotDashboardUITests.swift +++ b/BighelpUITests/BotDashboardUITests.swift @@ -17,11 +17,11 @@ final class BotDashboardUITests: BighelpUITestCase { private func checkProfileTabs(textSize: String) throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "dark", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "dark", "-UIPreferredContentSizeCategoryName", textSize] app.launch() defer { app.terminate() } - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 15)) primary.tap() let identity = app.buttons["chat.identity"] @@ -58,9 +58,9 @@ final class BotDashboardUITests: BighelpUITestCase { func testProfileOpensOnTheDashboardAndASwipeClearsAPost() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "light"] + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "light"] app.launch() - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 15)) primary.tap() let identity = app.buttons["chat.identity"] @@ -87,13 +87,14 @@ final class BotDashboardUITests: BighelpUITestCase { app.buttons["dashboard.undo"].tap() XCTAssertTrue(top.waitForExistence(timeout: 5), "Undo brings it back") - // Right: the bot's own chat (history and all) with the post in its message box, not sent. + // Right: the bot's own chat (history and all) with the post as a card in its message box, not sent. top.swipeRight(velocity: .fast) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 10), "The bot's chat opens") - let draft = NSPredicate(format: "value BEGINSWITH %@", "About “Lisbon fares dropped 18% for October”") - expectation(for: draft, evaluatedWith: composer) - waitForExpectations(timeout: 5) + let card = app.descendants(matching: .any)["chat.board-card-draft"].firstMatch + XCTAssertTrue(card.waitForExistence(timeout: 5), "The post waits in the message box as a card") + let title = app.descendants(matching: .any)["chat.board-card-draft.title"].firstMatch + XCTAssertTrue(title.label.contains("Lisbon fares dropped 18% for October"), "It is the post that was swiped") } /// Screenshots for design review, only when `BIGHELP_DASHBOARD_SHOTS` names a folder: the @@ -110,7 +111,7 @@ final class BotDashboardUITests: BighelpUITestCase { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance, + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance, "-bighelp.dashboard.swipe-tutorial-seen", "YES", "-bighelp.dashboard.activities.show-routines", "YES"] app.launch() @@ -164,7 +165,7 @@ final class BotDashboardUITests: BighelpUITestCase { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance, + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance, "-bighelp.dashboard.swipe-tutorial-seen", "NO"] app.launch() openProfile(app, bot: "simple-bots.primary") @@ -232,7 +233,7 @@ final class BotDashboardUITests: BighelpUITestCase { @MainActor private func openProfile(_ app: XCUIApplication, bot: String) { - let button = app.buttons[bot] + let button = bot == "simple-bots.primary" ? app.primaryBot : app.buttons[bot] XCTAssertTrue(button.waitForExistence(timeout: 15)) button.tap() let identity = app.buttons["chat.identity"] diff --git a/BighelpUITests/BotScreenHostUITests.swift b/BighelpUITests/BotScreenHostUITests.swift index e9bd4eea..ddd24f84 100644 --- a/BighelpUITests/BotScreenHostUITests.swift +++ b/BighelpUITests/BotScreenHostUITests.swift @@ -27,14 +27,17 @@ final class BotScreenHostUITests: BighelpUITestCase { } let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-loopdy.home.opens-chat", "YES", "-loopdy.settings.nerd-mode", "NO"] + "-loopdy.settings.nerd-mode", "NO"] app.launch() signIn(app, host: host, user: user, password: password) - let avatar = app.buttons["agent.hero.avatar"].firstMatch - XCTAssertTrue(avatar.waitForExistence(timeout: 30)) - avatar.tap() - let screenTab = app.buttons["agent.profile.tab.screen"] + // Bots › the primary bot's chat › its page's Computer tab. + showBots(in: app, timeout: 30) + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 30)) + primary.tap() + openBotPage(fromChatIn: app) + let screenTab = app.buttons["simple-bots.profile.tab.computer"] XCTAssertTrue(screenTab.waitForExistence(timeout: 20), "Hermes 0.22 answers display.status") screenTab.tap() diff --git a/BighelpUITests/BotScreenUITests.swift b/BighelpUITests/BotScreenUITests.swift index 7b96380d..446a053d 100644 --- a/BighelpUITests/BotScreenUITests.swift +++ b/BighelpUITests/BotScreenUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// An agent's screen in demo mode, with the real controls: the profile's Screen tab, +/// An agent's screen in demo mode, with the real controls: the bot page's Computer tab, /// Open screen, Take control, the keyboard and pointer buttons, Hand back and Close. /// Demo mode's screen is a small RFB server in the app, so the real client draws it. /// Set BIGHELP_BOT_SCREEN_EVIDENCE (TEST_RUNNER_BIGHELP_BOT_SCREEN_EVIDENCE) to a folder @@ -11,19 +11,15 @@ final class BotScreenUITests: BighelpUITestCase { let folder = ProcessInfo.processInfo.environment["BIGHELP_BOT_SCREEN_EVIDENCE"] for appearance in ["light", "dark"] { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", + // Avery Park's chat (demo-finance), then her page's Computer tab. + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-loopdy.settings.nerd-mode", "NO", "-loopdy.demo.appearance", appearance] app.launch() - let avatar = app.buttons["agent.hero.avatar"].firstMatch - XCTAssertTrue(avatar.waitForExistence(timeout: 25)) - avatar.tap() - XCTAssertTrue(element("agent.profile", in: app).waitForExistence(timeout: 10)) + XCTAssertTrue(app.buttons["chat.identity"].firstMatch.waitForExistence(timeout: 25)) + openBotPage(fromChatIn: app) - let screenTab = app.buttons["agent.profile.tab.screen"] + let screenTab = app.buttons["simple-bots.profile.tab.computer"] XCTAssertTrue(screenTab.waitForExistence(timeout: 10), "The demo host has screens") - let order = ["activity", "approvals", "screen", "schedules", "identity"] - .map { app.buttons["agent.profile.tab.\($0)"].frame.minX } - XCTAssertEqual(order, order.sorted(), "Screen is third, between Approvals and Schedules") screenTab.tap() let preview = app.buttons["agent.screen.preview"] XCTAssertTrue(preview.waitForExistence(timeout: 10)) @@ -92,10 +88,10 @@ final class BotScreenUITests: BighelpUITestCase { let folder = ProcessInfo.processInfo.environment["BIGHELP_BOT_SCREEN_EVIDENCE"] let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "light"] + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "light"] app.launch() - // Bots mode: the primary bot's chat, then its profile's Computer tab. - let primary = app.buttons["simple-bots.primary"] + // Bots: the primary bot's chat, then its profile's Computer tab. + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 20)) primary.tap() let identity = app.buttons["chat.identity"] diff --git a/BighelpUITests/BotsAppStateHostUITests.swift b/BighelpUITests/BotsAppStateHostUITests.swift index 2cf41362..5632f47c 100644 --- a/BighelpUITests/BotsAppStateHostUITests.swift +++ b/BighelpUITests/BotsAppStateHostUITests.swift @@ -1,7 +1,7 @@ import XCTest -/// #857 on a real host with the bighelp plugin (`native-app-state-v1`): the order of Bots mode's -/// home comes back after bighelp is deleted and installed again. Scripts/HostSignInMatrixProbe.py +/// #857 on a real host with the bighelp plugin (`native-app-state-v1`): the order of Bots +/// comes back after bighelp is deleted and installed again. Scripts/HostSignInMatrixProbe.py /// (`--modes appstate`) runs it twice against one isolated host: `save` pins a bot, drags it before /// the primary bot and saves; the probe deletes the app; `restore` connects the new install to the /// same host and finds the same top, pinned bot first. @@ -18,11 +18,11 @@ final class BotsAppStateHostUITests: BighelpUITestCase { let (address, phase, profile) = (parts[0], parts[1], parts[2]) let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", - "-bighelp.settings.simple-bots", "YES"] + "-loopdy.home.landing", "bots"] app.launch() try addHost(app, address: address) XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 30)) - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 30), "The primary bot is on top") let pinned = app.buttons["simple-bots.pinned.\(profile)"] @@ -39,7 +39,7 @@ final class BotsAppStateHostUITests: BighelpUITestCase { let saveButton = app.buttons["simple-bots.rearrange.save"] XCTAssertTrue(saveButton.waitForExistence(timeout: 5)) let dragged = app.descendants(matching: .any)["simple-bots.pinned.\(profile)"] - let first = app.descendants(matching: .any)["simple-bots.primary"] + let first = app.primaryBotTile dragged.press(forDuration: 0.1, thenDragTo: first, withVelocity: .slow, thenHoldForDuration: 0.3) XCTAssertTrue(waitUntil(timeout: 5) { dragged.frame.minX < first.frame.minX }, "Dragged before the primary bot") saveButton.tap() diff --git a/BighelpUITests/BotsWidgetUITests.swift b/BighelpUITests/BotsWidgetUITests.swift index f1e430b1..975f0dc2 100644 --- a/BighelpUITests/BotsWidgetUITests.swift +++ b/BighelpUITests/BotsWidgetUITests.swift @@ -5,11 +5,11 @@ import XCTest final class BotsWidgetUITests: BighelpUITestCase { private static let link = URL(string: "loopdy://agent-chat?agent=travel&host=0D0D0D0D-0000-4000-8000-000000000001")! - /// Bots mode, bighelp in the background: the bot's chat, with Back to the bots. + /// Bots, bighelp in the background: the bot's chat, with Back to the bots. @MainActor func testABotOpensItsChatInSimpleBotMode() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.settings.simple-bots", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "bots"] app.launch() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) XCUIDevice.shared.press(.home) @@ -24,7 +24,7 @@ final class BotsWidgetUITests: BighelpUITestCase { @MainActor func testABotOpensItsChatWhenBighelpWasClosed() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.settings.simple-bots", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "bots"] app.launch() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) app.terminate() diff --git a/BighelpUITests/BottomMenuUITests.swift b/BighelpUITests/BottomMenuUITests.swift deleted file mode 100644 index bd72b7a9..00000000 --- a/BighelpUITests/BottomMenuUITests.swift +++ /dev/null @@ -1,83 +0,0 @@ -import XCTest - -/// The bottom menu on the demo data: always open, each tab named; in a chat Chat is the lit tab and -/// tapping it stays put; a chat's Feed is its own agent's; Agents has New chat and no bottom menu; -/// and in the all-hosts view a chat has the menu too. BIGHELP_BOTTOM_MENU_EVIDENCE (TEST_RUNNER_…) -/// saves the screenshots. -final class BottomMenuUITests: BighelpUITestCase { - @MainActor - func testMenuNamesItsTabsAndChatsReachTheirAgentsBoard() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-bighelp.hosts.all-hosts", "NO"] - app.launch() - let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 15), "Opens on the agent's chat") - let chat = app.buttons["tab.sessions"] - XCTAssertTrue(chat.waitForExistence(timeout: 5), "The whole bar, not one button") - for name in ["Chat", "Feed", "Ideas", "Goals"] { - XCTAssertTrue(app.staticTexts[name].exists, "\(name) is named under its icon") - } - XCTAssertTrue(chatNewChatButton(in: app).exists, "New chat sits in the middle of the bar") - save("chat", app) - - app.buttons["tab.ideas"].tap() - XCTAssertTrue(app.descendants(matching: .any)["board.ideas"].waitForExistence(timeout: 5), "Ideas, from the chat") - save("ideas", app) - chat.tap() - XCTAssertTrue(composer.waitForExistence(timeout: 5), "Back in the chat") - XCTAssertTrue(chat.isSelected, "Chat is lit in a chat") - XCTAssertFalse(app.buttons["tab.ideas"].isSelected, "Ideas isn't") - chat.tap() - XCTAssertTrue(composer.waitForExistence(timeout: 3), "Chat again stays in the chat") - XCTAssertFalse(app.buttons["agents.new-chat"].exists, "Not thrown to Agents") - save("chat-selected", app) - - // Agents: pick an agent first; New chat sits bottom right. - openRootTab("tab.agents", in: app) - let newChat = app.buttons["agents.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5), "Agents has the big New chat") - XCTAssertFalse(app.buttons["tab.sessions"].exists, "No bottom menu on Agents") - XCTAssertFalse(app.buttons["tab.feed"].exists) - save("agents", app) - newChat.tap() - let started = app.textViews["chat.composer.text"].waitForExistence(timeout: 5) - || app.navigationBars.matching(NSPredicate(format: "identifier CONTAINS[c] 'chat'")).firstMatch.exists - XCTAssertTrue(started, "It starts a new chat (or opens the New chat picker)") - save("agents-new-chat", app) - } - - @MainActor - func testAllHostsChatsHaveTheMenu() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "YES"] - app.launch() - let mina = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(mina.waitForExistence(timeout: 15)) - XCTAssertFalse(app.buttons["tab.feed"].exists, "All agents is a list of agents: no bottom menu") - mina.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 5)) - let feed = app.buttons["tab.feed"] - XCTAssertTrue(feed.waitForExistence(timeout: 5), "An all-hosts chat has the bottom menu too") - save("all-hosts-chat", app) - feed.tap() - XCTAssertTrue(app.descendants(matching: .any)["board.feed"].waitForExistence(timeout: 5)) - save("all-hosts-feed", app) - // Chat goes back to the chat you were in, not to All agents. - app.buttons["tab.sessions"].tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 5), "Back in the chat") - XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label == %@", "Mina Shah")) - .firstMatch.exists, "Mina's chat") - XCTAssertFalse(app.descendants(matching: .any)["fleet.home"].exists) - } - - private func save(_ name: String, _ app: XCUIApplication) { - let shot = XCTAttachment(screenshot: app.screenshot()) - shot.name = name - shot.lifetime = .keepAlways - add(shot) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_BOTTOM_MENU_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? app.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } -} diff --git a/BighelpUITests/CardRepliesUITests.swift b/BighelpUITests/CardRepliesUITests.swift index 9753f267..ae9a52fd 100644 --- a/BighelpUITests/CardRepliesUITests.swift +++ b/BighelpUITests/CardRepliesUITests.swift @@ -7,7 +7,7 @@ final class CardRepliesUITests: BighelpUITestCase { @MainActor func testPickingAnOptionAndSendingAFormReachTheAgent() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-card-replies", "-loopdy.home.opens-chat", "YES", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-card-replies", "-start-chat", "-loopdy.settings.nerd-mode", "NO"] app.launch() @@ -67,7 +67,7 @@ final class CardRepliesUITests: BighelpUITestCase { @MainActor private func checkFormLimits(appearance: String) throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-card-replies", "-loopdy.home.opens-chat", "YES", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-card-replies", "-start-chat", "-loopdy.settings.nerd-mode", "NO", "-loopdy.demo.appearance", appearance] app.launch() diff --git a/BighelpUITests/ChatAgentTalkUITests.swift b/BighelpUITests/ChatAgentTalkUITests.swift index 43b4dd7d..613479c7 100644 --- a/BighelpUITests/ChatAgentTalkUITests.swift +++ b/BighelpUITests/ChatAgentTalkUITests.swift @@ -67,24 +67,6 @@ final class ChatAgentTalkUITests: BighelpUITestCase { save("agent-talk-tools-hidden-light", app) } - @MainActor - func testRailsShowInSimpleBotMode() throws { - for appearance in ["light", "dark"] { - let app = launch(appearance: appearance, extra: ["-bighelp.settings.simple-bots", "YES"]) - let timeline = app.tables["chat.timeline"] - XCTAssertTrue(timeline.waitForExistence(timeout: 15)) - XCTAssertTrue(rail(in: app, label: "Mina Shah is searching the web…").waitForExistence(timeout: 10)) - let finished = rail(in: app, label: "4 messages with Mina Shah and Jordan Lee") - reveal(finished, in: timeline) - XCTAssertTrue(finished.exists) - save("agent-talk-simple-\(appearance)", app) - finished.tap() - XCTAssertTrue(text(in: app, containing: "About $3,100 for two").waitForExistence(timeout: 5)) - save("agent-talk-simple-sheet-\(appearance)", app) - app.terminate() - } - } - /// An agent another one asked works in its own Hermes process. Opening its chat then shows it /// typing with Stop, and Stop ends that run. @MainActor diff --git a/BighelpUITests/ChatContextWindowUITests.swift b/BighelpUITests/ChatContextWindowUITests.swift index 638786b0..83e27770 100644 --- a/BighelpUITests/ChatContextWindowUITests.swift +++ b/BighelpUITests/ChatContextWindowUITests.swift @@ -121,16 +121,7 @@ final class ChatContextWindowUITests: BighelpUITestCase { let app = makeApp() app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - openRootTab("tab.agents", in: app) - let row = app.buttons["agent.\(agent)"].firstMatch - if !row.waitForExistence(timeout: 20) { - let search = app.descendants(matching: .any).matching(identifier: "agents.search").firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 10)) - search.tap() - app.typeText(agent + "\n") - } - XCTAssertTrue(row.waitForExistence(timeout: 30), "agent.\(agent) on Agents") - row.tap() + openHostBot(agent, in: app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 45), "Its chat opens") @@ -176,4 +167,25 @@ final class ChatContextWindowUITests: BighelpUITestCase { XCTAssertTrue(page.exists, "The Context page shows the chat's context") app.terminate() } + + /// Opens a real host's bot from Bots (`simple-bots.bot.`), through Search when the list hasn't + /// built its row; the tap opens its Bot Chat. + @MainActor + private func openHostBot(_ agent: String, in app: XCUIApplication) { + showBots(in: app) + var row = app.buttons["simple-bots.bot.\(agent)"].firstMatch + // A long list builds only the rows on screen. + if !row.waitForExistence(timeout: 20) { + let search = app.buttons["simple-bots.search"].firstMatch + XCTAssertTrue(search.waitForExistence(timeout: 10)) + search.tap() + let field = app.descendants(matching: .any)["simple-bots.search.field"].firstMatch + XCTAssertTrue(field.waitForExistence(timeout: 10)) + field.tap() + field.typeText(agent) + row = app.buttons["simple-bots.search.bot.\(agent)"].firstMatch + } + XCTAssertTrue(row.waitForExistence(timeout: 30), "\(agent) on Bots") + row.tap() + } } diff --git a/BighelpUITests/ChatEdgeBlurUITests.swift b/BighelpUITests/ChatEdgeBlurUITests.swift index ff5b4817..9661a930 100644 --- a/BighelpUITests/ChatEdgeBlurUITests.swift +++ b/BighelpUITests/ChatEdgeBlurUITests.swift @@ -2,7 +2,7 @@ import UIKit import XCTest /// Messages scroll on under the chat's header, blurred, instead of vanishing behind a solid band -/// of color. The test reads the pixels beside ☰ before and after a short scroll: a solid band +/// of color. The test reads the pixels beside Back before and after a short scroll: a solid band /// never changes there, blurred messages do. BIGHELP_CHAT_EDGE_EVIDENCE (TEST_RUNNER_…) saves /// the screenshots in light and dark. final class ChatEdgeBlurUITests: BighelpUITestCase { @@ -17,14 +17,14 @@ final class ChatEdgeBlurUITests: BighelpUITestCase { app.launch() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20)) - let menu = app.buttons["chat.menu"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) + let back = app.buttons["chat.back"] + XCTAssertTrue(back.waitForExistence(timeout: 10)) // Message text is a text view, not a static text. let latest = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "settled sentinel 1000")) XCTAssertTrue(latest.firstMatch.waitForExistence(timeout: 20)) - // Beside ☰, left of the avatar: only the backdrop and what scrolls under it. - let frame = menu.frame + // Beside Back, left of the bot's pill: only the backdrop and what scrolls under it. + let frame = back.frame let strip = CGRect(x: frame.maxX + 6, y: frame.minY + 4, width: max(app.frame.width * 0.3 - frame.maxX - 6, 24), height: frame.height - 8) let before = try Self.luminance(of: app.screenshot().image, in: strip) @@ -42,7 +42,7 @@ final class ChatEdgeBlurUITests: BighelpUITestCase { XCTAssertGreaterThan(meanChange, 0.2, "\(appearance): the header hides the messages behind a solid fill") // The controls still work over the blur. - XCTAssertTrue(menu.isHittable) + XCTAssertTrue(back.isHittable) XCTAssertTrue(composer.isHittable) app.terminate() } diff --git a/BighelpUITests/ChatFolderBrowserUITests.swift b/BighelpUITests/ChatFolderBrowserUITests.swift index 57f5315b..04db13f7 100644 --- a/BighelpUITests/ChatFolderBrowserUITests.swift +++ b/BighelpUITests/ChatFolderBrowserUITests.swift @@ -98,17 +98,7 @@ final class ChatFolderBrowserUITests: BighelpUITestCase { let app = makeApp() app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - openRootTab("tab.agents", in: app) - let row = app.buttons["agent.\(agent)"].firstMatch - // A long list builds only the rows on screen. - if !row.waitForExistence(timeout: 20) { - let search = app.descendants(matching: .any).matching(identifier: "agents.search").firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 10)) - search.tap() - app.typeText(agent + "\n") - } - XCTAssertTrue(row.waitForExistence(timeout: 30), "agent.\(agent) on Agents") - row.tap() + openHostBot(agent, in: app) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 45), "Its Bot Chat opens") chatMenuItem("chat.files", in: app).tap() @@ -165,4 +155,25 @@ final class ChatFolderBrowserUITests: BighelpUITestCase { try? app.screenshot().pngRepresentation.write( to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) } + + /// Opens a real host's bot from Bots (`simple-bots.bot.`), through Search when the list hasn't + /// built its row; the tap opens its Bot Chat. + @MainActor + private func openHostBot(_ agent: String, in app: XCUIApplication) { + showBots(in: app) + var row = app.buttons["simple-bots.bot.\(agent)"].firstMatch + // A long list builds only the rows on screen. + if !row.waitForExistence(timeout: 20) { + let search = app.buttons["simple-bots.search"].firstMatch + XCTAssertTrue(search.waitForExistence(timeout: 10)) + search.tap() + let field = app.descendants(matching: .any)["simple-bots.search.field"].firstMatch + XCTAssertTrue(field.waitForExistence(timeout: 10)) + field.tap() + field.typeText(agent) + row = app.buttons["simple-bots.search.bot.\(agent)"].firstMatch + } + XCTAssertTrue(row.waitForExistence(timeout: 30), "\(agent) on Bots") + row.tap() + } } diff --git a/BighelpUITests/ChatInfoUITests.swift b/BighelpUITests/ChatInfoUITests.swift index c8b34f07..85784123 100644 --- a/BighelpUITests/ChatInfoUITests.swift +++ b/BighelpUITests/ChatInfoUITests.swift @@ -16,7 +16,7 @@ final class ChatInfoUITests: BighelpUITestCase { @MainActor private func launchHomeChat(extra: [String] = []) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES"] + extra + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat"] + extra app.launch() XCTAssertTrue(app.buttons["chat.identity"].waitForExistence(timeout: 20), "A one-on-one chat") return app diff --git a/BighelpUITests/ChatLoadSpeedUITests.swift b/BighelpUITests/ChatLoadSpeedUITests.swift index 95a39379..421d7f13 100644 --- a/BighelpUITests/ChatLoadSpeedUITests.swift +++ b/BighelpUITests/ChatLoadSpeedUITests.swift @@ -31,7 +31,7 @@ final class ChatLoadSpeedUITests: BighelpUITestCase { @MainActor func testOpeningALongChatFromTheList() throws { let app = launch() - let row = app.descendants(matching: .any)["session.row.\(Self.longChat)"].firstMatch + let row = chatRow(Self.longChat, in: app) measureOpening(app) { XCTAssertTrue(row.waitForExistence(timeout: 20)) row.tap() @@ -41,7 +41,7 @@ final class ChatLoadSpeedUITests: BighelpUITestCase { @MainActor func testOpeningALongChatFromALink() throws { let app = launch() - let row = app.descendants(matching: .any)["session.row.\(Self.longChat)"].firstMatch + let row = chatRow(Self.longChat, in: app) measureOpening(app) { XCTAssertTrue(row.waitForExistence(timeout: 20)) app.open(URL(string: "loopdy://chat/\(Self.longChat)")!) @@ -64,7 +64,7 @@ final class ChatLoadSpeedUITests: BighelpUITestCase { @MainActor func testOpeningALongRealisticChatFromTheList() throws { let app = launchRealistic(label: "open") - let row = app.descendants(matching: .any)["session.row.\(Self.realisticChat)"].firstMatch + let row = chatRow(Self.realisticChat, in: app) let options = XCTMeasureOptions() options.invocationOptions = [.manuallyStart, .manuallyStop] options.iterationCount = 5 @@ -262,12 +262,12 @@ final class ChatLoadSpeedUITests: BighelpUITestCase { app.launchEnvironment["BIGHELP_PERF_LABEL"] = "memory-\(Self.turns)" app.launchArguments = realisticArguments(opensChat: false) + ["-test-long-chat-count", "4"] app.launch() - XCTAssertTrue(app.descendants(matching: .any)["session.row.\(Self.realisticChat)"].firstMatch + XCTAssertTrue(chatRow(Self.realisticChat, in: app) .waitForExistence(timeout: 20)) settle() post(ChatPerformance.read) for index in 1...4 { - let row = app.descendants(matching: .any)["session.row.demo-long-chat-\(index)"].firstMatch + let row = chatRow("demo-long-chat-\(index)", in: app) XCTAssertTrue(row.waitForExistence(timeout: 20)) row.tap() XCTAssertTrue(realisticLatest(in: app).waitForExistence(timeout: 30)) @@ -360,7 +360,7 @@ final class ChatLoadSpeedUITests: BighelpUITestCase { XCTAssertTrue(latest(in: app).waitForExistence(timeout: 20)) stopMeasuring() app.open(sessions) - XCTAssertTrue(app.descendants(matching: .any)["session.row.\(Self.longChat)"].firstMatch + XCTAssertTrue(chatRow(Self.longChat, in: app) .waitForExistence(timeout: 20)) } } @@ -400,8 +400,8 @@ final class ChatLoadSpeedUITests: BighelpUITestCase { @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-loopdy.home.opens-chat", "NO"] + // Opens on the Chats list (the base launch's place). + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3"] app.launch() return app } diff --git a/BighelpUITests/ChatOpenOnceUITests.swift b/BighelpUITests/ChatOpenOnceUITests.swift index d2352d91..b61eecee 100644 --- a/BighelpUITests/ChatOpenOnceUITests.swift +++ b/BighelpUITests/ChatOpenOnceUITests.swift @@ -7,10 +7,10 @@ final class ChatOpenOnceUITests: BighelpUITestCase { func testOpeningTheOpenChatAgainKeepsOneCopy() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-start-chat"] + "-loopdy.home.landing", "bots", "-start-chat"] app.launch() let back = app.buttons["chat.back"] - XCTAssertTrue(back.waitForExistence(timeout: 15), "Bots mode's chat has Back") + XCTAssertTrue(back.waitForExistence(timeout: 15), "The chat has Back") // The chat on screen, opened again from outside. let chat = URL(string: "loopdy://chat/demo-finance")! diff --git a/BighelpUITests/ChatReactionBarUITests.swift b/BighelpUITests/ChatReactionBarUITests.swift index 15239457..aed1c651 100644 --- a/BighelpUITests/ChatReactionBarUITests.swift +++ b/BighelpUITests/ChatReactionBarUITests.swift @@ -13,7 +13,7 @@ final class ChatReactionBarUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-native-reaction-ui", "-loopdy.demo.appearance", appearance] app.launch() - let conversation = app.buttons["session.row.demo-finance"] + let conversation = chatRow("demo-finance", in: app) XCTAssertTrue(conversation.waitForExistence(timeout: 20)) conversation.tap() let reply = app.textViews.matching(NSPredicate( @@ -80,7 +80,7 @@ final class ChatReactionBarUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-native-reaction-ui", "-loopdy.demo.appearance", appearance] app.launch() - let conversation = app.buttons["session.row.demo-finance"] + let conversation = chatRow("demo-finance", in: app) XCTAssertTrue(conversation.waitForExistence(timeout: 20)) conversation.tap() let sent = app.textViews.matching(NSPredicate( @@ -112,7 +112,7 @@ final class ChatReactionBarUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-native-reaction-ui", "-test-long-reaction-message", "-loopdy.demo.appearance", appearance] app.launch() - let conversation = app.buttons["session.row.demo-finance"] + let conversation = chatRow("demo-finance", in: app) XCTAssertTrue(conversation.waitForExistence(timeout: 20)) conversation.tap() let message = app.textViews.matching(NSPredicate( diff --git a/BighelpUITests/ChatStreamingAnchorUITests.swift b/BighelpUITests/ChatStreamingAnchorUITests.swift index e6dd885a..ed64e782 100644 --- a/BighelpUITests/ChatStreamingAnchorUITests.swift +++ b/BighelpUITests/ChatStreamingAnchorUITests.swift @@ -38,13 +38,9 @@ final class ChatStreamingAnchorUITests: BighelpUITestCase { @MainActor func testSecondToolTurnRetainsEarlierMessagesAndReturnsToLatest() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", "-test-companion-disabled", "-test-tool-stream", "-test-tool-stream-two-turns"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-companion-disabled", "-test-tool-stream", "-test-tool-stream-two-turns"] app.launch() - let newChat = chatNewChatButton(in: app).waitForExistence(timeout: 5) - ? chatNewChatButton(in: app) : app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) let input = app.textViews["Message"] for number in 1...2 { XCTAssertTrue(input.waitForExistence(timeout: 5)) @@ -88,18 +84,14 @@ final class ChatStreamingAnchorUITests: BighelpUITestCase { Unmanaged.fromOpaque(observer).release() } app.launchEnvironment["BIGHELP_TOOL_STREAM_COMPLETION_NOTIFICATION"] = completionName - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", "-test-companion-disabled", "-test-tool-stream"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-companion-disabled", "-test-tool-stream"] if long { app.launchArguments.append("-test-tool-stream-long") } if expanded { app.launchArguments.append("-test-tool-stream-expanded") } if backgroundChat { app.launchArguments.append("-test-two-chat-stream") } if consecutiveTools { app.launchArguments.append("-test-tool-stream-consecutive") } if inspectFullText { app.launchArguments.append("-test-tool-reader") } app.launch() - let newChat = chatNewChatButton(in: app).waitForExistence(timeout: 5) - ? chatNewChatButton(in: app) : app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) let input = app.otherElements["chat.composer-shell"].textViews["Message"] XCTAssertTrue(input.waitForExistence(timeout: 5)) input.tap() @@ -217,13 +209,9 @@ final class ChatStreamingAnchorUITests: BighelpUITestCase { CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFNotificationName(resumeSignal as CFString), nil, nil, true) } - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", "-test-companion-disabled", "-test-canvas-stream"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-companion-disabled", "-test-canvas-stream"] app.launch() - let newChat = chatNewChatButton(in: app).waitForExistence(timeout: 5) - ? chatNewChatButton(in: app) : app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) let input = app.textViews["Message"] XCTAssertTrue(input.waitForExistence(timeout: 5)) input.tap() @@ -268,14 +256,10 @@ final class ChatStreamingAnchorUITests: BighelpUITestCase { let resumeSignal = "app.loopdy.fixture.canvas-samples.\(UUID().uuidString)" app.launchEnvironment["BIGHELP_CANVAS_RESUME_NOTIFICATION"] = resumeSignal app.launchEnvironment["BIGHELP_CANVAS_SAMPLE_EACH_BATCH"] = "YES" - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", "-test-companion-disabled", "-test-canvas-stream", "-test-canvas-hold-open"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-companion-disabled", "-test-canvas-stream", "-test-canvas-hold-open"] app.launch() defer { app.terminate() } - let newChat = chatNewChatButton(in: app).waitForExistence(timeout: 5) - ? chatNewChatButton(in: app) : app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) let input = app.textViews["Message"] XCTAssertTrue(input.waitForExistence(timeout: 5)) input.tap() diff --git a/BighelpUITests/ChatTurnFailureHostUITests.swift b/BighelpUITests/ChatTurnFailureHostUITests.swift index a36b6f5a..512ba327 100644 --- a/BighelpUITests/ChatTurnFailureHostUITests.swift +++ b/BighelpUITests/ChatTurnFailureHostUITests.swift @@ -49,7 +49,7 @@ final class ChatTurnFailureHostUITests: BighelpUITestCase { next.tap() let newChat = app.buttons.matching(NSPredicate(format: "identifier IN %@", - ["sessions.empty.new-chat", "chat.home.new-chat", "chat.new-chat", "root.new-chat"])).firstMatch + ["home.new-chat", "chats.empty.new-chat"])).firstMatch if newChat.waitForExistence(timeout: 10) { newChat.tap() confirmNewChatPicker(in: app) diff --git a/BighelpUITests/ChatWorkStylesUITests.swift b/BighelpUITests/ChatWorkStylesUITests.swift index c9c4cd63..9d5948ae 100644 --- a/BighelpUITests/ChatWorkStylesUITests.swift +++ b/BighelpUITests/ChatWorkStylesUITests.swift @@ -1,8 +1,8 @@ import XCTest -/// Settings › Chat › Shows as in a Bots chat, on the demo tool stream (two notes, each before a tool, -/// then the answer). Card and Minimal gather the running turn into one block; Full keeps every step in -/// place. When the turn ends the work folds: above the answer, or under it for Minimal. +/// Settings › Chat › Shows as in the primary bot's chat (from Bots), on the demo tool stream (two +/// notes, each before a tool, then the answer). Card and Minimal gather the running turn into one +/// block; Full keeps every step in place. When the turn ends the work folds: above the answer, or under it for Minimal. final class ChatWorkStylesUITests: BighelpUITestCase { @MainActor func testEachStyleShowsTheRunningTurnAndFoldsItWhenItEnds() throws { @@ -10,13 +10,13 @@ final class ChatWorkStylesUITests: BighelpUITestCase { for style in ["card", "minimal", "full"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance, + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance, "-bighelp.chat.work-style", style, "-test-tool-stream", "-test-tool-stream-two-turns", "-test-tool-stream-slow", "-test-tool-stream-settles"] app.launch() - XCTAssertTrue(app.buttons["simple-bots.primary"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.primary"].tap() + XCTAssertTrue(app.primaryBot.waitForExistence(timeout: 15)) + app.primaryBot.tap() let input = app.textViews["chat.composer.text"] XCTAssertTrue(input.waitForExistence(timeout: 10)) input.tap() diff --git a/BighelpUITests/ChatsUnreadAndDraftsUITests.swift b/BighelpUITests/ChatsUnreadAndDraftsUITests.swift index de82ff0d..972e9b00 100644 --- a/BighelpUITests/ChatsUnreadAndDraftsUITests.swift +++ b/BighelpUITests/ChatsUnreadAndDraftsUITests.swift @@ -38,17 +38,16 @@ final class ChatsUnreadAndDraftsUITests: BighelpUITestCase { XCTAssertFalse(finance.label.contains("Unread")) finance.press(forDuration: 1.2) - let markUnread = app.buttons["session.action.unread.demo-finance"].firstMatch + let markUnread = app.buttons["chats.action.unread.here/demo-finance"].firstMatch XCTAssertTrue(markUnread.waitForExistence(timeout: 5)) - XCTAssertEqual(markUnread.label, "Mark Unread") + XCTAssertEqual(markUnread.label, "Mark unread") markUnread.tap() XCTAssertTrue(waitForLabel(of: finance, containing: "Unread", true)) shot("marked-unread", app) finance.tap() XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 10)) - // A chat from the list goes back with the edge swipe. - swipeBackFromLeadingEdge(in: app) + goBackFromChat(in: app) XCTAssertTrue(finance.waitForExistence(timeout: 10)) XCTAssertTrue(waitForLabel(of: finance, containing: "Unread", false), "Reading the chat marks it read") } @@ -56,15 +55,16 @@ final class ChatsUnreadAndDraftsUITests: BighelpUITestCase { @MainActor private func launch(_ arguments: [String]) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO"] + arguments + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "chats", + "-bighelp.hosts.all-hosts", "NO"] + arguments app.launch() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].firstMatch.waitForExistence(timeout: 15)) + XCTAssertTrue(app.descendants(matching: .any)["chats.inbox"].firstMatch.waitForExistence(timeout: 15)) return app } @MainActor private func row(_ id: String, in app: XCUIApplication) -> XCUIElement { - app.buttons["session.row.\(id)"].firstMatch + chatRow(id, in: app) } /// Until the row sits in the middle of the screen, clear of the header and the bar. diff --git a/BighelpUITests/CodeModeHostUITests.swift b/BighelpUITests/CodeModeHostUITests.swift index a45f3376..4897ec3c 100644 --- a/BighelpUITests/CodeModeHostUITests.swift +++ b/BighelpUITests/CodeModeHostUITests.swift @@ -1,80 +1,19 @@ import XCTest -/// Code mode against a real Hermes host: a send makes a worktree and a session on -/// the chosen model, the agent's change shows in Changes, and Ship commits it. -/// Needs a project whose main folder is a throwaway git repository with no remote. -/// Set (as TEST_RUNNER_…): +/// Coding from New chat against a real Hermes host: a send with a project picked makes a worktree +/// and a session, the agent's change shows in Changes (from its card on Work), and Ship commits it. +/// The session runs on the bot's own model. Needs a project whose main folder is a throwaway git +/// repository with no remote. Set (as TEST_RUNNER_…): /// - BIGHELP_CODE_HOST: the host's address, e.g. 127.0.0.1:9121 (an open host) /// - BIGHELP_CODE_PROJECT: the Hermes project ID -/// - BIGHELP_CODE_MODEL: words in the model's name, e.g. "Luna" -/// - BIGHELP_CODE_PROVIDER: the provider to take it from, e.g. openai-codex (the ChatGPT subscription) +/// - BIGHELP_CODE_AGENT: the bot whose project it is (optional; New chat's first bot otherwise) /// - BIGHELP_CODE_MODE_EVIDENCE: a folder for screenshots (optional) final class CodeModeHostUITests: BighelpUITestCase { @MainActor func testASendBecomesAWorktreeSessionWhoseChangeShips() throws { - let environment = ProcessInfo.processInfo.environment - guard let host = environment["BIGHELP_CODE_HOST"], let project = environment["BIGHELP_CODE_PROJECT"] else { - throw XCTSkip("Set BIGHELP_CODE_HOST and BIGHELP_CODE_PROJECT") - } - let app = makeApp() - app.launchArguments = ["-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code"] - app.launch() - try onboardOpenHost(app, address: host) - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 30), "Code mode is the home.") - - app.buttons["code.chip.project"].tap() - let probe = app.buttons["code.project.\(project)"] - if !probe.waitForExistence(timeout: 30) { save("host-projects-missing", app) } - XCTAssertTrue(probe.exists, "The host's project is listed.") - probe.tap() - - if let model = environment["BIGHELP_CODE_MODEL"] { - app.buttons["code.composer.agent"].tap() - app.buttons["code.runtime.model"].tap() - // Lists build only the rows on screen: search narrows it to the model. - let search = app.searchFields["code.runtime.search"].firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 10)) - search.tap() - search.typeText(model) - save("host-0-models", app) - let provider = environment["BIGHELP_CODE_PROVIDER"].map { "\($0)." } ?? "" - let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS[c] %@", - "code.runtime.model.\(provider)", model)).firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 30), "\(model) is offered.") - row.tap() - app.navigationBars.buttons.element(boundBy: 0).tap() - app.buttons["code.runtime.reasoning"].tap() - app.buttons["Low"].firstMatch.tap() - save("host-1-model", app) - app.buttons["Done"].firstMatch.tap() - } - - let cards = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "code.session.")) - let earlier = Set(cards.allElementsBoundByIndex.map(\.identifier)) - let field = element("code.composer.field", in: app) - XCTAssertTrue(field.waitForExistence(timeout: 10)) - field.tap() - field.typeText("Create a file named HELLO.md containing exactly one line: hello from Code mode. " - + "Do not change any other file and do not commit.") - app.buttons["code.composer.send"].tap() - - // This send's card: the one that wasn't there before. - var newID: String? - let appeared = Date().addingTimeInterval(120) - while newID == nil, Date() < appeared { - newID = cards.allElementsBoundByIndex.map(\.identifier).first { !earlier.contains($0) } - if newID == nil { sleep(2) } - } - // Real session IDs run past XCUITest's 128-character subscript limit. - let card = app.buttons.matching(NSPredicate(format: "identifier == %@", - try XCTUnwrap(newID, "The send became a session card."))).firstMatch - save("host-2-running", app) - let deadline = Date().addingTimeInterval(300) - while !card.label.contains("Ready"), Date() < deadline { - XCTAssertFalse(card.label.contains("Approve") || card.label.contains("Answer"), "The agent asked for help.") - sleep(3) - } - XCTAssertTrue(card.label.contains("Ready"), "The session finished: \(card.label)") + let (app, earlier) = try openProbe() + let card = try sendAndWait(after: earlier, "Create a file named HELLO.md containing exactly one line: hello from Code mode. " + + "Do not change any other file and do not commit.", in: app) save("host-3-ready", app) card.press(forDuration: 1.2) @@ -103,9 +42,9 @@ final class CodeModeHostUITests: BighelpUITestCase { /// Plan mode writes a Markdown plan that opens rendered from the chat. @MainActor func testPlanModeWritesAPlanThatOpensRendered() throws { - let app = try openProbe() + let (app, earlier) = try openProbe() choose("Plan", in: app) - let plan = try sendAndWait("Plan how to add a CONTRIBUTING.md file with one line of text. Keep the plan short.", + let plan = try sendAndWait(after: earlier, "Plan how to add a CONTRIBUTING.md file with one line of text. Keep the plan short.", in: app) save("host-7-plan-ready", app) plan.tap() @@ -122,82 +61,83 @@ final class CodeModeHostUITests: BighelpUITestCase { /// YOLO starts a session with Hermes' YOLO on (the app checks Hermes' answer, so a refusal fails the send). @MainActor func testYOLOModeStartsTheSessionWithYOLOOn() throws { - let app = try openProbe() + let (app, earlier) = try openProbe() choose("YOLO", in: app) - let yolo = try sendAndWait("Create a file named YOLO.md containing exactly one line: yolo. Do not commit.", in: app) + let yolo = try sendAndWait(after: earlier, "Create a file named YOLO.md containing exactly one line: yolo. Do not commit.", in: app) XCTAssertTrue(yolo.label.contains("YOLO"), "The card says YOLO: \(yolo.label)") XCTAssertFalse(yolo.label.contains("didn't turn on YOLO")) save("host-9-yolo-ready", app) } - /// Signs in to the host, picks the probe project and the model, on the IDE home. + /// Signs in to the host, notes the coding cards Work already shows, then opens New chat with the + /// bot and picks the probe project from the choices row. Returns the app and those cards' IDs. @MainActor - private func openProbe() throws -> XCUIApplication { + private func openProbe() throws -> (XCUIApplication, Set) { let environment = ProcessInfo.processInfo.environment guard let host = environment["BIGHELP_CODE_HOST"], let project = environment["BIGHELP_CODE_PROJECT"] else { throw XCTSkip("Set BIGHELP_CODE_HOST and BIGHELP_CODE_PROJECT") } let app = makeApp() - app.launchArguments = ["-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code"] app.launch() try onboardOpenHost(app, address: host) - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 30), "Code mode is the home.") - app.buttons["code.chip.project"].tap() + openHomeTab("work", in: app) + XCTAssertTrue(element("work.screen", in: app).waitForExistence(timeout: 30)) + let earlier = Set(codingCards(in: app).allElementsBoundByIndex.map(\.identifier)) + + chatNewChatButton(in: app).tap() + confirmNewChatPicker(in: app, botID: environment["BIGHELP_CODE_AGENT"]) + let chip = app.buttons["new-chat.chip.project"] + XCTAssertTrue(chip.waitForExistence(timeout: 30), "One bot picked: the choices row shows") + chip.tap() // By its ID, or its name (a project made with the CLI has an ID of the host's own). let probe = app.buttons.matching(NSPredicate( - format: "identifier == %@ OR (identifier BEGINSWITH %@ AND label CONTAINS[c] %@)", - "code.project.\(project)", "code.project.", project)).firstMatch - XCTAssertTrue(probe.waitForExistence(timeout: 30), "The host's project is listed.") + format: "identifier == %@ OR label CONTAINS[c] %@", "new-chat.project.\(project)", project)).firstMatch + if !probe.waitForExistence(timeout: 30) { save("host-projects-missing", app) } + XCTAssertTrue(probe.exists, "The host's project is listed.") probe.tap() - if let model = environment["BIGHELP_CODE_MODEL"] { pick(model, provider: environment["BIGHELP_CODE_PROVIDER"], in: app) } - return app + XCTAssertTrue(app.buttons["new-chat.chip.mode"].waitForExistence(timeout: 10), "The project's chips show") + save("host-1-project", app) + return (app, earlier) } + /// The coding cards on Work (a launch becomes one once Hermes has its session). @MainActor - private func pick(_ model: String, provider: String?, in app: XCUIApplication) { - app.buttons["code.composer.agent"].tap() - app.buttons["code.runtime.model"].tap() - let search = app.searchFields["code.runtime.search"].firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 10)) - search.tap() - search.typeText(model) - let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS[c] %@", - "code.runtime.model.\(provider.map { "\($0)." } ?? "")", model)).firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 30), "\(model) is offered.") - row.tap() - app.navigationBars.buttons.element(boundBy: 0).tap() - app.buttons["code.runtime.reasoning"].tap() - app.buttons["Low"].firstMatch.tap() - app.buttons["Done"].firstMatch.tap() + private func codingCards(in app: XCUIApplication) -> XCUIElementQuery { + app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "work.item.coding:")) } @MainActor private func choose(_ mode: String, in app: XCUIApplication) { - app.buttons["code.composer.mode"].tap() + app.buttons["new-chat.chip.mode"].tap() + // A menu item reports its title and subtitle as its label. app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", mode)).firstMatch.tap() - XCTAssertEqual(app.buttons["code.composer.mode"].label, "Mode: \(mode)") + XCTAssertEqual(app.buttons["new-chat.chip.mode"].label, "Mode: \(mode)") } - /// Sends `message` and returns its new card once the session is Ready. + /// Sends `message` (the project's Work opens) and returns its new card, one not in `earlier`, once + /// the session is Ready. @MainActor - private func sendAndWait(_ message: String, in app: XCUIApplication) throws -> XCUIElement { - let cards = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "code.session.")) - let earlier = Set(cards.allElementsBoundByIndex.map(\.identifier)) - let field = element("code.composer.field", in: app) + private func sendAndWait(after earlier: Set, _ message: String, in app: XCUIApplication) throws -> XCUIElement { + let field = app.textViews["chat.composer.text"] XCTAssertTrue(field.waitForExistence(timeout: 10)) field.tap() field.typeText(message) - app.buttons["code.composer.send"].tap() + app.buttons["chat.send"].tap() var newID: String? let appeared = Date().addingTimeInterval(120) while newID == nil, Date() < appeared { - newID = cards.allElementsBoundByIndex.map(\.identifier).first { !earlier.contains($0) } + newID = codingCards(in: app).allElementsBoundByIndex.map(\.identifier).first { !earlier.contains($0) } if newID == nil { sleep(2) } } + // Real session IDs run past XCUITest's 128-character subscript limit. let card = app.buttons.matching(NSPredicate(format: "identifier == %@", try XCTUnwrap(newID, "The send became a session card."))).firstMatch + save("host-2-running", app) let deadline = Date().addingTimeInterval(300) - while !card.label.contains("Ready"), Date() < deadline { sleep(3) } + while !card.label.contains("Ready"), Date() < deadline { + XCTAssertFalse(card.label.contains("Approve") || card.label.contains("Answer"), "The agent asked for help.") + sleep(3) + } XCTAssertTrue(card.label.contains("Ready"), "The session finished: \(card.label)") return card } diff --git a/BighelpUITests/CodeModeUITests.swift b/BighelpUITests/CodeModeUITests.swift index 3af425a6..918acdb1 100644 --- a/BighelpUITests/CodeModeUITests.swift +++ b/BighelpUITests/CodeModeUITests.swift @@ -1,225 +1,90 @@ import XCTest -/// Code mode on the demo data: chosen as the start mode it is the home, each send -/// starts its own session card without leaving the screen, and ☰ switches back to -/// Chat. Set BIGHELP_CODE_MODE_EVIDENCE (TEST_RUNNER_BIGHELP_CODE_MODE_EVIDENCE) -/// to a folder to save screenshots; BIGHELP_CODE_MODE_APPEARANCE picks light or dark. +/// Coding from New chat on the demo data (`DemoCodeProjectSource`, `DemoCodeGit`): with one bot +/// picked, the choices row under the message box picks a project, where it runs, the branch and the +/// mode; a coding send opens the project on Work, staged jobs go out with Send all as one batch, +/// and the project's ⋯ opens Dev Factory. Set BIGHELP_CODE_MODE_EVIDENCE +/// (TEST_RUNNER_BIGHELP_CODE_MODE_EVIDENCE) to a folder to save screenshots; +/// BIGHELP_CODE_MODE_APPEARANCE picks light or dark. final class CodeModeUITests: BighelpUITestCase { @MainActor - func testSendsStartSessionsBackToBackAndMenuSwitchesModes() throws { - let app = makeApp() - let appearance = ProcessInfo.processInfo.environment["BIGHELP_CODE_MODE_APPEARANCE"] ?? "dark" - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code", - "-loopdy.demo.appearance", appearance] - app.launch() - - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 10), "Code mode opens as the home.") - XCTAssertTrue(app.buttons["code.chip.project"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["code.chip.project"].label.contains("bighelp"), "The first project is picked.") - save("01-home", app) - - // Two sends in a row: each one is its own session, and the screen stays. - send("Fix the widget tap when the host is asleep", in: app) - send("Tighten the Usage chart spacing", in: app) - let cards = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "code.session.")) - let deadline = Date().addingTimeInterval(10) - while cards.count < 2, Date() < deadline { usleep(200_000) } - XCTAssertEqual(cards.count, 2, "Each send adds its own session card.") - XCTAssertTrue(element("code.screen", in: app).exists, "Sending doesn't leave the Code home.") - // A tap in the list puts the keyboard away, so the shot shows the message box and its chips. The - // chosen filter chip is in it and stays chosen; the cards would open their chats. - app.buttons["code.filter.all"].tap() - XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5), "A tap in the list closes the keyboard.") - sleep(1) - save("02-two-sessions", app) - - app.buttons["code.chip.placement"].tap() - // A menu item's name is its title and subtitle together. - let local = app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Local checkout")).firstMatch - XCTAssertTrue(local.waitForExistence(timeout: 3), "Where it runs offers the local checkout.") + func testNewChatChoicesPickProjectWhereItRunsBranchAndMode() throws { + let app = launch() + pickProject("bighelp", in: app) + save("01-project", app) + + app.buttons["new-chat.chip.placement"].tap() + XCTAssertTrue(menuItem("new-chat.placement.local", title: "Local checkout", in: app).waitForExistence(timeout: 3), + "Where it runs offers the local checkout.") save("03-where-it-runs", app) - app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "New worktree")).firstMatch.tap() + menuItem("new-chat.placement.newWorktree", title: "New worktree", in: app).tap() - app.buttons["code.chip.branch"].tap() + app.buttons["new-chat.chip.branch"].tap() XCTAssertTrue(element("code.branches", in: app).waitForExistence(timeout: 3)) XCTAssertTrue(app.buttons["code.branch.main"].exists, "Worktrees start from the default branch.") save("04-branch", app) app.buttons["code.branch.done"].tap() - app.buttons["code.chip.project"].tap() + // The mode button: Plan for a plain message. + reveal("new-chat.chip.mode", in: app).tap() + let plan = menuItem("new-chat.mode.plan", title: "Plan", in: app) + XCTAssertTrue(plan.waitForExistence(timeout: 3)) + save("04b-mode", app) + plan.tap() + // The chip takes the pick once the menu has closed. + let picked = expectation(for: NSPredicate(format: "label == %@", "Mode: Plan"), + evaluatedWith: app.buttons["new-chat.chip.mode"]) + wait(for: [picked], timeout: 5) + + app.buttons["new-chat.chip.project"].tap() + let moreProjects = menuItem("new-chat.project.more", title: "More projects", in: app) + XCTAssertTrue(moreProjects.waitForExistence(timeout: 3)) + moreProjects.tap() XCTAssertTrue(element("code.projects", in: app).waitForExistence(timeout: 3)) XCTAssertTrue(app.buttons["code.project.bighelp-plugin"].exists) - save("05-project", app) + save("05-project-picker", app) app.buttons["Done"].firstMatch.tap() - - // A card opens its session's chat, with no bottom bar; ☰ › Sessions returns to the Code mode home. - cards.element(boundBy: 0).tap() - XCTAssertTrue(element("chat.composer-shell", in: app).waitForExistence(timeout: 8), "The card opens its chat.") - XCTAssertFalse(app.buttons["tab.feed"].exists, "Code mode's chats have no bottom bar.") - save("06-session", app) - app.buttons["chat.menu"].tap() - app.buttons["menu.code.sessions"].tap() - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 5)) - - // ☰: the mode switch on top and Code's places; Chat brings the chat home back. - app.buttons["home.drawer.open"].tap() - XCTAssertTrue(element("menu.experience", in: app).waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["menu.code.pull-requests"].exists) - XCTAssertTrue(app.buttons["menu.code.worktrees"].exists) - XCTAssertFalse(app.buttons["menu.agents"].exists, "Code mode's ☰ lists its own places.") - save("07-menu", app) - app.segmentedControls.buttons["Chat"].tap() - XCTAssertTrue(element("code.screen", in: app).waitForNonExistence(timeout: 5), "Chat leaves Code.") - } - - /// A tap outside the message box puts the keyboard away, on an empty home and - /// between session cards (it used to stay up until you scrolled just right). - @MainActor - func testTappingOutsideTheMessageBoxClosesTheKeyboard() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code"] - app.launch() - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 10)) - let field = element("code.composer.field", in: app) - XCTAssertTrue(field.waitForExistence(timeout: 5)) - - field.tap() - XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) - app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.35)).tap() - XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 3), "The empty home closes the keyboard.") - - send("Fix the widget tap", in: app) - XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) - app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.42)).tap() - XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 3), "Space under the cards closes the keyboard.") } - /// `/` lists the new session's commands, a picked command starts the session as one, - /// and the plan it writes opens rendered from the chat and from Changes. The mode - /// button's Plan does the same for a plain message. + /// A coding send starts its session without a chat of its own: the project's Work shows its card, + /// and the card opens the session's chat. @MainActor - func testSlashCommandsModesAndPlansOpenRendered() throws { - let app = makeApp() - let appearance = ProcessInfo.processInfo.environment["BIGHELP_CODE_MODE_APPEARANCE"] ?? "dark" - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code", - "-loopdy.demo.appearance", appearance] - app.launch() - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 10)) - - let field = element("code.composer.field", in: app) - XCTAssertTrue(field.waitForExistence(timeout: 5)) - field.tap() - field.typeText("/") - XCTAssertTrue(element("code.slash", in: app).waitForExistence(timeout: 5), "/ opens the commands list.") - XCTAssertTrue(element("code.slash.row.plan", in: app).waitForExistence(timeout: 5)) - XCTAssertTrue(element("code.slash.row.review", in: app).exists, "Skills list too.") - save("08-slash", app) - element("code.slash.row.plan", in: app).tap() - XCTAssertTrue(element("code.slash", in: app).waitForNonExistence(timeout: 3), "A pick closes the list.") - XCTAssertEqual(field.value as? String, "/plan ") - field.typeText("Add a loading state to Usage") - app.buttons["code.composer.send"].tap() - - let cards = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "code.session.")) - XCTAssertTrue(cards.firstMatch.waitForExistence(timeout: 10)) - cards.firstMatch.tap() - XCTAssertTrue(element("chat.composer-shell", in: app).waitForExistence(timeout: 8)) - let planLink = app.links.matching(NSPredicate(format: "label CONTAINS %@", "usage-loading-state.md")).firstMatch - XCTAssertTrue(planLink.waitForExistence(timeout: 10), "The plan's path in the reply is a link.") - planLink.tap() - XCTAssertTrue(element("markdown-file.rendered", in: app).waitForExistence(timeout: 5), "The plan opens rendered.") - XCTAssertTrue(app.staticTexts["Usage loading state"].exists, "Its heading shows as a heading, not as # text.") - save("09-plan-from-chat", app) - app.buttons["markdown-file.edit"].tap() - XCTAssertTrue(element("markdown-file.editor", in: app).waitForExistence(timeout: 3), "Edit shows the text.") - app.buttons["markdown-file.cancel"].tap() - app.buttons["markdown-file.done"].tap() - app.buttons["chat.menu"].tap() - app.buttons["menu.code.sessions"].tap() - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 5)) - - XCTAssertTrue(cards.firstMatch.label.contains("Add a loading state to Usage")) - XCTAssertFalse(cards.firstMatch.label.contains("/plan"), "The command isn't part of the card's name.") - - // The mode button: Plan for a plain message. - app.buttons["code.composer.mode"].tap() - app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Plan")).firstMatch.tap() - XCTAssertEqual(app.buttons["code.composer.mode"].label, "Mode: Plan") - - // The agent chip opens the model, reasoning and fast mode; Send sits beside the text, and the - // agent, mode and Stage each keep a full-size place on the line under it. - app.buttons["code.composer.agent"].tap() - app.buttons["code.runtime.model"].tap() - let mini = app.buttons["code.runtime.model.openai.gpt-5.6-mini"] - XCTAssertTrue(mini.waitForExistence(timeout: 5)) - mini.tap() - app.navigationBars["Model"].buttons.element(boundBy: 0).tap() - app.buttons["code.runtime.reasoning"].tap() - app.buttons["X-High"].firstMatch.tap() - app.buttons["code.runtime.fast"].tap() - app.buttons["On"].firstMatch.tap() - app.buttons["Done"].firstMatch.tap() - let agent = app.buttons["code.composer.agent"] - let mode = app.buttons["code.composer.mode"] - let stageButton = app.buttons["code.composer.stage"] - let sendButton = app.buttons["code.composer.send"] - XCTAssertTrue(agent.waitForExistence(timeout: 3)) - XCTAssertTrue(agent.label.hasSuffix("GPT-5.6 Mini · X-High · Fast"), agent.label) - XCTAssertLessThan(sendButton.frame.maxY, agent.frame.minY + 1, "Send sits beside the text, above the chips.") - XCTAssertLessThanOrEqual(agent.frame.maxX, mode.frame.minX - 4, "The agent stops before the mode.") - XCTAssertLessThanOrEqual(mode.frame.maxX, stageButton.frame.minX - 4) - for control in [agent, mode, stageButton, sendButton] { - XCTAssertGreaterThanOrEqual(control.frame.height, 44, "\(control.identifier) is a full-size target") - } - save("10-mode", app) - - // Changes: the plan file opens on its rendered preview. - cards.firstMatch.press(forDuration: 1.0) - app.buttons["Changes"].firstMatch.tap() - XCTAssertTrue(element("code.changes", in: app).waitForExistence(timeout: 5)) - let planFile = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "usage-loading-state.md")).firstMatch - XCTAssertTrue(planFile.waitForExistence(timeout: 5)) - planFile.tap() - XCTAssertTrue(element("markdown-file.rendered", in: app).waitForExistence(timeout: 5), "Changes opens the preview.") - XCTAssertTrue(app.buttons["Changes"].exists || element("code.diff.mode", in: app).exists) - save("11-plan-in-changes", app) + func testACodingSendOpensItsProjectOnWork() throws { + let app = launch() + pickProject("bighelp", in: app) + send("Fix the widget tap when the host is asleep", in: app) + let card = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "work.item.coding:")).firstMatch + XCTAssertTrue(card.waitForExistence(timeout: 10), "The send shows as its session's card.") + save("02-session-card", app) + card.tap() + XCTAssertTrue(element("chat.composer-shell", in: app).waitForExistence(timeout: 8), "The card opens its chat.") + save("06-session", app) } - /// Orchestration mode: two staged jobs and the one in the box go out with Send all as - /// one batch; its chat sends to every session, `#` lists the sessions and the project's - /// open pull requests, and a mention sends to that session only. + /// Orchestration: two staged jobs and the one in the box go out with Send all as one batch; its + /// chat sends to every session, `#` lists the sessions and the project's open pull requests, and + /// a mention sends to that session only. @MainActor func testStagedJobsSendAllAndTheBatchChat() throws { - let app = makeApp() - let appearance = ProcessInfo.processInfo.environment["BIGHELP_CODE_MODE_APPEARANCE"] ?? "dark" - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code", - "-loopdy.demo.appearance", appearance] - app.launch() - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 10)) + let app = launch() + pickProject("bighelp", in: app) stage("Fix the widget tap when the host is asleep", in: app) - XCTAssertTrue(element("code.staged", in: app).waitForExistence(timeout: 3), "Stage keeps it in the tray.") + XCTAssertTrue(element("new-chat.staged", in: app).waitForExistence(timeout: 3), "Stage keeps it in the tray.") stage("Add a loading state to the Usage page", in: app) - XCTAssertTrue(element("code.staged.job.2", in: app).exists) - let field = element("code.composer.field", in: app) + XCTAssertTrue(element("new-chat.staged.job.2", in: app).exists) + let field = app.textViews["chat.composer.text"] field.tap() field.typeText("Write tests for the branch name helper") - let sendAll = app.buttons["code.composer.send-all"] + let sendAll = app.buttons["new-chat.staged.send-all"] XCTAssertEqual(sendAll.label, "Send all 3") - XCTAssertGreaterThanOrEqual(sendAll.frame.minX, element("code.composer.field", in: app).frame.maxX, - "Send all sits beside the text.") - XCTAssertLessThanOrEqual(sendAll.frame.maxX, app.windows.firstMatch.frame.maxX - 12, - "Send all stays inside the message box.") save("12-staged", app) sendAll.tap() - let card = app.buttons["code.batch-card"] + // Send all opens the project's Work, with the batch as one card. + let card = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "work.item.batch:")).firstMatch XCTAssertTrue(card.waitForExistence(timeout: 10), "The batch shows as one card.") - XCTAssertFalse(element("code.staged", in: app).exists, "Send all empties the tray.") + XCTAssertFalse(element("new-chat.staged", in: app).exists, "Send all empties the tray.") let deadline = Date().addingTimeInterval(15) while card.label.contains("Starting"), Date() < deadline { usleep(300_000) } save("13-batch-card", app) @@ -255,22 +120,20 @@ final class CodeModeUITests: BighelpUITestCase { save("17-sent", app) } - /// Dev Factory on the demo data: ☰ opens it; the sample start shows one card per - /// project, and you approve one project's changes there; a template makes a new recipe, - /// and Run starts it on the projects you pick. + /// Dev Factory on the demo data: the project's ⋯ on Work opens it; the sample start shows one card + /// per project, and you approve one project's changes there; a template makes a new recipe, and + /// Run starts it on the projects you pick. @MainActor func testDevFactoryRecipesRunsAndSignOff() throws { - let app = makeApp() - let appearance = ProcessInfo.processInfo.environment["BIGHELP_CODE_MODE_APPEARANCE"] ?? "dark" - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code", - "-loopdy.demo.appearance", appearance] - app.launch() - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 10)) - - app.buttons["home.drawer.open"].tap() - let menuRow = app.buttons["menu.code.dev-factory"] - XCTAssertTrue(menuRow.waitForExistence(timeout: 5), "☰ in Code mode lists Dev Factory.") + let app = launch() + pickProject("bighelp", in: app) + // A coding send opens the project's Work, whose ⋯ has Dev Factory. + send("Fix the widget tap when the host is asleep", in: app) + let more = app.buttons["work.project.more"] + XCTAssertTrue(more.waitForExistence(timeout: 10)) + more.tap() + let menuRow = app.buttons["work.project.dev-factory"] + XCTAssertTrue(menuRow.waitForExistence(timeout: 5), "The project's ⋯ lists Dev Factory.") menuRow.tap() XCTAssertTrue(element("devfactory.home", in: app).waitForExistence(timeout: 8)) let group = app.buttons["devfactory.group-row"].firstMatch @@ -312,34 +175,75 @@ final class CodeModeUITests: BighelpUITestCase { save("22-new-run", app) } - /// Out of the box there's no Code mode: no switch in ☰. @MainActor - func testCodeModeIsOffByDefault() throws { + private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] + let appearance = ProcessInfo.processInfo.environment["BIGHELP_CODE_MODE_APPEARANCE"] ?? "dark" + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() - app.buttons["home.drawer.open"].firstMatch.tap() - XCTAssertTrue(element("navigation.menu", in: app).waitForExistence(timeout: 5)) - XCTAssertFalse(element("menu.experience", in: app).exists) - XCTAssertTrue(app.buttons["menu.agents"].exists) + return app + } + + /// New chat with the demo's default bot, then a project from its chip: the choices row grows the rest. + @MainActor + private func pickProject(_ id: String, in app: XCUIApplication) { + startNewChat(with: "finance", in: app) + let chip = app.buttons["new-chat.chip.project"] + XCTAssertTrue(chip.waitForExistence(timeout: 10), "One bot picked: the choices row shows") + XCTAssertEqual(chip.label, "Project: none") + chip.tap() + let project = app.buttons.matching(NSPredicate(format: "identifier == %@ OR label == %@", + "new-chat.project.\(id)", id)).firstMatch + XCTAssertTrue(project.waitForExistence(timeout: 5)) + project.tap() + XCTAssertEqual(chip.label, "Project: \(id)") + XCTAssertTrue(app.buttons["new-chat.chip.placement"].waitForExistence(timeout: 3)) + } + + /// A menu item reports its title (and subtitle) instead of its identifier, so look for both. + @MainActor + private func menuItem(_ identifier: String, title: String, in app: XCUIApplication) -> XCUIElement { + app.buttons.matching(NSPredicate(format: "identifier == %@ OR label BEGINSWITH %@", identifier, title)).firstMatch + } + + /// One of the last chips of the choices row (the mode, Stage), scrolled into view: the choices + /// are one row that scrolls sideways, and its last chips start past its right edge. The row is + /// always dragged left once, along the chips' own line: `isHittable` says yes for a chip that is + /// only partly in view, and the tap then lands beside it. The row stops at its end, so a chip + /// that was in view stays there. + @MainActor + private func reveal(_ identifier: String, in app: XCUIApplication) -> XCUIElement { + let chip = app.buttons[identifier] + XCTAssertTrue(chip.waitForExistence(timeout: 3), "\(identifier) is in the choices row") + let rail = element("new-chat.choices", in: app) + let origin = app.coordinate(withNormalizedOffset: .zero) + for attempt in 0..<3 { + let bounds = rail.frame + if attempt > 0, chip.frame.minX >= bounds.minX, chip.frame.maxX <= bounds.maxX { break } + // The staged jobs sit over the chips in the same container, so its middle isn't the row. + let line = chip.frame.midY + origin.withOffset(CGVector(dx: bounds.maxX - 24, dy: line)) + .press(forDuration: 0.05, thenDragTo: origin.withOffset(CGVector(dx: bounds.minX + 24, dy: line))) + } + return chip } @MainActor private func stage(_ message: String, in app: XCUIApplication) { - let field = element("code.composer.field", in: app) + let field = app.textViews["chat.composer.text"] XCTAssertTrue(field.waitForExistence(timeout: 5)) field.tap() field.typeText(message) - app.buttons["code.composer.stage"].tap() + reveal("new-chat.chip.stage", in: app).tap() } @MainActor private func send(_ message: String, in app: XCUIApplication) { - let field = element("code.composer.field", in: app) + let field = app.textViews["chat.composer.text"] XCTAssertTrue(field.waitForExistence(timeout: 5)) field.tap() field.typeText(message) - app.buttons["code.composer.send"].tap() + app.buttons["chat.send"].tap() } @MainActor diff --git a/BighelpUITests/CompactChatMenuUITests.swift b/BighelpUITests/CompactChatMenuUITests.swift index 9ddfdea2..ee111e63 100644 --- a/BighelpUITests/CompactChatMenuUITests.swift +++ b/BighelpUITests/CompactChatMenuUITests.swift @@ -3,15 +3,18 @@ import XCTest /// Fixture-only layout and navigation checks; no live host or paid turns. final class CompactChatMenuUITests: BighelpUITestCase { @MainActor - func testHomeOpensCanonicalBotChatInsteadOfTheNewerOrdinaryConversation() { + func testABotOpensItsCanonicalBotChatInsteadOfTheNewerOrdinaryConversation() { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-canonical-agent-chat", - "-loopdy.home.opens-chat", "YES"] + "-loopdy.home.landing", "bots"] app.launch() + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 20)) + primary.tap() let canonical = app.textViews.matching(NSPredicate(format: "value CONTAINS %@", "This is the shared Bot Chat.")).firstMatch - XCTAssertTrue(canonical.waitForExistence(timeout: 20), "Home must open the canonical chat, not the newer ordinary one") + XCTAssertTrue(canonical.waitForExistence(timeout: 20), "The bot must open the canonical chat, not the newer ordinary one") chatNewChatButton(in: app).tap() - confirmNewChatPicker(in: app) + confirmNewChatPicker(in: app, botID: "finance") XCTAssertTrue(canonical.waitForNonExistence(timeout: 8), "Explicit New chat still starts an ordinary conversation") } @@ -34,8 +37,8 @@ final class CompactChatMenuUITests: BighelpUITestCase { evidence("compact-menu-\(appearance)-\(size ?? "default")") let rootRows = large ? ["chat.options.model-speed", "chat.options.this-chat", "chat.options.agent", "chat.options.more"] - : ["chat.switch-agent", "chat.rename", "chat.move-project", "chat.files", "chat.file-changes", - "chat.options.model-speed", "chat.options.usage", "chat.edit-current-agent", "chat.options.advanced"] + : ["chat.rename", "chat.move-project", "chat.files", "chat.file-changes", + "chat.options.model-speed", "chat.options.usage", "chat.bot-page", "chat.options.advanced"] for title in rootRows { let row = chatMenuElement(title, in: app) let at = size ?? "the default size" @@ -63,7 +66,7 @@ final class CompactChatMenuUITests: BighelpUITestCase { // More and This chat still exercise full rows. let submenus = large ? [ ["chat.rename", "chat.move-project", "chat.files"], - ["chat.switch-agent", "chat.edit-current-agent"], + ["chat.bot-page"], ["chat.file-changes", "chat.options.usage", "chat.options.advanced"], ["chat.provider-usage", "chat.context-window", "chat.compact"] ] + (accessibility ? [["chat.options.display"]] : []) + [ diff --git a/BighelpUITests/CompactHostUITests.swift b/BighelpUITests/CompactHostUITests.swift index 0c0d42fb..e8e98e5d 100644 --- a/BighelpUITests/CompactHostUITests.swift +++ b/BighelpUITests/CompactHostUITests.swift @@ -13,13 +13,11 @@ final class CompactHostUITests: BighelpUITestCase { let probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) guard probe["mode"] == "features" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 45), "A chat opens") let newChat = chatNewChatButton(in: app) - XCTAssertTrue(newChat.waitForExistence(timeout: 15)) + XCTAssertTrue(newChat.waitForExistence(timeout: 45), "The home opens with New chat") newChat.tap() confirmNewChatPicker(in: app) XCTAssertTrue(composer.waitForExistence(timeout: 30)) diff --git a/BighelpUITests/CompanionSettingsUITests.swift b/BighelpUITests/CompanionSettingsUITests.swift index bd3e1a0e..735ecb8b 100644 --- a/BighelpUITests/CompanionSettingsUITests.swift +++ b/BighelpUITests/CompanionSettingsUITests.swift @@ -10,10 +10,9 @@ final class CompanionSettingsUITests: BighelpUITestCase { let app = makeApp() app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() - _ = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu", "tab.profile"])) - .firstMatch.waitForExistence(timeout: 60) + _ = app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 60) openSettings(in: app) - // The pet is a row in Appearance, under Chat layout and App layout. + // The pet is a row in Appearance. settingsRow("settings.themes", in: app).tap() let entry = app.buttons["companion-settings-entry"].firstMatch for _ in 0..<8 where !(entry.exists && entry.isHittable) { app.swipeUp() } diff --git a/BighelpUITests/ComposerInteractionUITests.swift b/BighelpUITests/ComposerInteractionUITests.swift index a188e089..9dd936d8 100644 --- a/BighelpUITests/ComposerInteractionUITests.swift +++ b/BighelpUITests/ComposerInteractionUITests.swift @@ -2,29 +2,26 @@ import XCTest import UIKit final class ComposerInteractionUITests: BighelpUITestCase { + /// The bot's pill stays small in the header, and New chat (its own page now, with the To row in + /// the pill's place) takes a draft once a bot is picked. @MainActor - func testChatPillAndNewChatKeepChromeInPlace() { + func testChatPillFitsAndNewChatTakesADraft() { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", - "-bighelp.settings.simple-bots", "NO", "-loopdy.demo.appearance", appearance] + "-loopdy.demo.appearance", appearance] app.launch() let identity = app.buttons["chat.identity"] let input = app.textViews["chat.composer.text"] - let field = app.otherElements["chat.composer.field"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) XCTAssertTrue(input.waitForExistence(timeout: 5)) let headerFrame = identity.frame - let fieldFrame = field.frame XCTAssertLessThanOrEqual(headerFrame.height, 54) XCTAssertLessThan(headerFrame.width, app.frame.width * 0.75) saveComposer("chat-pill-\(appearance)", app) - chatNewChatButton(in: app).tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) XCTAssertTrue(input.waitForExistence(timeout: 5)) - XCTAssertEqual(identity.frame.midY, headerFrame.midY, accuracy: 1) - XCTAssertEqual(field.frame.midY, fieldFrame.midY, accuracy: 1) input.tap() input.typeText("A draft in the new chat") XCTAssertEqual(input.value as? String, "A draft in the new chat") @@ -184,6 +181,7 @@ final class ComposerInteractionUITests: BighelpUITestCase { } type(untilLines: 3) XCTAssertTrue(rail.waitForExistence(timeout: 3), "Three lines offer Expand") + saveComposer("composer-expand-rail-3-lines-\(appearance)", app) checkBoxStill("Expand shows") XCTAssertTrue(rail.isHittable) XCTAssertGreaterThanOrEqual(rail.frame.width, 44) diff --git a/BighelpUITests/ComposioAppsUITests.swift b/BighelpUITests/ComposioAppsUITests.swift index 88c3fe96..89d20169 100644 --- a/BighelpUITests/ComposioAppsUITests.swift +++ b/BighelpUITests/ComposioAppsUITests.swift @@ -9,8 +9,7 @@ final class ComposioAppsUITests: BighelpUITestCase { let app = makeApp() app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() - _ = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu", "tab.profile"])) - .firstMatch.waitForExistence(timeout: 60) + _ = app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 60) openSettings(in: app) settingsRow("settings.apps", in: app).tap() diff --git a/BighelpUITests/ConnectorCardUITests.swift b/BighelpUITests/ConnectorCardUITests.swift index c59dd4c6..093b0e86 100644 --- a/BighelpUITests/ConnectorCardUITests.swift +++ b/BighelpUITests/ConnectorCardUITests.swift @@ -43,8 +43,7 @@ final class ConnectorCardUITests: BighelpUITestCase { let app = makeApp() app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() - _ = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu", "tab.profile"])) - .firstMatch.waitForExistence(timeout: 60) + _ = app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 60) openSettings(in: app) settingsRow("settings.apps", in: app).tap() let native = app.buttons["apps.native"] @@ -93,12 +92,11 @@ final class ConnectorCardUITests: BighelpUITestCase { throw XCTSkip("Set BIGHELP_CONNECTOR_HOST and BIGHELP_CONNECTOR_TOOL") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: host) let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 30), "The agent's chat opens") - // A new chat: the home chat is the person's own, and /model pins the chat it runs in. + // A new chat: the Bot Chat is the person's own, and /model pins the chat it runs in. + XCTAssertTrue(chatNewChatButton(in: app).waitForExistence(timeout: 30), "The home opens with New chat") chatNewChatButton(in: app).tap() confirmNewChatPicker(in: app) XCTAssertTrue(composer.waitForExistence(timeout: 30), "A new chat opens") diff --git a/BighelpUITests/CredentialVaultUITests.swift b/BighelpUITests/CredentialVaultUITests.swift index c80400b4..2444cafe 100644 --- a/BighelpUITests/CredentialVaultUITests.swift +++ b/BighelpUITests/CredentialVaultUITests.swift @@ -2,7 +2,7 @@ import XCTest /// The Credential Vault on the demo data: a bot's profile opens its own vault (the wallet, then /// websites), Add a Website saves a login and a saved card for a new website with one Save, and a -/// saved card goes on another website without being typed again. ☰ opens the same screens. +/// saved card goes on another website without being typed again. Settings opens the same screens. /// BIGHELP_VAULT_EVIDENCE (TEST_RUNNER_…) saves the screenshots. final class CredentialVaultUITests: BighelpUITestCase { @MainActor @@ -10,7 +10,7 @@ final class CredentialVaultUITests: BighelpUITestCase { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance] + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance] app.launch() openPrimaryProfile(app) app.buttons["simple-bots.profile.tab.info"].tap() @@ -73,8 +73,7 @@ final class CredentialVaultUITests: BighelpUITestCase { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", "light"] app.launch() - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])) - .firstMatch.waitForExistence(timeout: 15)) + XCTAssertTrue(app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 15)) openConnectionsRow("settings.connections.vault", in: app) let unlinked = app.buttons["vault.wallet.demo-card-3"] @@ -105,8 +104,7 @@ final class CredentialVaultUITests: BighelpUITestCase { let app = makeApp() app.launch() try onboardOpenHost(app, address: address) - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])) - .firstMatch.waitForExistence(timeout: 30)) + XCTAssertTrue(app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 30)) openConnectionsRow("settings.connections.vault", in: app) let tile = button(app, containing: card) @@ -142,7 +140,7 @@ final class CredentialVaultUITests: BighelpUITestCase { @MainActor private func openPrimaryProfile(_ app: XCUIApplication) { XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.primary"].tap() + app.primaryBot.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) let profile = app.descendants(matching: .any)["simple-bots.profile"] diff --git a/BighelpUITests/DefaultModelUITests.swift b/BighelpUITests/DefaultModelUITests.swift index 992b71a8..fda3d428 100644 --- a/BighelpUITests/DefaultModelUITests.swift +++ b/BighelpUITests/DefaultModelUITests.swift @@ -61,8 +61,7 @@ final class DefaultModelUITests: BighelpUITestCase { let app = makeApp() app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() - _ = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu", "tab.profile"])) - .firstMatch.waitForExistence(timeout: 60) + _ = app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 60) openSettings(in: app) settingsRow("settings.default-model", in: app).tap() XCTAssertTrue(app.navigationBars["Models"].waitForExistence(timeout: 8)) @@ -89,8 +88,7 @@ final class DefaultModelUITests: BighelpUITestCase { let app = makeApp() app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() - _ = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu", "tab.profile"])) - .firstMatch.waitForExistence(timeout: 60) + _ = app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 60) openSettings(in: app) settingsRow("settings.default-model", in: app).tap() XCTAssertTrue(app.navigationBars["Models"].waitForExistence(timeout: 8)) @@ -156,8 +154,7 @@ final class DefaultModelUITests: BighelpUITestCase { @MainActor func openDefaultModel(in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { // A busy simulator can take a while to show the first screen. - _ = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu", "tab.profile"])) - .firstMatch.waitForExistence(timeout: 60) + _ = app.buttons["simple-bots.settings"].firstMatch.waitForExistence(timeout: 60) openSettings(in: app, file: file, line: line) settingsRow("settings.default-model", in: app, file: file, line: line).tap() XCTAssertTrue(firstBotRow(in: app).waitForExistence(timeout: 10), @@ -180,9 +177,10 @@ final class DefaultModelUITests: BighelpUITestCase { file: file, line: line) } + /// The Settings sheet's own Back: the home behind the sheet has a bar of its own. @MainActor private func goBack(in app: XCUIApplication) { - app.navigationBars.buttons.element(boundBy: 0).tap() + app.buttons["BackButton"].firstMatch.tap() } @MainActor diff --git a/BighelpUITests/DeviceAccessCardUITests.swift b/BighelpUITests/DeviceAccessCardUITests.swift index a61e5117..81cf7499 100644 --- a/BighelpUITests/DeviceAccessCardUITests.swift +++ b/BighelpUITests/DeviceAccessCardUITests.swift @@ -111,10 +111,10 @@ final class DeviceAccessCardUITests: BighelpUITestCase { @MainActor private func openDemoChat(in app: XCUIApplication) { - let chat = app.buttons["session.row.demo-finance"].firstMatch + let chat = chatRow("demo-finance", in: app) XCTAssertTrue(chat.waitForExistence(timeout: 15)) chat.tap() - XCTAssertTrue(app.buttons["chat.menu"].firstMatch.waitForExistence(timeout: 10), "The chat opened") + XCTAssertTrue(app.buttons["chat.back"].firstMatch.waitForExistence(timeout: 10), "The chat opened") } @MainActor diff --git a/BighelpUITests/DeviceAccessHostUITests.swift b/BighelpUITests/DeviceAccessHostUITests.swift index 93b89f53..6de89605 100644 --- a/BighelpUITests/DeviceAccessHostUITests.swift +++ b/BighelpUITests/DeviceAccessHostUITests.swift @@ -67,6 +67,11 @@ final class DeviceAccessHostUITests: BighelpUITestCase { sleep(3) save("sleep-1-device-access", app) closeSettings(in: app) + // Settings opens from the home, so the chat closed under it: it's the newest in Chats. + let chat = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "chats.row.")).firstMatch + XCTAssertTrue(chat.waitForExistence(timeout: 10), "The chat is in Chats") + chat.tap() + XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 20)) send("How did I sleep this week?", in: app) let card = element("device-access.card.health", in: app) @@ -126,19 +131,17 @@ final class DeviceAccessHostUITests: BighelpUITestCase { let app = makeApp() // Every data-sharing switch off for this run, and Apple Health's note not yet agreed to, whatever the // simulator saved before. - app.launchArguments = ["-loopdy.home.opens-chat", "YES", "-bighelp.device-tools.grants", "()", + app.launchArguments = ["-bighelp.device-tools.grants", "()", "-bighelp.device-tools.health-sharing", "NO"] app.launch() let composer = app.textViews["chat.composer.text"] - if !composer.waitForExistence(timeout: 10) { + let newChat = app.buttons["home.new-chat"].firstMatch + if !newChat.waitForExistence(timeout: 10) { try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) } - XCTAssertTrue(composer.waitForExistence(timeout: 30), "The agent's chat opens") - let newChat = chatNewChatButton(in: app) - if newChat.waitForExistence(timeout: 5) { - newChat.tap() - confirmNewChatPicker(in: app) - } + XCTAssertTrue(newChat.waitForExistence(timeout: 30), "The home opens") + newChat.tap() + confirmNewChatPicker(in: app) XCTAssertTrue(composer.waitForExistence(timeout: 20)) // A new chat has no session until its first message, and the phone opens the chat's channel only // then. A person's agent takes seconds to call a tool; the scripted one calls at once, so say hi first. diff --git a/BighelpUITests/DraftAttachmentRailUITests.swift b/BighelpUITests/DraftAttachmentRailUITests.swift index 793298d6..602b6bb2 100644 --- a/BighelpUITests/DraftAttachmentRailUITests.swift +++ b/BighelpUITests/DraftAttachmentRailUITests.swift @@ -48,7 +48,7 @@ final class DraftAttachmentRailUITests: BighelpUITestCase { @MainActor private func launch(_ hold: String, appearance: String) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-loopdy.demo.appearance", appearance, "-test-draft-attachments", hold] app.launch() return app diff --git a/BighelpUITests/DuoLayoutUITests.swift b/BighelpUITests/DuoLayoutUITests.swift index 7565ab97..6f49fac5 100644 --- a/BighelpUITests/DuoLayoutUITests.swift +++ b/BighelpUITests/DuoLayoutUITests.swift @@ -1,7 +1,7 @@ import XCTest /// The iPhone Duo. The cover-screen tests run on the Duo's simulator, which starts folded: the bar in -/// the side column (Chat mode) and the switcher beside a chat (Bots and Code mode). A test can't open +/// the side column and the switcher beside a chat. A test can't open /// or fold that simulator, so the open screen and the half-folded laptop run on an iPad simulator with /// `-bighelp.debug.screen-posture` and `-bighelp.debug.fold-halfway`. Each test skips on a screen it /// isn't for. Set BIGHELP_DUO_EVIDENCE (TEST_RUNNER_…) to a folder to save the screenshots. @@ -19,25 +19,20 @@ final class DuoLayoutUITests: BighelpUITestCase { app.launch() try requireCoverScreen(app) // The bar's places are toolbar items, which iOS stacks down the side strip. - let feed = app.buttons["tab.feed"].firstMatch - XCTAssertTrue(feed.waitForExistence(timeout: 20), "The places show") + let today = app.buttons["home.tab.today"].firstMatch + XCTAssertTrue(today.waitForExistence(timeout: 20), "The places show") let window = app.windows.firstMatch.frame - XCTAssertGreaterThan(feed.frame.minX, window.maxX - 90, "In the side strip") - XCTAssertGreaterThan(feed.frame.minY, window.minY + 150, "Under the camera and the status") - let chat = app.buttons["tab.sessions"].firstMatch - XCTAssertLessThan(abs(chat.frame.midX - feed.frame.midX), 4, "One above the other") - let menu = app.buttons["home.drawer.open"].firstMatch - if menu.exists { - XCTAssertFalse(menu.frame.intersects(feed.frame) || menu.frame.intersects(chat.frame), - "Nothing lies over the screen's own buttons") - } + XCTAssertGreaterThan(today.frame.minX, window.maxX - 90, "In the side strip") + XCTAssertGreaterThan(today.frame.minY, window.minY + 150, "Under the camera and the status") + let chat = app.buttons["home.tab.conversations"].firstMatch + XCTAssertLessThan(abs(chat.frame.midX - today.frame.midX), 4, "One above the other") save("cover-chat-\(appearance)", app) if appearance == "light" { - feed.tap() - // iOS doesn't report a toolbar button as selected: the Feed page is what shows. - XCTAssertTrue(element("chat.composer.field", in: app).waitForNonExistence(timeout: 5), + today.tap() + // iOS doesn't report a toolbar button as selected: the Today page is what shows. + XCTAssertTrue(element("today.home", in: app).waitForExistence(timeout: 5), "The places in the strip work") - save("cover-feed-light", app) + save("cover-today-light", app) } app.terminate() } @@ -47,7 +42,7 @@ final class DuoLayoutUITests: BighelpUITestCase { func testCoverScreenSwitchesBotsFromBesideTheChat() throws { for appearance in appearances { let app = makeApp() - app.launchArguments = demo + ["-bighelp.settings.simple-bots", "YES", "-test-bot-activity", + app.launchArguments = demo + ["-loopdy.home.landing", "bots", "-test-bot-activity", "-loopdy.demo.appearance", appearance] app.launch() try requireCoverScreen(app) @@ -73,49 +68,13 @@ final class DuoLayoutUITests: BighelpUITestCase { } } - @MainActor - func testCoverScreenSwitchesCodeSessionsFromBesideTheChat() throws { - let app = makeApp() - app.launchArguments = demo + ["-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code", - "-loopdy.demo.appearance", "light"] - app.launch() - try requireCoverScreen(app) - XCTAssertTrue(element("code.screen", in: app).waitForExistence(timeout: 15)) - for message in ["Fix the widget tap when the host is asleep", "Tighten the Usage chart spacing"] { - let field = element("code.composer.field", in: app) - XCTAssertTrue(field.waitForExistence(timeout: 5)) - field.tap() - field.typeText(message) - app.buttons["code.composer.send"].tap() - } - let cards = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "code.session.")) - let deadline = Date().addingTimeInterval(10) - while cards.count < 2, Date() < deadline { usleep(200_000) } - XCTAssertEqual(cards.count, 2) - cards.firstMatch.tap() - let switcher = element("chat-switcher", in: app) - XCTAssertTrue(switcher.waitForExistence(timeout: 10), "A session's chat has the switcher beside it") - let stops = app.buttons.matching(identifier: "chat-switcher.stop") - XCTAssertEqual(stops.count, 2, "One tile for each session") - sleep(1) - save("cover-code-switcher-light", app) - // Switching goes in place of the open chat (it never piles chats up for Back to walk - // through; the shell drops the open chat first), and the tapped session becomes the one open. - for _ in 0..<2 { - let label = stops.matching(NSPredicate(format: "selected == NO")).firstMatch.label - stops.matching(NSPredicate(format: "label == %@", label)).firstMatch.tap() - XCTAssertTrue(stops.matching(NSPredicate(format: "label == %@", label)).firstMatch.waitForSelection(timeout: 10)) - } - XCTAssertEqual(app.descendants(matching: .any).matching(identifier: "chat-switcher").count, 1) - } - @MainActor func testIPadBotSwitcherStaysBelowStatusBar() throws { XCUIDevice.shared.orientation = .landscapeLeft defer { XCUIDevice.shared.orientation = .portrait } for appearance in appearances { let app = makeApp() - app.launchArguments = demo + ["-bighelp.settings.simple-bots", "YES", "-test-bot-activity", + app.launchArguments = demo + ["-loopdy.home.landing", "bots", "-test-bot-activity", "-bighelp.settings.chat-switcher", "YES", "-loopdy.demo.appearance", appearance] app.launch() @@ -143,11 +102,10 @@ final class DuoLayoutUITests: BighelpUITestCase { // MARK: Open and half-folded (an iPad simulator standing in) @MainActor - func testOpenScreenShowsTheListBesideTheChatInEveryMode() throws { + func testOpenScreenShowsTheListBesideTheChatInBothViews() throws { let modes: [(name: String, arguments: [String], list: String)] = [ - ("bots", ["-bighelp.settings.simple-bots", "YES", "-test-bot-activity"], "simple-bots.home"), - ("chat", [], "sessions.screen"), - ("code", ["-bighelp.settings.code-mode", "YES", "-bighelp.settings.code-mode.open-in", "code"], "code.screen"), + ("bots", ["-loopdy.home.landing", "bots", "-test-bot-activity"], "simple-bots.home"), + ("chat", ["-loopdy.home.landing", "chats"], "chats.inbox"), ] XCUIDevice.shared.orientation = .landscapeLeft defer { XCUIDevice.shared.orientation = .portrait } @@ -187,7 +145,7 @@ final class DuoLayoutUITests: BighelpUITestCase { app.launch() try requireWideScreen(app) let field = element("chat.composer.field", in: app) - XCTAssertTrue(field.waitForExistence(timeout: 20), "The home chat opens") + XCTAssertTrue(field.waitForExistence(timeout: 20), "The chat opens") let window = app.windows.firstMatch.frame XCTAssertGreaterThan(field.frame.minY, window.midY, "The message box sits under the fold") XCTAssertLessThan(field.frame.minY, window.midY + 120, "Just under it") diff --git a/BighelpUITests/FeedPostFilesUITests.swift b/BighelpUITests/FeedPostFilesUITests.swift index 8d710518..70936c7a 100644 --- a/BighelpUITests/FeedPostFilesUITests.swift +++ b/BighelpUITests/FeedPostFilesUITests.swift @@ -8,7 +8,11 @@ final class FeedPostFilesUITests: BighelpUITestCase { func testAPostsFilesOpenToPreviewSaveAndShare() throws { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) - openRootTab("tab.feed", in: app) + // Today › Feed › See all, on one bot's own board. + openTodayBoard("feed", in: app) + let finance = app.buttons["today.board-page.chip.finance"].firstMatch + XCTAssertTrue(finance.waitForExistence(timeout: 10)) + finance.tap() let strip = app.buttons["board.feed.files.feed-1"] XCTAssertTrue(strip.waitForExistence(timeout: 10), "The post shows its files") XCTAssertEqual(strip.label, "2 attachments: 1 picture, Lisbon trip options.pdf") @@ -61,8 +65,7 @@ final class FeedPostFilesUITests: BighelpUITestCase { @MainActor private func launch(appearance: String) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance, - "-loopdy.home.opens-chat", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() return app } diff --git a/BighelpUITests/FirstRunOnboardingUITests.swift b/BighelpUITests/FirstRunOnboardingUITests.swift index d9399618..f007a066 100644 --- a/BighelpUITests/FirstRunOnboardingUITests.swift +++ b/BighelpUITests/FirstRunOnboardingUITests.swift @@ -69,8 +69,7 @@ final class FirstRunOnboardingUITests: BighelpUITestCase { ocean.tap() XCTAssertTrue(ocean.isSelected) capture("Chosen bubble color in dark appearance") - app.terminate() - app.launch() + relaunch(app) XCTAssertTrue(app.buttons["onboarding.appearance.continue"].waitForExistence(timeout: 15)) let restored = app.buttons["appearance.bubble.ocean"] for _ in 0..<4 where !restored.isHittable { app.swipeUp() } @@ -90,8 +89,7 @@ final class FirstRunOnboardingUITests: BighelpUITestCase { XCTAssertTrue(app.buttons["onboarding.ai-consent.privacy"].exists, "It links the privacy policy.") agree.tap() XCTAssertTrue(app.textFields["host-setup.address"].waitForExistence(timeout: 5)) - app.terminate() - app.launch() + relaunch(app) let back = app.buttons["onboarding.back"] XCTAssertTrue(back.waitForExistence(timeout: 15)) back.tap() @@ -105,13 +103,13 @@ final class FirstRunOnboardingUITests: BighelpUITestCase { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] app.launch() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 15)) + XCTAssertTrue(app.buttons["home.new-chat"].waitForExistence(timeout: 15)) XCTAssertFalse(app.buttons["onboarding.get-started"].exists) } - /// After Connect: the plugin and notifications can be skipped, the mode can't, and the - /// mode chosen is the home onboarding ends on. - func testOptionalStepsSkipAndTheChosenModeOpens() { + /// After Connect: the plugin and notifications can be skipped, "How do you want to start?" can't, + /// and the home opens on the place chosen. + func testOptionalStepsSkipAndTheChosenHomeOpens() { let app = launchAfterConnect(at: 3) XCTAssertTrue(app.buttons["onboarding.plugin.install"].waitForExistence(timeout: 15)) let skip = app.buttons["onboarding.skip"] @@ -120,20 +118,16 @@ final class FirstRunOnboardingUITests: BighelpUITestCase { skip.tap() XCTAssertTrue(app.staticTexts["onboarding.mode.later"].waitForExistence(timeout: 5)) - XCTAssertFalse(skip.exists, "Choosing a mode can't be skipped.") - XCTAssertTrue(app.buttons["onboarding.mode.bots"].exists) - capture("Choose your mode") - app.buttons["onboarding.mode.bots"].swipeLeft() - app.buttons["onboarding.mode.sessions"].swipeLeft() - let code = app.buttons["onboarding.mode.code"] - XCTAssertTrue(code.waitForExistence(timeout: 5)) - code.tap() - let use = app.buttons["onboarding.mode.preview.use"] - XCTAssertTrue(use.waitForExistence(timeout: 5), "A card shows its mode's preview.") - capture("Code preview") - use.tap() - XCTAssertTrue(app.descendants(matching: .any)["code.screen"].firstMatch.waitForExistence(timeout: 10), - "Code opens as the home.") + XCTAssertFalse(skip.exists, "How to start can't be skipped.") + XCTAssertTrue(app.buttons["onboarding.mode.chats"].exists) + capture("How do you want to start") + // The run's own landing is Chats (the base class pins it): Bots must come from the answer. + let bots = app.buttons["onboarding.mode.bots"] + XCTAssertTrue(bots.waitForExistence(timeout: 5)) + bots.tap() + app.buttons["onboarding.mode.continue"].tap() + XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].firstMatch.waitForExistence(timeout: 10), + "The home opens on Bots.") } func testNotificationsCanBeSkipped() { @@ -153,13 +147,25 @@ final class FirstRunOnboardingUITests: BighelpUITestCase { return app } + /// A first launch: nobody has agreed to share data yet, whatever an earlier run on this + /// simulator left saved. private func launchFresh() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", "-force-signed-out-onboarding"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", + "-force-signed-out-onboarding", Self.forgetsAgreement] app.launch() return app } + private static let forgetsAgreement = "-test-forget-ai-data-agreement" + + /// Closes the app and opens it again, keeping what the first launch saved. + private func relaunch(_ app: XCUIApplication) { + app.terminate() + app.launchArguments.removeAll { $0 == Self.forgetsAgreement } + app.launch() + } + private func capture(_ name: String) { let attachment = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) attachment.name = name diff --git a/BighelpUITests/FleetSettingsUITests.swift b/BighelpUITests/FleetSettingsUITests.swift index 16020a96..b4d91d73 100644 --- a/BighelpUITests/FleetSettingsUITests.swift +++ b/BighelpUITests/FleetSettingsUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Settings › Fleet settings in the all-hosts demo: every host's plugin +/// Settings › Update every computer in the multi-host demo: every host's plugin /// updates at once, each host that needs it shows Restart, and a restart /// ends in done. Demo hosts: Home Hermes and Studio Mac (both a plugin /// release behind) and Office Linux (out of reach, skipped). @@ -35,26 +35,7 @@ final class FleetSettingsUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-use-multi-host-fixtures", "-bighelp.hosts.all-hosts", "NO", "-loopdy.demo.appearance", appearance] app.launch() - - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let allHosts = app.buttons["menu.all-hosts"] - XCTAssertTrue(allHosts.waitForExistence(timeout: 5)) - allHosts.tap() - XCTAssertTrue(app.descendants(matching: .any)["fleet.home"].waitForExistence(timeout: 5)) - - // Settings asks which host, and offers settings for every host first. - menu.tap() - let settings = app.buttons["menu.settings"] - XCTAssertTrue(settings.waitForExistence(timeout: 5)) - settings.tap() - let fleetSettings = app.buttons["fleet.gate.fleet-settings"] - XCTAssertTrue(fleetSettings.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["fleet.gate.host.Home Hermes"].exists, "The hosts are still listed") - save("settings-popup-\(appearance)", app) - fleetSettings.tap() - XCTAssertTrue(app.navigationBars["Update every computer"].waitForExistence(timeout: 5)) + openUpdateEveryComputer(in: app) let homePlugin = status("fleet.settings.plugin.Home Hermes", in: app) XCTAssertTrue(wait(for: homePlugin, toRead: "2.19.0 → 2.20.1"), homePlugin.label) @@ -99,28 +80,14 @@ final class FleetSettingsUITests: BighelpUITestCase { save("hermes-done-\(appearance)", app) } - /// One host at a time, from its own row, and this app's Appearance and Chat from the same page. + /// One host at a time, from its own row. @MainActor - func testOneHostAtATimeAndThisAppsPages() throws { + func testOneHostAtATime() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-use-multi-host-fixtures", "-bighelp.hosts.all-hosts", "NO"] app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let allHosts = app.buttons["menu.all-hosts"] - XCTAssertTrue(allHosts.waitForExistence(timeout: 5)) - allHosts.tap() - XCTAssertTrue(app.descendants(matching: .any)["fleet.home"].waitForExistence(timeout: 5)) - menu.tap() - let settings = app.buttons["menu.settings"] - XCTAssertTrue(settings.waitForExistence(timeout: 5)) - settings.tap() - let fleetSettings = app.buttons["fleet.gate.fleet-settings"] - XCTAssertTrue(fleetSettings.waitForExistence(timeout: 5)) - fleetSettings.tap() - XCTAssertTrue(app.navigationBars["Update every computer"].waitForExistence(timeout: 5)) + openUpdateEveryComputer(in: app) let homeHermes = status("fleet.settings.hermes.Home Hermes", in: app) XCTAssertTrue(wait(for: homeHermes, toRead: "12 commits behind"), homeHermes.label) @@ -140,15 +107,13 @@ final class FleetSettingsUITests: BighelpUITestCase { confirm.tap() XCTAssertTrue(wait(for: homeHermes, toRead: "Updated · 0.21.5", timeout: 15), homeHermes.label) XCTAssertTrue(app.buttons["fleet.settings.hermes.Studio Mac.action"].exists, "Only that host updated") + } - let appearanceLink = app.buttons["fleet.settings.app.appearance"] - for _ in 0..<6 where !(appearanceLink.exists && appearanceLink.isHittable) { list.swipeUp() } - XCTAssertTrue(appearanceLink.exists, "Appearance is here") - XCTAssertTrue(app.buttons["fleet.settings.app.chat"].exists, "Chat is here") - save("this-app", app) - appearanceLink.tap() - XCTAssertTrue(app.descendants(matching: .any)["appearance.studio"].waitForExistence(timeout: 5)) - save("appearance-from-fleet", app) + /// Settings › Your computers › Update every computer. + @MainActor private func openUpdateEveryComputer(in app: XCUIApplication) { + openSettings(in: app) + settingsRow("settings.update-every-computer", in: app).tap() + XCTAssertTrue(app.navigationBars["Update every computer"].waitForExistence(timeout: 5)) } @MainActor private func status(_ row: String, in app: XCUIApplication) -> XCUIElement { diff --git a/BighelpUITests/GroupSettingsUITests.swift b/BighelpUITests/GroupSettingsUITests.swift index 706c2084..a344d5c1 100644 --- a/BighelpUITests/GroupSettingsUITests.swift +++ b/BighelpUITests/GroupSettingsUITests.swift @@ -10,14 +10,16 @@ final class GroupSettingsUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-group-settings", "-loopdy.demo.appearance", appearance] + extra app.launch() - openAgents(in: app) - let search = app.searchFields["Search agents and groups"].firstMatch - XCTAssertTrue(revealSearchField(search, in: app)) - search.tap() - search.typeText("Garden\n") - let group = app.buttons["agents.group.group-settings-demo"] - XCTAssertTrue(group.waitForExistence(timeout: 8)) + // The demo has many group chats: New chat's To field finds this one among them. + chatNewChatButton(in: app).tap() + let to = app.textFields["new-chat.to.field"].firstMatch + XCTAssertTrue(to.waitForExistence(timeout: 10)) + to.tap() + to.typeText("Garden party") + let group = app.buttons["new-chat.group.hermes-room:group-settings-demo"].firstMatch + XCTAssertTrue(group.waitForExistence(timeout: 8), "New chat lists the demo's group chat") group.tap() + XCTAssertTrue(to.waitForNonExistence(timeout: 10), "The group chat takes New chat's place") XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 10)) return app } @@ -125,9 +127,13 @@ final class GroupSettingsUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-group-create", "-loopdy.demo.appearance", "light"] app.launch() - openAgents(in: app) - let create = app.buttons["agents.groups.create"] - for _ in 0..<6 where !(create.exists && create.isHittable) { app.swipeUp() } + // Bots › + › New Group Chat. + showBots(in: app) + let add = app.buttons["simple-bots.new"].firstMatch + XCTAssertTrue(add.waitForExistence(timeout: 5)) + add.tap() + let create = app.buttons.matching(NSPredicate(format: "identifier == %@ OR label == %@", + "simple-bots.new.group", "New Group Chat")).firstMatch XCTAssertTrue(create.waitForExistence(timeout: 5)) create.tap() let everyone = app.buttons["bot-mode.create.routing.everyone"] diff --git a/BighelpUITests/HTMLAppsHostUITests.swift b/BighelpUITests/HTMLAppsHostUITests.swift index 4efbe0a4..8ec396f9 100644 --- a/BighelpUITests/HTMLAppsHostUITests.swift +++ b/BighelpUITests/HTMLAppsHostUITests.swift @@ -64,12 +64,11 @@ final class HTMLAppsHostUITests: BighelpUITestCase { let next = app.buttons["host-setup.continue"] XCTAssertTrue(next.waitForExistence(timeout: 45), "Connected") next.tap() - let newChat = app.buttons.matching(NSPredicate(format: "identifier IN %@", - ["sessions.empty.new-chat", "chat.home.new-chat", "chat.new-chat", "root.new-chat"])).firstMatch - if newChat.waitForExistence(timeout: 10) { - newChat.tap() - confirmNewChatPicker(in: app) - } + // The home's New chat, beside the bar; it opens with nobody picked. + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 20), "The home opens") + newChat.tap() + confirmNewChatPicker(in: app) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 20), "A chat opens") return app } diff --git a/BighelpUITests/HTMLAppsUITests.swift b/BighelpUITests/HTMLAppsUITests.swift index cde9c4e9..5d5f5d94 100644 --- a/BighelpUITests/HTMLAppsUITests.swift +++ b/BighelpUITests/HTMLAppsUITests.swift @@ -74,7 +74,7 @@ final class HTMLAppsUITests: BighelpUITestCase { private func launch(appearance: String) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-html-apps", - "-loopdy.home.opens-chat", "YES", "-loopdy.settings.nerd-mode", "NO", + "-start-chat", "-loopdy.settings.nerd-mode", "NO", "-loopdy.demo.appearance", appearance] app.launch() return app diff --git a/BighelpUITests/HermesGroupsHostUITests.swift b/BighelpUITests/HermesGroupsHostUITests.swift index 1fe7a64d..4cc82ab8 100644 --- a/BighelpUITests/HermesGroupsHostUITests.swift +++ b/BighelpUITests/HermesGroupsHostUITests.swift @@ -28,9 +28,13 @@ final class HermesGroupsHostUITests: BighelpUITestCase { app.launch() try connect(app) - // New group chat with both agents. - openRootTab("tab.agents", in: app, timeout: 30) - let create = app.buttons["agents.groups.create"] + // New group chat with both agents: Bots › + › New Group Chat. + showBots(in: app, timeout: 30) + let add = app.buttons["simple-bots.new"].firstMatch + XCTAssertTrue(add.waitForExistence(timeout: 30)) + add.tap() + let create = app.buttons.matching(NSPredicate(format: "identifier == %@ OR label == %@", + "simple-bots.new.group", "New Group Chat")).firstMatch XCTAssertTrue(create.waitForExistence(timeout: 30), "Group chats are offered") create.tap() let title = app.textFields["bot-mode.create.title"] @@ -98,17 +102,17 @@ final class HermesGroupsHostUITests: BighelpUITestCase { save("\(label)-6-recovered", app) } - // Delete the group. - swipeBackFromLeadingEdge(in: app) - openRootTab("tab.agents", in: app, timeout: 20) + // Delete the group: its row on Bots, held, › Delete Group Chat. + goBackFromChat(in: app) + showBots(in: app, timeout: 20) let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND label CONTAINS %@", - "agents.group.", "Paths \(label)")).firstMatch + "simple-bots.group.", "Paths \(label)")).firstMatch XCTAssertTrue(row.waitForExistence(timeout: 20)) - row.swipeLeft() - let delete = app.buttons["Delete"].firstMatch + row.press(forDuration: 1.2) + let delete = app.buttons["Delete Group Chat"].firstMatch XCTAssertTrue(delete.waitForExistence(timeout: 5)) delete.tap() - let confirm = app.buttons["Delete group"].firstMatch + let confirm = app.buttons["simple-bots.group.delete.confirm"].firstMatch XCTAssertTrue(confirm.waitForExistence(timeout: 5)) confirm.tap() XCTAssertTrue(row.waitForNonExistence(timeout: 30), "The group is gone") diff --git a/BighelpUITests/HomeShellUITests.swift b/BighelpUITests/HomeShellUITests.swift new file mode 100644 index 00000000..8eed20ab --- /dev/null +++ b/BighelpUITests/HomeShellUITests.swift @@ -0,0 +1,333 @@ +import XCTest + +/// The one home: three places (Bots or Chats, Today, Work), New chat beside the bar, Settings behind +/// the person's circle, and every chat a pushed page with Back. Set BIGHELP_HOME_EVIDENCE +/// (TEST_RUNNER_BIGHELP_HOME_EVIDENCE) to a folder to save a screenshot of each screen, light and dark. +final class HomeShellUITests: BighelpUITestCase { + // Each scenario runs once in light and once in dark, as tests of their own: a test's launches + // share one saved state, and the second look must start from a clean one. + + @MainActor func testALaunchLandsOnThePlaceThePersonPicked() { aLaunchLandsOnThePlaceThePersonPicked("light") } + @MainActor func testALaunchLandsOnThePlaceThePersonPickedInDark() { aLaunchLandsOnThePlaceThePersonPicked("dark") } + + @MainActor + private func aLaunchLandsOnThePlaceThePersonPicked(_ appearance: String) { + do { + let roots = ["bots": "simple-bots.home", "chats": "chats.inbox", "today": "today.home", "work": "work.screen"] + for landing in ["bots", "chats", "today", "work"] { + let app = launch(landing: landing, appearance: appearance) + XCTAssertTrue(element(roots[landing]!, in: app).waitForExistence(timeout: 20), "\(landing) is the root") + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 5), "The bar shows at the root") + XCTAssertFalse(app.textViews["chat.composer.text"].exists, "No chat opens by itself") + shot("landing-\(landing)", appearance, app) + app.terminate() + } + } + } + + @MainActor func testTheSwitchTheTabsAndTheCircle() { theSwitchTheTabsAndTheCircle("light") } + @MainActor func testTheSwitchTheTabsAndTheCircleInDark() { theSwitchTheTabsAndTheCircle("dark") } + + @MainActor + private func theSwitchTheTabsAndTheCircle(_ appearance: String) { + do { + let app = launch(landing: "bots", appearance: appearance) + XCTAssertTrue(element("simple-bots.home", in: app).waitForExistence(timeout: 20)) + app.buttons["home.switch.chats"].firstMatch.tap() + XCTAssertTrue(element("chats.inbox", in: app).waitForExistence(timeout: 10), "The switch shows Chats") + shot("switch-to-chats", appearance, app) + app.buttons["home.switch.bots"].firstMatch.tap() + XCTAssertTrue(element("simple-bots.home", in: app).waitForExistence(timeout: 10), "And Bots again") + + app.buttons["home.tab.today"].firstMatch.tap() + XCTAssertTrue(element("today.home", in: app).waitForExistence(timeout: 10)) + app.buttons["home.tab.work"].firstMatch.tap() + XCTAssertTrue(element("work.screen", in: app).waitForExistence(timeout: 10)) + app.buttons["home.tab.conversations"].firstMatch.tap() + XCTAssertTrue(element("simple-bots.home", in: app).waitForExistence(timeout: 10), "The view stays as it was left") + + for tab in ["conversations", "today", "work"] { + app.buttons["home.tab.\(tab)"].firstMatch.tap() + let circle = app.buttons["simple-bots.settings"].firstMatch + XCTAssertTrue(circle.waitForExistence(timeout: 10), "The circle is on \(tab)") + XCTAssertFalse(app.buttons["home.drawer.open"].exists, "iPhone has no menu on \(tab)") + circle.tap() + XCTAssertTrue(element("settings.screen", in: app).waitForExistence(timeout: 10), "It opens Settings from \(tab)") + if tab == "conversations" { shot("settings", appearance, app) } + app.buttons["Done"].firstMatch.tap() + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 10)) + } + app.terminate() + } + } + + @MainActor func testAChatIsAPushedPageWithBackTheBotAndNoBar() { aChatIsAPushedPageWithBackTheBotAndNoBar("light") } + @MainActor func testAChatIsAPushedPageWithBackTheBotAndNoBarInDark() { aChatIsAPushedPageWithBackTheBotAndNoBar("dark") } + + @MainActor + private func aChatIsAPushedPageWithBackTheBotAndNoBar(_ appearance: String) { + do { + let app = launch(landing: "chats", appearance: appearance) + let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "chats.row.")).firstMatch + XCTAssertTrue(row.waitForExistence(timeout: 20)) + row.tap() + let back = app.buttons["chat.back"].firstMatch + XCTAssertTrue(back.waitForExistence(timeout: 15), "A chat has Back") + XCTAssertTrue(app.buttons["chat.options"].firstMatch.exists, "And its options") + XCTAssertTrue(app.textViews["chat.composer.text"].firstMatch.waitForExistence(timeout: 10)) + XCTAssertFalse(app.buttons["home.tab.today"].exists, "No bar under a chat") + XCTAssertFalse(app.buttons["home.new-chat"].exists) + shot("chat-from-chats", appearance, app) + + let identity = app.buttons["chat.identity"].firstMatch + XCTAssertTrue(identity.waitForExistence(timeout: 5), "The bot is in the header") + identity.tap() + XCTAssertTrue(element("simple-bots.profile", in: app).waitForExistence(timeout: 10), "It opens the bot's page") + shot("bot-page-from-chat", appearance, app) + app.buttons["simple-bots.profile.back"].firstMatch.tap() + + XCTAssertTrue(back.waitForExistence(timeout: 10)) + back.tap() + XCTAssertTrue(element("chats.inbox", in: app).waitForExistence(timeout: 10), "Back returns to Chats") + XCTAssertTrue(app.buttons["home.tab.today"].firstMatch.waitForExistence(timeout: 5), "With the bar") + shot("back-on-chats", appearance, app) + + // The computer in use's own Sessions page (projects, imports) is one row down the list. + let thisComputer = app.buttons["chats.more.this-computer"].firstMatch + for _ in 0..<20 where !(thisComputer.exists && thisComputer.isHittable) { + element("chats.inbox", in: app).swipeUp(velocity: .fast) + } + XCTAssertTrue(thisComputer.exists && thisComputer.isHittable, "This computer is at the end of Chats") + thisComputer.tap() + XCTAssertTrue(app.navigationBars["Sessions"].waitForExistence(timeout: 10), "It is a pushed page") + XCTAssertFalse(app.buttons["home.new-chat"].exists) + shot("chats-this-computer", appearance, app) + app.navigationBars["Sessions"].buttons.firstMatch.tap() + XCTAssertTrue(element("chats.inbox", in: app).waitForExistence(timeout: 10)) + app.terminate() + } + } + + @MainActor func testNewChatWithOneBotBecomesAnOrdinaryChat() { newChatWithOneBotBecomesAnOrdinaryChat("light") } + @MainActor func testNewChatWithOneBotBecomesAnOrdinaryChatInDark() { newChatWithOneBotBecomesAnOrdinaryChat("dark") } + + @MainActor + private func newChatWithOneBotBecomesAnOrdinaryChat(_ appearance: String) { + do { + let app = launch(landing: "chats", appearance: appearance) + openNewChat(in: app) + shot("new-chat", appearance, app) + + app.buttons["new-chat.bot.travel"].firstMatch.tap() + XCTAssertTrue(element("new-chat.to.chip.travel", in: app).waitForExistence(timeout: 10), "The pick is in the To row") + shot("new-chat-one-bot", appearance, app) + + // The plain demo's computer makes no group chats, so the other bots show dimmed: a tap on + // one adds nobody and says why. + app.buttons["new-chat.bot.finance"].firstMatch.tap() + XCTAssertTrue(element("new-chat.to.refusal", in: app).waitForExistence(timeout: 5), "A bot that can't join says why") + XCTAssertFalse(element("new-chat.to.chip.finance", in: app).exists) + + send("Plan one day in Lisbon", in: app) + XCTAssertTrue(element("new-chat.to", in: app).waitForNonExistence(timeout: 15), "Once sent it is an ordinary chat") + XCTAssertFalse(element("new-chat.people", in: app).exists) + XCTAssertTrue(app.buttons["chat.identity"].firstMatch.waitForExistence(timeout: 10), "With its bot in the header") + shot("new-chat-one-bot-sent", appearance, app) + + app.buttons["chat.back"].firstMatch.tap() + XCTAssertTrue(element("chats.inbox", in: app).waitForExistence(timeout: 10)) + app.terminate() + } + } + + @MainActor func testNewChatWithTwoBotsOpensAGroupChat() { newChatWithTwoBotsOpensAGroupChat("light") } + @MainActor func testNewChatWithTwoBotsOpensAGroupChatInDark() { newChatWithTwoBotsOpensAGroupChat("dark") } + + @MainActor + private func newChatWithTwoBotsOpensAGroupChat(_ appearance: String) { + do { + // The demo makes group chats only with this argument; they then sit quiet. + let app = launch(landing: "bots", appearance: appearance, extra: ["-preview-group-create"]) + openNewChat(in: app) + app.buttons["new-chat.bot.finance"].firstMatch.tap() + XCTAssertTrue(element("new-chat.to.chip.finance", in: app).waitForExistence(timeout: 10)) + // Here a second bot can join, so nobody is dimmed. + shot("new-chat-group-one-bot", appearance, app) + app.buttons["new-chat.bot.travel"].firstMatch.tap() + XCTAssertTrue(element("new-chat.to.chip.travel", in: app).waitForExistence(timeout: 10)) + shot("new-chat-two-bots", appearance, app) + + send("What should a week in Lisbon cost?", in: app) + XCTAssertTrue(element("new-chat.to", in: app).waitForNonExistence(timeout: 20), "The group chat takes New chat's place") + XCTAssertTrue(app.textViews["chat.composer.text"].firstMatch.waitForExistence(timeout: 10)) + XCTAssertTrue(app.buttons["chat.back"].firstMatch.exists) + // The group chat's own ⋯ has Group Settings; a chat with one bot doesn't. + XCTAssertTrue(chatMenuItem("chat.group-settings", in: app).exists, "It is a group chat") + app.tapCoordinate(x: 0.5, y: 0.5) + shot("new-chat-group-sent", appearance, app) + + app.buttons["chat.back"].firstMatch.tap() + XCTAssertTrue(element("simple-bots.home", in: app).waitForExistence(timeout: 10), "No blank chat is left under it") + app.terminate() + } + } + + @MainActor func testTodayHasItsCardPanelsAndEdit() { todayHasItsCardPanelsAndEdit("light") } + @MainActor func testTodayHasItsCardPanelsAndEditInDark() { todayHasItsCardPanelsAndEdit("dark") } + + @MainActor + private func todayHasItsCardPanelsAndEdit(_ appearance: String) { + do { + let app = launch(landing: "today", appearance: appearance) + XCTAssertTrue(element("today.home", in: app).waitForExistence(timeout: 20)) + XCTAssertTrue(element("today.boards.kind", in: app).waitForExistence(timeout: 10), "Feed, Ideas and Goals") + shot("today", appearance, app) + + app.buttons["today.boards.see-all"].firstMatch.tap() + XCTAssertTrue(app.buttons["today.board-page.back"].firstMatch.waitForExistence(timeout: 10), "See all is a page with Back") + XCTAssertFalse(app.buttons["home.new-chat"].exists) + shot("today-see-all", appearance, app) + app.buttons["today.board-page.chip.finance"].firstMatch.tap() + shot("today-see-all-one-bot", appearance, app) + app.buttons["today.board-page.back"].firstMatch.tap() + XCTAssertTrue(element("today.boards.kind", in: app).waitForExistence(timeout: 10)) + + let space = app.descendants(matching: .any) + .matching(NSPredicate(format: "identifier BEGINSWITH %@ AND identifier ENDSWITH %@", "today.space.", ".open")).firstMatch + if space.waitForExistence(timeout: 10) { + for _ in 0..<4 where !space.isHittable { element("today.home", in: app).swipeUp() } + shot("today-space-panel", appearance, app) + space.tap() + sleep(3) + shot("today-space-page", appearance, app) + let close = app.buttons.matching(NSPredicate(format: "label IN %@", ["Close", "Done"])).firstMatch + if close.waitForExistence(timeout: 5) { close.tap() } + // The Wide panel below it, for a look at its bottom edge (whole lines only). + element("today.home", in: app).swipeUp() + shot("today-space-wide", appearance, app) + element("today.home", in: app).swipeDown() + } else { + XCTFail("The demo's space has no panel on Today") + } + + let edit = app.buttons["today.edit"].firstMatch + XCTAssertTrue(edit.waitForExistence(timeout: 10)) + edit.tap() + let rows = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "today.edit.row.")) + XCTAssertTrue(rows.firstMatch.waitForExistence(timeout: 10), "Edit lists the panels") + shot("today-edit", appearance, app) + edit.tap() + XCTAssertTrue(element("today.boards.kind", in: app).waitForExistence(timeout: 10), "Done shows them again") + app.terminate() + } + } + + @MainActor func testWorkHasItsChipsCardsAndDoors() { workHasItsChipsCardsAndDoors("light") } + @MainActor func testWorkHasItsChipsCardsAndDoorsInDark() { workHasItsChipsCardsAndDoors("dark") } + + @MainActor + private func workHasItsChipsCardsAndDoors(_ appearance: String) { + do { + let app = launch(landing: "work", appearance: appearance) + XCTAssertTrue(element("work.screen", in: app).waitForExistence(timeout: 20)) + XCTAssertTrue(element("work.filters", in: app).waitForExistence(timeout: 10)) + let card = app.descendants(matching: .any) + .matching(NSPredicate(format: "identifier BEGINSWITH %@", "work.item.")).firstMatch + XCTAssertTrue(card.waitForExistence(timeout: 15), "The demo has work to show") + shot("work", appearance, app) + + app.buttons["work.filter.working"].firstMatch.tap() + shot("work-working", appearance, app) + app.buttons["work.filter.all"].firstMatch.tap() + + XCTAssertTrue(card.waitForExistence(timeout: 5)) + card.tap() + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForNonExistence(timeout: 10), "A card opens its page over Work") + shot("work-card-open", appearance, app) + leavePushedPage(in: app) + XCTAssertTrue(element("work.screen", in: app).waitForExistence(timeout: 10)) + + let door = app.buttons["work.door.schedules"].firstMatch + for _ in 0..<5 where !(door.exists && door.isHittable) { element("work.screen", in: app).swipeUp() } + shot("work-doors", appearance, app) + XCTAssertTrue(door.exists && door.isHittable, "Schedules is one tap down") + door.tap() + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForNonExistence(timeout: 10), "The door opens its page") + shot("work-door-open", appearance, app) + leavePushedPage(in: app) + XCTAssertTrue(element("work.screen", in: app).waitForExistence(timeout: 10), "Back returns to Work") + app.terminate() + } + } + + // MARK: Helpers + + @MainActor + private func launch(landing: String, appearance: String, extra: [String] = []) -> XCUIApplication { + let app = makeApp() + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.home.migrated-v1", "YES", + "-loopdy.home.landing", landing, "-bighelp.hosts.all-hosts", "NO", + "-loopdy.demo.appearance", appearance] + extra + app.launch() + return app + } + + @MainActor + private func element(_ identifier: String, in app: XCUIApplication) -> XCUIElement { + app.descendants(matching: .any)[identifier].firstMatch + } + + @MainActor + private func openNewChat(in app: XCUIApplication) { + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 20)) + newChat.tap() + XCTAssertTrue(element("new-chat.to", in: app).waitForExistence(timeout: 15), "New chat has its To row") + XCTAssertTrue(element("new-chat.people", in: app).waitForExistence(timeout: 10), "And the bots to pick from") + XCTAssertTrue(app.buttons["chat.back"].firstMatch.exists, "It is a chat: Back leaves it") + XCTAssertFalse(app.buttons["home.tab.today"].exists, "No bar under it") + } + + @MainActor + private func send(_ text: String, in app: XCUIApplication) { + let editor = app.textViews["chat.composer.text"].firstMatch + XCTAssertTrue(editor.waitForExistence(timeout: 10)) + editor.tap() + editor.typeText(text) + let send = app.buttons["chat.send"].firstMatch + XCTAssertTrue(send.waitForExistence(timeout: 5)) + send.tap() + } + + /// A chat's own Back, a bot page's, else the navigation bar's. + @MainActor + private func leavePushedPage(in app: XCUIApplication) { + for identifier in ["chat.back", "simple-bots.profile.back"] { + let back = app.buttons[identifier].firstMatch + if back.exists, back.isHittable { back.tap(); return } + } + let back = app.navigationBars.buttons.firstMatch + if back.waitForExistence(timeout: 5) { back.tap() } + } + + @MainActor + private func shot(_ name: String, _ appearance: String, _ app: XCUIApplication) { + // A push or a sheet still moving would be caught halfway. + usleep(700_000) + let image = XCUIScreen.main.screenshot() + let attachment = XCTAttachment(screenshot: image) + attachment.name = "\(name)-\(appearance)" + attachment.lifetime = .keepAlways + add(attachment) + guard let folder = ProcessInfo.processInfo.environment["BIGHELP_HOME_EVIDENCE"], !folder.isEmpty else { return } + try? image.pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name)-\(appearance).png")) + } +} + +private extension XCUIApplication { + /// Closes an open menu without picking from it. + @MainActor + func tapCoordinate(x: CGFloat, y: CGFloat) { + windows.firstMatch.coordinate(withNormalizedOffset: CGVector(dx: x, dy: y)).tap() + } +} diff --git a/BighelpUITests/HostOnboardingUITestSupport.swift b/BighelpUITests/HostOnboardingUITestSupport.swift index 9450a5ea..0f3eaba2 100644 --- a/BighelpUITests/HostOnboardingUITestSupport.swift +++ b/BighelpUITests/HostOnboardingUITestSupport.swift @@ -31,7 +31,7 @@ extension BighelpUITestCase { XCTAssertTrue(continueAfterConnecting(app), "Connected") } - /// Connected: the step says so, and its button goes on through the plugin and mode steps. The + /// Connected: the step says so, and its button goes on through the plugin and home steps. The /// button reads Continue in first setup, like Connect's, so the step's own line tells them apart. @MainActor @discardableResult func continueAfterConnecting(_ app: XCUIApplication, timeout: TimeInterval = 45) -> Bool { @@ -45,8 +45,8 @@ extension BighelpUITestCase { return true } - /// After Connect: skips the optional plugin (and notifications) and chooses Sessions, the app as it - /// comes, which these tests expect. + /// After Connect: skips the optional plugin (and notifications) and answers "How do you want to + /// start?" with Chats, the list these tests expect. /// BIGHELP_FIRST_SETUP_EVIDENCE (TEST_RUNNER_…) saves the plugin step as the host shows it. @MainActor func finishFirstSetup(_ app: XCUIApplication) { let skip = app.buttons["onboarding.skip"] @@ -60,11 +60,10 @@ extension BighelpUITestCase { skip.tap() } if app.buttons["onboarding.notifications.enable"].waitForExistence(timeout: 2) { skip.tap() } - let sessions = app.buttons["onboarding.mode.sessions"] - guard sessions.waitForExistence(timeout: 10) else { return } - app.buttons["onboarding.mode.bots"].swipeLeft() - sessions.tap() - let use = app.buttons["onboarding.mode.preview.use"] - if use.waitForExistence(timeout: 5) { use.tap() } + let chats = app.buttons["onboarding.mode.chats"] + guard chats.waitForExistence(timeout: 10) else { return } + chats.tap() + let next = app.buttons["onboarding.mode.continue"] + if next.waitForExistence(timeout: 5) { next.tap() } } } diff --git a/BighelpUITests/HostSignInMatrixUITests.swift b/BighelpUITests/HostSignInMatrixUITests.swift index 53464f9d..4112acd3 100644 --- a/BighelpUITests/HostSignInMatrixUITests.swift +++ b/BighelpUITests/HostSignInMatrixUITests.swift @@ -55,11 +55,10 @@ final class HostSignInMatrixUITests: BighelpUITestCase { try connect(app) app.buttons["host-setup.continue"].tap() // A new host has no chats yet: start the first one. - let firstChat = app.buttons["sessions.empty.new-chat"] - if firstChat.waitForExistence(timeout: 10) { - firstChat.tap() - confirmNewChatPicker(in: app) - } + let firstChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(firstChat.waitForExistence(timeout: 20), "The home opens") + firstChat.tap() + confirmNewChatPicker(in: app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20), "A chat opens after connecting") composer.tap() @@ -232,10 +231,10 @@ final class HostSignInMatrixUITests: BighelpUITestCase { XCTAssertFalse(text("MEDIA:", in: app).exists, "No raw MEDIA line in its place") save("media-1-after-turn", app) - swipeBackFromLeadingEdge(in: app) + goBackFromChat(in: app) let row = app.descendants(matching: .any) - .matching(NSPredicate(format: "identifier BEGINSWITH %@", "session.row.")).firstMatch - if !row.waitForExistence(timeout: 5) { openRootTab("tab.sessions", in: app) } + .matching(NSPredicate(format: "identifier BEGINSWITH %@", "chats.row.")).firstMatch + if !row.waitForExistence(timeout: 5) { showChats(in: app) } XCTAssertTrue(row.waitForExistence(timeout: 15), "The chat is listed") row.tap() XCTAssertTrue(picture.waitForExistence(timeout: 30), "The picture is there after reopening the chat") @@ -260,10 +259,10 @@ final class HostSignInMatrixUITests: BighelpUITestCase { XCTAssertFalse(text("MEDIA:", in: app).exists, "No raw MEDIA line in their place") save("media-11-saved-pictures", app) - swipeBackFromLeadingEdge(in: app) + goBackFromChat(in: app) let row = app.descendants(matching: .any) - .matching(NSPredicate(format: "identifier BEGINSWITH %@", "session.row.")).firstMatch - if !row.waitForExistence(timeout: 5) { openRootTab("tab.sessions", in: app) } + .matching(NSPredicate(format: "identifier BEGINSWITH %@", "chats.row.")).firstMatch + if !row.waitForExistence(timeout: 5) { showChats(in: app) } XCTAssertTrue(row.waitForExistence(timeout: 15), "The chat is listed") row.tap() XCTAssertTrue(pictures.waitForExistence(timeout: 30), "The pictures are there after reopening the chat") @@ -277,8 +276,8 @@ final class HostSignInMatrixUITests: BighelpUITestCase { let app = try beginSetup(mode: "media") try connect(app) app.buttons["host-setup.continue"].tap() - openRootTab("tab.agents", in: app) - let agent = app.buttons["agent.default"].firstMatch + showBots(in: app) + let agent = app.buttons["simple-bots.bot.default"].firstMatch XCTAssertTrue(agent.waitForExistence(timeout: 30), "The agent is listed") agent.tap() let composer = app.textViews["chat.composer.text"] @@ -311,7 +310,7 @@ final class HostSignInMatrixUITests: BighelpUITestCase { app.terminate() app.launch() - openRootTab("tab.agents", in: app) + showBots(in: app) XCTAssertTrue(agent.waitForExistence(timeout: 30)) agent.tap() XCTAssertTrue(pictures.waitForExistence(timeout: 45), "The pictures are there after a relaunch") @@ -326,8 +325,8 @@ final class HostSignInMatrixUITests: BighelpUITestCase { let app = try beginSetup(mode: "media") try connect(app) app.buttons["host-setup.continue"].tap() - openRootTab("tab.agents", in: app) - let agent = app.buttons["agent.default"].firstMatch + showBots(in: app) + let agent = app.buttons["simple-bots.bot.default"].firstMatch XCTAssertTrue(agent.waitForExistence(timeout: 30), "The agent is listed") agent.tap() let composer = app.textViews["chat.composer.text"] @@ -447,7 +446,7 @@ final class HostSignInMatrixUITests: BighelpUITestCase { let app = try beginSetup(mode: "media", extraArguments: ["-test-vault-import"]) try connect(app) app.buttons["host-setup.continue"].tap() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 20)) + XCTAssertTrue(app.buttons["home.new-chat"].waitForExistence(timeout: 20)) openConnectionsRow("settings.connections.vault", in: app) XCTAssertTrue(app.staticTexts["vault.empty"].waitForExistence(timeout: 20), "A new host's vault is empty") app.buttons["vault.add"].tap() @@ -482,13 +481,11 @@ final class HostSignInMatrixUITests: BighelpUITestCase { @MainActor private func openFirstChat(_ app: XCUIApplication) throws -> XCUIElement { try connect(app) app.buttons["host-setup.continue"].tap() - // A new host has no chats yet; one used by an earlier test opens its latest. - let newChat = app.buttons.matching(NSPredicate(format: "identifier IN %@", - ["sessions.empty.new-chat", "chat.home.new-chat", "chat.new-chat", "root.new-chat"])).firstMatch - if newChat.waitForExistence(timeout: 10) { - newChat.tap() - confirmNewChatPicker(in: app) - } + // The home's New chat, beside the bar; it opens with nobody picked. + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 20), "The home opens") + newChat.tap() + confirmNewChatPicker(in: app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20), "A chat opens after connecting") return composer diff --git a/BighelpUITests/ImageDraftsHostUITests.swift b/BighelpUITests/ImageDraftsHostUITests.swift index dc8e30a8..036109a5 100644 --- a/BighelpUITests/ImageDraftsHostUITests.swift +++ b/BighelpUITests/ImageDraftsHostUITests.swift @@ -97,12 +97,11 @@ final class ImageDraftsHostUITests: BighelpUITestCase { let next = app.buttons["host-setup.continue"] XCTAssertTrue(next.waitForExistence(timeout: 45), "Connected") next.tap() - let newChat = app.buttons.matching(NSPredicate(format: "identifier IN %@", - ["sessions.empty.new-chat", "chat.home.new-chat", "chat.new-chat", "root.new-chat"])).firstMatch - if newChat.waitForExistence(timeout: 10) { - newChat.tap() - confirmNewChatPicker(in: app) - } + // The home's New chat, beside the bar; it opens with nobody picked. + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 20), "The home opens") + newChat.tap() + confirmNewChatPicker(in: app) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 20), "A chat opens") XCTAssertTrue(app.descendants(matching: .any)["chat.draft-attachments"].firstMatch.waitForExistence(timeout: 10) || app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS %@", "1 photo")).firstMatch.exists, diff --git a/BighelpUITests/ImageDraftsUITests.swift b/BighelpUITests/ImageDraftsUITests.swift index 5c046525..dc78c840 100644 --- a/BighelpUITests/ImageDraftsUITests.swift +++ b/BighelpUITests/ImageDraftsUITests.swift @@ -160,18 +160,13 @@ final class ImageDraftsUITests: BighelpUITestCase { func testPhotoActionsSettingsSaveAndReset() throws { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) - let options = app.buttons["chat.options"].firstMatch - XCTAssertTrue(options.waitForExistence(timeout: 20)) - options.tap() - let thisChat = app.buttons["This chat"].firstMatch - XCTAssertTrue(thisChat.waitForExistence(timeout: 5)) - thisChat.tap() - // SwiftUI menu items take their title as their identifier. - let edit = app.buttons["Edit this agent"].firstMatch - XCTAssertTrue(edit.waitForExistence(timeout: 5)) - edit.tap() - let row = app.buttons["agent.editor.photo-actions"].firstMatch - XCTAssertTrue(revealBelow(row, in: app).waitForExistence(timeout: 10), "Photo actions sits beside Instructions") + // The bot's page from the chat's pill, then its Info tab's What it can use. + openBotPage(fromChatIn: app) + let info = app.buttons["simple-bots.profile.tab.info"].firstMatch + XCTAssertTrue(info.waitForExistence(timeout: 5)) + info.tap() + let row = app.buttons["simple-bots.profile.photo-actions"].firstMatch + XCTAssertTrue(revealBelow(row, in: app).waitForExistence(timeout: 10), "Photo actions is on the bot's Info") row.tap() XCTAssertTrue(element("photo-actions.page", in: app).waitForExistence(timeout: 5)) XCTAssertTrue(app.switches["photo-actions.business_card.offer"].firstMatch.waitForExistence(timeout: 5)) @@ -207,7 +202,7 @@ final class ImageDraftsUITests: BighelpUITestCase { private func launch(appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-image-drafts", - "-loopdy.home.opens-chat", "YES", "-loopdy.settings.nerd-mode", "NO", + "-start-chat", "-loopdy.settings.nerd-mode", "NO", "-loopdy.demo.appearance", appearance] + extra app.launch() return app diff --git a/BighelpUITests/InstructionsEditingUITests.swift b/BighelpUITests/InstructionsEditingUITests.swift index 82104742..2b8b9be3 100644 --- a/BighelpUITests/InstructionsEditingUITests.swift +++ b/BighelpUITests/InstructionsEditingUITests.swift @@ -1,86 +1,17 @@ import XCTest -import CoreFoundation -/// Editing an agent's instructions (#727) on demo data with a long SOUL (`-test-long-soul`, about -/// 6,000 characters): the box in Edit Agent, the full-screen editor its expand button opens, and -/// Bots mode's Instructions sheet. Set BIGHELP_INSTRUCTIONS_EVIDENCE (TEST_RUNNER_…) to a folder to -/// save the screenshots. -/// -/// `testEditingSpeed` (only with BIGHELP_SPEED) measures typing and scrolling with the DEBUG probe -/// (`ChatPerformanceRecorder`). Its readings land in the app's Documents as -/// `chat-performance-instructions-.json`: 1 typing in the box, 2 scrolling it, 3 swiping it, -/// 4 typing full screen, 5 scrolling it, 6 swiping it. +/// Editing a bot's instructions on demo data with a long SOUL (`-test-long-soul`, about 6,000 +/// characters): a bot page's Instructions sheet. Set BIGHELP_INSTRUCTIONS_EVIDENCE (TEST_RUNNER_…) to a +/// folder to save the screenshots. final class InstructionsEditingUITests: BighelpUITestCase { @MainActor - func testInstructionsBoxClearsTheKeyboardAndKeepsItWhileScrolling() throws { - for appearance in ["light", "dark"] { - let app = launch(appearance: appearance) - let box = openInstructionsBox(in: app) - XCTAssertGreaterThan((box.value as? String)?.count ?? 0, 3_000, "The long SOUL fixture is loaded") - box.tap() - let keyboard = app.keyboards.firstMatch - guard keyboard.waitForExistence(timeout: 5) else { - throw XCTSkip("This simulator types with a hardware keyboard") - } - Thread.sleep(forTimeInterval: 1) - // Where the screen has room for it above the keyboard, the whole box clears it. - let top = app.navigationBars.firstMatch.frame.maxY - if keyboardTop(app) - top >= box.frame.height + 16 { - XCTAssertLessThanOrEqual(box.frame.maxY, keyboardTop(app) + 1, "The whole box clears the keyboard") - } - save("instructions-box-\(appearance)", app) - - // Back up through the text: a drag down the box that ends in the keyboard. - box.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.1)) - .press(forDuration: 0.05, thenDragTo: keyboard.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.4))) - XCTAssertFalse(keyboard.waitForNonExistence(timeout: 2), "Scrolling the box keeps the keyboard") - box.typeText(" Keep receipts.") - XCTAssertTrue((box.value as? String)?.contains("Keep receipts.") == true) - - // Down through the text: a drag that starts on the box scrolls its text, not the form. - let frame = box.frame - box.swipeUp(velocity: .slow) - XCTAssertEqual(box.frame.minY, frame.minY, accuracy: 2, "A drag on the box scrolls its text") - XCTAssertTrue(keyboard.exists) - - app.buttons["agent.editor.cancel"].tap() - let discard = app.buttons["Discard changes"] - if discard.waitForExistence(timeout: 3) { discard.tap() } - app.terminate() - } - } - - @MainActor - func testFullScreenInstructionsComeBackToTheBox() { - for appearance in ["light", "dark"] { - let app = launch(appearance: appearance) - let box = openInstructionsBox(in: app) - app.buttons["agent.editor.instructions.expand"].tap() - let editor = app.textViews["agent.editor.instructions.expand.focused"] - XCTAssertTrue(editor.waitForExistence(timeout: 5)) - XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5), "The full-screen editor starts typing") - editor.typeText("\nAlways show the total first.") - save("instructions-full-screen-\(appearance)", app) - app.buttons["agent.editor.instructions.expand.done"].tap() - XCTAssertTrue(editor.waitForNonExistence(timeout: 5)) - XCTAssertTrue((box.value as? String)?.hasSuffix("Always show the total first.") == true, - "What was typed full screen is in the box") - app.buttons["agent.editor.cancel"].tap() - let discard = app.buttons["Discard changes"] - XCTAssertTrue(discard.waitForExistence(timeout: 3), "The full-screen edit counts as a change") - discard.tap() - app.terminate() - } - } - - @MainActor - func testBotsModeInstructionsSheet() { + func testBotPageInstructionsSheet() { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-long-soul", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance] + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance] app.launch() - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 15)) primary.tap() let identity = app.buttons["chat.identity"] @@ -113,94 +44,6 @@ final class InstructionsEditingUITests: BighelpUITestCase { } } - @MainActor - func testEditingSpeed() throws { - guard ProcessInfo.processInfo.environment["BIGHELP_SPEED"] != nil else { - throw XCTSkip("Speed checks run on request") - } - let app = launch(appearance: "light", probe: true) - let box = openInstructionsBox(in: app) - box.tap() - XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) - measurePhases(of: box) - - app.buttons["agent.editor.instructions.expand"].tap() - let editor = app.textViews["agent.editor.instructions.expand.focused"] - XCTAssertTrue(editor.waitForExistence(timeout: 5)) - XCTAssertTrue(app.keyboards.firstMatch.waitForExistence(timeout: 5)) - measurePhases(of: editor) - } - - /// Typing, a scroll through the text and back, then real swipes, each its own reading. - @MainActor - private func measurePhases(of editor: XCUIElement) { - Thread.sleep(forTimeInterval: 1.5) - post(Probe.editorType) - Thread.sleep(forTimeInterval: 9) - post(Probe.editorScroll) - Thread.sleep(forTimeInterval: 10) - post(Probe.reset) - for _ in 0..<3 { editor.swipeUp() } - for _ in 0..<3 { editor.swipeDown() } - Thread.sleep(forTimeInterval: 1) - post(Probe.read) - Thread.sleep(forTimeInterval: 1) - } - - private enum Probe { - static let reset = "app.loopdy.fixture.chat-performance.reset" - static let read = "app.loopdy.fixture.chat-performance.read" - static let editorType = "app.loopdy.fixture.chat-performance.editor-type" - static let editorScroll = "app.loopdy.fixture.chat-performance.editor-scroll" - } - - private func post(_ name: String) { - CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), - CFNotificationName(name as CFString), nil, nil, true) - } - - @MainActor - private func launch(appearance: String, probe: Bool = false) -> XCUIApplication { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-long-soul", - "-loopdy.demo.appearance", appearance] - if probe { - app.launchArguments.append("-test-chat-performance-probe") - app.launchEnvironment["BIGHELP_PERF_LABEL"] = "instructions" - } - app.launch() - return app - } - - /// Edit Agent for Avery Park, scrolled to the instructions box. - @MainActor - private func openInstructionsBox(in app: XCUIApplication) -> XCUIElement { - openAgents(in: app) - let more = app.buttons["agent.finance.more"] - XCTAssertTrue(more.waitForExistence(timeout: 10)) - more.tap() - let edit = app.buttons["agent.finance.edit"] - for _ in 0..<4 where !edit.isHittable { - app.descendants(matching: .any)["agent.actions.list"].firstMatch.swipeUp() - } - edit.tap() - XCTAssertTrue(app.textFields["agent.editor.name"].waitForExistence(timeout: 5)) - // The form builds its rows as they scroll in. - let box = app.textViews["agent.editor.instructions"] - for _ in 0..<6 where !box.exists || !box.isHittable { app.swipeUp() } - XCTAssertTrue(box.isHittable) - return box - } - - /// The top of the keyboard, with the bar above it when there is one. - @MainActor - private func keyboardTop(_ app: XCUIApplication) -> CGFloat { - var top = app.keyboards.firstMatch.frame.minY - let done = app.buttons["Dismiss keyboard"].firstMatch - if done.exists, done.frame.maxY <= top + 1 { top = min(top, done.frame.minY - 6) } - return top - } - @MainActor private func save(_ name: String, _ app: XCUIApplication) { let shot = XCTAttachment(screenshot: app.screenshot()) diff --git a/BighelpUITests/LandingScreenUITests.swift b/BighelpUITests/LandingScreenUITests.swift index 69f88113..b49bfd2d 100644 --- a/BighelpUITests/LandingScreenUITests.swift +++ b/BighelpUITests/LandingScreenUITests.swift @@ -1,13 +1,13 @@ import XCTest -/// Settings › Chat › Opens on: each choice is where a cold launch lands, and -/// Start with picks the agent. Demo data. Set BIGHELP_LANDING_EVIDENCE -/// (TEST_RUNNER_BIGHELP_LANDING_EVIDENCE) to a folder to save the picker in -/// light and dark. +/// Settings › Chat › Opens on: a choice saved before the one home lands on the place that holds it +/// now, a link that opens the app wins over it, and the picker. Demo data. Set +/// BIGHELP_LANDING_EVIDENCE (TEST_RUNNER_BIGHELP_LANDING_EVIDENCE) to a folder to save the picker in +/// light and dark. Each new choice's own landing is `HomeShellUITests`'. final class LandingScreenUITests: BighelpUITestCase { - private func launch(_ app: XCUIApplication, landing: String?, extra: [String] = []) { - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.settings.nerd-mode", "NO"] - + (landing.map { ["-loopdy.home.landing", $0] } ?? []) + extra + private func launch(_ app: XCUIApplication, landing: String, extra: [String] = []) { + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.settings.nerd-mode", "NO", + "-loopdy.home.landing", landing] + extra app.launch() } @@ -15,107 +15,81 @@ final class LandingScreenUITests: BighelpUITestCase { app.descendants(matching: .any)[identifier].firstMatch } + /// Opens on as the old shell saved it: each screen opens the place that holds it now, with no chat. @MainActor - func testEachChoiceOpensOnItsScreen() throws { + func testAChoiceSavedBeforeOpensOnThePlaceThatHoldsItNow() throws { let app = makeApp() - let screens: [(landing: String, identifier: String, tab: String?)] = [ - ("feed", "board.feed", "tab.feed"), - ("ideas", "board.ideas", "tab.ideas"), - ("goals", "board.goals", "tab.goals"), - ("projects", "projects.screen", nil), - ("kanban", "kanban.screen", nil), - ("agents", "agents.screen", nil), - ("last-chat", "chat.identity", nil), - ("sessions", "sessions.screen", nil), - ("all-agents", "fleet.home", nil), + let screens: [(landing: String, identifier: String)] = [ + ("feed", "today.home"), + ("goals", "today.home"), + ("projects", "work.screen"), + ("kanban", "work.screen"), + ("agents", "simple-bots.home"), + ("all-agents", "simple-bots.home"), + ("last-chat", "chats.inbox"), + ("sessions", "chats.inbox"), ] for screen in screens { launch(app, landing: screen.landing) XCTAssertTrue(element(screen.identifier, in: app).waitForExistence(timeout: 25), "\(screen.landing) opens on \(screen.identifier)") - if let tab = screen.tab { - XCTAssertTrue(app.buttons[tab].firstMatch.isSelected, "\(screen.landing): its tab is selected") - } - if screen.landing == "last-chat" { - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 5), "A chat is open") - } - if screen.landing == "sessions" { - XCTAssertTrue(app.navigationBars["Sessions"].exists, "All sessions, to pick a recent one") - } - if screen.landing == "agents" { - XCTAssertFalse(element("fleet.home", in: app).exists, "One computer's agents, not every computer's") - } + XCTAssertFalse(app.textViews["chat.composer.text"].exists, "\(screen.landing): no chat opens by itself") app.terminate() } } - /// The real controls: pick a screen and an agent in Settings, then the - /// next launch opens there with that agent. + /// The real controls: Opens on picks a place, and Today or Work asks which view the first tab shows. @MainActor - func testPickedInSettingsOpensThereWithThatAgent() throws { + func testOpensOnPicksAPlaceAndTheFirstTabsView() throws { let app = makeApp() - launch(app, landing: nil, extra: ["-loopdy.home.opens-chat", "YES"]) - let hero = app.buttons["chat.identity"].firstMatch - XCTAssertTrue(hero.waitForExistence(timeout: 25), "Nothing picked: today's start, the agent's chat") - XCTAssertEqual(hero.label, "Avery Park", "The demo's default agent") + launch(app, landing: "chats") + XCTAssertTrue(element("chats.inbox", in: app).waitForExistence(timeout: 25)) - openRootTab("tab.profile", in: app) + openSettings(in: app) settingsRow("settings.menu.chat", in: app).tap() let openOn = app.buttons["settings.landing.screen"].firstMatch XCTAssertTrue(openOn.waitForExistence(timeout: 5), "Opens on leads Settings › Chat") - XCTAssertTrue(openOn.label.contains("Last chat"), "Shows today's start until you pick: \(openOn.label)") - openOn.tap() - let feed = app.buttons["Feed"].firstMatch - XCTAssertTrue(feed.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["Agents (multi)"].firstMatch.exists) - feed.tap() - XCTAssertTrue(openOn.label.contains("Feed"), openOn.label) - - let startWith = app.buttons["settings.landing.agent"].firstMatch - XCTAssertTrue(startWith.waitForExistence(timeout: 5)) - XCTAssertTrue(startWith.label.contains("Last bot used"), startWith.label) - startWith.tap() - let mina = app.buttons["Mina Shah"].firstMatch - XCTAssertTrue(mina.waitForExistence(timeout: 5)) - mina.tap() - XCTAssertTrue(startWith.label.contains("Mina Shah"), startWith.label) + XCTAssertTrue(openOn.label.contains("Chats"), "Shows where this launch opened: \(openOn.label)") + let firstTab = app.buttons["settings.landing.view"].firstMatch + XCTAssertFalse(firstTab.exists, "Bots and Chats name the first tab's view themselves") - // Agents (multi) has no one agent to start with. openOn.tap() - app.buttons["Agents (multi)"].firstMatch.tap() - XCTAssertTrue(startWith.waitForNonExistence(timeout: 3), "No Start with for every computer's agents") + let today = app.buttons["Today"].firstMatch + XCTAssertTrue(today.waitForExistence(timeout: 5)) + XCTAssertTrue(app.buttons["Work"].firstMatch.exists) + today.tap() + XCTAssertTrue(openOn.label.contains("Today"), openOn.label) + XCTAssertTrue(firstTab.waitForExistence(timeout: 3), "Today asks which view the first tab shows") + firstTab.tap() + let bots = app.buttons["Bots"].firstMatch + XCTAssertTrue(bots.waitForExistence(timeout: 5)) + bots.tap() + XCTAssertTrue(firstTab.label.contains("Bots"), firstTab.label) + openOn.tap() - app.buttons["Feed"].firstMatch.tap() - XCTAssertTrue(startWith.waitForExistence(timeout: 3)) + app.buttons["Chats"].firstMatch.tap() + XCTAssertTrue(firstTab.waitForNonExistence(timeout: 3), "Back to Chats, the row goes") app.terminate() - - // The same test run keeps its saved settings across relaunches. The - // Chat tab opens the agent's chat, as it does outside these tests. - launch(app, landing: nil, extra: ["-loopdy.home.opens-chat", "YES"]) - XCTAssertTrue(element("board.feed", in: app).waitForExistence(timeout: 25), "Opens on Feed") - XCTAssertTrue(app.buttons["tab.feed"].firstMatch.isSelected) - app.buttons["tab.sessions"].firstMatch.tap() - let homeHero = app.buttons["chat.identity"].firstMatch - XCTAssertTrue(homeHero.waitForExistence(timeout: 10)) - XCTAssertEqual(homeHero.label, "Mina Shah", "Started with the picked agent") } /// A link that opens the app wins over the landing screen. @MainActor func testALinkOpeningTheAppWinsOverTheLandingScreen() throws { let app = makeApp() - launch(app, landing: "feed") - XCTAssertTrue(element("board.feed", in: app).waitForExistence(timeout: 25)) + launch(app, landing: "today") + XCTAssertTrue(element("today.home", in: app).waitForExistence(timeout: 25)) app.terminate() - // Cold launch through a widget-style link to Goals. + // Cold launch through a widget-style link to Goals: every bot's Goals over Today. app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.settings.nerd-mode", "NO", - "-loopdy.home.landing", "projects"] + "-loopdy.home.landing", "work"] app.open(URL(string: "loopdy://agent/goals")!) - XCTAssertTrue(element("board.goals", in: app).waitForExistence(timeout: 25), "The link's screen opens") + let board = element("today.board-page", in: app) + XCTAssertTrue(board.waitForExistence(timeout: 25), "The link's screen opens") sleep(3) - XCTAssertFalse(element("projects.screen", in: app).exists, "The landing screen doesn't cover the link") - XCTAssertTrue(app.buttons["tab.goals"].firstMatch.isSelected) + XCTAssertTrue(board.exists, "The landing screen doesn't cover the link") + let work = element("work.screen", in: app) + XCTAssertFalse(work.exists && work.isHittable, "Work, the landing, isn't on top") } @MainActor @@ -123,26 +97,25 @@ final class LandingScreenUITests: BighelpUITestCase { let folder = ProcessInfo.processInfo.environment["BIGHELP_LANDING_EVIDENCE"] for appearance in ["light", "dark"] { let app = makeApp() - launch(app, landing: "goals", extra: ["-loopdy.demo.appearance", appearance]) - XCTAssertTrue(element("board.goals", in: app).waitForExistence(timeout: 25)) - app.buttons["tab.sessions"].firstMatch.tap() - openRootTab("tab.profile", in: app) + launch(app, landing: "today", extra: ["-loopdy.demo.appearance", appearance]) + XCTAssertTrue(element("today.home", in: app).waitForExistence(timeout: 25)) + openSettings(in: app) settingsRow("settings.menu.chat", in: app).tap() let openOn = app.buttons["settings.landing.screen"].firstMatch XCTAssertTrue(openOn.waitForExistence(timeout: 5)) save(folder, "\(appearance)-1-chat-page", app) openOn.tap() - XCTAssertTrue(app.buttons["Projects"].firstMatch.waitForExistence(timeout: 5)) + XCTAssertTrue(app.buttons["Work"].firstMatch.waitForExistence(timeout: 5)) sleep(1) save(folder, "\(appearance)-2-open-on", app) - app.buttons["Goals"].firstMatch.tap() - let startWith = app.buttons["settings.landing.agent"].firstMatch - XCTAssertTrue(startWith.waitForExistence(timeout: 5)) - startWith.tap() - XCTAssertTrue(app.buttons["Last bot used"].firstMatch.waitForExistence(timeout: 5)) + app.buttons["Today"].firstMatch.tap() + let firstTab = app.buttons["settings.landing.view"].firstMatch + XCTAssertTrue(firstTab.waitForExistence(timeout: 5)) + firstTab.tap() + XCTAssertTrue(app.buttons["Chats"].firstMatch.waitForExistence(timeout: 5)) sleep(1) - save(folder, "\(appearance)-3-start-with", app) - app.buttons["Last bot used"].firstMatch.tap() + save(folder, "\(appearance)-3-first-tab", app) + app.buttons["Chats"].firstMatch.tap() app.terminate() } } diff --git a/BighelpUITests/LocalizationUITests.swift b/BighelpUITests/LocalizationUITests.swift index 094549b5..aaedb9c1 100644 --- a/BighelpUITests/LocalizationUITests.swift +++ b/BighelpUITests/LocalizationUITests.swift @@ -36,7 +36,7 @@ final class LocalizationUITests: BighelpUITestCase { } } - func testOptionalPluginAndModeInBothLanguagesAndAppearances() { + func testOptionalPluginAndHowToStartInBothLanguagesAndAppearances() { for (language, appearance) in variants { let app = localizedApp(language, appearance, extra: [ "-force-signed-out-onboarding", "-bighelp.onboarding.after-connect", "YES", @@ -50,7 +50,7 @@ final class LocalizationUITests: BighelpUITestCase { app.buttons["onboarding.skip"].tap() let use = app.buttons["onboarding.mode.continue"] XCTAssertTrue(use.waitForExistence(timeout: 5)) - XCTAssertEqual(use.label, language == "en" ? "Use Bots" : "使用机器人") + XCTAssertEqual(use.label, language == "en" ? "Continue" : "继续") XCTAssertTrue(use.isHittable) capture("mode", language, appearance) app.terminate() @@ -70,20 +70,16 @@ final class LocalizationUITests: BighelpUITestCase { func testNavigationSettingsAndComposerInBothLanguagesAndAppearances() { for (language, appearance) in variants { - let app = localizedApp(language, appearance) + // The first tab takes its view's name: Bots here. + let app = localizedApp(language, appearance, extra: ["-loopdy.home.landing", "bots"]) app.launch() - XCTAssertTrue(app.buttons["tab.feed"].waitForExistence(timeout: 20)) - XCTAssertEqual(app.buttons["tab.feed"].label, language == "en" ? "Feed" : "动态") - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - menu.tap() - let settings = app.buttons["menu.settings"] - let menuList = app.descendants(matching: .any)["navigation.menu"].firstMatch - XCTAssertTrue(menuList.waitForExistence(timeout: 5)) - for _ in 0..<4 where !settings.isHittable { menuList.swipeUp() } + let firstTab = app.buttons["home.tab.conversations"] + XCTAssertTrue(firstTab.waitForExistence(timeout: 20)) + XCTAssertEqual(firstTab.label, language == "en" ? "Bots" : "机器人") + let settings = app.buttons["simple-bots.settings"].firstMatch XCTAssertTrue(settings.waitForExistence(timeout: 5)) XCTAssertTrue(settings.label.contains(language == "en" ? "Settings" : "设置")) - capture("menu", language, appearance) + capture("home", language, appearance) settings.tap() XCTAssertTrue(app.buttons["settings.you"].waitForExistence(timeout: 5)) capture("settings-identity", language, appearance) @@ -95,7 +91,7 @@ final class LocalizationUITests: BighelpUITestCase { capture("settings", language, appearance) app.terminate() - app.launchArguments += ["-start-chat"] + app.launchArguments += ["-start-chat"] // A chat opens over the home. app.launch() let attachment = app.buttons["chat.attachment"] XCTAssertTrue(attachment.waitForExistence(timeout: 20)) @@ -121,11 +117,11 @@ final class LocalizationUITests: BighelpUITestCase { } } - /// #527: Simple Bot mode's home, a bot's menu with More, Rearrange, search, New Bot with Templates, and a profile. + /// #527: the Bots home, a bot's menu, Rearrange, search, New Bot with Templates, and a profile. func testSimpleBotHomeMenuAndProfileInBothLanguagesAndAppearances() { for (language, appearance) in variants { let say = { (english: String, chinese: String) in language == "en" ? english : chinese } - let app = localizedApp(language, appearance, extra: ["-bighelp.settings.simple-bots", "YES"]) + let app = localizedApp(language, appearance, extra: ["-loopdy.home.landing", "bots"]) app.launch() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 20)) let search = app.buttons["simple-bots.search"] @@ -136,7 +132,7 @@ final class LocalizationUITests: BighelpUITestCase { app.buttons["simple-bots.bot.travel"].press(forDuration: 1.2) let unread = app.buttons[say("Mark Unread", "标为未读")] XCTAssertTrue(unread.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons[say("Make Primary Bot", "设为主机器人")].exists) + XCTAssertTrue(app.buttons[say("Bot Profile", "机器人资料")].exists) capture("simple-menu", language, appearance) app.buttons[say("Rearrange", "重新排列")].tap() let save = app.buttons["simple-bots.rearrange.save"] @@ -170,13 +166,8 @@ final class LocalizationUITests: BighelpUITestCase { app.buttons["simple-bots.create.close"].tap() app.buttons["simple-bots.bot.travel"].press(forDuration: 1.2) - let more = app.buttons[say("More", "更多")] - XCTAssertTrue(more.waitForExistence(timeout: 5)) - more.tap() let profile = app.buttons[say("Bot Profile", "机器人资料")] XCTAssertTrue(profile.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons[say("Routines", "例行任务")].exists) - capture("simple-menu-more", language, appearance) profile.tap() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.profile"].waitForExistence(timeout: 10)) capture("simple-dashboard", language, appearance) @@ -190,11 +181,11 @@ final class LocalizationUITests: BighelpUITestCase { } } - /// #527: Settings in Bots mode with Teamwork, and the Notifications, Chat and Appearance pages it opens. + /// #527: Settings from the circle, with Teamwork, and the Notifications, Chat and Appearance pages it opens. func testSimpleBotSettingsAndItsPagesInBothLanguagesAndAppearances() { for (language, appearance) in variants { let say = { (english: String, chinese: String) in language == "en" ? english : chinese } - let app = localizedApp(language, appearance, extra: ["-bighelp.settings.simple-bots", "YES"]) + let app = localizedApp(language, appearance) app.launch() let person = app.buttons["simple-bots.settings"] XCTAssertTrue(person.waitForExistence(timeout: 20)) @@ -228,12 +219,12 @@ final class LocalizationUITests: BighelpUITestCase { } } - /// #527: agents talking to each other, as a line in a Simple Bot mode chat and in its sheet. + /// #527: agents talking to each other, as a line in a chat and in its sheet. func testTeamworkLineAndSheetInBothLanguagesAndAppearances() { for (language, appearance) in variants { let say = { (english: String, chinese: String) in language == "en" ? english : chinese } let app = localizedApp(language, appearance, extra: [ - "-bighelp.settings.simple-bots", "YES", "-start-chat", "-preview-ui-v3", "-test-agent-talk", + "-start-chat", "-preview-ui-v3", "-test-agent-talk", "-loopdy.chat.foldCompletedTurns", "YES", ]) app.launch() @@ -258,27 +249,6 @@ final class LocalizationUITests: BighelpUITestCase { } } - /// The Header mode switcher's pill on Bots mode's home: Bots, Chat and Code (#528). - func testModePillInBothLanguagesAndAppearances() { - for (language, appearance) in variants { - let say = { (english: String, chinese: String) in language == "en" ? english : chinese } - let app = localizedApp(language, appearance, extra: [ - "-bighelp.settings.simple-bots", "YES", "-bighelp.settings.unified-mode-toggle", "YES", - "-bighelp.settings.code-mode", "YES", - ]) - app.launch() - let bots = app.buttons["mode.pill.bots"] - XCTAssertTrue(bots.waitForExistence(timeout: 20)) - XCTAssertTrue(bots.isSelected) - XCTAssertEqual(bots.label, say("Bots", "机器人")) - XCTAssertEqual(app.buttons["mode.pill.chat"].label, say("Chat", "聊天")) - XCTAssertEqual(app.buttons["mode.pill.code"].label, say("Code", "代码")) - XCTAssertEqual(app.buttons["simple-bots.search"].label, say("Search bots", "搜索机器人")) - capture("mode-pill", language, appearance) - app.terminate() - } - } - private func localizedApp(_ language: String, _ appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.settings.nerd-mode", "NO", diff --git a/BighelpUITests/MarketplaceUITests.swift b/BighelpUITests/MarketplaceUITests.swift index cfe82a26..47be102c 100644 --- a/BighelpUITests/MarketplaceUITests.swift +++ b/BighelpUITests/MarketplaceUITests.swift @@ -31,7 +31,7 @@ final class MarketplaceUITests: BighelpUITestCase { @MainActor func testABotsProfileOpensItsOwnMarketplace() { - let app = launch(appearance: "light", extra: ["-preview-ui-v3", "-bighelp.settings.simple-bots", "YES"]) + let app = launch(appearance: "light", extra: ["-preview-ui-v3", "-loopdy.home.landing", "bots"]) openPrimaryProfileInfo(app) let row = app.buttons["simple-bots.profile.marketplace"] @@ -63,7 +63,7 @@ final class MarketplaceUITests: BighelpUITestCase { @MainActor func testABotsProfileOpensItsCoreFilesAndConnections() { for appearance in ["light", "dark"] { - let app = launch(appearance: appearance, extra: ["-preview-ui-v3", "-bighelp.settings.simple-bots", "YES"]) + let app = launch(appearance: appearance, extra: ["-preview-ui-v3", "-loopdy.home.landing", "bots"]) openPrimaryProfileInfo(app) let coreFiles = app.buttons["simple-bots.profile.core-files"] @@ -93,11 +93,11 @@ final class MarketplaceUITests: BighelpUITestCase { } } - /// A bot's profile sets the project its new chats start in, for that bot (also in Bots mode). + /// A bot's profile sets the project its new chats start in, for that bot. @MainActor func testABotsProfileChoosesItsActiveProject() { for appearance in ["light", "dark"] { - let app = launch(appearance: appearance, extra: ["-preview-ui-v3", "-bighelp.settings.simple-bots", "YES"]) + let app = launch(appearance: appearance, extra: ["-preview-ui-v3", "-loopdy.home.landing", "bots"]) openPrimaryProfileInfo(app) let row = app.buttons["simple-bots.profile.active-project"] @@ -132,7 +132,7 @@ final class MarketplaceUITests: BighelpUITestCase { @MainActor private func openPrimaryProfileInfo(_ app: XCUIApplication) { XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.primary"].tap() + app.primaryBot.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) let profile = app.descendants(matching: .any)["simple-bots.profile"] @@ -175,10 +175,13 @@ final class MarketplaceUITests: BighelpUITestCase { return app } + /// The sheet's own Back: the screen behind a sheet has a navigation bar too. @MainActor private func goBack(in app: XCUIApplication) { - let back = app.navigationBars.buttons.element(boundBy: 0) - if back.waitForExistence(timeout: 3) { back.tap() } + let back = app.buttons["BackButton"].firstMatch + if back.waitForExistence(timeout: 3) { back.tap(); return } + let bar = app.navigationBars.buttons.element(boundBy: 0) + if bar.waitForExistence(timeout: 1) { bar.tap() } } @MainActor diff --git a/BighelpUITests/MenuButtonPlacementUITests.swift b/BighelpUITests/MenuButtonPlacementUITests.swift index 1a8a0f6d..aa74c104 100644 --- a/BighelpUITests/MenuButtonPlacementUITests.swift +++ b/BighelpUITests/MenuButtonPlacementUITests.swift @@ -1,85 +1,55 @@ import XCTest -/// ☰ sits in the same spot on every screen with a bottom bar (Agents' spot: the top bar's -/// leading button), and it's always there. Chat, Agents, Feed and Files with Agents pinned -/// to the bottom bar, on demo data. Set BIGHELP_MENU_PLACEMENT_EVIDENCE (TEST_RUNNER_…) to -/// save screenshots. +/// The person's circle (which opens Settings) sits in the same spot on every root of the home: Bots, +/// Chats, Today and Work, and it's always there after switching. On demo data. Set +/// BIGHELP_MENU_PLACEMENT_EVIDENCE (TEST_RUNNER_…) to save screenshots. final class MenuButtonPlacementUITests: BighelpUITestCase { @MainActor - func testMenuButtonSitsInOnePlaceOnEveryScreen() throws { + func testTheCircleSitsInOnePlaceOnEveryRoot() throws { let app = launch() var frames: [String: CGRect] = [:] - for (tab, name) in [("tab.agents", "agents"), ("tab.sessions", "chat"), ("tab.feed", "feed"), - ("tab.apps", "files"), ("tab.agents", "agents-again")] { - app.buttons[tab].firstMatch.tap() + for (door, name) in [("home.switch.bots", "bots"), ("home.switch.chats", "chats"), ("home.tab.today", "today"), + ("home.tab.work", "work"), ("home.tab.conversations", "bots-again")] { + if name == "bots" || name == "chats" { app.buttons["home.tab.conversations"].firstMatch.tap() } + app.buttons[door].firstMatch.tap() // Let the switch settle before measuring. Thread.sleep(forTimeInterval: 1.2) - let menu = menuButton(in: app) - XCTAssertTrue(menu.waitForExistence(timeout: 10), "☰ on \(name)") - frames[name] = menu.frame - save("menu-\(name)", app) + let circle = app.buttons["simple-bots.settings"].firstMatch + XCTAssertTrue(circle.waitForExistence(timeout: 10), "The circle on \(name)") + frames[name] = circle.frame + save("circle-\(name)", app) } - // The top bar reports ☰'s glyph and our header its whole tap area, so compare centers. - let expected = try XCTUnwrap(frames["agents"]) + let expected = try XCTUnwrap(frames["bots"]) for (name, frame) in frames.sorted(by: { $0.key < $1.key }) { - print("☰ \(name): \(frame)") - XCTAssertEqual(frame.midX, expected.midX, accuracy: 1, "☰ moves sideways on \(name): \(frame) vs \(expected)") - XCTAssertEqual(frame.midY, expected.midY, accuracy: 1, "☰ moves up or down on \(name): \(frame) vs \(expected)") + print("Circle \(name): \(frame)") + XCTAssertEqual(frame.midX, expected.midX, accuracy: 1, "The circle moves sideways on \(name): \(frame) vs \(expected)") + XCTAssertEqual(frame.midY, expected.midY, accuracy: 1, "The circle moves up or down on \(name): \(frame) vs \(expected)") } } @MainActor - func testAgentsAlwaysHasTheMenuButtonAfterChat() throws { + func testBotsAlwaysHasTheCircleAfterChats() throws { let app = launch() for round in 1...12 { - app.buttons["tab.sessions"].firstMatch.tap() - XCTAssertTrue(menuButton(in: app).waitForExistence(timeout: 10), "☰ in the chat, round \(round)") - app.buttons["tab.agents"].firstMatch.tap() - let menu = app.buttons["home.drawer.open"].firstMatch - let shown = menu.waitForExistence(timeout: 5) && menu.isHittable - if !shown { save("agents-missing-menu-\(round)", app) } - XCTAssertTrue(shown, "☰ on Agents after Chat, round \(round)") + app.buttons["home.switch.chats"].firstMatch.tap() + XCTAssertTrue(app.descendants(matching: .any)["chats.inbox"].firstMatch.waitForExistence(timeout: 10), + "Chats, round \(round)") + app.buttons["home.switch.bots"].firstMatch.tap() + let circle = app.buttons["simple-bots.settings"].firstMatch + let shown = circle.waitForExistence(timeout: 5) && circle.isHittable + if !shown { save("bots-missing-circle-\(round)", app) } + XCTAssertTrue(shown, "The circle on Bots after Chats, round \(round)") } } - /// Agents in the bottom bar still has its ☰ row, like Settings: quick screens hide the bar. - @MainActor - func testPinnedAgentsAndSettingsStayInTheMenu() throws { - let app = launch() - app.buttons["tab.feed"].firstMatch.tap() - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let agents = app.buttons["menu.agents"] - XCTAssertTrue(agents.waitForExistence(timeout: 5), "Agents stays in ☰ while pinned") - XCTAssertFalse(app.buttons["menu.feed"].exists, "Other pinned places aren't listed twice") - save("menu-pinned-agents", app) - agents.tap() - XCTAssertTrue(app.buttons["tab.agents"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["tab.agents"].isSelected, "☰'s Agents opens the Agents tab") - - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let settings = app.buttons["menu.settings"] - for _ in 0..<4 where !settings.isHittable { app.collectionViews.firstMatch.swipeUp() } - XCTAssertTrue(settings.isHittable, "Settings stays in ☰") - } - @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-bighelp.app-layout", "{pinned=(agents,feed,files);menu=();}"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "bots"] app.launch() - XCTAssertTrue(app.buttons["tab.agents"].waitForExistence(timeout: 20), "Agents is pinned") + XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].firstMatch.waitForExistence(timeout: 20)) return app } - /// The chat's ☰ has its own name; every other screen's is home.drawer.open. - @MainActor private func menuButton(in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "identifier IN %@", ["chat.menu", "home.drawer.open"])) - .allElementsBoundByIndex.first { $0.isHittable } ?? app.buttons["home.drawer.open"].firstMatch - } - @MainActor private func save(_ name: String, _ app: XCUIApplication) { let screenshot = XCUIScreen.main.screenshot() let shot = XCTAttachment(screenshot: screenshot) diff --git a/BighelpUITests/MoveChatToProjectUITests.swift b/BighelpUITests/MoveChatToProjectUITests.swift index a9540b76..a2e3b3a6 100644 --- a/BighelpUITests/MoveChatToProjectUITests.swift +++ b/BighelpUITests/MoveChatToProjectUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Move to Project…, from a chat's ⋯ menu and from a chat's hold menu in Chats, on the demo +/// Move to Project…, from a chat's ⋯ menu and from a chat's hold menu on Chats › This computer, on the demo /// computer: the chat lands in the project picked, and the sheet and the list say so. final class MoveChatToProjectUITests: BighelpUITestCase { @MainActor @@ -28,10 +28,9 @@ final class MoveChatToProjectUITests: BighelpUITestCase { @MainActor func testAChatsHoldMenuMovesItIntoTheProjectsFolder() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO", - "-loopdy.sessions.organizeByProjects", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.sessions.organizeByProjects", "YES"] app.launch() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].firstMatch.waitForExistence(timeout: 20)) + openThisComputerSessions(in: app) let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'session.row.'")) let row = rows.firstMatch XCTAssertTrue(row.waitForExistence(timeout: 8)) diff --git a/BighelpUITests/MusicCardStreamUITests.swift b/BighelpUITests/MusicCardStreamUITests.swift index 3afabe51..f32d05d0 100644 --- a/BighelpUITests/MusicCardStreamUITests.swift +++ b/BighelpUITests/MusicCardStreamUITests.swift @@ -6,14 +6,10 @@ final class MusicCardStreamUITests: BighelpUITestCase { @MainActor func testMusicCardStreamsInAndStaysResponsive() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-companion-disabled", "-test-music-card-reply"] app.launch() - let newChat = chatNewChatButton(in: app).waitForExistence(timeout: 5) - ? chatNewChatButton(in: app) : app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) let input = app.textViews["Message"] XCTAssertTrue(input.waitForExistence(timeout: 5)) input.tap() diff --git a/BighelpUITests/NativeSubagentProductionUITests.swift b/BighelpUITests/NativeSubagentProductionUITests.swift index 441fc497..1e7a2138 100644 --- a/BighelpUITests/NativeSubagentProductionUITests.swift +++ b/BighelpUITests/NativeSubagentProductionUITests.swift @@ -25,9 +25,13 @@ final class NativeSubagentProductionUITests: BighelpUITestCase { app.launch() defer { capture("real-subagent-final-state-2102", app, directory: artifactDirectory) } - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 30), + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 30), "The authorized Hermes workspace must expose New Chat.") - app.buttons["root.new-chat"].tap() + app.buttons["home.new-chat"].firstMatch.tap() + // New chat opens with nobody picked: the first bot listed takes it. + let bot = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "new-chat.bot.")).firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 20), "New chat lists the host's bots.") + bot.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20), "The real chat composer must be available before sending.") @@ -84,9 +88,10 @@ final class NativeSubagentProductionUITests: BighelpUITestCase { app.terminate() app.launch() - XCTAssertTrue(app.buttons["tab.sessions"].waitForExistence(timeout: 30), - "The real chat catalog must restore after relaunch.") - app.buttons["tab.sessions"].tap() + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 30), + "The home must restore after relaunch.") + // Chats › This computer: the real chat catalog. + openThisComputerSessions(in: app) let search = app.descendants(matching: .any).matching(identifier: "sessions.search").firstMatch XCTAssertTrue(search.waitForExistence(timeout: 15), "The session catalog must expose its real search field.") diff --git a/BighelpUITests/NativeWorkspaceProductionUITests.swift b/BighelpUITests/NativeWorkspaceProductionUITests.swift index 0037b334..35707888 100644 --- a/BighelpUITests/NativeWorkspaceProductionUITests.swift +++ b/BighelpUITests/NativeWorkspaceProductionUITests.swift @@ -13,7 +13,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = true let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - XCTAssertTrue(app.buttons["tab.sessions"].waitForExistence(timeout: 20)) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 20)) exerciseImageAfterFirstMessage(app) } @@ -29,7 +29,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { try? app.debugDescription.write(toFile: evidence + "/\(name).txt", atomically: true, encoding: .utf8) } } - app.buttons["root.new-chat"].firstMatch.tap() + startFreshChat(app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20)) composer.tap(); composer.typeText("Hi") @@ -107,8 +107,10 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { let deadline = Date().addingTimeInterval(30) while Date() < deadline, (try? String(contentsOfFile: signal, encoding: .utf8)) != "done" { sleep(1) } } - app.buttons["Back"].firstMatch.tap() + // Back, then the computer's Sessions page (Chats › This computer), newest first. + goBackFromChat(in: app) sleep(2) + openThisComputerSessions(in: app) let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "session.row.")).firstMatch XCTAssertTrue(row.waitForExistence(timeout: 10)) row.tap() @@ -127,7 +129,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { /// screen offers turn-based voice, which opens the listening screen. @MainActor private func exerciseVoiceFallback(_ app: XCUIApplication) { - app.buttons["root.new-chat"].firstMatch.tap() + startFreshChat(app) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 20)) app.buttons["chat.voice"].firstMatch.tap() let unavailable = app.buttons["voice.live-unavailable.use-turn-based"] @@ -158,12 +160,19 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { } sleep(8) record("start") - for tab in ["feed", "goals", "apps"] { - openRootTab("tab.\(tab)", in: app) - sleep(tab == "apps" ? 8 : 4) - record(tab) + for kind in ["feed", "goals"] { + openOwnBoard(kind, in: app) + sleep(4) + record(kind) } - let media = app.buttons["Media"].firstMatch + // The bot's own Files and Media, on its page. + returnToHome(in: app) + openBot("default", in: app) + openBotPage(fromChatIn: app) + app.buttons["simple-bots.profile.tab.files"].firstMatch.tap() + sleep(8) + record("files") + let media = app.buttons["simple-bots.profile.tab.media"].firstMatch if media.exists { media.tap(); sleep(10); record("media") let first = app.buttons["board.media.item"].firstMatch @@ -182,10 +191,10 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { try? app.screenshot().pngRepresentation.write(to: URL(fileURLWithPath: evidence + "/\(name).png")) } } - // Signing in lands in the agent's home chat; Chat reopens it from the list. - let avatar = app.buttons["agent.hero.avatar"] - if !avatar.waitForExistence(timeout: 15) { openRootTab("tab.sessions", in: app) } - XCTAssertTrue(avatar.waitForExistence(timeout: 20), "The Chat tab opens the agent's home chat with its live avatar.") + // The default bot's chat, from Bots: its header pill says what it's doing. + openBot("default", in: app) + let avatar = app.buttons["chat.identity"].firstMatch + XCTAssertTrue(avatar.waitForExistence(timeout: 20), "The bot's chat opens with the bot in its header.") record("home-chat") let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20)) @@ -250,22 +259,23 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTAssertTrue(reacted, "The agent's reaction must show on my message.") } - avatar.tap() - XCTAssertTrue(app.descendants(matching: .any)["agent.profile"].waitForExistence(timeout: 10)) + // The bot's page: its Dashboard (recorded activity), then Info. + openBotPage(fromChatIn: app) sleep(3) record("profile-activity") - app.buttons["agent.profile.tab.identity"].tap() + app.buttons["simple-bots.profile.tab.info"].tap() sleep(2) record("profile-identity") - app.buttons["agent.profile.close"].tap() + app.buttons["simple-bots.profile.back"].tap() - for (tab, screen) in [("feed", "board.feed.empty"), ("goals", "board.goals.empty")] { - openRootTab("tab.\(tab)", in: app) + for (kind, screen) in [("feed", "board.feed.empty"), ("goals", "board.goals.tracking.empty")] { + openOwnBoard(kind, in: app) XCTAssertTrue(app.descendants(matching: .any)[screen].firstMatch.waitForExistence(timeout: 15), screen) XCTAssertFalse(app.descendants(matching: .any)["board.plugin-required"].exists, "The host advertises the board.") - record(tab) + record(kind) } - openRootTab("tab.sessions", in: app) + returnToHome(in: app) + showChats(in: app) record("chat-list") // Settings › Models (the providers and each bot's default model) loads from this host. @@ -283,8 +293,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { record("settings-\(name)") XCTAssertFalse(app.descendants(matching: .any).matching(invalid).firstMatch.exists, "\(name) must load from this host") - let back = app.navigationBars.buttons.firstMatch - if back.exists { back.tap() } + leaveSettings(in: app) } } @@ -313,7 +322,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { let identity = chatStatus(in: app) for round in 1...Int(environment["BIGHELP_TURN_BACKGROUND_ROUNDS"] ?? "1")! { if round == 1 { - app.buttons["root.new-chat"].firstMatch.tap() + startFreshChat(app) } let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20)) @@ -399,7 +408,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { return found } func startChat(_ text: String) { - app.buttons["root.new-chat"].firstMatch.tap() + startFreshChat(app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20)) composer.tap(); composer.typeText(text) @@ -409,9 +418,11 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTAssertTrue(reply.waitForExistence(timeout: 60), "First turn must complete.") sleep(2) } + /// Back to the computer's Sessions page (Chats › This computer), where the rows are. func back() { - app.buttons["Back"].firstMatch.tap() + goBackFromChat(in: app) sleep(2) + if !app.descendants(matching: .any)["sessions.screen"].firstMatch.exists { openThisComputerSessions(in: app) } } let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "session.row.")) func open(_ row: XCUIElement, _ step: String) { @@ -516,7 +527,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = true let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - XCTAssertTrue(app.buttons["tab.sessions"].waitForExistence(timeout: 20), "The saved host must open the tab bar.") + XCTAssertTrue(app.buttons["home.tab.conversations"].firstMatch.waitForExistence(timeout: 20), + "The saved host must open the tab bar.") func alive(_ step: String) { sleep(2) XCTAssertEqual(app.state, .runningForeground, "App must survive: \(step)") @@ -529,24 +541,30 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { if discard.waitForExistence(timeout: 1) { discard.tap() } sleep(1) } - for tab in ["tab.sessions", "tab.feed", "tab.ideas", "tab.goals", "tab.apps", - "tab.agents", "tab.scheduled-tasks", "tab.profile"] { - openRootTab(tab, in: app) - alive(tab) - } - // The agent home's sheets: switcher from Feed, ☰ from Chat. - openRootTab("tab.feed", in: app) - if app.buttons["agent.hero.name"].waitForExistence(timeout: 5) { - app.buttons["agent.hero.name"].tap(); alive("agent-switcher") - app.buttons["Done"].firstMatch.tap() + // Every root, then every door from them. + for (door, name) in [("home.switch.bots", "bots"), ("home.switch.chats", "chats"), + ("home.tab.today", "today"), ("home.tab.work", "work")] { + if name == "bots" || name == "chats" { app.buttons["home.tab.conversations"].firstMatch.tap() } + app.buttons[door].firstMatch.tap() + alive(name) + } + for kind in ["feed", "ideas", "goals"] { + // See all shows once a board has something on it. + openTodayBoard(kind, in: app) + alive("today-\(kind)") + returnToHome(in: app) + } + for door in ["projects", "tasks", "workflows", "schedules"] { + app.buttons["home.tab.work"].firstMatch.tap() + // Each door shows only where the computer has it. + let button = app.buttons["work.door.\(door)"].firstMatch + for _ in 0..<4 where !button.waitForExistence(timeout: 1) { app.swipeUp() } + guard button.exists else { continue } + openWorkDoor(door, in: app) + alive("work-\(door)") + returnToHome(in: app) } - openRootTab("tab.sessions", in: app) - let menu = [app.buttons["chat.menu"], app.buttons["home.drawer.open"]].first { $0.waitForExistence(timeout: 5) } - if let menu { - menu.tap(); alive("home-drawer") - app.buttons["menu.done"].tap() - } - openRootTab("tab.profile", in: app) + openSettings(in: app) let nerd = app.switches["settings.nerd-mode"] for _ in 0..<6 where !nerd.isHittable { app.swipeUp() } if nerd.isHittable { @@ -565,16 +583,26 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { if colors.exists && colors.isHittable { colors.tap(); alive("appearance") } - openRootTab("tab.agents", in: app) - if app.buttons["agents.create"].waitForExistence(timeout: 5), app.buttons["agents.create"].isEnabled { - app.buttons["agents.create"].tap(); alive("agent-studio"); dismiss() + leaveSettings(in: app) + // Bots' + › New Bot. + showBots(in: app) + let add = app.buttons["simple-bots.new"].firstMatch + if add.waitForExistence(timeout: 5) { + add.tap() + let newBot = app.buttons["New Bot"].firstMatch + if newBot.waitForExistence(timeout: 5) { + newBot.tap(); alive("new-bot") + let close = app.buttons["simple-bots.create.close"].firstMatch + if close.waitForExistence(timeout: 5) { close.tap() } + } } - openRootTab("tab.scheduled-tasks", in: app) + openWorkDoor("schedules", in: app) if app.buttons["scheduled-tasks.create"].waitForExistence(timeout: 5), app.buttons["scheduled-tasks.create"].isEnabled { app.buttons["scheduled-tasks.create"].tap(); alive("task-editor"); dismiss() } - app.buttons["tab.sessions"].tap() - let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "session.row.")).firstMatch + returnToHome(in: app) + showChats(in: app) + let row = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "chats.row.")).firstMatch if row.waitForExistence(timeout: 5) { row.tap(); alive("chat") if openChatInfo(in: app) { alive("chat-info") } @@ -627,8 +655,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { try? app.debugDescription.write(to: URL(fileURLWithPath: directory).appendingPathComponent("real-model-picker-tree.txt"), atomically: true, encoding: .utf8) capture("real-model-picker", app) } - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 20)) - app.buttons["root.new-chat"].tap() + startFreshChat(app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 10)); composer.tap() let controls = app.buttons["chat.composer.model"].firstMatch @@ -677,9 +704,10 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = false let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 20)) + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 20)) let started = Date() - app.buttons["root.new-chat"].tap() + newChat.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 2), "New Chat must present a canvas immediately.") let timing = ["automationTapToComposerSeconds": Date().timeIntervalSince(started)] @@ -687,6 +715,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTAssertFalse(app.staticTexts["Opening new chat"].exists) XCTAssertFalse(app.otherElements["new-chat.opening"].exists) capture("real-host-fresh-canvas-2101", app) + // New chat opens with nobody picked: the first bot listed takes it. + pickFirstBot(app) composer.tap() composer.typeText("Reply with exactly UI2101 OK. Do not call tools or delegate.") let send = app.buttons["chat.send"] @@ -718,9 +748,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = false let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - openRootTab("tab.agents", in: app, timeout: 20) - XCTAssertTrue(app.buttons["agents.groups.create"].waitForExistence(timeout: 20)) - app.buttons["agents.groups.create"].tap() + openNewGroupChat(app) let name = app.textFields["bot-mode.create.title"] XCTAssertTrue(name.waitForExistence(timeout: 10)) name.tap(); name.typeText("bighelp verification 117") @@ -749,7 +777,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTAssertTrue(sentTree.contains("Juno NEWGROUP117 OK")) XCTAssertTrue(sentTree.contains("Nova NEWGROUP117 OK")) app.terminate(); app.launch() - openRootTab("tab.agents", in: app, timeout: 20) + showBots(in: app) let group = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "bighelp verification 117")).firstMatch XCTAssertTrue(group.waitForExistence(timeout: 20)); group.tap() XCTAssertTrue(composer.waitForExistence(timeout: 20)) @@ -834,14 +862,11 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = false let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 20)) - app.buttons["root.new-chat"].tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 15)) - openChatWorkspaceMenu(in: app) - app.buttons["menu.settings"].tap() - app.buttons["settings.apps"].tap() + // Settings › Apps & skills › Device access, from the home's circle. + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 20)) + openSettings(in: app) + settingsRow("settings.apps", in: app).tap() app.buttons["settings.connections.device-access"].tap() - app.buttons["permissions.open.calendar"].firstMatch.tap() let toggle = app.switches["permissions.device-tools.calendar"].firstMatch XCTAssertTrue(toggle.waitForExistence(timeout: 10)) if toggle.value as? String != "1" { @@ -850,10 +875,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { if grant.waitForExistence(timeout: 5) { grant.tap() } } capture("real-host-phone-calendar-enabled-116", app) - for _ in 0..<3 { app.navigationBars.buttons.firstMatch.tap() } - if app.buttons["Done"].exists { app.buttons["Done"].tap() } - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 10)) - app.buttons["root.new-chat"].tap() + leaveSettings(in: app) + startFreshChat(app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 15)) composer.tap() @@ -876,8 +899,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = false let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 20)) - app.buttons["root.new-chat"].tap() + startFreshChat(app) let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 15)) composer.tap(); composer.typeText("/") @@ -910,69 +932,54 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { app.launchArguments = [] app.launchEnvironment = [:] app.launch() - let entry = app.buttons["root.new-chat"] + let entry = app.buttons["home.new-chat"].firstMatch let available = entry.waitForExistence(timeout: 20) capture("real-host-root-116", app) XCTAssertTrue(available, "The real saved host must expose its normal workspace controls.") - let sessions = app.buttons["tab.sessions"] - sessions.tap() + showChats(in: app) let knownSession = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Confirm bighelp direct-connect message")).firstMatch XCTAssertTrue(knownSession.waitForExistence(timeout: 20)) knownSession.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 20), "Existing Hermes chat must load.") capture("real-host-existing-chat-116", app) - openChatWorkspaceMenu(in: app) - let chatsMenu = app.buttons["quick-workspace.menu.chats"] - let agentsMenu = app.buttons["menu.agents"] - let agentsVisible = agentsMenu.waitForExistence(timeout: 5) - capture("real-host-sidebar-116", app) - XCTAssertTrue(agentsVisible) - XCTAssertGreaterThan(agentsMenu.frame.minY, chatsMenu.frame.minY) - capture("real-host-sidebar-116", app) - app.buttons["menu.settings"].tap() - let chatSettings = app.buttons["settings.menu.chat"] - XCTAssertTrue(chatSettings.waitForExistence(timeout: 5)) - chatSettings.tap() - app.buttons["settings.chat.voice-settings"].tap() + // Settings › Voice, from the home's circle. + goBackFromChat(in: app) + openSettings(in: app) + settingsRow("settings.chat.voice-settings", in: app).tap() let voicePlugin = app.descendants(matching: .any).matching(identifier: "settings.plugin-status.liveVoice").firstMatch XCTAssertTrue(voicePlugin.waitForExistence(timeout: 10)) capture("real-host-voice-plugin-settings-116", app) - app.navigationBars.buttons.firstMatch.tap() - app.navigationBars.buttons.firstMatch.tap() - app.buttons["settings.apps"].tap() + // The sheet's own Back: the screen behind Settings has a navigation bar too. + app.buttons["BackButton"].firstMatch.tap() + settingsRow("settings.apps", in: app).tap() app.buttons["settings.connections.device-access"].tap() // Device access shows the plugin only while something needs doing; a ready plugin shows nothing. let devicePlugin = app.descendants(matching: .any).matching(identifier: "settings.plugin-status.deviceAccess").firstMatch XCTAssertTrue(devicePlugin.waitForNonExistence(timeout: 20)) capture("real-host-device-plugin-settings-116", app) - app.buttons["permissions.open.calendar"].tap() XCTAssertTrue(app.switches["permissions.device-tools.calendar"].firstMatch.waitForExistence(timeout: 5)) capture("real-host-calendar-plugin-settings-116", app) } @MainActor - func testSavedRealHostGroupsNewChatAndWorkspace() throws { + func testSavedRealHostNewGroupAndNewChat() throws { guard ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_UI"] == "1" else { throw XCTSkip("Requires explicit authorization and a saved real Hermes host.") } continueAfterFailure = false let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - openRootTab("tab.agents", in: app, timeout: 20) - let createGroup = app.buttons["agents.groups.create"] - let canCreate = createGroup.waitForExistence(timeout: 20) + openNewGroupChat(app) capture("real-host-agents-before-group-116", app) if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { try app.debugDescription.write(to: URL(fileURLWithPath: directory).appendingPathComponent("real-host-agents-tree.txt"), atomically: true, encoding: .utf8) } - XCTAssertTrue(canCreate) - createGroup.tap() XCTAssertTrue(app.textFields["bot-mode.create.title"].waitForExistence(timeout: 8)) capture("real-host-new-group-116", app) app.buttons["Cancel"].tap() let started = Date() - app.buttons["root.new-chat"].tap() + app.buttons["home.new-chat"].firstMatch.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 15)) if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { @@ -980,18 +987,6 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { try JSONEncoder().encode(value).write(to: URL(fileURLWithPath: directory).appendingPathComponent("new-chat-ui-timing.json")) } capture("real-host-new-chat-116", app) - openChatWorkspaceMenu(in: app) - app.buttons["menu.folder"].tap() - XCTAssertTrue(app.otherElements["hermes-workspaces.screen"].waitForExistence(timeout: 8)) - let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND NOT identifier BEGINSWITH %@", "hermes-workspace.", "hermes-workspace.archive.")) - let loadedRows = rows.firstMatch.waitForExistence(timeout: 15) - capture("real-host-project-picker-116", app) - if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { - try app.debugDescription.write(to: URL(fileURLWithPath: directory).appendingPathComponent("real-host-project-picker-tree.txt"), atomically: true, encoding: .utf8) - } - XCTAssertTrue(loadedRows, "The real host project registry must load.") - capture("real-host-project-picker-116", app) - app.buttons["Done"].tap() } /// Opt-in actual microphone/provider test. Spoken input is supplied outside @@ -1005,8 +1000,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { continueAfterFailure = false let app = XCUIApplication() app.launchArguments = []; app.launchEnvironment = [:]; app.launch() - XCTAssertTrue(app.buttons["root.new-chat"].waitForExistence(timeout: 20)) - app.buttons["root.new-chat"].tap() + startFreshChat(app) XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 15)) app.buttons["chat.voice"].tap() // Live voice starts as its screen opens: no Start tap. @@ -1068,9 +1062,6 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { if browserHost.state != .notRunning { browserHost.terminate() } let app = makeApp() app.launchArguments = ["-native-workspace-acceptance"] - if ProcessInfo.processInfo.environment["NATIVE_PROBE_AGENT_HOME"] == "1" { - app.launchArguments += ["-loopdy.home.opens-chat", "YES"] - } app.launch() let getStarted = app.buttons["onboarding.get-started"] XCTAssertTrue(getStarted.waitForExistence(timeout: 15)) @@ -1140,12 +1131,9 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { capture("native-production-auth-result", app) return } - let newChat = app.buttons["root.new-chat"] - let homeChat = app.buttons["agent.hero.avatar"] - let reachDeadline = Date().addingTimeInterval(60) - while Date() < reachDeadline, !newChat.exists, !homeChat.exists { usleep(500_000) } - XCTAssertTrue(newChat.exists || homeChat.exists, "Real native feature clients must reach the shared workspace.") - guard newChat.exists || homeChat.exists else { capture("native-production-workspace-load", app); return } + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 60), "Real native feature clients must reach the shared workspace.") + guard newChat.exists else { capture("native-production-workspace-load", app); return } if ProcessInfo.processInfo.environment["NATIVE_PROBE_IMAGE_FOLLOWUP"] == "1" { continueAfterFailure = true exerciseImageAfterFirstMessage(app) @@ -1176,78 +1164,17 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { inspectBoardReadOnly(app) return } - if ProcessInfo.processInfo.environment["NATIVE_PROBE_VERIFY_AGENTS"] == "1" { - openAgents(in: app) - let create = app.buttons["agents.create"] - XCTAssertTrue(create.waitForExistence(timeout: 15)) - create.tap() - XCTAssertTrue(app.textFields["agent.editor.name"].waitForExistence(timeout: 10)) - XCTAssertTrue(app.buttons["agent.editor.avatar-picker"].exists) - app.buttons["agent.editor.design-avatar"].tap() - // Every Bot Studio tab must render (Release builds run on a 1 MB main stack on iPhone). - let studio = app.descendants(matching: .any)["avatar.chooser.studio"].firstMatch - XCTAssertTrue(studio.waitForExistence(timeout: 10)) - studio.tap() - for tab in ["eyes", "color", "shape", "moves", "body"] { - app.buttons["bot.studio.tab.\(tab)"].tap() - XCTAssertTrue(app.buttons["bot.studio.save"].waitForExistence(timeout: 5), tab) - } - app.buttons["bot.studio.chip.classics"].tap() - let pinch = app.buttons["bot.studio.choice.Pinch"] - XCTAssertTrue(pinch.waitForExistence(timeout: 10)) - pinch.tap() - app.buttons["bot.studio.save"].tap() - let preview = app.descendants(matching: .any)["agent.editor.avatar-preview"].firstMatch - XCTAssertTrue(preview.waitForExistence(timeout: 20)) - capture("native-agent-pet-avatar-selected", app) - for (id, text) in [("name", "MiXeD Avatar BOT"), ("role", "Helper")] { - let field = app.textFields["agent.editor.\(id)"] - for _ in 0..<5 where !field.isHittable { app.swipeUp() } - field.tap(); field.typeText(text) - app.buttons["Dismiss keyboard"].tap() - } - for (id, text) in [("summary", "A controlled avatar fixture."), ("instructions", "Be concise.")] { - let field = app.descendants(matching: .any)["agent.editor.\(id)"].firstMatch - for _ in 0..<6 where !field.isHittable { app.swipeUp() } - field.tap(); field.typeText(text) - app.buttons["Dismiss keyboard"].tap() - } - app.buttons["agent.editor.save"].tap() - guard app.buttons["agent.editor.save"].waitForNonExistence(timeout: 40) else { - capture("native-agent-create-failed", app) - XCTFail("The real profile/avatar creation must complete: " + app.debugDescription) - return - } - let catalog = try await get(config: config, components: ["api", "profiles"], query: []) - let rows = try XCTUnwrap(catalog["profiles"] as? [[String: Any]]) - XCTAssertEqual(rows.filter { $0["name"] as? String == "mixed-avatar-bot" }.count, 1) - XCTAssertFalse(rows.contains { $0["name"] as? String == "MiXeD Avatar BOT" }) - app.terminate(); app.launch() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 60)) - openAgents(in: app) - let agent = app.buttons["agent.mixed-avatar-bot"] - XCTAssertTrue(agent.waitForExistence(timeout: 25)) - for _ in 0..<5 where !agent.isHittable { app.swipeUp() } - XCTAssertTrue(agent.label.contains("MiXeD Avatar BOT")) - capture("native-agent-avatar-cold-reload", app) - return - } - app.buttons["home.drawer.open"].tap() - for id in ["menu.agents", "menu.chats", "menu.scheduled-tasks"] { - XCTAssertTrue(app.buttons[id].exists, id) - } - app.buttons["menu.done"].tap() if ProcessInfo.processInfo.environment["NATIVE_PROBE_VERIFY_SESSION_RECOVERY"] == "1" { try await verifyNativeSessionRecovery(config: config, in: app) return } if ProcessInfo.processInfo.environment["NATIVE_PROBE_VERIFY_MANAGEMENT"] == "1" { - // Each page opens from where it lives: Projects and Files from ☰, the rest from Settings. - for (key, title) in [("projects", "Projects"), ("files", "Files"), ("toolsets", "Toolsets"), + // Each page opens from where it lives: Projects from Work, the rest from Settings. + for (key, title) in [("projects", "Projects"), ("toolsets", "Toolsets"), ("plugins", "Plugins"), ("mcp", "MCP Servers"), ("logs", "Logs")] { - let fromMenu = key == "projects" || key == "files" - if fromMenu { - openRootDestination(key, sidebarIdentifier: "menu.\(key)", in: app) + let fromWork = key == "projects" + if fromWork { + openWorkDoor(key, in: app) } else { openHostPage(key, in: app) } @@ -1256,63 +1183,38 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTFail("The \(title) destination did not open on first tap.") return } - if key == "files" { - let root = try XCTUnwrap(config["workspace_path"]) - let rootText = app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", root)).firstMatch - XCTAssertTrue(rootText.waitForExistence(timeout: 20), "The confirmed host workspace must be visible.") - XCTAssertFalse(app.staticTexts["Workspace unavailable"].exists) - } capture("native-management-\(key)", app) - if ProcessInfo.processInfo.environment["NATIVE_PROBE_VERIFY_MEDIA"] == "1" { - if key == "files" { - let video = app.buttons.containing(NSPredicate(format: "label CONTAINS %@", "native-preview.mp4")).firstMatch - XCTAssertTrue(video.waitForExistence(timeout: 15)) - video.tap() - let play = app.buttons["workspace.file-transfers.play-media"] - for _ in 0..<6 where !play.isHittable { app.swipeUp() } - XCTAssertTrue(play.isHittable) - play.tap() - XCTAssertTrue(app.navigationBars["Video Preview"].waitForExistence(timeout: 15)) - let player = app.descendants(matching: .any)["workspace.managed-media.player"].firstMatch - XCTAssertTrue(player.waitForExistence(timeout: 20), "The actual native video decoder must become ready.") - XCTAssertFalse(app.staticTexts["Playback unavailable"].exists) - capture("native-managed-video-playing", app) - app.buttons["Done"].tap() - XCTAssertTrue(app.navigationBars["Files"].waitForExistence(timeout: 10)) - } else if key == "logs" { - let row = app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", "NATIVE_UI_LOG_PROOF")).firstMatch - for _ in 0..<8 where !row.isHittable { app.swipeUp() } - XCTAssertTrue(row.waitForExistence(timeout: 15), "The bounded host log line must render, not only a severity count.") - capture("native-logs-rendered-line", app) - } + if ProcessInfo.processInfo.environment["NATIVE_PROBE_VERIFY_MEDIA"] == "1", key == "logs" { + let row = app.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", "NATIVE_UI_LOG_PROOF")).firstMatch + for _ in 0..<8 where !row.isHittable { app.swipeUp() } + XCTAssertTrue(row.waitForExistence(timeout: 15), "The bounded host log line must render, not only a severity count.") + capture("native-logs-rendered-line", app) } - if fromMenu { - let back = app.navigationBars.buttons.element(boundBy: 0) - XCTAssertTrue(back.isHittable) - back.tap() + if fromWork { + returnToHome(in: app) } else { leaveSettings(in: app) } - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 10)) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 10)) } } - openRootDestination("scheduledTasks", sidebarIdentifier: "menu.scheduled-tasks", in: app) + openWorkDoor("schedules", in: app) let createTask = app.buttons["scheduled-tasks.create"] - XCTAssertTrue(createTask.waitForExistence(timeout: 15), "Native cron management must be reachable from the Tasks menu.") + XCTAssertTrue(createTask.waitForExistence(timeout: 15), "Native cron management must be reachable from Work's Schedules.") XCTAssertFalse(app.alerts["Unable to open"].exists) guard createTask.exists else { capture("native-production-cron-route", app); return } createTask.tap() let taskName = app.textFields["scheduled-task.editor.name"] XCTAssertTrue(taskName.waitForExistence(timeout: 10), "Native tasks must expose their existing editor.") app.buttons["Cancel"].tap() - openAgents(in: app) - XCTAssertTrue(app.buttons["agent.default"].waitForExistence(timeout: 15)) - XCTAssertTrue(app.staticTexts["agents.groups.empty"].waitForExistence(timeout: 15)) + returnToHome(in: app) + showBots(in: app) + let defaultBot = botButton("default", in: app) + XCTAssertTrue(defaultBot.waitForExistence(timeout: 15)) XCUIDevice.shared.press(.home) app.activate() - XCTAssertTrue(app.buttons["agent.default"].waitForExistence(timeout: 3), "Cached agents should remain visible on foreground.") - XCTAssertFalse(app.staticTexts["agents.groups.error"].exists) - app.buttons["agent.default"].tap() + XCTAssertTrue(defaultBot.waitForExistence(timeout: 3), "Cached bots should remain visible on foreground.") + defaultBot.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 30)) guard composer.exists else { capture("native-production-create", app); return } @@ -1352,8 +1254,9 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { capture("native-production-stream", app) app.terminate() app.launch() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 60), "Device-only credentials must restore the same native workspace.") - openRootDestination("chats", sidebarIdentifier: "menu.chats", in: app) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 60), + "Device-only credentials must restore the same native workspace.") + openThisComputerSessions(in: app) let saved = app.buttons.matching(NSPredicate( format: "identifier BEGINSWITH %@ AND label CONTAINS %@", "session.row.native-session-v1:", nonce )).firstMatch @@ -1421,8 +1324,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { capture("native-reaction-confirmed", app) app.terminate() app.launch() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 60)) - openRootDestination("chats", sidebarIdentifier: "menu.chats", in: app) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 60)) + openThisComputerSessions(in: app) XCTAssertTrue(saved.waitForExistence(timeout: 25)) saved.tap() for target in reactionRows { @@ -1465,9 +1368,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { thenDragTo: app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.95)) ) XCTAssertTrue(app.buttons["chat.options"].waitForExistence(timeout: 10)) - openChatWorkspaceMenu(in: app) - openSidebarDestination("menu.chats", in: app) - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 10)) + returnToHome(in: app) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 10)) openHostPage("sessionMaintenance", in: app) XCTAssertTrue(app.navigationBars["Session Maintenance"].waitForExistence(timeout: 15)) let mostRecent = app.buttons["session-maintenance.most-recent"] @@ -1505,7 +1407,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTAssertTrue(close.waitForExistence(timeout: 5)) close.tap() app.buttons["Close Runtime"].tap() - if !app.buttons["home.drawer.open"].waitForExistence(timeout: 5) { + if !app.buttons["settings.done"].firstMatch.waitForNonExistence(timeout: 5) { let success = app.descendants(matching: .any)["session-maintenance.success"].firstMatch let error = app.descendants(matching: .any)["session-maintenance.error"].firstMatch for _ in 0..<10 where !success.isHittable && !error.isHittable { app.swipeDown() } @@ -1514,10 +1416,10 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTFail("Close must reconcile the exact runtime and preserve history: " + app.debugDescription) return } - app.navigationBars.buttons["Back"].tap() + leaveSettings(in: app) } - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 15)) - openRootDestination("chats", sidebarIdentifier: "menu.chats", in: app) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 15)) + openThisComputerSessions(in: app) XCTAssertFalse(app.staticTexts["Route unavailable"].exists) let preservedSession = try await storedSession(config: config, prompt: followup, reply: followupReply) XCTAssertEqual(preservedSession, originalSession) @@ -1545,7 +1447,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { predicate: NSPredicate(format: "label CONTAINS %@", "bighelp plugin connected."), object: voice )], timeout: 20), .completed) capture("native-reviewed-plugin-voice-ready", app) - app.navigationBars.buttons.firstMatch.tap() + // The sheet's own Back: the screen behind Settings has a navigation bar too. + app.buttons["BackButton"].firstMatch.tap() let connections = app.buttons["settings.apps"] for _ in 0..<5 where !connections.isHittable { app.collectionViews["settings.screen"].swipeUp() } guard connections.isHittable else { XCTFail("Connections must be reachable from Settings."); return } @@ -1649,10 +1552,7 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { let receiptPath = try XCTUnwrap(config["receipt_path"]) var receipts: [[String: String]] = [] for profile in ["default", secondary] { - openAgents(in: app) - let agent = app.buttons["agent.\(profile)"] - XCTAssertTrue(agent.waitForExistence(timeout: 20)) - agent.tap() + openBot(profile, in: app) let composer = app.textViews["chat.composer.text"] let send = app.buttons["chat.send"] XCTAssertTrue(composer.waitForExistence(timeout: 30), "One agent tap must open its new native chat.") @@ -1671,8 +1571,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { if phase == "cold-reopen" { app.terminate() app.launch() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 60)) - openRootDestination("chats", sidebarIdentifier: "menu.chats", in: app) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 60)) + openThisComputerSessions(in: app) let saved = nativeSessionRow(in: app, profileID: profile, storedID: try XCTUnwrap(storedID)) XCTAssertTrue(saved.waitForExistence(timeout: 25)) saved.tap() @@ -1693,7 +1593,8 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { XCTAssertTrue(composer.waitForExistence(timeout: 15)) XCTAssertEqual(composer.value as? String, prompt, "Suspension must preserve the exact draft.") } else if phase == "warm-reopen" { - openRootDestination("chats", sidebarIdentifier: "menu.chats", in: app) + returnToHome(in: app) + openThisComputerSessions(in: app) let saved = nativeSessionRow(in: app, profileID: profile, storedID: try XCTUnwrap(storedID)) XCTAssertTrue(saved.waitForExistence(timeout: 25)) saved.tap() @@ -1802,6 +1703,69 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { return values } + // MARK: The one home + + /// New chat from the home; the first bot listed takes it, so the box becomes its chat. + @MainActor + private func startFreshChat(_ app: XCUIApplication) { + returnToHome(in: app) + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 20), "The home has New chat.") + newChat.tap() + pickFirstBot(app) + } + + /// New chat opens with nobody picked. + @MainActor + private func pickFirstBot(_ app: XCUIApplication) { + let bot = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "new-chat.bot.")).firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 20), "New chat lists the host's bots.") + bot.tap() + } + + /// A bot on Bots: listed or pinned by its profile, or (for the default one) the primary tile. + @MainActor + private func botButton(_ profile: String, in app: XCUIApplication) -> XCUIElement { + let row = app.buttons.matching(NSPredicate(format: "identifier IN %@", + ["simple-bots.bot.\(profile)", "simple-bots.pinned.\(profile)"])).firstMatch + if profile == "default", !row.waitForExistence(timeout: 5) { return app.primaryBot } + return row + } + + /// Bots › a bot: its chat (Settings › Chat › A bot opens, out of the box). + @MainActor + private func openBot(_ profile: String, in app: XCUIApplication) { + returnToHome(in: app) + showBots(in: app) + let bot = botButton(profile, in: app) + XCTAssertTrue(bot.waitForExistence(timeout: 20), "Bots lists \(profile).") + bot.tap() + } + + /// Today › See all for one kind, then the host's first bot: its own board. + @MainActor + private func openOwnBoard(_ kind: String, in app: XCUIApplication) { + returnToHome(in: app) + openTodayBoard(kind, in: app) + let bot = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND identifier != %@", + "today.board-page.chip.", "today.board-page.chip.all")).firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "See all lists the host's bots.") + bot.tap() + } + + /// Bots' + › New Group Chat. + @MainActor + private func openNewGroupChat(_ app: XCUIApplication) { + returnToHome(in: app) + showBots(in: app) + let add = app.buttons["simple-bots.new"].firstMatch + XCTAssertTrue(add.waitForExistence(timeout: 20), "Bots has +.") + add.tap() + let newGroup = app.buttons["New Group Chat"].firstMatch + XCTAssertTrue(newGroup.waitForExistence(timeout: 10), "+ offers New Group Chat on a host that can make one.") + newGroup.tap() + } + @MainActor private func capture(_ name: String, _ app: XCUIApplication) { let attachment = XCTAttachment(screenshot: app.screenshot()) @@ -1818,134 +1782,3 @@ final class NativeWorkspaceProductionUITests: BighelpUITestCase { } } } - - -/// Production-path checks that deliberately require an explicit project ID. -/// The test creates a fresh chat and associates only that disposable session -/// with an already-registered project. It never creates, renames, archives, or -/// moves an existing session. -final class NativeProjectActivityProductionUITests: BighelpUITestCase { - @MainActor - func testSavedRealHostNewChatSelectsExistingProjectAndShowsCheckmark() throws { - guard ProcessInfo.processInfo.environment["BIGHELP_REAL_PROJECT_SELECTION_UI"] == "1", - let projectID = ProcessInfo.processInfo.environment["BIGHELP_REAL_PROJECT_ID"], - !projectID.isEmpty else { - throw XCTSkip( - "Requires explicit real-host project-selection authorization and BIGHELP_REAL_PROJECT_ID." - ) - } - continueAfterFailure = false - let app = XCUIApplication() - app.launchArguments = [] - app.launchEnvironment = [:] - app.launch() - - let newChat = app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 20), "The saved native host must expose New Chat.") - newChat.tap() - - let composer = app.textViews["chat.composer.text"] - XCTAssertTrue( - composer.waitForExistence(timeout: 20), - "A newly-created disposable chat must reach the composer before project selection." - ) - guard composer.exists else { return } - - XCTAssertTrue(app.buttons["chat.options"].waitForExistence(timeout: 10)) - openChatWorkspaceMenu(in: app) - - let workspaceChooser = app.buttons["menu.folder"] - XCTAssertTrue( - workspaceChooser.waitForExistence(timeout: 10), - "The native chat must expose the workspace chooser." - ) - guard workspaceChooser.exists else { return } - workspaceChooser.tap() - - let picker = app.descendants(matching: .any)["hermes-workspaces.screen"].firstMatch - XCTAssertTrue( - picker.waitForExistence(timeout: 15), - "The workspace picker must load from the selected native host." - ) - guard picker.exists else { return } - - let project = app.buttons["hermes-workspace.\(projectID)"] - XCTAssertTrue( - project.waitForExistence(timeout: 20), - "The explicitly selected existing project must be present in the host catalog." - ) - guard project.exists else { return } - for _ in 0..<8 where !project.isHittable { app.swipeUp() } - XCTAssertTrue(project.isHittable, "The existing project row must be selectable.") - project.tap() - // Successful selection closes the sheet. Reopen it to verify the - // host-backed association rather than querying a dismissed row. - let dismissed = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: picker) - let selectionResult = XCTWaiter.wait(for: [dismissed], timeout: 20) - if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { - try? app.debugDescription.write(to: URL(fileURLWithPath: directory).appendingPathComponent("real-project-after-selection.txt"), atomically: true, encoding: .utf8) - } - XCTAssertEqual(selectionResult, .completed) - XCTAssertTrue(composer.waitForExistence(timeout: 5)) - openChatWorkspaceMenu(in: app) - XCTAssertTrue(workspaceChooser.waitForExistence(timeout: 5)) - workspaceChooser.tap() - XCTAssertTrue(project.waitForExistence(timeout: 15)) - - let selected = NSPredicate(format: "value == %@", "Selected") - expectation(for: selected, evaluatedWith: project) - waitForExpectations(timeout: 20) - XCTAssertEqual( - project.value as? String, - "Selected", - "Hermes must confirm the existing project association for this new session." - ) - - // The row's selected accessibility state is backed by the visible - // checkmark in HermesWorkspaceRows. Keep a tree artifact for review - // without recording prompts, credentials, or host response content. - if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { - try app.debugDescription.write( - to: URL(fileURLWithPath: directory).appendingPathComponent( - "real-project-selection-checkmark-tree.txt" - ), - atomically: true, - encoding: .utf8 - ) - } - let screenshot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) - screenshot.name = "real-project-selection-checkmark" - screenshot.lifetime = .keepAlways - add(screenshot) - app.buttons["Done"].tap() - XCTAssertTrue(composer.waitForExistence(timeout: 5)) - composer.tap() - composer.typeText("Reply with exactly PROJECT2102 OK. Do not call tools or delegate.") - let send = app.buttons["chat.send"] - let canSend = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == true AND enabled == true"), object: send) - XCTAssertEqual(XCTWaiter.wait(for: [canSend], timeout: 20), .completed) - send.tap() - XCTAssertTrue(app.buttons["chat.voice"].waitForExistence(timeout: 90)) - app.terminate(); app.launch() - XCTAssertTrue(app.buttons["tab.sessions"].waitForExistence(timeout: 20)) - app.buttons["tab.sessions"].tap() - let filters = app.descendants(matching: .any).matching(identifier: "sessions.filters").firstMatch - XCTAssertTrue(filters.waitForExistence(timeout: 10)); filters.tap() - let projectFilter = app.buttons["sessions.filter.project"] - XCTAssertTrue(projectFilter.waitForExistence(timeout: 10)); projectFilter.tap() - let home = app.buttons["sessions.filter.project.\(projectID)"].firstMatch - XCTAssertTrue(home.waitForExistence(timeout: 10), "The Chats catalog must restore Home as an assigned project.") - home.tap() - let saved = app.descendants(matching: .any).matching(NSPredicate( - format: "label CONTAINS[c] %@", "PROJECT2102" - )).firstMatch - let visible = saved.waitForExistence(timeout: 15) - if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { - try app.debugDescription.write(to: URL(fileURLWithPath: directory).appendingPathComponent("real-project-filter-state.txt"), atomically: true, encoding: .utf8) - } - XCTAssertTrue(visible, "The newly created chat must remain inside the Home project filter.") - if let directory = ProcessInfo.processInfo.environment["BIGHELP_REAL_HOST_ARTIFACTS"] { - try app.debugDescription.write(to: URL(fileURLWithPath: directory).appendingPathComponent("real-project-chats-after-relaunch.txt"), atomically: true, encoding: .utf8) - } - } -} diff --git a/BighelpUITests/NeedsYouBlueprintsModesUITests.swift b/BighelpUITests/NeedsYouBlueprintsModesUITests.swift index 8c28898a..78ae83ee 100644 --- a/BighelpUITests/NeedsYouBlueprintsModesUITests.swift +++ b/BighelpUITests/NeedsYouBlueprintsModesUITests.swift @@ -1,15 +1,15 @@ import XCTest -/// The Needs you deck, an empty board's starters and their chips in the message box, and -/// Settings › Modes' picker, in demo mode. BIGHELP_UX_EVIDENCE (a folder) also saves the screenshots. +/// The Needs you deck, and an empty board's starters (a bot's Feed, from Today › See all) and their +/// chips in the message box, in demo mode. BIGHELP_UX_EVIDENCE (a folder) also saves the screenshots. final class NeedsYouBlueprintsModesUITests: BighelpUITestCase { @MainActor - func testDeckStartersChipsAndModesDark() throws { + func testDeckStartersAndChipsDark() throws { try walkthrough(appearance: "dark") } @MainActor - func testDeckStartersChipsAndModesLight() throws { + func testDeckStartersAndChipsLight() throws { try walkthrough(appearance: "light") } @@ -45,8 +45,11 @@ final class NeedsYouBlueprintsModesUITests: BighelpUITestCase { app.buttons["needs-you.later"].tap() XCTAssertTrue(deck.waitForNonExistence(timeout: 5), "Later closes the deck") - // An empty Feed offers starters. - openRootTab("tab.feed", in: app) + // An empty Feed offers starters: one bot's, from Today › See all. + openTodayBoard("feed", in: app) + let bot = app.buttons["today.board-page.chip.finance"].firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "See all lists the bots") + bot.tap() XCTAssertTrue(app.descendants(matching: .any)["board.feed.empty"].firstMatch.waitForExistence(timeout: 10)) let starter = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "board.starter.")).firstMatch XCTAssertTrue(starter.waitForExistence(timeout: 5), "A starter to pick") @@ -65,29 +68,6 @@ final class NeedsYouBlueprintsModesUITests: BighelpUITestCase { blank.typeText("Acme\n") XCTAssertTrue(send.isEnabled) save("blueprint-chips-filled-\(appearance)", app) - - // Modes: one picker for the home, and Code mode's own switch. - openSettings(in: app) - settingsRow("settings.menu.modes", in: app).tap() - let chat = app.buttons["settings.mode.chat"] - let code = app.buttons["settings.mode.code"] - XCTAssertTrue(chat.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["settings.mode.bots"].exists) - XCTAssertTrue(chat.isSelected) - let codeMode = app.switches["settings.code-mode"] - XCTAssertEqual(codeMode.value as? String, "0") - save("settings-modes-\(appearance)", app) - - code.tap() - XCTAssertTrue(code.isSelected) - XCTAssertEqual(codeMode.value as? String, "1", "Picking Code turns Code mode on") - codeMode.switches.firstMatch.tap() - XCTAssertTrue(chat.isSelected, "Code mode off goes back to Chat") - code.tap() - app.buttons["settings.done"].tap() - XCTAssertTrue(app.descendants(matching: .any)["code.screen"].waitForExistence(timeout: 10), - "Picking Code makes it the home") - app.terminate() } diff --git a/BighelpUITests/NewBotChatHostUITests.swift b/BighelpUITests/NewBotChatHostUITests.swift index b288d0e1..4e658463 100644 --- a/BighelpUITests/NewBotChatHostUITests.swift +++ b/BighelpUITests/NewBotChatHostUITests.swift @@ -15,9 +15,9 @@ final class NewBotChatHostUITests: BighelpUITestCase { let app = makeApp() app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - openRootTab("tab.agents", in: app) - let row = app.buttons["agent.\(agent)"].firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 30), "agent.\(agent) on Agents") + showBots(in: app) + let row = botRow(agent, in: app) + XCTAssertTrue(row.waitForExistence(timeout: 30), "\(agent) on Bots") row.tap() let composer = app.textViews["chat.composer.text"] XCTAssertTrue(composer.waitForExistence(timeout: 45), "Its Bot Chat opens") @@ -66,9 +66,11 @@ final class NewBotChatHostUITests: BighelpUITestCase { app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) func openAgent() { - openRootTab("tab.agents", in: app) - let row = app.buttons["agent.\(agent)"].firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 30), "agent.\(agent) on Agents") + // From a chat: Back to the home first. + if app.buttons["chat.back"].firstMatch.exists { goBackFromChat(in: app) } + showBots(in: app) + let row = botRow(agent, in: app) + XCTAssertTrue(row.waitForExistence(timeout: 30), "\(agent) on Bots") row.tap() } func send(_ text: String) -> XCUIElement { @@ -118,13 +120,20 @@ final class NewBotChatHostUITests: BighelpUITestCase { let newChat = chatNewChatButton(in: app) XCTAssertTrue(newChat.waitForExistence(timeout: 10), "New chat is there") newChat.tap() - confirmNewChatPicker(in: app) + confirmNewChatPicker(in: app, botID: agent) XCTAssertFalse(failed.waitForExistence(timeout: 20), "A new chat starts: \(failed.staticTexts.allElementsBoundByIndex.map(\.label))") save("new-chat", app) app.terminate() } + /// The agent on Bots, in the list or among the pinned ones. A bot tapped there opens its Bot Chat + /// (Settings › Chat › A bot opens, as it is out of the box). + @MainActor private func botRow(_ agent: String, in app: XCUIApplication) -> XCUIElement { + app.buttons.matching(NSPredicate(format: "identifier IN %@", + ["simple-bots.bot.\(agent)", "simple-bots.pinned.\(agent)"])).firstMatch + } + @MainActor private func save(_ name: String, _ app: XCUIApplication) { let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) shot.name = name diff --git a/BighelpUITests/NoodleUITests.swift b/BighelpUITests/NoodleUITests.swift index 366073ef..25e8d49b 100644 --- a/BighelpUITests/NoodleUITests.swift +++ b/BighelpUITests/NoodleUITests.swift @@ -1,7 +1,7 @@ import XCTest -/// The brand kit's Noodle: its motions in the loader gallery, the chat's one-loader rule, -/// the wordmark in the header and the first run's reveal. Set `BIGHELP_NOODLE_EVIDENCE` +/// The brand kit's Noodle: its motions in the loader gallery, the chat's one-loader rule +/// and the first run's reveal. Set `BIGHELP_NOODLE_EVIDENCE` /// (as TEST_RUNNER_…) to a folder to keep screenshots; `BIGHELP_NOODLE_APPEARANCE` picks /// light or dark (dark by default). final class NoodleUITests: BighelpUITestCase { @@ -24,15 +24,7 @@ final class NoodleUITests: BighelpUITestCase { } @MainActor - func testHeaderShowsTheWordmarkAndTheFirstRunWritesTheMark() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] - app.launch() - XCTAssertTrue(app.buttons["brand.host-switcher"].waitForExistence(timeout: 15) - || app.otherElements["brand.host-switcher"].exists) - save("noodle-header", app) - app.terminate() - + func testTheFirstRunWritesTheMark() throws { let fresh = makeApp() fresh.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-no-configured-hosts", "-force-signed-out-onboarding", "-loopdy.demo.appearance", appearance] diff --git a/BighelpUITests/NotificationErrorCodeUITests.swift b/BighelpUITests/NotificationErrorCodeUITests.swift index 1d4635f9..3288c775 100644 --- a/BighelpUITests/NotificationErrorCodeUITests.swift +++ b/BighelpUITests/NotificationErrorCodeUITests.swift @@ -60,15 +60,9 @@ final class NotificationErrorCodeUITests: BighelpUITestCase { app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-host-setup", "connected", "-test-notification-failure", failure, "-loopdy.demo.appearance", appearance] app.launch() - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15), "☰ menu") - menu.tap() - let hosts = app.buttons["menu.hosts"] - XCTAssertTrue(hosts.waitForExistence(timeout: 5)) - hosts.tap() - let add = app.buttons["menu.host.add"] - XCTAssertTrue(add.waitForExistence(timeout: 5)) - add.tap() + // Settings › Your computers › Add a computer. + openSettings(in: app) + settingsRow("settings.add-computer", in: app).tap() return app } diff --git a/BighelpUITests/ObjectCardsUITests.swift b/BighelpUITests/ObjectCardsUITests.swift index e527400f..c054e1c4 100644 --- a/BighelpUITests/ObjectCardsUITests.swift +++ b/BighelpUITests/ObjectCardsUITests.swift @@ -62,7 +62,7 @@ final class ObjectCardsUITests: BighelpUITestCase { private func launch(appearance: String) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-object-cards", - "-loopdy.home.opens-chat", "YES", "-loopdy.settings.nerd-mode", "NO", + "-start-chat", "-loopdy.settings.nerd-mode", "NO", "-loopdy.demo.appearance", appearance] app.launch() return app diff --git a/BighelpUITests/PluginReleaseUpdateHostUITests.swift b/BighelpUITests/PluginReleaseUpdateHostUITests.swift index a2064134..6f6c8d72 100644 --- a/BighelpUITests/PluginReleaseUpdateHostUITests.swift +++ b/BighelpUITests/PluginReleaseUpdateHostUITests.swift @@ -13,10 +13,9 @@ final class PluginReleaseUpdateHostUITests: BighelpUITestCase { let probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) guard probe["mode"] == "update" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30), "The agent's chat opens") + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 30), "The home opens") openSettings(in: app) // Your computers: the computer's row says so once the check finds a newer release. diff --git a/BighelpUITests/ProjectsAndBoardHostUITests.swift b/BighelpUITests/ProjectsAndBoardHostUITests.swift index c4d96257..b9472be8 100644 --- a/BighelpUITests/ProjectsAndBoardHostUITests.swift +++ b/BighelpUITests/ProjectsAndBoardHostUITests.swift @@ -13,17 +13,16 @@ final class ProjectsAndBoardHostUITests: BighelpUITestCase { let probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) guard probe["mode"] == "features" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30), "The agent's chat opens") + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 30), "The home opens") - // The seeded posts are new: the Feed tab says so before it's opened. - let feedTab = app.buttons["tab.feed"] - XCTAssertTrue(feedTab.waitForExistence(timeout: 10)) - let newOnTab = expectation(for: NSPredicate(format: "value == %@", "New"), evaluatedWith: feedTab) + // The seeded posts are new: the Today tab says so before it's opened. + let todayTab = app.buttons["home.tab.today"].firstMatch + XCTAssertTrue(todayTab.waitForExistence(timeout: 10)) + let newOnTab = expectation(for: NSPredicate(format: "value == %@", "New"), evaluatedWith: todayTab) wait(for: [newOnTab], timeout: 20) - feedTab.tap() + openBoard("feed", in: app) let stockTips = app.descendants(matching: .any)["board.feed.post.probe-stock-tips"] XCTAssertTrue(stockTips.waitForExistence(timeout: 20), "The host's Feed shows") save("features-1-feed", app) @@ -74,7 +73,7 @@ final class ProjectsAndBoardHostUITests: BighelpUITestCase { XCTAssertTrue(news.waitForExistence(timeout: 10), "Undo brings the post back") // An idea becomes a goal. - app.buttons["tab.ideas"].tap() + openBoard("ideas", in: app) let idea = app.buttons["board.idea.probe-trip"] XCTAssertTrue(idea.waitForExistence(timeout: 10)) idea.press(forDuration: 1.2) @@ -82,19 +81,13 @@ final class ProjectsAndBoardHostUITests: BighelpUITestCase { XCTAssertTrue(promote.waitForExistence(timeout: 5)) promote.tap() XCTAssertTrue(idea.waitForNonExistence(timeout: 10), "The idea leaves Ideas") - app.buttons["tab.goals"].tap() + openBoard("goals", in: app) let goal = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS %@", "Plan a weekend trip")).firstMatch XCTAssertTrue(goal.waitForExistence(timeout: 10), "…and shows in Goals") save("features-4-idea-to-goal", app) - // Projects: make one, start a chat in it, find the chat in the project. - app.buttons["tab.sessions"].tap() - let menu = app.buttons["chat.menu"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let projects = app.buttons["menu.projects"] - XCTAssertTrue(projects.waitForExistence(timeout: 5), "Projects is in the menu") - projects.tap() + // Projects (Work's door): make one, start a chat in it, find the chat in the project. + openWorkDoor("projects", in: app) XCTAssertTrue(app.descendants(matching: .any)["projects.screen"].waitForExistence(timeout: 10)) let create = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["projects.new", "projects.empty.new"])).firstMatch XCTAssertTrue(create.waitForExistence(timeout: 10)) @@ -139,7 +132,7 @@ final class ProjectsAndBoardHostUITests: BighelpUITestCase { } /// The host's profile sets no terminal.cwd, so its agent works where Hermes was started. - /// The Apps tab still shows the agent's files from there, not "Workspace unavailable". + /// The bot page's Files tab still shows the agent's files from there, not "Workspace unavailable". @MainActor func testAppsShowsTheAgentsFilesWithNoWorkingFolderSet() throws { guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { @@ -150,22 +143,36 @@ final class ProjectsAndBoardHostUITests: BighelpUITestCase { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } let app = makeApp() - // Files lives in ☰ by default; pinned here so the bar holds it. - app.launchArguments = ["-loopdy.home.opens-chat", "YES", "-bighelp.app-layout", "{pinned=(feed,ideas,files);menu=();}"] app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30), "The agent's chat opens") - let appsTab = app.buttons["tab.apps"] - XCTAssertTrue(appsTab.waitForExistence(timeout: 10)) - appsTab.tap() + // Bots › the primary bot's chat › its page › Files. + showBots(in: app) + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 30), "Bots shows the primary bot") + primary.tap() + XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30), "The bot's chat opens") + openBotPage(fromChatIn: app) + let filesTab = app.buttons["simple-bots.profile.tab.files"] + XCTAssertTrue(filesTab.waitForExistence(timeout: 10)) + filesTab.tap() let file = app.descendants(matching: .any) .matching(NSPredicate(format: "label CONTAINS %@", fileName)).firstMatch let shown = file.waitForExistence(timeout: 30) - save("features-8-apps-files", app) - XCTAssertTrue(shown, "The agent's file shows in Apps") + save("features-8-bot-files", app) + XCTAssertTrue(shown, "The agent's file shows in its Files") XCTAssertFalse(app.staticTexts["Workspace unavailable"].exists) } + /// Today › See all for one kind, then the host's bot: its own board, with posts, ideas or goals. + @MainActor private func openBoard(_ kind: String, in app: XCUIApplication) { + returnToHome(in: app) + openTodayBoard(kind, in: app) + let bot = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND identifier != %@", + "today.board-page.chip.", "today.board-page.chip.all")).firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "See all lists the host's bot") + bot.tap() + } + @MainActor private func save(_ name: String, _ app: XCUIApplication) { let shot = XCTAttachment(screenshot: app.screenshot()) shot.name = name diff --git a/BighelpUITests/ProviderUsageHostUITests.swift b/BighelpUITests/ProviderUsageHostUITests.swift index 7feea674..7974742f 100644 --- a/BighelpUITests/ProviderUsageHostUITests.swift +++ b/BighelpUITests/ProviderUsageHostUITests.swift @@ -2,9 +2,8 @@ import XCTest /// Provider usage against a real, isolated Hermes host with the bighelp plugin /// (Scripts/HostSignInMatrixProbe.py --modes features), set up as on a phone: -/// no demo fixtures, and the agent's chat opens at launch, covering the home -/// screen. Usage must load from that chat now, after a reconnect, and after a -/// relaunch. Skipped without the probe. +/// no demo fixtures, and the primary bot's chat opened from Bots. Usage must load +/// from that chat now, after a reconnect, and after a relaunch. Skipped without the probe. final class ProviderUsageHostUITests: BighelpUITestCase { @MainActor func testUsageLoadsFromTheChatTheAppOpensWith() throws { guard let path = ProcessInfo.processInfo.environment["BIGHELP_SIGNIN_PROBE"] else { @@ -13,10 +12,10 @@ final class ProviderUsageHostUITests: BighelpUITestCase { let probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) guard probe["mode"] == "features" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30), "The agent's chat opens") + openPrimaryBotChat(in: app) + XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30), "The bot's chat opens") try expectUsage(in: app, "usage-1-after-setup") // Past the grace period the app closes its host connection; coming back reconnects. @@ -27,10 +26,11 @@ final class ProviderUsageHostUITests: BighelpUITestCase { XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 30)) try expectUsage(in: app, "usage-2-after-reconnect") - // A relaunch opens the agent's chat over the home screen before the host is ready. + // After a relaunch, the chat opened again as soon as the home shows, before the host is ready. app.terminate() app.launch() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 45), "The chat opens at launch") + openPrimaryBotChat(in: app) + XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 45), "The chat opens after a relaunch") try expectUsage(in: app, "usage-3-after-relaunch") } @@ -58,7 +58,15 @@ final class ProviderUsageHostUITests: BighelpUITestCase { XCTAssertTrue(loaded.exists, "Usage shows when it was updated (\(name))") // The host's own analytics fill the page too. XCTAssertTrue(app.descendants(matching: .any)["usage.hero"].waitForExistence(timeout: 30), "Hermes usage loads (\(name))") - app.navigationBars.buttons.element(boundBy: 0).tap() + app.navigationBars["Usage"].buttons.element(boundBy: 0).tap() + } + + /// Bots › the primary bot: its Bot Chat (Settings › Chat › A bot opens, out of the box). + @MainActor private func openPrimaryBotChat(in app: XCUIApplication) { + showBots(in: app) + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 45), "Bots shows the primary bot") + primary.tap() } @MainActor private func save(_ name: String, _ app: XCUIApplication) { diff --git a/BighelpUITests/ProviderUsageUITests.swift b/BighelpUITests/ProviderUsageUITests.swift index ee7ae70a..e37d5e32 100644 --- a/BighelpUITests/ProviderUsageUITests.swift +++ b/BighelpUITests/ProviderUsageUITests.swift @@ -1,26 +1,17 @@ import XCTest -/// ☰ › Usage on demo data: it sits right above Settings, opens one page with -/// plans and limits, the chart, totals and the models behind them, and covers -/// every computer while All hosts is on. The chat's ⋯ opens the same page. +/// Settings › Usage on demo data: one page with plans and limits, the chart, totals +/// and the models behind them, and it covers every computer while Show every computer +/// is on. The chat's ⋯ opens the same page. /// BIGHELP_USAGE_EVIDENCE (TEST_RUNNER_…) saves screenshots; /// BIGHELP_USAGE_APPEARANCE picks light or dark (light by default). final class ProviderUsageUITests: BighelpUITestCase { private var appearance: String { ProcessInfo.processInfo.environment["BIGHELP_USAGE_APPEARANCE"] ?? "light" } @MainActor - func testUsageOpensFromTheMenuAboveSettings() throws { + func testUsageOpensFromSettings() throws { let app = launch(["-bighelp.hosts.all-hosts", "NO"]) - openMenu(app) - let usage = app.buttons["menu.usage"] - let settings = app.buttons["menu.settings"] - XCTAssertTrue(usage.waitForExistence(timeout: 8), "Usage is in ☰") - XCTAssertTrue(usage.isHittable, "on the first screen") - XCTAssertLessThan(usage.frame.maxY, settings.frame.minY + 2, "right above Settings") - XCTAssertLessThan(app.buttons["menu.scheduled-tasks"].frame.maxY, usage.frame.minY + 2) - XCTAssertEqual(app.buttons.matching(identifier: "menu.usage").count, 1, "One Usage, not a second copy under More") - save("usage-0-menu-\(appearance)", app) - usage.tap() + openUsage(app) let page = expectPage(app) XCTAssertTrue(app.descendants(matching: .any)["provider-usage.claude"].waitForExistence(timeout: 8), @@ -95,10 +86,7 @@ final class ProviderUsageUITests: BighelpUITestCase { @MainActor func testLimitsFollowTheChosenOrder() throws { let app = launch(["-bighelp.hosts.all-hosts", "NO", "-bighelp.provider-usage.order", "copilot"]) - openMenu(app) - let usage = app.buttons["menu.usage"] - XCTAssertTrue(usage.waitForExistence(timeout: 8)) - usage.tap() + openUsage(app) let page = expectPage(app) XCTAssertTrue(app.descendants(matching: .any)["provider-usage.copilot"].waitForExistence(timeout: 8), "Limits shows the plan put first") @@ -132,21 +120,11 @@ final class ProviderUsageUITests: BighelpUITestCase { app.alerts.buttons["Save"].firstMatch.tap() } + /// Settings › Show every computer on: Usage adds up every computer. @MainActor - func testAllHostsAddsUpEveryComputer() throws { - let app = launch(["-bighelp.hosts.all-hosts", "NO"]) - openMenu(app) - let allHosts = app.buttons["menu.all-hosts"] - XCTAssertTrue(allHosts.waitForExistence(timeout: 5)) - allHosts.tap() - XCTAssertTrue(app.descendants(matching: .any)["fleet.home"].waitForExistence(timeout: 8)) - openMenu(app) - let usage = app.buttons["menu.usage"] - XCTAssertTrue(usage.waitForExistence(timeout: 5)) - XCTAssertLessThan(usage.frame.maxY, app.buttons["menu.settings"].frame.minY + 2, "Above Settings here too") - usage.tap() - XCTAssertFalse(app.buttons["fleet.gate.host.Home Hermes"].waitForExistence(timeout: 2), - "Usage covers every host, so it doesn't ask which") + func testEveryComputerAddsUp() throws { + let app = launch(["-bighelp.hosts.all-hosts", "YES"]) + openUsage(app) let page = expectPage(app) save("usage-4-all-hosts-\(appearance)", app) @@ -167,10 +145,7 @@ final class ProviderUsageUITests: BighelpUITestCase { @MainActor func testLimitsShowOneComputerOrAllUnderTheirNames() throws { let app = launch(["-bighelp.hosts.all-hosts", "YES"]) - openMenu(app) - let usage = app.buttons["menu.usage"] - XCTAssertTrue(usage.waitForExistence(timeout: 8)) - usage.tap() + openUsage(app) _ = expectPage(app) let any = app.descendants(matching: .any) let menu = app.buttons["usage.limits.computer"] @@ -213,8 +188,7 @@ final class ProviderUsageUITests: BighelpUITestCase { @MainActor func testShareOffersFourFormats() throws { let app = launch(["-bighelp.hosts.all-hosts", "YES", "-test-slow-usage-export"]) - openMenu(app) - app.buttons["menu.usage"].tap() + openUsage(app) _ = expectPage(app) let share = app.buttons["usage.share"] XCTAssertTrue(share.waitForExistence(timeout: 8)) @@ -240,8 +214,7 @@ final class ProviderUsageUITests: BighelpUITestCase { @MainActor func testOneComputerHasNoLimitsMenu() throws { let app = launch(["-bighelp.hosts.all-hosts", "NO"]) - openMenu(app) - app.buttons["menu.usage"].tap() + openUsage(app) _ = expectPage(app) XCTAssertTrue(app.descendants(matching: .any)["provider-usage.claude"].waitForExistence(timeout: 8)) XCTAssertFalse(app.buttons["usage.limits.computer"].exists) @@ -252,7 +225,7 @@ final class ProviderUsageUITests: BighelpUITestCase { @MainActor func testTheChatMenuOpensTheSamePage() throws { let app = launch(["-preview-simple-chat"]) - let conversation = app.buttons["session.row.demo-finance"] + let conversation = chatRow("demo-finance", in: app) XCTAssertTrue(conversation.waitForExistence(timeout: 15)) conversation.tap() let options = app.buttons["chat.options"] @@ -261,7 +234,7 @@ final class ProviderUsageUITests: BighelpUITestCase { XCTAssertTrue(usage.waitForExistence(timeout: 5)) usage.tap() _ = expectPage(app) - app.navigationBars.buttons.element(boundBy: 0).tap() + app.navigationBars["Usage"].buttons.element(boundBy: 0).tap() XCTAssertTrue(app.buttons["chat.options"].waitForExistence(timeout: 5), "Back returns to the chat") } @@ -276,11 +249,11 @@ final class ProviderUsageUITests: BighelpUITestCase { return app } + /// Settings › Usage: Settings closes and Usage opens over the home. @MainActor - private func openMenu(_ app: XCUIApplication) { - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 10), "☰ menu") - menu.tap() + private func openUsage(_ app: XCUIApplication) { + openSettings(in: app) + settingsRow("simple-bots.settings.usage", in: app).tap() } /// On screen and below the glass header, which takes taps over the page. diff --git a/BighelpUITests/ReferenceHubUITests.swift b/BighelpUITests/ReferenceHubUITests.swift index 77ef6922..078a1185 100644 --- a/BighelpUITests/ReferenceHubUITests.swift +++ b/BighelpUITests/ReferenceHubUITests.swift @@ -11,9 +11,18 @@ final class BighelpTestApplication: XCUIApplication { if !launchArguments.contains("-loopdy.settings.nerd-mode") { launchArguments += ["-loopdy.settings.nerd-mode", "YES"] } - // Older flows start on the chat list; the agent-home tests opt back in. - if !launchArguments.contains("-loopdy.home.opens-chat") { - launchArguments += ["-loopdy.home.opens-chat", "NO"] + // The one home's settings are moved over from the old shell's once; tests start past that. + if !launchArguments.contains("-bighelp.home.migrated-v1") { + launchArguments += ["-bighelp.home.migrated-v1", "YES"] + } + // Tests start on the Chats list with the bar; a test pins its own place (bots, chats, today + // or work, with `-bighelp.home.view bots|chats` under today or work). + if !launchArguments.contains("-loopdy.home.landing") { + launchArguments += ["-loopdy.home.landing", "chats"] + } + // The computer in use only; tests of every computer at once opt in. + if !launchArguments.contains("-bighelp.hosts.all-hosts") { + launchArguments += ["-bighelp.hosts.all-hosts", "NO"] } // A bot profile's one-time swipe tutorial dims the page; tests of it opt back in. if !launchArguments.contains("-bighelp.dashboard.swipe-tutorial-seen") { @@ -27,6 +36,19 @@ final class BighelpTestApplication: XCUIApplication { } } +extension XCUIApplication { + /// The Bots view's primary bot, whichever bot it is: its row is `simple-bots.primary.`. + var primaryBot: XCUIElement { + buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "simple-bots.primary.")).firstMatch + } + + /// The primary bot's tile while the Bots view is being rearranged (not a button then). + var primaryBotTile: XCUIElement { + descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "simple-bots.primary.")) + .firstMatch + } +} + class BighelpUITestCase: XCTestCase { private let fixtureRunID = UUID().uuidString @@ -44,36 +66,38 @@ class BighelpUITestCase: XCTestCase { return app } - /// Agents, Tasks and Settings left the iPhone bottom bar for ☰ (the chat - /// list's leading button, or the home chat's menu). Bar tabs still tap directly. - /// Who the chat is with: the big live avatar on iPhone, the name chip on - /// iPad and in group chats. + /// Who the chat is with: the pill in a chat's header (a bot's opens its page). @MainActor func chatIdentity(in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "identifier IN %@", ["agent.hero.avatar", "chat.identity"])).firstMatch + app.buttons["chat.identity"].firstMatch } - /// The chat header's New chat button (the big-avatar header on iPhone, - /// the name-chip header on iPad). + /// The bar's New chat. Chats have no New chat of their own, so this leaves an open chat (its + /// Back) first; the bar shows again under it. @MainActor func chatNewChatButton(in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "identifier IN %@", ["chat.home.new-chat", "chat.new-chat"])).firstMatch + let back = app.buttons["chat.back"].firstMatch + if back.exists, back.isHittable { + back.tap() + _ = back.waitForNonExistence(timeout: 5) + } + return app.buttons["home.new-chat"].firstMatch } - /// The big header's New chat asks who to chat with, with the current - /// agent already picked. Confirms it when it shows. + /// New chat opens with nobody picked: picks `botID`'s `new-chat.bot.`, or the first bot listed. @MainActor - func confirmNewChatPicker(in app: XCUIApplication) { - let start = app.buttons["bot-mode.create.submit"].firstMatch - if start.waitForExistence(timeout: 3), start.isEnabled { start.tap() } + func confirmNewChatPicker(in app: XCUIApplication, botID: String? = nil) { + guard app.descendants(matching: .any)["new-chat.to"].firstMatch.waitForExistence(timeout: 5) else { return } + let bot = botID.map { app.buttons["new-chat.bot.\($0)"].firstMatch } + ?? app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "new-chat.bot.")).firstMatch + if bot.waitForExistence(timeout: 5), bot.isHittable { bot.tap() } } - /// The header's status line ("Updating…" while a chat reloads). + /// The header's status (the pill's value reads "Updating…" while a chat reloads). @MainActor func chatStatus(in app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "identifier IN %@", ["agent.hero.name", "chat.identity"])).firstMatch + app.buttons["chat.identity"].firstMatch } - /// Chat Info (People & Chat): a group chat's members. One-agent chats have /// none; everything it held is in their ⋯ menu. @MainActor @@ -109,7 +133,7 @@ class BighelpUITestCase: XCTestCase { groups = ["chat.options.more", "chat.options.usage"] case "chat.info", "chat.group-settings", "chat.rename", "chat.move-project", "chat.files": groups = ["chat.options.this-chat"] - case "chat.edit-current-agent", "chat.new-bot-chat", "chat.switch-agent": groups = ["chat.options.agent"] + case "chat.bot-page", "chat.new-bot-chat": groups = ["chat.options.agent"] case "chat.options.usage", "chat.options.advanced", "chat.file-changes": groups = ["chat.options.more"] case "chat.force-refresh", "chat.options.display": groups = ["chat.options.more", "chat.options.advanced"] case "chat.visibility.reasoning", "chat.visibility.tool-calls": groups = ["chat.options.more", "chat.options.advanced", "chat.options.display"] @@ -138,8 +162,8 @@ class BighelpUITestCase: XCTestCase { func chatMenuElement(_ identifier: String, in app: XCUIApplication) -> XCUIElement { let titles: [String: [String]] = [ "chat.info": ["Chat info"], "chat.group-settings": ["Group Settings"], "chat.rename": ["Rename…"], "chat.move-project": ["Move to Project…", "Move…"], - "chat.files": ["Files"], "chat.edit-current-agent": ["Edit agent"], - "chat.new-bot-chat": ["New Bot Chat"], "chat.switch-agent": ["Switch agent"], "chat.compact": ["Compact"], + "chat.files": ["Files"], "chat.bot-page": ["Bot page"], + "chat.new-bot-chat": ["New Bot Chat"], "chat.compact": ["Compact"], "chat.file-changes": ["File changes"], "chat.options.usage": ["Usage"], "chat.options.advanced": ["Advanced"], "chat.options.model-speed": ["Model & speed", "Model"], "chat.session-controls": ["Model settings", "Model"], "chat.fast-mode": ["Fast Mode"], "chat.fast-mode.on": ["On"], "chat.fast-mode.off": ["Off"], @@ -162,13 +186,11 @@ class BighelpUITestCase: XCTestCase { return matches.firstMatch } - /// Leaves a pushed chat the way people do: a swipe from the leading edge. - /// Chats have ☰ in the top left, not Back. + /// Leaves a pushed chat by its Back (`chat.back`), top left in its header. @MainActor func swipeBackFromLeadingEdge(in app: XCUIApplication) { - let window = app.windows.firstMatch - let start = window.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0.5)).withOffset(CGVector(dx: 2, dy: 0)) - start.press(forDuration: 0.05, thenDragTo: window.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: 0.5))) + let back = app.buttons["chat.back"].firstMatch + if back.waitForExistence(timeout: 5) { back.tap() } } /// ⋯ › Context window (Nerd Mode, a chat with context). Returns the pop-up. @@ -182,47 +204,29 @@ class BighelpUITestCase: XCTestCase { return popover } + /// The old shell's tabs, through the one home's doors: `tab.sessions` is Chats and `tab.agents` + /// Bots (the first tab's switch), `tab.feed|ideas|goals` Today's panel on that board, + /// `tab.scheduled-tasks`, `tab.kanban`, `tab.workflows` and `tab.projects` Work's doors, and + /// `tab.profile` Settings (the circle). Anything else has no place now and fails. @MainActor func openRootTab(_ identifier: String, in app: XCUIApplication, timeout: TimeInterval = 20, file: StaticString = #filePath, line: UInt = #line) { - let drawerRows = ["tab.agents": "menu.agents", "tab.scheduled-tasks": "menu.scheduled-tasks", - "tab.profile": "menu.settings", "tab.apps": "menu.files"] - let sidebar = ["tab.sessions": "chats", "tab.agents": "agents", - "tab.scheduled-tasks": "scheduledTasks", "tab.profile": "settings"] - let deadline = Date.now.addingTimeInterval(timeout) - repeat { - let direct = app.buttons[identifier].firstMatch - if direct.exists, direct.isHittable { direct.tap(); return } - if let id = sidebar[identifier], app.buttons["root.destination.\(id)"].firstMatch.isHittable { - app.buttons["root.destination.\(id)"].firstMatch.tap() - return - } - if let row = drawerRows[identifier] { - let menu = [app.buttons["home.drawer.open"].firstMatch, app.buttons["chat.menu"].firstMatch] - .first { $0.exists && $0.isHittable } - if let menu { - menu.tap() - let item = app.buttons[row].firstMatch - let list = app.descendants(matching: .any)["navigation.menu"].firstMatch - _ = list.waitForExistence(timeout: 10) - // Hosts come first, so later rows can sit below the fold. - for _ in 0..<6 where !(item.exists && item.isHittable) { list.swipeUp() } - XCTAssertTrue(item.waitForExistence(timeout: 10), "Missing \(row)", file: file, line: line) - item.tap() - return - } - // Feed, Ideas, Goals and Apps have no ☰; Chat does. - let chat = app.buttons["tab.sessions"].firstMatch - // A pushed page (Activity, a task) has the system Back button. - let navigationBack = app.navigationBars.firstMatch.buttons.firstMatch - if chat.exists, chat.isHittable { chat.tap() } - else if navigationBack.exists, navigationBack.isHittable, navigationBack.frame.minX < 60 { - navigationBack.tap() - } + let doors = ["tab.scheduled-tasks": "schedules", "tab.kanban": "tasks", + "tab.workflows": "workflows", "tab.projects": "projects"] + let boards = ["tab.feed": "feed", "tab.ideas": "ideas", "tab.goals": "goals"] + switch identifier { + case "tab.sessions", "tab.session-list": showChats(in: app, timeout: timeout, file: file, line: line) + case "tab.agents": showBots(in: app, timeout: timeout, file: file, line: line) + case "tab.profile": openSettings(in: app, file: file, line: line) + default: + if let door = doors[identifier] { + openWorkDoor(door, in: app, timeout: timeout, file: file, line: line) + } else if let board = boards[identifier] { + openTodayPanel(board, in: app, timeout: timeout, file: file, line: line) + } else { + XCTFail("\(identifier) has no place in the one home", file: file, line: line) } - usleep(300_000) - } while Date.now < deadline - XCTFail("Could not open \(identifier)", file: file, line: line) + } } @MainActor @@ -262,10 +266,7 @@ final class ReferenceHubUITests: BighelpUITestCase { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", "dark"] app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - menu.tap() - app.buttons["menu.new-chat"].tap() + startNewChat(with: "finance", in: app) let editor = app.textViews["chat.composer.text"] XCTAssertTrue(editor.waitForExistence(timeout: 5)) editor.tap() @@ -327,11 +328,7 @@ final class ReferenceHubUITests: BighelpUITestCase { app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"] } app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 5)) - menu.tap() - XCTAssertFalse(app.buttons["quick-workspace.wiki"].exists) - app.buttons["menu.new-chat"].tap() + startNewChat(with: "finance", in: app) let editor = app.textViews["chat.composer.text"] XCTAssertTrue(editor.waitForExistence(timeout: 5)) editor.tap() diff --git a/BighelpUITests/ReleaseScreensWalkthroughUITests.swift b/BighelpUITests/ReleaseScreensWalkthroughUITests.swift index cccb3ccb..354641bf 100644 --- a/BighelpUITests/ReleaseScreensWalkthroughUITests.swift +++ b/BighelpUITests/ReleaseScreensWalkthroughUITests.swift @@ -2,8 +2,8 @@ import XCTest /// For a Release build with the phone's 1 MB main-thread stack (see /// device-stack notes): real onboarding, a real host behind a password proxy, -/// then the chat header, Provider Usage, Settings › Voice with its provider -/// list, Chat layout and Provider Usage settings. Test shortcuts are +/// then the primary bot's chat header, Provider Usage, Settings › Voice with its +/// provider list, and Settings › Appearance › Chat layout. Test shortcuts are /// Debug-only, so this uses none. /// BIGHELP_RELEASE_WALK is "address|proxy username|proxy password". final class ReleaseScreensWalkthroughUITests: BighelpUITestCase { @@ -19,7 +19,6 @@ final class ReleaseScreensWalkthroughUITests: BighelpUITestCase { parts[0] = "release-\(UUID().uuidString.prefix(8).lowercased()).\(parts[0])" } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() let start = app.buttons["onboarding.get-started"] @@ -57,9 +56,13 @@ final class ReleaseScreensWalkthroughUITests: BighelpUITestCase { connected = continueAfterConnecting(app, timeout: 30) } XCTAssertTrue(connected, "Connected") - // The chat header the 16 Pro tester found cramped. - let avatar = app.buttons["agent.hero.avatar"] - XCTAssertTrue(avatar.waitForExistence(timeout: 30), "The agent's chat opens") + // The primary bot's chat, from Bots: the chat header the 16 Pro tester found cramped. + showBots(in: app) + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 30), "Bots shows the primary bot") + primary.tap() + let identity = app.buttons["chat.identity"] + XCTAssertTrue(identity.waitForExistence(timeout: 30), "The bot's chat opens") // iOS offers to save the proxy password, sometimes after the chat // shows; it covers the chat, so wait for it before tapping on. let springboard = XCUIApplication(bundleIdentifier: "com.apple.springboard") @@ -83,38 +86,41 @@ final class ReleaseScreensWalkthroughUITests: BighelpUITestCase { save("release-5-usage", app) for _ in 0..<6 { page.swipeUp() } save("release-6-usage-bottom", app) - app.navigationBars.buttons.element(boundBy: 0).tap() + app.navigationBars["Usage"].buttons.element(boundBy: 0).tap() XCTAssertTrue(page.waitForNonExistence(timeout: 5)) - app.buttons["chat.menu"].tap() - XCTAssertTrue(app.buttons["menu.done"].waitForExistence(timeout: 5)) - // Settings sits below the fold, past Go to. - let settingsEntry = app.buttons["menu.settings"] - for _ in 0..<4 where !(settingsEntry.exists && settingsEntry.isHittable) { app.swipeUp() } - settingsEntry.tap() - let mode = app.segmentedControls["settings.voice.mode"] - for _ in 0..<6 where !(mode.exists && mode.isHittable) { app.swipeUp() } - XCTAssertTrue(mode.waitForExistence(timeout: 5)) - mode.buttons["Take turns"].tap() + // Settings, from the home's circle. + goBackFromChat(in: app) + openSettings(in: app) let voice = settingsRow("settings.chat.voice-settings", in: app) XCTAssertTrue(voice.waitForExistence(timeout: 5)) voice.tap() + // Take turns lists the host's speech providers. + let mode = app.segmentedControls["voice.settings.conversation-mode"] + XCTAssertTrue(mode.waitForExistence(timeout: 10)) + mode.buttons["Take turns"].tap() let provider = app.buttons["voice.settings.provider"] XCTAssertTrue(provider.waitForExistence(timeout: 20), "The host's speech settings load") save("release-2-voice", app) provider.tap() XCTAssertTrue(app.buttons["voice.provider.piper"].waitForExistence(timeout: 5)) save("release-3-providers", app) - app.navigationBars.buttons.element(boundBy: 0).tap() + // The sheet's own Back: the screen behind Settings has a navigation bar too. + app.buttons["BackButton"].firstMatch.tap() XCTAssertTrue(provider.waitForExistence(timeout: 5)) - app.navigationBars.buttons.element(boundBy: 0).tap() + app.buttons["BackButton"].firstMatch.tap() - let layout = settingsRow("settings.appearance.chat-layout", in: app) + // Appearance › Chat layout. + settingsRow("settings.themes", in: app).tap() + let studio = app.descendants(matching: .any)["appearance.studio"].firstMatch + XCTAssertTrue(studio.waitForExistence(timeout: 5)) + let layout = app.buttons["settings.appearance.chat-layout"].firstMatch + for _ in 0..<6 where !(layout.exists && layout.isHittable) { studio.swipeUp() } XCTAssertTrue(layout.waitForExistence(timeout: 5)) layout.tap() XCTAssertTrue(app.segmentedControls["chat-layout.avatar-size"].waitForExistence(timeout: 5)) save("release-4-chat-layout", app) - app.navigationBars.buttons.element(boundBy: 0).tap() + app.buttons["BackButton"].firstMatch.tap() XCTAssertEqual(app.state, .runningForeground, "No crash on the phone-sized stack") } diff --git a/BighelpUITests/ScheduledAlertTapUITests.swift b/BighelpUITests/ScheduledAlertTapUITests.swift index 7c82a28d..dab7f3b1 100644 --- a/BighelpUITests/ScheduledAlertTapUITests.swift +++ b/BighelpUITests/ScheduledAlertTapUITests.swift @@ -35,7 +35,7 @@ final class ScheduledAlertTapUITests: BighelpUITestCase { private func launch(tap: String, appearance: String) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "NO", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-scheduled-alert-tap", tap, "-loopdy.demo.appearance", appearance] app.launch() return app diff --git a/BighelpUITests/ScreenKindsUITests.swift b/BighelpUITests/ScreenKindsUITests.swift index dfab4bae..58715de3 100644 --- a/BighelpUITests/ScreenKindsUITests.swift +++ b/BighelpUITests/ScreenKindsUITests.swift @@ -1,78 +1,29 @@ import XCTest -/// Long-stay screens (Kanban, Workflows, Projects) open from ☰ as screens of their own with ☰ -/// in the corner. Quick ones (Usage; Feed when the bottom bar doesn't hold it) slide in with -/// Back, and Settings is a sheet: Back steps through its pages, Done closes it. Demo data. +/// Settings is a sheet over the screen it was opened from: Back steps through its pages, Done +/// closes it and leaves that screen as it was. Demo data. final class ScreenKindsUITests: BighelpUITestCase { - @MainActor - func testLongStayScreensHaveTheMenuAndQuickOnesHaveBack() throws { - let app = launch() - app.buttons["tab.agents"].firstMatch.tap() - XCTAssertTrue(app.navigationBars["Agents"].waitForExistence(timeout: 10)) - - // Kanban: a screen of its own. - openFromMenu("menu.kanban", in: app) - XCTAssertTrue(kanban(app).waitForExistence(timeout: 10)) - XCTAssertTrue(app.buttons["home.drawer.open"].firstMatch.isHittable, "☰ in the corner") - XCTAssertFalse(app.navigationBars.buttons["BackButton"].exists, "No Back on a long-stay screen") - - // Usage: over Kanban, and Back returns there. - openFromMenu("menu.usage", in: app) - let back = app.navigationBars.buttons["BackButton"].firstMatch - XCTAssertTrue(back.waitForExistence(timeout: 10), "Back on a quick screen") - back.tap() - XCTAssertTrue(kanban(app).waitForExistence(timeout: 5), "Back returns to Kanban") - - // Feed isn't in the bar here: a quick screen with Back. - openFromMenu("menu.feed", in: app) - let boardBack = app.buttons["board.back"].firstMatch - XCTAssertTrue(boardBack.waitForExistence(timeout: 10), "Back where ☰ would be") - boardBack.tap() - XCTAssertTrue(kanban(app).waitForExistence(timeout: 5), "Back returns to Kanban") - } - @MainActor func testSettingsIsASheetWithDone() throws { - let app = launch() - app.buttons["tab.agents"].firstMatch.tap() - XCTAssertTrue(app.navigationBars["Agents"].waitForExistence(timeout: 10)) - openFromMenu("menu.settings", in: app) + let app = makeApp() + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "chats"] + app.launch() + let chats = app.descendants(matching: .any)["chats.inbox"].firstMatch + XCTAssertTrue(chats.waitForExistence(timeout: 20)) + openSettings(in: app) let done = app.buttons["settings.done"].firstMatch XCTAssertTrue(done.waitForExistence(timeout: 10), "Done, top right") let appearance = settingsRow("settings.themes", in: app) XCTAssertTrue(appearance.waitForExistence(timeout: 5)) appearance.tap() - let back = app.navigationBars.buttons["BackButton"].firstMatch + // The sheet's own Back: the screen behind it has a navigation bar too. + let back = app.buttons["BackButton"].firstMatch XCTAssertTrue(back.waitForExistence(timeout: 5), "Back inside Settings") back.tap() XCTAssertTrue(app.buttons["settings.themes"].firstMatch.waitForExistence(timeout: 5), "One step back") XCTAssertTrue(done.exists, "Still in Settings") done.tap() XCTAssertTrue(done.waitForNonExistence(timeout: 5)) - XCTAssertTrue(app.navigationBars["Agents"].waitForExistence(timeout: 5), "Done returns to where you were") - } - - @MainActor private func launch() -> XCUIApplication { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-bighelp.app-layout", "{pinned=(agents,ideas,goals,files);menu=();}"] - app.launch() - XCTAssertTrue(app.buttons["tab.agents"].waitForExistence(timeout: 20), "Agents is pinned") - return app - } - - @MainActor private func kanban(_ app: XCUIApplication) -> XCUIElement { - app.descendants(matching: .any)["kanban.screen"].firstMatch - } - - @MainActor private func openFromMenu(_ identifier: String, in app: XCUIApplication) { - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])) - .firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - let row = app.buttons[identifier].firstMatch - for _ in 0..<6 where !(row.waitForExistence(timeout: 1) && row.isHittable) { app.swipeUp() } - XCTAssertTrue(row.isHittable, identifier) - row.tap() + XCTAssertTrue(chats.waitForExistence(timeout: 5), "Done returns to where you were") } } diff --git a/BighelpUITests/SearchPlacementUITests.swift b/BighelpUITests/SearchPlacementUITests.swift index 5758501d..6a0ab720 100644 --- a/BighelpUITests/SearchPlacementUITests.swift +++ b/BighelpUITests/SearchPlacementUITests.swift @@ -1,146 +1,67 @@ import XCTest -/// Main screens look the same whichever tab you came from. The bottom bar never moves, and -/// each screen's search field is the first thing under its title, never down by the bar. -/// On one computer (Chat as the agent's chat, or the Sessions list) and with all hosts -/// showing, on demo data. Set BIGHELP_SEARCH_PLACEMENT_EVIDENCE (TEST_RUNNER_…) to save -/// screenshots. +/// Main screens keep their search where people look for it. The home's bar never moves between +/// Bots, Chats, Today and Work, nothing searches down by it, and each list's search field is the +/// first thing under its title: Chats, and Work's Schedules and Tasks. On demo data. Set +/// BIGHELP_SEARCH_PLACEMENT_EVIDENCE (TEST_RUNNER_…) to save screenshots. final class SearchPlacementUITests: BighelpUITestCase { @MainActor - func testAllHostsTasksHaveSearch() { + func testTheBarNeverMovesAndSearchSitsAtTheTop() throws { let app = makeApp() - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.hosts.all-hosts", "YES", "-bighelp.app-layout", layout] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "chats"] app.launch() - let agent = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "fleet.agent.")).firstMatch - XCTAssertTrue(agent.waitForExistence(timeout: 15)) - agent.tap() - let tasks = app.buttons["tab.scheduled-tasks"] - XCTAssertTrue(tasks.waitForExistence(timeout: 15)) - tasks.tap() - let search = app.descendants(matching: .any)["scheduled-tasks.search"].firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 5), "All hosts has the same task search as one computer") - search.tap() - search.typeText("No matching task 9327") - XCTAssertTrue(app.staticTexts["No matching tasks"].waitForExistence(timeout: 3)) - XCTAssertTrue(search.exists, "An empty result must keep its search usable") - app.buttons["scheduled-tasks.search.clear"].firstMatch.tap() - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "fleet.task.")).firstMatch - .waitForExistence(timeout: 5), "Clearing restores the tasks") - } - - @MainActor - func testPinnedKanbanKeepsTheAllHostsBarReachable() { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "YES", - "-bighelp.app-layout", layout] - app.launch() - let agent = app.buttons["fleet.agent.Mina Shah"] - XCTAssertTrue(agent.waitForExistence(timeout: 15)) - agent.tap() - XCTAssertTrue(tap("tab.kanban", in: app)) - XCTAssertTrue(app.buttons["tab.kanban"].isSelected, "Pinned Kanban is a root tab") - XCTAssertTrue(tap("tab.scheduled-tasks", in: app), "Kanban must leave the bar reachable") - XCTAssertTrue(app.descendants(matching: .any)["scheduled-tasks.search"].firstMatch.waitForExistence(timeout: 5)) - } - - /// Agents, Scheduled tasks and Kanban in the bar beside Chat (three places at most). - private let layout = "{pinned=(agents,scheduledTasks,kanban);menu=();}" - private let searchedTabs = ["tab.sessions", "tab.agents", "tab.scheduled-tasks", "tab.kanban"] - private let origins = ["tab.sessions", "tab.agents", "tab.scheduled-tasks", "tab.kanban"] - private let searchIDs = ["tab.sessions": "sessions.search", "tab.agents": "agents.search", - "tab.scheduled-tasks": "scheduled-tasks.search", "tab.kanban": "kanban.search"] - - @MainActor - func testSearchSitsInOnePlaceOnOneComputer() throws { - try audit(allHosts: false, homeOpensChat: true) - } - - @MainActor - func testSearchSitsInOnePlaceWithTheSessionsList() throws { - try audit(allHosts: false, homeOpensChat: false) - } + XCTAssertTrue(app.descendants(matching: .any)["chats.inbox"].firstMatch.waitForExistence(timeout: 20)) - @MainActor - func testSearchSitsInOnePlaceWithAllHosts() throws { - try audit(allHosts: true, homeOpensChat: false) - } - - @MainActor private func audit(allHosts: Bool, homeOpensChat: Bool) throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-loopdy.home.opens-chat", homeOpensChat ? "YES" : "NO", - "-bighelp.app-layout", layout, "-bighelp.hosts.all-hosts", allHosts ? "YES" : "NO"] - app.launch() - let mode = (allHosts ? "all-hosts" : "one-host") + (homeOpensChat ? "-chat" : "-list") - if allHosts { - // All agents is the home: its search is at the top too. - let search = app.descendants(matching: .any)["fleet.search"].firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 20), "All agents has its search") - XCTAssertLessThan(search.frame.minY, app.frame.height * 0.35, "All agents' search is at the top") - save("\(mode)-home", app) - let agent = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "fleet.agent.")).firstMatch - if agent.waitForExistence(timeout: 5) { agent.tap() } - } - guard app.buttons["tab.agents"].waitForExistence(timeout: 20) else { - XCTFail("The configured bottom bar must show") - return - } + // The bar is in one place on every root. var barFrame: CGRect? - var searches: [String: [String: CGRect]] = [:] - // All agents is intentionally a list without the bar. Audit the pinned pages - // explicitly instead of entering that home and silently skipping the remaining tabs. - let targets = allHosts ? searchedTabs.filter { $0 != "tab.sessions" } : searchedTabs - let fromTabs = allHosts ? origins.filter { $0 != "tab.sessions" } : origins - for target in targets { - for origin in fromTabs where origin != target { - guard tap(origin, in: app), tap(target, in: app) else { - XCTFail("Could not visit pinned tabs \(origin) → \(target)") - return - } - let name = "\(mode)-\(target.dropFirst(4))-from-\(origin.dropFirst(4))" - // The tab row itself (the bar's container also holds Sessions' New chat button). - let bar = app.buttons["tab.sessions"].firstMatch - save(name, app) - XCTAssertTrue(bar.exists, "\(name): the bottom bar") - // The bar is in one place on every screen. - if let barFrame { - XCTAssertEqual(bar.frame.minY, barFrame.minY, accuracy: 0.5, "\(name): the bottom bar moved") - XCTAssertEqual(bar.frame.height, barFrame.height, accuracy: 0.5, "\(name): the bottom bar changed") - } else { - barFrame = bar.frame - } - // Nothing searches along the bottom any more. - let low = app.searchFields.allElementsBoundByIndex.filter { $0.exists && $0.frame.minY > bar.frame.minY - 60 } - XCTAssertTrue(low.isEmpty, "\(name): a search field sits down by the bar") - // An agent's chat has no search; every list does, at the top. - if target == "tab.sessions", app.textViews["chat.composer.text"].exists { continue } - let searchID = allHosts && target == "tab.sessions" ? "fleet.search" : searchIDs[target]! - let search = app.descendants(matching: .any)[searchID].firstMatch - print("SEARCH \(name): search \(search.exists ? search.frame : .zero) bar \(bar.frame)") - XCTAssertTrue(search.waitForExistence(timeout: 5), "\(name): its search field") - XCTAssertLessThan(search.frame.minY, app.frame.height * 0.35, "\(name): the search field is at the top") - searches[target, default: [:]][origin] = search.frame + for (door, name) in [("home.switch.bots", "bots"), ("home.switch.chats", "chats"), + ("home.tab.today", "today"), ("home.tab.work", "work")] { + if name == "bots" || name == "chats" { app.buttons["home.tab.conversations"].firstMatch.tap() } + app.buttons[door].firstMatch.tap() + Thread.sleep(forTimeInterval: 1.2) + let bar = app.buttons["home.tab.conversations"].firstMatch + XCTAssertTrue(bar.waitForExistence(timeout: 10), "\(name): the bar") + save("bar-\(name)", app) + if let barFrame { + XCTAssertEqual(bar.frame.minY, barFrame.minY, accuracy: 0.5, "\(name): the bar moved") + XCTAssertEqual(bar.frame.height, barFrame.height, accuracy: 0.5, "\(name): the bar changed") + } else { + barFrame = bar.frame } + // Nothing searches along the bottom. + let low = app.searchFields.allElementsBoundByIndex.filter { $0.exists && $0.frame.minY > bar.frame.minY - 60 } + XCTAssertTrue(low.isEmpty, "\(name): a search field sits down by the bar") } - for (target, frames) in searches { - guard let first = frames.values.first else { continue } - for (origin, frame) in frames { - XCTAssertEqual(frame.midY, first.midY, accuracy: 2, - "\(mode) \(target): the search field moves when you come from \(origin)") - } + + // Chats: its search is the first row. + app.buttons["home.tab.conversations"].firstMatch.tap() + app.buttons["home.switch.chats"].firstMatch.tap() + expectSearchAtTop("chats.search", name: "chats", in: app) + + // Work's pushed lists: Schedules and Tasks. + for (door, searchID) in [("schedules", "scheduled-tasks.search"), ("tasks", "kanban.search")] { + openWorkDoor(door, in: app) + expectSearchAtTop(searchID, name: door, in: app) + leavePushedPage(in: app) + XCTAssertTrue(app.descendants(matching: .any)["work.screen"].firstMatch.waitForExistence(timeout: 10), + "Back returns to Work") } } - /// Taps a bottom bar tab, when this screen's bar has it. - @MainActor private func tap(_ tab: String, in app: XCUIApplication) -> Bool { - let button = app.buttons[tab].firstMatch - guard button.waitForExistence(timeout: 4), button.isHittable else { return false } - button.tap() - let host = app.buttons["fleet.gate.host.Home Hermes"] - if tab == "tab.kanban", host.waitForExistence(timeout: 1) { host.tap() } - Thread.sleep(forTimeInterval: 1.5) - return true + @MainActor private func expectSearchAtTop(_ identifier: String, name: String, in app: XCUIApplication) { + let search = app.descendants(matching: .any)[identifier].firstMatch + XCTAssertTrue(search.waitForExistence(timeout: 10), "\(name): its search field") + print("SEARCH \(name): \(search.exists ? search.frame : .zero)") + XCTAssertLessThan(search.frame.minY, app.frame.height * 0.35, "\(name): the search field is at the top") + save("search-\(name)", app) + } + + /// The page's own Back, else the navigation bar's. + @MainActor private func leavePushedPage(in app: XCUIApplication) { + let back = app.buttons["BackButton"].firstMatch + if back.exists, back.isHittable { back.tap(); return } + let bar = app.navigationBars.buttons.firstMatch + if bar.waitForExistence(timeout: 5) { bar.tap() } } @MainActor private func save(_ name: String, _ app: XCUIApplication) { diff --git a/BighelpUITests/SessionAppFilterUITests.swift b/BighelpUITests/SessionAppFilterUITests.swift index 900de688..e3962a21 100644 --- a/BighelpUITests/SessionAppFilterUITests.swift +++ b/BighelpUITests/SessionAppFilterUITests.swift @@ -1,14 +1,13 @@ import XCTest -/// Sessions on demo data: Hermes, Codex and Claude Code above the list, on one computer -/// and on all of them. Codex and Claude Code cover the chats Hermes already brought in -/// and the ones still in those apps. Set BIGHELP_APP_FILTER_EVIDENCE (TEST_RUNNER_…) to +/// Sessions (Chats › This computer) on demo data: Hermes, Codex and Claude Code above the list. +/// Codex and Claude Code cover the chats Hermes already brought in and the ones still in those apps. Set BIGHELP_APP_FILTER_EVIDENCE (TEST_RUNNER_…) to /// save screenshots. final class SessionAppFilterUITests: BighelpUITestCase { @MainActor func testOneComputerFiltersHermesCodexAndClaudeCode() throws { - let app = launch(allHosts: false) - openRootTab("tab.sessions", in: app) + let app = launch() + openThisComputerSessions(in: app) let codex = segment("Codex", in: app) XCTAssertTrue(codex.waitForExistence(timeout: 15), "The choice sits above the list") save("sessions-app-all", app) @@ -51,45 +50,9 @@ final class SessionAppFilterUITests: BighelpUITestCase { save("sessions-filter-menu-agent", app) } - @MainActor - func testAllComputersFilterTheSameWayAndKeepTheChoice() throws { - let app = launch(allHosts: true) - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - app.buttons["menu.chats"].firstMatch.tap() - XCTAssertTrue(app.navigationBars["All sessions"].waitForExistence(timeout: 8)) - - segment("Codex", in: app).tap() - XCTAssertTrue(app.buttons["fleet.chat.Release checklist"].waitForExistence(timeout: 8), - "A chat another computer brought in from Codex") - XCTAssertFalse(app.buttons["fleet.chat.Market scan"].exists, "Hermes' own chats are filtered out") - XCTAssertTrue(scrollTo(otherApp("fleet.other-app.Speed up the test suite", in: app), in: app), - "A chat still in Codex on another computer") - XCTAssertTrue(scrollTo(otherApp("fleet.other-app.Polish the Mac menus", in: app), in: app), "And on this one") - save("all-sessions-app-codex", app) - - scrollToTop(app) - segment("Claude Code", in: app).tap() - XCTAssertTrue(scrollTo(otherApp("fleet.other-app.Draft the launch post", in: app), in: app)) - XCTAssertFalse(otherApp("fleet.other-app.Speed up the test suite", in: app).exists) - save("all-sessions-app-claude-code", app) - scrollToTop(app) - - // A computer's own Sessions keeps the choice. - app.buttons["fleet.filter.Home Hermes"].tap() - XCTAssertTrue(row(containing: "Started in Claude Code", in: app).waitForExistence(timeout: 10), - "That computer's Sessions shows Claude Code too") - XCTAssertTrue(segment("Claude Code", in: app).isSelected) - XCTAssertTrue(scrollTo(otherApp("sessions.other-app.Trip budget script", in: app), in: app)) - save("one-computer-in-all-hosts-claude-code", app) - } - - @MainActor private func launch(allHosts: Bool) -> XCUIApplication { + @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.hosts.all-hosts", allHosts ? "YES" : "NO", - "-loopdy.home.opens-chat", "NO"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] app.launch() return app } diff --git a/BighelpUITests/SessionOriginUITests.swift b/BighelpUITests/SessionOriginUITests.swift index c992bd9b..05c87033 100644 --- a/BighelpUITests/SessionOriginUITests.swift +++ b/BighelpUITests/SessionOriginUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Sessions on demo data: each chat shows where it started, and Started in shows chats from one +/// Sessions (Chats › This computer) on demo data: each chat shows where it started, and Started in shows chats from one /// place. BIGHELP_SESSION_ORIGIN_SHOTS (TEST_RUNNER_…) names a folder for screenshots. final class SessionOriginUITests: BighelpUITestCase { @MainActor @@ -8,7 +8,7 @@ final class SessionOriginUITests: BighelpUITestCase { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] app.launch() - openRootTab("tab.sessions", in: app) + openThisComputerSessions(in: app) let telegram = row(containing: "Started in Telegram", in: app) XCTAssertTrue(telegram.waitForExistence(timeout: 15), "A chat from Telegram says so") save("sessions-origin-tags", app) diff --git a/BighelpUITests/SessionsParityUITests.swift b/BighelpUITests/SessionsParityUITests.swift index 66a6c066..5c8b89a5 100644 --- a/BighelpUITests/SessionsParityUITests.swift +++ b/BighelpUITests/SessionsParityUITests.swift @@ -1,42 +1,13 @@ import XCTest -/// One computer and all computers work alike: ☰ is one menu from anywhere, See all opens -/// the chat list, project folders fold, and All sessions has the same tags and filters, with -/// a computer's chip opening that computer's own Sessions screen without leaving all hosts. +/// The computer in use's own Sessions page, pushed from Chats › This computer: project folders fold, +/// and chats other apps (Codex, Claude Code) made on the computer show and open. /// Set BIGHELP_PARITY_EVIDENCE (TEST_RUNNER_…) to save screenshots. final class SessionsParityUITests: BighelpUITestCase { - @MainActor - func testOneMenuFromAChatAndSeeAllOpensSessions() throws { - let app = launch(allHosts: false) - let menu = chatMenu(app) - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - - // A chat's ⋯ has no second menu of its own. - XCTAssertTrue(chatMenuItem("chat.rename", in: app).waitForExistence(timeout: 5)) - XCTAssertFalse(app.buttons["chat.workspace-menu"].exists, "Go to… is gone: ☰ is the menu") - // Close it with a tap on the chat, away from the menu. - app.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.6)).tap() - XCTAssertTrue(chatMenuElement("chat.rename", in: app).waitForNonExistence(timeout: 3)) - - menu.tap() - let seeAll = app.buttons["menu.chats"].firstMatch - XCTAssertTrue(seeAll.waitForExistence(timeout: 5)) - XCTAssertFalse(app.descendants(matching: .any)["quick-workspace.drawer"].exists) - save("one-host-menu", app) - seeAll.tap() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].waitForExistence(timeout: 8), - "See all opens Sessions") - save("one-host-sessions", app) - } - @MainActor func testProjectFolderFoldsItsChats() throws { - let app = launch(allHosts: false, extra: ["-loopdy.sessions.organizeByProjects", "YES"]) - let menu = chatMenu(app) - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - app.buttons["menu.chats"].firstMatch.tap() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].waitForExistence(timeout: 8)) + let app = launch(extra: ["-loopdy.sessions.organizeByProjects", "YES"]) + openThisComputerSessions(in: app) let folder = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'sessions.section-toggle.'")).firstMatch XCTAssertTrue(folder.waitForExistence(timeout: 8), "Group by Project shows project folders") @@ -61,12 +32,8 @@ final class SessionsParityUITests: BighelpUITestCase { @MainActor func testCodexAndClaudeCodeChatsShowAndOpen() throws { - let app = launch(allHosts: false) - let menu = chatMenu(app) - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - app.buttons["menu.chats"].firstMatch.tap() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].waitForExistence(timeout: 8)) + let app = launch() + openThisComputerSessions(in: app) let codex = app.buttons["sessions.other-app.Polish the Mac menus"] for _ in 0..<6 where !codex.exists { app.swipeUp() } @@ -81,119 +48,15 @@ final class SessionsParityUITests: BighelpUITestCase { XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 8), "Open opens it as a chat") } - /// As on one computer's list, chats running now come first under Active Sessions, from every - /// computer: the demo's other computer has a review running. The Chat tab's home (All agents) - /// lists them too. - @MainActor - func testAllSessionsListsActiveSessionsAcrossComputers() throws { - for appearance in ["light", "dark"] { - let app = launch(allHosts: true, extra: ["-loopdy.demo.appearance", appearance]) - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - XCTAssertTrue(app.descendants(matching: .any)["fleet.sessions.section.active"].waitForExistence(timeout: 8), - "All agents shows Active Sessions") - let onHome = app.buttons["fleet.active.Pull request review"] - XCTAssertTrue(onHome.exists, "The other computer's running chat, on the home") - save("all-agents-active-\(appearance)", app) - menu.tap() - app.buttons["menu.chats"].firstMatch.tap() - XCTAssertTrue(app.navigationBars["All sessions"].waitForExistence(timeout: 8)) - let active = app.descendants(matching: .any)["fleet.sessions.section.active"] - XCTAssertTrue(active.waitForExistence(timeout: 8), "Active Sessions shows with every computer") - let running = app.buttons["fleet.chat.Pull request review"] - XCTAssertTrue(running.exists, "The other computer's running chat is listed") - let recent = app.descendants(matching: .any)["fleet.sessions.section.recent"] - XCTAssertTrue(recent.exists) - XCTAssertLessThan(running.frame.minY, recent.frame.minY, "Running chats come before the rest") - save("all-sessions-active-\(appearance)", app) - app.terminate() - } - } - - @MainActor - func testAllSessionsHasTagsFiltersAndAComputersOwnScreen() throws { - let app = launch(allHosts: true) - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - app.buttons["menu.chats"].firstMatch.tap() - XCTAssertTrue(app.navigationBars["All sessions"].waitForExistence(timeout: 8), "See all opens All sessions") - - let tagged = app.buttons.matching(NSPredicate(format: "label CONTAINS 'Started in'")) - // Active Sessions comes first, so the chat brought in from Codex can sit below the fold. - if tagged.count == 0 { app.swipeUp() } - XCTAssertGreaterThan(tagged.count, 0, "Rows say where each chat started") - app.swipeDown() - let filters = app.buttons["fleet.chats.filters"] - XCTAssertTrue(filters.exists, "The same filter menu as one computer") - filters.tap() - // Each filter is its own labeled choice, not one long list. - let agentChoice = app.buttons.matching(NSPredicate(format: "label BEGINSWITH 'Agent,'")).firstMatch - XCTAssertTrue(agentChoice.waitForExistence(timeout: 3), "Agent, to filter by") - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label BEGINSWITH 'Started in,'")).firstMatch.exists, - "Started in, to filter by") - save("all-sessions-filters", app) - agentChoice.tap() - let allAgents = app.buttons.matching(NSPredicate(format: "label == 'All agents' AND identifier != 'BackButton'")) - .firstMatch - XCTAssertTrue(allAgents.waitForExistence(timeout: 3), "Agents to filter by") - save("all-sessions-filter-agent", app) - allAgents.tap() - XCTAssertTrue(agentChoice.waitForNonExistence(timeout: 3), "The menu closes") - - // A computer's chip opens its own Sessions screen (folders, agents), still in all hosts. - app.buttons["fleet.filter.Home Hermes"].tap() - let folder = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'sessions.section-toggle.'")).firstMatch - XCTAssertTrue(folder.waitForExistence(timeout: 10), "That computer's own Sessions screen, with its folders") - XCTAssertTrue(app.buttons["fleet.filter.all"].exists, "Its chips stay, to go back to every computer") - save("all-sessions-one-computer", app) - - // Back on All agents, ☰ still says all hosts, focused on that computer; Projects opens there. - let back = app.navigationBars.buttons["BackButton"].firstMatch - if back.exists { back.tap() } else { swipeBackFromLeadingEdge(in: app) } - XCTAssertTrue(menu.waitForExistence(timeout: 8)) - save("all-agents-focused", app) - menu.tap() - XCTAssertEqual(app.buttons["menu.all-hosts"].label, "Show one host", "Still in all hosts") - XCTAssertTrue(app.buttons["menu.hosts"].label.contains("Home Hermes"), app.buttons["menu.hosts"].label) - let projects = app.buttons["menu.projects"] - XCTAssertTrue(projects.waitForExistence(timeout: 3), "Projects is in the all-hosts menu") - save("all-hosts-menu-focused", app) - projects.tap() - XCTAssertFalse(app.buttons["fleet.gate.host.Home Hermes"].waitForExistence(timeout: 2), - "The focused computer doesn't need asking") - XCTAssertTrue(app.navigationBars["Projects"].waitForExistence(timeout: 8)) - // Projects is a screen people stay on: ☰ in the corner, no Back. ☰ leads to All agents. - XCTAssertFalse(app.navigationBars.buttons["BackButton"].exists, "Projects is a screen of its own") - menu.tap() - let allAgentsRow = app.buttons["menu.all-agents"] - XCTAssertTrue(allAgentsRow.waitForExistence(timeout: 5)) - allAgentsRow.tap() - let homeChip = app.buttons["fleet.filter.Home Hermes"] - XCTAssertTrue(homeChip.waitForExistence(timeout: 8)) - XCTAssertTrue(homeChip.isSelected, "All agents shows the focused computer too") - - // Every computer again. - app.buttons["fleet.filter.all"].tap() - XCTAssertTrue(app.buttons["fleet.filter.all"].isSelected) - } - // MARK: Helpers - @MainActor private func launch(allHosts: Bool, extra: [String] = []) -> XCUIApplication { + @MainActor private func launch(extra: [String] = []) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", - "-bighelp.hosts.all-hosts", allHosts ? "YES" : "NO", - "-loopdy.home.opens-chat", allHosts ? "NO" : "YES"] + extra + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "chats"] + extra app.launch() return app } - /// ☰ in the chat header, or on a list. - @MainActor private func chatMenu(_ app: XCUIApplication) -> XCUIElement { - app.buttons.matching(NSPredicate(format: "identifier IN %@", ["chat.menu", "home.drawer.open"])).firstMatch - } - @MainActor private func save(_ name: String, _ app: XCUIApplication) { let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) shot.name = name @@ -205,3 +68,20 @@ final class SessionsParityUITests: BighelpUITestCase { .write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) } } + +extension BighelpUITestCase { + /// Chats › This computer: the computer in use's own Sessions page (projects, filters, other apps' + /// chats), pushed from the More section at the end of the Chats list. + @MainActor + func openThisComputerSessions(in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { + showChats(in: app) + let list = app.descendants(matching: .any)["chats.inbox"].firstMatch + XCTAssertTrue(list.waitForExistence(timeout: 20), "Chats shows", file: file, line: line) + let row = app.buttons["chats.more.this-computer"].firstMatch + for _ in 0..<20 where !(row.exists && row.isHittable) { list.swipeUp(velocity: .fast) } + XCTAssertTrue(row.exists && row.isHittable, "This computer is at the end of Chats", file: file, line: line) + row.tap() + XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].firstMatch.waitForExistence(timeout: 10), + "This computer opens its Sessions page", file: file, line: line) + } +} diff --git a/BighelpUITests/SessionsSearchUITests.swift b/BighelpUITests/SessionsSearchUITests.swift index a15e017f..e66a692a 100644 --- a/BighelpUITests/SessionsSearchUITests.swift +++ b/BighelpUITests/SessionsSearchUITests.swift @@ -1,32 +1,27 @@ import XCTest -/// Sessions on one computer and All sessions on every host search from the field -/// at the top, under the title, like every main screen. The bottom bar never covers -/// the last session, and a scroll puts the keyboard away. +/// The computer in use's Sessions page (Chats › This computer) searches from the field at the +/// top, under the title, like every main screen, and a scroll puts the keyboard away. /// Set BIGHELP_SESSIONS_SEARCH_SHOTS (TEST_RUNNER_…) to a folder to save screenshots. final class SessionsSearchUITests: BighelpUITestCase { @MainActor func testOneComputerSessionsSearchFromTheTop() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] app.launch() - XCTAssertTrue(app.descendants(matching: .any)["sessions.screen"].firstMatch.waitForExistence(timeout: 15)) + openThisComputerSessions(in: app) let search = app.searchFields["Search sessions"].firstMatch XCTAssertTrue(search.waitForExistence(timeout: 5), "Sessions has a search field without a pull") XCTAssertLessThan(search.frame.minY, app.windows.firstMatch.frame.height * 0.35, "It sits at the top") shot("one-computer-list", app) - // The last session scrolls clear of the tab bar. + // The list scrolls to its last session (a pushed page: no bar under it). let list = app.collectionViews.firstMatch for _ in 0..<6 { list.swipeUp() } let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'session.row.'")) let last = rows.element(boundBy: rows.count - 1) XCTAssertTrue(last.exists) - let feed = app.buttons["tab.feed"].firstMatch - if feed.exists { - XCTAssertLessThanOrEqual(last.frame.maxY, feed.frame.minY + 1, "The tab bar doesn't cover the last session") - } shot("one-computer-end", app) for _ in 0..<6 { list.swipeDown() } @@ -54,44 +49,6 @@ final class SessionsSearchUITests: BighelpUITestCase { XCTAssertEqual(app.searchFields.firstMatch.value as? String, "session", "The search stays") } - @MainActor - func testAllHostsSessionsSearchFromTheTop() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-bighelp.hosts.all-hosts", "NO"] - app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - XCTAssertTrue(app.buttons["menu.all-hosts"].waitForExistence(timeout: 5)) - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(app.navigationBars["All agents"].waitForExistence(timeout: 5)) - menu.tap() - let seeAll = app.buttons["menu.chats"].firstMatch - XCTAssertTrue(seeAll.waitForExistence(timeout: 5)) - seeAll.tap() - XCTAssertTrue(app.navigationBars["All sessions"].waitForExistence(timeout: 5)) - - let search = app.searchFields["Search sessions"].firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 5), "All sessions has the search field") - XCTAssertLessThan(search.frame.minY, app.windows.firstMatch.frame.height * 0.35, "It sits at the top") - XCTAssertTrue(text("Pull request review", in: app).waitForExistence(timeout: 10)) - shot("all-hosts-list", app) - - // The preview text matches too, on another host's session. - search.tap() - search.typeText("competitors") - XCTAssertTrue(text("Market scan", in: app).waitForExistence(timeout: 5)) - XCTAssertFalse(text("Pull request review", in: app).exists, "Other sessions step aside") - shot("all-hosts-searching", app) - scrollResults(from: text("Market scan", in: app), in: app) - XCTAssertTrue(app.keyboards.firstMatch.waitForNonExistence(timeout: 5), "A scroll closes the keyboard") - - app.searchFields.firstMatch.tap() - app.searchFields.firstMatch.typeText("zzz") - XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "No Results")).firstMatch - .waitForExistence(timeout: 5), "No match says so") - } - /// A finger drag up the results, starting on a row. @MainActor private func scrollResults(from row: XCUIElement, in app: XCUIApplication) { diff --git a/BighelpUITests/SettingsLayoutUITests.swift b/BighelpUITests/SettingsLayoutUITests.swift index 65e0a828..2d1fef16 100644 --- a/BighelpUITests/SettingsLayoutUITests.swift +++ b/BighelpUITests/SettingsLayoutUITests.swift @@ -1,10 +1,11 @@ import XCTest /// Settings' first screen in short groups: you, your bots and what they can use (Apps & skills, -/// with this device's access first), this app (Appearance, Chat, ...), your computers, then Help. Set BIGHELP_SETTINGS_EVIDENCE (TEST_RUNNER_BIGHELP_SETTINGS_EVIDENCE) to save screenshots. +/// with this device's access first), this app (Appearance, Chat, ...), your computers, then Help. +/// Settings is a sheet: its pages go back with the sheet's own Back button. Set BIGHELP_SETTINGS_EVIDENCE (TEST_RUNNER_BIGHELP_SETTINGS_EVIDENCE) to save screenshots. final class SettingsLayoutUITests: BighelpUITestCase { @MainActor - func testConnectionsHoldDeviceAccessAndModesHoldTheModeSwitches() throws { + func testConnectionsHoldDeviceAccess() throws { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] @@ -14,15 +15,6 @@ final class SettingsLayoutUITests: BighelpUITestCase { XCTAssertFalse(app.textFields["profile.display-name"].exists, "The name box is on the You page") save("01-settings-\(appearance)", app) - settingsRow("settings.menu.modes", in: app).tap() - XCTAssertTrue(app.buttons["settings.mode.bots"].waitForExistence(timeout: 5), "Bots mode is under Modes") - XCTAssertTrue(app.buttons["settings.mode.chat"].exists, "Chat mode is under Modes") - XCTAssertTrue(app.buttons["settings.mode.code"].exists, "Code mode is under Modes") - XCTAssertTrue(app.switches["settings.unified-mode-toggle"].exists, "Header mode switcher is under Modes") - XCTAssertTrue(app.switches["settings.code-mode"].exists, "Code mode keeps its own switch") - save("02-modes-\(appearance)", app) - app.navigationBars.buttons.firstMatch.tap() - settingsRow("settings.apps", in: app).tap() let device = app.buttons["settings.connections.device-access"].firstMatch let composio = app.buttons["apps.composio"].firstMatch @@ -73,7 +65,7 @@ final class SettingsLayoutUITests: BighelpUITestCase { reach(header("Advanced · Chat list", in: app), in: app) reach(app.switches["settings.show-cron-sessions"].firstMatch, in: app) reach(app.buttons["settings.chat.clean-up-chats"].firstMatch, in: app) - app.navigationBars.buttons.firstMatch.tap() + app.buttons["BackButton"].firstMatch.tap() settingsRow("settings.menu.notifications", in: app).tap() XCTAssertTrue(app.descendants(matching: .any)["settings.notifications"].firstMatch.waitForExistence(timeout: 8)) @@ -90,7 +82,7 @@ final class SettingsLayoutUITests: BighelpUITestCase { reach(app.descendants(matching: .any)["settings.notifications.details"].firstMatch, in: app) reach(app.buttons["settings.notifications.turn-off"].firstMatch, in: app) save("08-notifications-end-\(appearance)", app) - app.navigationBars.buttons.firstMatch.tap() + app.buttons["BackButton"].firstMatch.tap() settingsRow("settings.apps", in: app).tap() app.buttons["settings.connections.device-access"].firstMatch.tap() @@ -111,13 +103,14 @@ final class SettingsLayoutUITests: BighelpUITestCase { } } - /// One Settings in every mode (#976): you, Your bots, This app, Your computers, then Help & feedback - /// and Advanced options. Bots mode's circle opens the same page. + /// One Settings (#976): you, Your bots, This app, Your computers, then Help & feedback and Advanced + /// options. The circle on Chats and on Bots opens the same page. @MainActor - func testOneSettingsInChatAndBotsMode() throws { - for (mode, extra) in [("chat", [String]()), ("bots", ["-bighelp.settings.simple-bots", "YES"])] { + func testOneSettingsFromChatsAndBots() throws { + for mode in ["chats", "bots"] { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3"] + extra + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", + "-loopdy.home.landing", mode] app.launch() if mode == "bots" { let circle = app.buttons["simple-bots.settings"] diff --git a/BighelpUITests/ShortcutGatewaySwitchHostUITests.swift b/BighelpUITests/ShortcutGatewaySwitchHostUITests.swift index 4251e37a..9e595c5a 100644 --- a/BighelpUITests/ShortcutGatewaySwitchHostUITests.swift +++ b/BighelpUITests/ShortcutGatewaySwitchHostUITests.swift @@ -27,7 +27,9 @@ final class ShortcutGatewaySwitchHostUITests: BighelpUITestCase { try onboardOpenHost(app, address: try XCTUnwrap(probe["address_a"])) addAnotherHost(in: app) try addHost(app, address: try XCTUnwrap(probe["address_b"]), name: "Lab Hermes") - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 30)) + // Setup finishes over Settings; Done shows the home. + closeSettings(in: app) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 30)) save("1-lab-in-use", app) // Lab Hermes is in use; the Shortcut asks on the first host (named by its address). @@ -42,20 +44,14 @@ final class ShortcutGatewaySwitchHostUITests: BighelpUITestCase { XCTAssertTrue(text.contains("fixture complete"), "The agent on the other gateway answers: \(text)") } - /// Add host from ☰'s host switcher, after a fresh launch so setup's screens are gone. + /// Settings › Your computers › Add a computer, after a fresh launch so setup's screens are gone. @MainActor private func addAnotherHost(in app: XCUIApplication) { app.terminate() app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 30)) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 30)) sleep(3) - let hosts = app.buttons["menu.hosts"] - for _ in 0..<3 where !hosts.exists { - menu.tap() - _ = hosts.waitForExistence(timeout: 8) - } - hosts.tap() - app.buttons["menu.host.add"].tap() + openSettings(in: app) + settingsRow("settings.add-computer", in: app).tap() } @MainActor private func addHost(_ app: XCUIApplication, address: String, name: String) throws { diff --git a/BighelpUITests/SilentReplyUITests.swift b/BighelpUITests/SilentReplyUITests.swift index 5e7c7187..6432cb38 100644 --- a/BighelpUITests/SilentReplyUITests.swift +++ b/BighelpUITests/SilentReplyUITests.swift @@ -7,14 +7,10 @@ final class SilentReplyUITests: BighelpUITestCase { @MainActor func testBareMarkerToThePersonShowsHermesNotice() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", "-test-companion-disabled", "-test-silent-reply"] app.launch() - let newChat = chatNewChatButton(in: app).waitForExistence(timeout: 5) - ? chatNewChatButton(in: app) : app.buttons["root.new-chat"] - XCTAssertTrue(newChat.waitForExistence(timeout: 5)) - newChat.tap() - confirmNewChatPicker(in: app) + startNewChat(with: "finance", in: app) let input = app.textViews["Message"] XCTAssertTrue(input.waitForExistence(timeout: 5)) input.tap() diff --git a/BighelpUITests/SimpleBotsActivityUITests.swift b/BighelpUITests/SimpleBotsActivityUITests.swift index 7d90952f..f7df956a 100644 --- a/BighelpUITests/SimpleBotsActivityUITests.swift +++ b/BighelpUITests/SimpleBotsActivityUITests.swift @@ -1,9 +1,9 @@ import XCTest -/// #504: Bots mode shows which bots are working on a turn and which need you, and (#890) which run +/// #504: the Bots view shows which bots are working on a turn and which need you, and (#890) which run /// work in the background. On the demo data with `-test-bot-activity`, Mina Shah browses the web in -/// her Bot Chat, Jordan Lee needs you and Avery Park has work in the background; with Multi-gateway, -/// Sage Ortiz works on the sample Studio Mac. Light and dark. +/// her Bot Chat, Jordan Lee needs you and Avery Park has work in the background; with every computer +/// showing, Sage Ortiz works on the sample Studio Mac. Light and dark. /// TEST_RUNNER_BIGHELP_BOT_ACTIVITY_EVIDENCE= saves the screenshots there, and /// TEST_RUNNER_BIGHELP_BOT_ACTIVITY_REDUCED=1 says the simulator has Reduce Motion on (a test can't /// switch it), which names them "-reduced". @@ -18,7 +18,7 @@ final class SimpleBotsActivityUITests: BighelpUITestCase { XCTAssertTrue(wait(for: mina, toSay: "Browsing the web"), mina.label) XCTAssertTrue(wait(for: jordan, toSay: "Needs you"), jordan.label) // Avery has no turn running but has work in the background: its tile says so, calmly. - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(wait(for: primary, toSay: "2 things running in the background"), primary.value as? String ?? "") // Said once: the row's value, not again in its label. XCTAssertFalse(mina.label.contains("Browsing the web"), mina.label) @@ -45,7 +45,8 @@ final class SimpleBotsActivityUITests: BighelpUITestCase { @MainActor func testAnotherGatewaysBotShowsItsOwnState() throws { - let app = launch(appearance: "light", extra: ["-test-bot-activity", "-bighelp.simple-bots.multi-gateway", "YES"]) + // Settings › Show every computer. + let app = launch(appearance: "light", extra: ["-test-bot-activity", "-bighelp.hosts.all-hosts", "YES"]) XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) let sage = app.buttons.matching(NSPredicate(format: "identifier ENDSWITH %@", "/reviewer")).firstMatch XCTAssertTrue(sage.waitForExistence(timeout: 10)) @@ -69,25 +70,11 @@ final class SimpleBotsActivityUITests: BighelpUITestCase { } } - @MainActor - func testTheAgentsScreenShowsTheSameStates() throws { - let app = makeApp() - app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-test-bot-activity"] - app.launch() - openRootTab("tab.agents", in: app) - let mina = app.buttons["agent.travel"] - XCTAssertTrue(mina.waitForExistence(timeout: 10)) - XCTAssertTrue(wait(for: mina, toSay: "Thinking"), mina.label) - let jordan = app.buttons["agent.home"] - XCTAssertTrue(wait(for: jordan, toSay: "Has an update"), jordan.label) - save("agents-light", app) - } - @MainActor private func launch(appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance] + extra app.launch() return app diff --git a/BighelpUITests/SimpleBotsAppearanceUITests.swift b/BighelpUITests/SimpleBotsAppearanceUITests.swift index 8cd33042..e89b7946 100644 --- a/BighelpUITests/SimpleBotsAppearanceUITests.swift +++ b/BighelpUITests/SimpleBotsAppearanceUITests.swift @@ -1,16 +1,16 @@ import XCTest -/// Bots mode on demo data, switching Light and Dark the way people do: in Settings, with a -/// page open. The open page, its name field and the home behind it change at once. Back from a -/// bot's chat never shows ☰. Set BIGHELP_SIMPLE_BOTS_EVIDENCE (TEST_RUNNER_…) to a folder to save -/// the screenshots. +/// The Bots view on demo data, switching Light and Dark the way people do: in Settings, with a +/// page open. The open page, its name field and the home behind it change at once. Settings is a +/// sheet, so its pages go back with the sheet's own Back button. Set BIGHELP_SIMPLE_BOTS_EVIDENCE +/// (TEST_RUNNER_…) to a folder to save the screenshots. final class SimpleBotsAppearanceUITests: BighelpUITestCase { - /// Bots mode's Settings is the one Settings: its Chat row opens Settings › Chat. + /// The circle on Bots opens Settings: its Chat row opens Settings › Chat. @MainActor func testSettingsOpensChatDirectly() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES"] + "-loopdy.home.landing", "bots"] app.launch() XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 15)) app.buttons["simple-bots.settings"].tap() @@ -29,21 +29,17 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { let app = makeApp() // The appearance isn't pinned here, so Settings can change it. app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES"] + "-loopdy.home.landing", "bots"] app.launch() defer { setAppearance("System", in: app) } XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) setAppearance("Light", in: app) XCTAssertGreaterThan(brightness(of: app.windows.firstMatch, in: app), 0.8, "Light: a light home") - // Back from a bot's chat: the home's own header, never ☰ on the way. + // Back from a bot's chat: the home's own header. app.buttons["simple-bots.bot.travel"].tap() XCTAssertTrue(app.buttons["chat.back"].waitForExistence(timeout: 10)) app.buttons["chat.back"].tap() - for _ in 0..<10 { - XCTAssertFalse(app.buttons["home.drawer.open"].exists, "☰ showed while going back") - Thread.sleep(forTimeInterval: 0.08) - } XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 5)) // Dark from Settings › Appearance: the open page changes now, not after reopening it. @@ -57,7 +53,7 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { XCTAssertLessThan(brightness(of: app.windows.firstMatch, in: app), 0.25, "The open page turned dark") // Your name: a dark box with light text, readable. - app.navigationBars.buttons.firstMatch.tap() + app.buttons["BackButton"].firstMatch.tap() app.buttons["settings.you"].tap() let name = app.textFields["profile.display-name"] XCTAssertTrue(name.waitForExistence(timeout: 5)) @@ -65,20 +61,20 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { XCTAssertLessThan(brightness(of: name, in: app, edge: true), 0.35, "The name box is dark") // The home behind the sheet changed too. - app.navigationBars.buttons.firstMatch.tap() + app.buttons["BackButton"].firstMatch.tap() app.buttons["settings.done"].tap() XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 5)) save("appearance-home-dark", app) XCTAssertLessThan(brightness(of: app.windows.firstMatch, in: app), 0.25, "The home turned dark") } - /// The dark page picked in Appearance (Graphite or Black) is Bots mode's page too, and the + /// The dark page picked in Appearance (Graphite or Black) is the Bots view's page too, and the /// home, Settings and a bot's chat change as soon as it's picked (#718). @MainActor - func testDarkBackgroundChoiceRepaintsBotsMode() throws { + func testDarkBackgroundChoiceRepaintsBots() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "dark", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "dark", "-loopdy.appearance.darkBackground", "black"] app.launch() let home = app.descendants(matching: .any)["simple-bots.home"] @@ -102,7 +98,7 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { func testLightHomeKeepsItsPage() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "light", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "light", "-loopdy.appearance.darkBackground", "graphite"] app.launch() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) @@ -110,7 +106,7 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { save("light-home", app) } - /// Picks a dark page in Bots mode's Settings › Appearance and goes back to the home. + /// Picks a dark page in Settings › Appearance and goes back to the home. @MainActor private func pickDarkBackground(_ choice: String, in app: XCUIApplication) { app.buttons["simple-bots.settings"].tap() @@ -118,13 +114,13 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { let tile = app.buttons["appearance.dark.\(choice)"] XCTAssertTrue(tile.waitForExistence(timeout: 5)) tile.tap() - app.navigationBars.buttons.firstMatch.tap() + app.buttons["BackButton"].firstMatch.tap() app.buttons["settings.done"].tap() XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 5)) Thread.sleep(forTimeInterval: 0.6) } - /// The home, Bots mode's Settings and a bot's chat, for the evidence folder. + /// The home, Settings and a bot's chat, for the evidence folder. @MainActor private func saveScreens(_ suffix: String, _ app: XCUIApplication) { save("home-\(suffix)", app) @@ -142,13 +138,13 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 5)) } - /// Your name in Bots mode's Settings: a box that reads in light and in dark. + /// Your name in Settings, opened from Bots: a box that reads in light and in dark. @MainActor func testNameRowReadsInBothModes() throws { for (appearance, isDark) in [("light", false), ("dark", true)] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance] + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance] app.launch() XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 15)) app.buttons["simple-bots.settings"].tap() @@ -171,7 +167,7 @@ final class SimpleBotsAppearanceUITests: BighelpUITestCase { let mode = app.buttons["appearance.mode.\(title.lowercased())"] guard mode.waitForExistence(timeout: 5) else { return } mode.tap() - app.navigationBars.buttons.firstMatch.tap() + app.buttons["BackButton"].firstMatch.tap() app.buttons["settings.done"].tap() _ = app.buttons["simple-bots.settings"].waitForExistence(timeout: 5) } diff --git a/BighelpUITests/SimpleBotsSectionsUITests.swift b/BighelpUITests/SimpleBotsSectionsUITests.swift index acf4b722..07d20ec8 100644 --- a/BighelpUITests/SimpleBotsSectionsUITests.swift +++ b/BighelpUITests/SimpleBotsSectionsUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Bots mode's sections and group chats on demo data: + makes a section, Move to Section files a +/// The Bots view's sections and group chats on demo data: + makes a section, Move to Section files a /// bot, the card opens the section's page, and deleting it keeps its bots; New Group Chat makes one /// and Pin puts it on top. Set BIGHELP_SIMPLE_BOTS_EVIDENCE (TEST_RUNNER_…) to a folder to save the /// screenshots. @@ -128,6 +128,10 @@ final class SimpleBotsSectionsUITests: BighelpUITestCase { XCTAssertTrue(app.buttons["simple-bots.section.Work"].exists, "Mina is in Work on this computer") save("sections-demo-home-\(suffix)", app) + // At a large text size the cards stack, and this one starts under the bar. + let home = app.descendants(matching: .any)["simple-bots.home"].firstMatch + let bar = app.buttons["home.tab.conversations"].firstMatch + for _ in 0..<4 where card.frame.maxY > bar.frame.minY { home.swipeUp() } card.press(forDuration: 1.2) for label in ["Open", "Rename", "Edit Members", "Edit Sections", "Delete Section"] { XCTAssertTrue(app.buttons[label].waitForExistence(timeout: 3), "Section action: \(label)") @@ -155,7 +159,7 @@ final class SimpleBotsSectionsUITests: BighelpUITestCase { private func launch(appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance, + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance, "-bighelp.simple-bots.order", "{}"] + extra app.launch() return app diff --git a/BighelpUITests/SimpleBotsUITests.swift b/BighelpUITests/SimpleBotsUITests.swift index 2c8b4d5c..7fa2a11c 100644 --- a/BighelpUITests/SimpleBotsUITests.swift +++ b/BighelpUITests/SimpleBotsUITests.swift @@ -1,6 +1,6 @@ import XCTest -/// Bots mode on demo data: the home (your circle, search, +, the primary +/// The Bots view on demo data: the home (your circle, search, +, the primary /// bot, the rest), Settings, Create New Bot, search, a bot's menu, its chat and /// its profile, in light and dark. Set BIGHELP_SIMPLE_BOTS_EVIDENCE /// (TEST_RUNNER_…) to a folder to save the screenshots. @@ -8,7 +8,7 @@ final class SimpleBotsUITests: BighelpUITestCase { @MainActor func testCachedBotChatOpensWithoutTheLookupLoader() { let app = launch(appearance: "dark", extra: ["-test-canonical-agent-chat", "-test-simple-bots-open-delay-ms", "3000"]) - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 15)) primary.tap() XCTAssertTrue(app.buttons["chat.identity"].waitForExistence(timeout: 2), @@ -24,22 +24,20 @@ final class SimpleBotsUITests: BighelpUITestCase { } @MainActor - func testSimpleBotModeHomeChatAndProfile() throws { + func testBotsHomeChatAndProfile() throws { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) let home = app.descendants(matching: .any)["simple-bots.home"] - XCTAssertTrue(home.waitForExistence(timeout: 15), "Bots mode opens on its home") - XCTAssertFalse(app.buttons["home.drawer.open"].exists, "No ☰ in Bots mode") - XCTAssertFalse(app.descendants(matching: .any)["tabbar.sessions"].exists, "No tab bar") - let primary = app.buttons["simple-bots.primary"] + XCTAssertTrue(home.waitForExistence(timeout: 15), "The launch opens on Bots") + let primary = app.primaryBot XCTAssertTrue(primary.exists) XCTAssertTrue(app.buttons["simple-bots.bot.travel"].exists, "Other bots are listed") save("simple-home-\(appearance)", app) - // Settings: the one Settings, the same as in Chat mode. + // Settings: the one Settings, from the circle. app.buttons["simple-bots.settings"].tap() XCTAssertTrue(app.descendants(matching: .any)["settings.screen"].firstMatch.waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["settings.apps"].exists, "Apps & skills, as in every mode") + XCTAssertTrue(app.buttons["settings.apps"].exists, "Apps & skills") save("simple-settings-\(appearance)", app) app.buttons["settings.done"].tap() @@ -92,7 +90,6 @@ final class SimpleBotsUITests: BighelpUITestCase { primary.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) - XCTAssertFalse(app.buttons["chat.new-chat"].exists, "One chat per bot on the home") save("simple-chat-\(appearance)", app) identity.tap() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.profile"].waitForExistence(timeout: 5)) @@ -181,7 +178,7 @@ final class SimpleBotsUITests: BighelpUITestCase { @MainActor private func openPrimaryProfile(_ app: XCUIApplication) { XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.primary"].tap() + app.primaryBot.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) let profile = app.descendants(matching: .any)["simple-bots.profile"] @@ -198,7 +195,7 @@ final class SimpleBotsUITests: BighelpUITestCase { let app = launch(appearance: "dark") XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) save("simple-home-dark", app) - app.buttons["simple-bots.primary"].tap() + app.primaryBot.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) identity.tap() @@ -258,7 +255,7 @@ final class SimpleBotsUITests: BighelpUITestCase { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.primary"].tap() + app.primaryBot.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) let profile = app.descendants(matching: .any)["simple-bots.profile"] @@ -349,7 +346,7 @@ final class SimpleBotsUITests: BighelpUITestCase { func testProfileFilesAndMedia() throws { for appearance in ["light", "dark"] { let app = launch(appearance: appearance) - let primary = app.buttons["simple-bots.primary"] + let primary = app.primaryBot XCTAssertTrue(primary.waitForExistence(timeout: 15)) primary.tap() let identity = app.buttons["chat.identity"] @@ -496,7 +493,7 @@ final class SimpleBotsUITests: BighelpUITestCase { app.buttons["simple-bots.create.close"].tap() // A bot's Share saves it as a template on the computer. - app.buttons["simple-bots.primary"].tap() + app.primaryBot.tap() let identity = app.buttons["chat.identity"] XCTAssertTrue(identity.waitForExistence(timeout: 10)) identity.tap() @@ -547,8 +544,11 @@ final class SimpleBotsUITests: BighelpUITestCase { let labels = ["New Chat", "Pin", "Rearrange", "Move to Section", "Mark Unread", "Bot Profile", "Hide"] for label in labels { XCTAssertTrue(app.buttons[label].waitForExistence(timeout: 3), "First-level action: \(label)") - XCTAssertTrue(app.buttons[label].isHittable) } + // The menu grows into place: its last row can be tapped once it has. + let settled = expectation(for: NSPredicate(format: "isHittable == true"), evaluatedWith: app.buttons["Hide"]) + wait(for: [settled], timeout: 5) + for label in labels { XCTAssertTrue(app.buttons[label].isHittable, "Can be tapped: \(label)") } for (before, after) in zip(labels, labels.dropFirst()) { XCTAssertLessThan(app.buttons[before].frame.midY, app.buttons[after].frame.midY) } @@ -560,7 +560,10 @@ final class SimpleBotsUITests: BighelpUITestCase { bot.press(forDuration: 1.2) XCTAssertTrue(app.buttons["Mark Read"].waitForExistence(timeout: 3)) app.buttons["Mark Read"].tap() + // The row moves as its dot goes, so the next press waits for it. + XCTAssertTrue(app.buttons["Mark Read"].waitForNonExistence(timeout: 5)) bot.press(forDuration: 1.2) + XCTAssertTrue(app.buttons["Bot Profile"].waitForExistence(timeout: 5), "The menu opens again") app.buttons["Bot Profile"].tap() XCTAssertTrue(app.descendants(matching: .any)["simple-bots.profile"].waitForExistence(timeout: 5)) app.terminate() @@ -573,7 +576,7 @@ final class SimpleBotsUITests: BighelpUITestCase { func testRearrangeReordersTheListAndTheTop() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "dark", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "dark", // Each run starts with no saved order, and keeps its own out of later runs. "-bighelp.simple-bots.order", "{}"] app.launch() @@ -602,24 +605,24 @@ final class SimpleBotsUITests: BighelpUITestCase { save("simple-rearrange-dark", app) // The list's rows use the system's reorder handles, which the test can't drive; the top bots drag here. let pinned = app.descendants(matching: .any)["simple-bots.pinned.\(agentID)"] - let primary = app.descendants(matching: .any)["simple-bots.primary"] + let primary = app.primaryBotTile XCTAssertGreaterThan(pinned.frame.minX, primary.frame.minX) pinned.press(forDuration: 0.1, thenDragTo: primary, withVelocity: .slow, thenHoldForDuration: 0.3) XCTAssertTrue(waitUntil { pinned.frame.minX < primary.frame.minX }, "On top, the dragged bot goes first") save("simple-rearranged-dark", app) saveButton.tap() XCTAssertTrue(app.buttons["simple-bots.search"].waitForExistence(timeout: 5), "Save ends rearranging") - XCTAssertLessThan(app.buttons["simple-bots.pinned.\(agentID)"].frame.minX, app.buttons["simple-bots.primary"].frame.minX) + XCTAssertLessThan(app.buttons["simple-bots.pinned.\(agentID)"].frame.minX, app.primaryBot.frame.minX) // Cancel drops a change. app.buttons["simple-bots.pinned.\(agentID)"].press(forDuration: 1.2) tapBotMenuAction("Rearrange", in: app) let pinnedAgain = app.descendants(matching: .any)["simple-bots.pinned.\(agentID)"] - pinnedAgain.press(forDuration: 0.1, thenDragTo: app.descendants(matching: .any)["simple-bots.primary"], + pinnedAgain.press(forDuration: 0.1, thenDragTo: app.primaryBotTile, withVelocity: .slow, thenHoldForDuration: 0.3) app.buttons["simple-bots.rearrange.cancel"].tap() XCTAssertTrue(app.buttons["simple-bots.search"].waitForExistence(timeout: 5)) - XCTAssertLessThan(app.buttons["simple-bots.pinned.\(agentID)"].frame.minX, app.buttons["simple-bots.primary"].frame.minX, + XCTAssertLessThan(app.buttons["simple-bots.pinned.\(agentID)"].frame.minX, app.primaryBot.frame.minX, "Cancel keeps the saved order") app.buttons["simple-bots.pinned.\(agentID)"].press(forDuration: 1.2) @@ -652,34 +655,21 @@ final class SimpleBotsUITests: BighelpUITestCase { return condition() } - /// The message box: voice mode's pill inside it, Send in its place once there's text. Voice opens as a - /// bar over the chat, which stays in use, and End closes the bar. Needs the microphone allowed for - /// bighelp on the simulator (`simctl privacy … grant microphone`). + /// The message box: voice mode's button inside it, Send in its place once there's text, and Expand + /// once the draft runs to three lines. @MainActor - func testVoiceIsABarOverTheChat() throws { + func testTheMessageBoxSwapsVoiceForSend() throws { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", "dark", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", "dark", "-loopdy.voice.conversation-mode", "turnBased", "-bighelp.voice.transcription", "hermes"] app.launch() - XCTAssertTrue(app.buttons["simple-bots.primary"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.primary"].tap() + XCTAssertTrue(app.primaryBot.waitForExistence(timeout: 15)) + app.primaryBot.tap() let voice = app.buttons["chat.voice"] XCTAssertTrue(voice.waitForExistence(timeout: 10)) save("simple-composer-idle-dark", app) - voice.tap() - let bar = app.descendants(matching: .any)["simple-bots.voice"] - XCTAssertTrue(bar.waitForExistence(timeout: 10), "Voice is a bar over the chat") - XCTAssertFalse(app.descendants(matching: .any)["voice.screen"].exists, "Not the voice screen") - XCTAssertTrue(app.buttons["simple-bots.voice.microphone"].exists) - XCTAssertTrue(app.buttons["chat.attachment"].isHittable, "The chat stays in use") - save("simple-voice-bar-dark", app) - app.buttons["simple-bots.voice.end"].tap() - let gone = NSPredicate(format: "exists == false") - expectation(for: gone, evaluatedWith: bar) - waitForExpectations(timeout: 10) - let input = app.textViews.firstMatch input.tap() input.typeText("Text 123") @@ -693,29 +683,6 @@ final class SimpleBotsUITests: BighelpUITestCase { "Expand shows above the box once the draft has three lines") } - /// Settings › Modes with Bots picked; picking Chat leaves Bots mode. - @MainActor - func testTurningSimpleBotModeOffComesBackToBighelp() throws { - let app = launch(appearance: "light") - XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 15)) - app.buttons["simple-bots.settings"].tap() - let modes = app.buttons["settings.menu.modes"] - for _ in 0..<4 where !(modes.exists && modes.isHittable) { app.swipeUp() } - XCTAssertTrue(modes.waitForExistence(timeout: 5)) - XCTAssertTrue(modes.label.contains("Bots mode"), modes.label) - modes.tap() - let bots = app.buttons["settings.mode.bots"] - XCTAssertTrue(bots.waitForExistence(timeout: 5)) - XCTAssertTrue(bots.isSelected) - XCTAssertTrue(app.switches["settings.code-mode"].exists, "Code mode's switch") - save("simple-settings-modes", app) - app.buttons["settings.mode.chat"].tap() - let done = app.buttons["settings.done"] - if done.waitForExistence(timeout: 5) { done.tap() } - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 10), "☰ is back") - XCTAssertFalse(app.descendants(matching: .any)["simple-bots.home"].exists) - } - /// A bot whose chat is slow to open (the demo's Bot Chat lookup takes as long as a slow computer's): /// the opening loader shows with its name and Cancel, Cancel stays on the home, and the next tap /// opens the chat once it's ready, with the loader gone. @@ -754,7 +721,7 @@ final class SimpleBotsUITests: BighelpUITestCase { private func launch(appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance] + extra app.launch() return app diff --git a/BighelpUITests/TeamworkUITests.swift b/BighelpUITests/TeamworkUITests.swift index 5b7b42c6..61593d59 100644 --- a/BighelpUITests/TeamworkUITests.swift +++ b/BighelpUITests/TeamworkUITests.swift @@ -1,7 +1,6 @@ import XCTest -/// Settings › Teamwork on demo data: off by default, and its line says what it does; the same -/// Settings in Bots mode. +/// Settings › Teamwork on demo data: off by default, and its line says what it does. final class TeamworkUITests: BighelpUITestCase { @MainActor func testTeamworkTurnsOnInSettings() throws { @@ -20,21 +19,4 @@ final class TeamworkUITests: BighelpUITestCase { let on = app.switches.matching(NSPredicate(format: "identifier == %@ AND value == '1'", "settings.teamwork")).firstMatch XCTAssertTrue(on.waitForExistence(timeout: 5)) } - - @MainActor - func testTeamworkInBotsModeIsTheSameSwitch() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES"] - app.launch() - let settingsButton = app.buttons["simple-bots.settings"] - XCTAssertTrue(settingsButton.waitForExistence(timeout: 15)) - settingsButton.tap() - let teamwork = app.switches["settings.teamwork"] - XCTAssertTrue(teamwork.waitForExistence(timeout: 10)) - XCTAssertTrue(app.descendants(matching: .any)["settings.screen"].firstMatch.exists, "Bots mode opens the one Settings") - teamwork.switches.firstMatch.tap() - let on = app.switches.matching(NSPredicate(format: "identifier == %@ AND value == '1'", "settings.teamwork")).firstMatch - XCTAssertTrue(on.waitForExistence(timeout: 5)) - } } diff --git a/BighelpUITests/TemplateCatalogUITests.swift b/BighelpUITests/TemplateCatalogUITests.swift index 5067db87..7a2f1818 100644 --- a/BighelpUITests/TemplateCatalogUITests.swift +++ b/BighelpUITests/TemplateCatalogUITests.swift @@ -1,8 +1,8 @@ import XCTest /// Every template picker by topic: the search row, the topic chips, a section per topic, Sort, and -/// a search that finds nothing. Agents' New agent (its rail and Browse all), Bots mode's New -/// Bot › Templates (My Templates first), and Feed, Ideas and Goals blueprints. Demo data (bundled, +/// a search that finds nothing. Bots' New Bot › Templates (My Templates first), and Feed, Ideas and +/// Goals blueprints on a bot's board (Today › See all, one bot). Demo data (bundled, /// offline). BIGHELP_CATALOG_EVIDENCE (TEST_RUNNER_…) saves light and dark shots. final class TemplateCatalogUITests: BighelpUITestCase { @MainActor @@ -10,9 +10,12 @@ final class TemplateCatalogUITests: BighelpUITestCase { for appearance in ["light", "dark"] { let app = launch(appearance) let any = app.descendants(matching: .any) - for tab in ["tab.feed", "tab.ideas", "tab.goals"] { - let page = String(tab.dropFirst(4)) - openRootTab(tab, in: app) + for page in ["feed", "ideas", "goals"] { + // Today › See all, then one bot's board: Blueprints sits by its title. + openTodayBoard(page, in: app) + let bot = app.buttons["today.board-page.chip.finance"].firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "\(page) lists the bots") + bot.tap() let open = app.buttons["board.blueprints"].firstMatch XCTAssertTrue(open.waitForExistence(timeout: 10), "Blueprints on \(page)") open.tap() @@ -30,7 +33,7 @@ final class TemplateCatalogUITests: BighelpUITestCase { XCTAssertTrue(marketing.isSelected) save("blueprints-\(page)-marketing-\(appearance)", app) - if tab == "tab.ideas" { + if page == "ideas" { let search = any["board.blueprints.search"].firstMatch search.tap() search.typeText("zzz") @@ -62,66 +65,19 @@ final class TemplateCatalogUITests: BighelpUITestCase { } app.buttons["board.blueprints.done"].tap() XCTAssertTrue(any["board.blueprints.sheet"].firstMatch.waitForNonExistence(timeout: 5)) + app.buttons["today.board-page.back"].firstMatch.tap() } app.terminate() } } - @MainActor - func testAgentTemplatesByTopic() throws { - for appearance in ["light", "dark"] { - let app = launch(appearance) - let any = app.descendants(matching: .any) - openNewAgentTemplates(app) - - // The rail over the editor narrows to a topic. - let railCoding = app.buttons["agent.editor.templates.category.coding"] - XCTAssertTrue(railCoding.waitForExistence(timeout: 5), "Topic chips over the rail") - railCoding.tap() - XCTAssertTrue(app.buttons["agent.editor.template.forge"].waitForExistence(timeout: 3)) - XCTAssertFalse(app.buttons["agent.editor.template.anchor"].exists, "Only Coding's templates") - save("agent-editor-rail-coding-\(appearance)", app) - - app.buttons["agent.editor.templates.browse"].firstMatch.tap() - XCTAssertTrue(any["agent.templates.browser"].firstMatch.waitForExistence(timeout: 5)) - XCTAssertTrue(any["agent.templates.search"].firstMatch.waitForExistence(timeout: 5), "The search row") - XCTAssertTrue(any["agent.templates.section.productivity"].firstMatch.exists, "A section per topic") - XCTAssertTrue(app.buttons["agent.templates.category.all"].isSelected) - save("agent-templates-\(appearance)", app) - - app.buttons["agent.templates.category.coding"].tap() - XCTAssertTrue(app.buttons["agent.templates.forge"].waitForExistence(timeout: 3)) - XCTAssertTrue(app.buttons["agent.templates.beacon"].exists) - XCTAssertFalse(any["agent.templates.section.productivity"].firstMatch.exists, "Only Coding") - save("agent-templates-coding-\(appearance)", app) - - let search = any["agent.templates.search"].firstMatch - search.tap() - search.typeText("zzz") - XCTAssertTrue(any["agent.templates.empty"].firstMatch.waitForExistence(timeout: 3)) - XCTAssertTrue(app.staticTexts["Nothing in Coding matches \u{201C}zzz\u{201D}."].exists) - save("agent-templates-empty-\(appearance)", app) - app.buttons["agent.templates.empty.all"].tap() - XCTAssertTrue(app.buttons["agent.templates.category.all"].waitForExistence(timeout: 3)) - app.buttons["agent.templates.search.clear"].tap() - search.typeText("research") - XCTAssertTrue(app.buttons["agent.templates.lens"].waitForExistence(timeout: 3), "Lens is the research partner") - XCTAssertTrue(any["agent.templates.section.science"].firstMatch.exists, "…under Science") - save("agent-templates-search-\(appearance)", app) - app.buttons["agent.templates.lens"].tap() - XCTAssertFalse(any["agent.templates.browser"].firstMatch.waitForExistence(timeout: 2), "Picking one closes it") - XCTAssertEqual(editorRole(app).value as? String, "Research partner") - app.terminate() - } - } - /// New Bot's Templates: My Templates first and as a chip, then the catalog by topic. @MainActor func testNewBotTemplatesByTopic() throws { for appearance in ["light", "dark"] { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.simple-bots", "YES", "-loopdy.demo.appearance", appearance] + "-loopdy.home.landing", "bots", "-loopdy.demo.appearance", appearance] app.launch() let any = app.descendants(matching: .any) XCTAssertTrue(any["simple-bots.home"].waitForExistence(timeout: 15)) @@ -156,75 +112,6 @@ final class TemplateCatalogUITests: BighelpUITestCase { } } - /// A catalog template with fill-in fields (the demo Field Lead) opens a short form from Browse all: - /// name first, then its fields. Continue fills the editor's instructions with no `{{` left. - @MainActor - func testTemplateFormFillsTheInstructions() throws { - for appearance in ["light", "dark"] { - let app = launch(appearance) - openNewAgentTemplates(app) - app.buttons["agent.editor.templates.browse"].firstMatch.tap() - let search = app.descendants(matching: .any)["agent.templates.search"].firstMatch - XCTAssertTrue(search.waitForExistence(timeout: 5)) - search.tap() - search.typeText("Field") - let card = app.buttons["agent.templates.field-lead"] - XCTAssertTrue(card.waitForExistence(timeout: 3), "The demo template with fields") - card.tap() - - let any = app.descendants(matching: .any) - XCTAssertTrue(any["agent.template-form"].firstMatch.waitForExistence(timeout: 5), "Its form opens") - let name = app.textFields["agent.template-form.field.agent_name"] - let role = app.textFields["agent.template-form.field.agent_role"] - XCTAssertTrue(name.waitForExistence(timeout: 3)) - XCTAssertTrue(role.exists, "Role follows the name") - XCTAssertEqual(role.placeholderValue, "Release coordinator", "The example is a hint, not a value") - let continueButton = app.buttons["agent.template-form.continue"] - XCTAssertFalse(continueButton.isEnabled, "Required fields are empty") - save("template-form-empty-\(appearance)", app) - - name.tap() - name.typeText("Kai") - XCTAssertFalse(continueButton.isEnabled, "Role is required too") - role.tap() - role.typeText("Release coordinator") - let tone = any["agent.template-form.field.tone"].firstMatch - let formList = app.collectionViews.firstMatch - for _ in 0..<3 where !tone.isHittable { formList.swipeUp() } - tone.tap() - let warm = app.buttons["Warm"].firstMatch - XCTAssertTrue(warm.waitForExistence(timeout: 3), "Tone offers its choices") - warm.tap() - if appearance == "dark" { - let context = any["agent.template-form.field.operating_context"].firstMatch - for _ in 0..<3 where !context.isHittable { formList.swipeUp() } - context.tap() - context.typeText("A two-person studio") - } - save("template-form-filled-\(appearance)", app) - XCTAssertTrue(continueButton.isEnabled) - continueButton.tap() - XCTAssertTrue(any["agent.template-form"].firstMatch.waitForNonExistence(timeout: 5)) - - XCTAssertEqual(app.textFields["agent.editor.name"].value as? String, "Kai") - XCTAssertEqual(editorRole(app).value as? String, "Release coordinator") - save("template-form-editor-\(appearance)", app) - // The editor builds its rows as they scroll into view. - let instructionsView = app.textViews["agent.editor.instructions"] - for _ in 0..<5 where !instructionsView.exists { app.swipeUp() } - let instructions = (instructionsView.value as? String) ?? "" - XCTAssertTrue(instructions.hasPrefix("# Kai"), instructions) - XCTAssertTrue(instructions.contains("Role: Release coordinator")) - XCTAssertTrue(instructions.contains("Tone: Warm.")) - XCTAssertTrue(instructions.contains(appearance == "dark" ? "Operating context: A two-person studio" - : "Operating context: General work for the user.")) - XCTAssertFalse(instructions.contains("{{"), "No placeholder is left") - XCTAssertFalse(instructions.contains("}}")) - save("template-form-instructions-\(appearance)", app) - app.terminate() - } - } - @MainActor private func launch(_ appearance: String) -> XCUIApplication { let app = makeApp() @@ -233,28 +120,6 @@ final class TemplateCatalogUITests: BighelpUITestCase { return app } - /// Agents › New agent, on its Templates choice. - @MainActor - private func openNewAgentTemplates(_ app: XCUIApplication) { - openRootTab("tab.agents", in: app) - let create = app.buttons["agents.create"].firstMatch - XCTAssertTrue(create.waitForExistence(timeout: 10)) - create.tap() - let start = app.segmentedControls["agent.editor.start"].firstMatch - XCTAssertTrue(start.waitForExistence(timeout: 10)) - start.buttons["Templates"].tap() - XCTAssertTrue(app.buttons["agent.editor.templates.browse"].firstMatch.waitForExistence(timeout: 5), "Browse all") - } - - /// The editor's Role field: the form builds rows as they scroll in, and the template rail with - /// its topic chips can leave Role just below the fold. - @MainActor - private func editorRole(_ app: XCUIApplication) -> XCUIElement { - let role = app.textFields["agent.editor.role"] - for _ in 0..<3 where !role.exists || !role.isHittable { app.swipeUp() } - return role - } - private func save(_ name: String, _ app: XCUIApplication) { let shot = XCTAttachment(screenshot: app.screenshot()) shot.name = name diff --git a/BighelpUITests/TextSizeDefaultUITests.swift b/BighelpUITests/TextSizeDefaultUITests.swift index 70561a73..9fc50da4 100644 --- a/BighelpUITests/TextSizeDefaultUITests.swift +++ b/BighelpUITests/TextSizeDefaultUITests.swift @@ -62,14 +62,16 @@ final class TextSizeDefaultUITests: BighelpUITestCase { app.launch() let name = "text-size-\(pinsTextSize ? "pinned" : "default")" - let chat = app.buttons["session.row.demo-finance"].firstMatch + let chat = chatRow("demo-finance", in: app) XCTAssertTrue(chat.waitForExistence(timeout: 15)) chat.tap() - XCTAssertTrue(app.buttons["chat.menu"].firstMatch.waitForExistence(timeout: 10), "The chat opened") + XCTAssertTrue(app.buttons["chat.back"].firstMatch.waitForExistence(timeout: 10), "The chat opened") XCTAssertTrue(app.descendants(matching: .any)["chat.message.inline-selection"].firstMatch .waitForExistence(timeout: 10), "The chat shows its messages") capture("\(name)-chat-\(appearance)", in: app) + // Settings opens from the home's circle. + goBackFromChat(in: app) openSettings(in: app) settingsRow("settings.themes", in: app).tap() let studio = app.descendants(matching: .any)["appearance.studio"].firstMatch diff --git a/BighelpUITests/ThemePresetsUITests.swift b/BighelpUITests/ThemePresetsUITests.swift index 73516128..46996338 100644 --- a/BighelpUITests/ThemePresetsUITests.swift +++ b/BighelpUITests/ThemePresetsUITests.swift @@ -54,7 +54,7 @@ final class ThemePresetsUITests: BighelpUITestCase { } /// Light and dark screenshots of Appearance and a chat with bubbles on and off, for three - /// presets, and Bots mode's home and chat. + /// presets, and the Bots view and a bot's chat. @MainActor func testEvidenceScreens() throws { guard let folder = ProcessInfo.processInfo.environment["BIGHELP_THEME_EVIDENCE"] else { @@ -83,7 +83,7 @@ final class ThemePresetsUITests: BighelpUITestCase { } for (scheme, preset) in [("light", "moss"), ("dark", "violet")] { let app = launch(scheme: scheme, light: "moss", dark: "violet", style: "page", - extra: ["-bighelp.settings.simple-bots", "YES"]) + extra: ["-loopdy.home.landing", "bots"]) XCTAssertTrue(app.buttons["simple-bots.settings"].waitForExistence(timeout: 15)) Thread.sleep(forTimeInterval: 0.6) save("bots-\(preset)-\(scheme)-home", app, folder) diff --git a/BighelpUITests/ToolCodeCellUITests.swift b/BighelpUITests/ToolCodeCellUITests.swift index 4dbdcaf5..6167e58c 100644 --- a/BighelpUITests/ToolCodeCellUITests.swift +++ b/BighelpUITests/ToolCodeCellUITests.swift @@ -11,7 +11,7 @@ final class ToolCodeCellUITests: BighelpUITestCase { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-preview-ui-v3", "-test-code-tool", - "-loopdy.chat.foldCompletedTurns", "NO", "-bighelp.settings.simple-bots", "NO", + "-loopdy.chat.foldCompletedTurns", "NO", "-loopdy.demo.appearance", appearance] app.launch() let timeline = app.tables["chat.timeline"] diff --git a/BighelpUITests/UnifiedModeToggleUITests.swift b/BighelpUITests/UnifiedModeToggleUITests.swift deleted file mode 100644 index e6844655..00000000 --- a/BighelpUITests/UnifiedModeToggleUITests.swift +++ /dev/null @@ -1,87 +0,0 @@ -import XCTest - -/// Settings › Modes › Header mode switcher: Bots, Chat and Code in a pill at the top of each -/// home, on the demo data, in light and dark. Off out of the box. -/// TEST_RUNNER_BIGHELP_MODE_PILL_EVIDENCE= saves the screenshots there. -final class UnifiedModeToggleUITests: BighelpUITestCase { - @MainActor - func testThePillSwitchesBetweenBotsChatAndCode() throws { - for appearance in ["light", "dark"] { - let app = launch(appearance: appearance, extra: ["-bighelp.settings.code-mode", "YES"]) - let pill = app.descendants(matching: .any)["mode.pill"] - - // Chat: the list's bar holds the pill, Chat chosen. - XCTAssertTrue(pill.waitForExistence(timeout: 15), "The pill shows on the Chat tab") - XCTAssertTrue(app.buttons["mode.pill.chat"].isSelected) - XCTAssertTrue(app.buttons["mode.pill.code"].exists, "Code is offered while Code mode is on") - save("chat-\(appearance)", app) - - // Code: its home, with the same pill in its bar. - app.buttons["mode.pill.code"].tap() - XCTAssertTrue(app.descendants(matching: .any)["code.screen"].waitForExistence(timeout: 10)) - XCTAssertTrue(app.buttons["mode.pill.code"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["mode.pill.code"].isSelected) - save("code-\(appearance)", app) - - // Bots: its calm home; Search moves under the pill. - app.buttons["mode.pill.bots"].tap() - XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForExistence(timeout: 10)) - XCTAssertTrue(app.buttons["mode.pill.bots"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["mode.pill.bots"].isSelected) - let search = app.buttons["simple-bots.search"] - XCTAssertTrue(search.exists) - XCTAssertGreaterThan(search.frame.minY, app.buttons["mode.pill.bots"].frame.maxY, - "Search sits on the row under the pill") - save("bots-\(appearance)", app) - - // And back to Chat. - app.buttons["mode.pill.chat"].tap() - XCTAssertTrue(app.descendants(matching: .any)["simple-bots.home"].waitForNonExistence(timeout: 10)) - XCTAssertTrue(app.buttons["mode.pill.chat"].waitForExistence(timeout: 5)) - XCTAssertTrue(app.buttons["mode.pill.chat"].isSelected) - app.terminate() - } - } - - @MainActor - func testTheAgentsOwnChatCarriesThePill() throws { - let app = launch(appearance: "light", extra: ["-loopdy.home.opens-chat", "YES"]) - XCTAssertTrue(app.buttons["chat.menu"].waitForExistence(timeout: 15), "The Chat tab opens the agent's chat") - XCTAssertTrue(app.buttons["mode.pill.chat"].waitForExistence(timeout: 5)) - XCTAssertFalse(app.buttons["mode.pill.code"].exists, "Code waits for Settings › Code mode") - XCTAssertGreaterThan(chatIdentity(in: app).frame.minY, app.buttons["mode.pill.chat"].frame.maxY, - "The agent steps down below the pill") - save("home-chat-light", app) - } - - @MainActor - func testThePillIsOffOutOfTheBox() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3"] - app.launch() - XCTAssertTrue(app.buttons["home.drawer.open"].waitForExistence(timeout: 15)) - XCTAssertFalse(app.descendants(matching: .any)["mode.pill"].exists) - } - - @MainActor - private func launch(appearance: String, extra: [String] = []) -> XCUIApplication { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-preview-ui-v3", - "-bighelp.settings.unified-mode-toggle", "YES", - "-loopdy.demo.appearance", appearance] + extra - app.launch() - return app - } - - @MainActor - private func save(_ name: String, _ app: XCUIApplication) { - let screenshot = app.screenshot() - let shot = XCTAttachment(screenshot: screenshot) - shot.name = name - shot.lifetime = .keepAlways - add(shot) - guard let folder = ProcessInfo.processInfo.environment["BIGHELP_MODE_PILL_EVIDENCE"] else { return } - try? FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) - try? screenshot.pngRepresentation.write(to: URL(fileURLWithPath: folder).appendingPathComponent("\(name).png")) - } -} diff --git a/BighelpUITests/UsageNavigationUITests.swift b/BighelpUITests/UsageNavigationUITests.swift index cacbbabd..54f72723 100644 --- a/BighelpUITests/UsageNavigationUITests.swift +++ b/BighelpUITests/UsageNavigationUITests.swift @@ -1,14 +1,14 @@ import XCTest -/// Usage opened from a chat's ⋯ menu and from ☰, the way people open the app (on the agent's -/// chat): it has a top bar with Back, and Back returns to where it was opened from. +/// Usage opened from a chat's ⋯ menu and from Settings: it has a top bar with Back, and Back +/// returns to where it was opened from (the chat, or the home Settings was opened over). /// BIGHELP_USAGE_NAV_EVIDENCE (TEST_RUNNER_…) saves the screenshots. final class UsageNavigationUITests: BighelpUITestCase { @MainActor func testUsageFromTheChatMenuHasBackAndReturnsToTheChat() throws { let app = launch() let options = app.buttons["chat.options"].firstMatch - XCTAssertTrue(options.waitForExistence(timeout: 15), "Opens on the agent's chat") + XCTAssertTrue(options.waitForExistence(timeout: 15), "Opens on the agent's chat (-start-chat)") let usage = chatMenuItem("chat.provider-usage", in: app) XCTAssertTrue(usage.waitForExistence(timeout: 5)) usage.tap() @@ -22,27 +22,28 @@ final class UsageNavigationUITests: BighelpUITestCase { } @MainActor - func testUsageFromTheMenuReturnsWhereItWasOpened() throws { - let app = launch() - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - let usage = app.buttons["menu.usage"] - XCTAssertTrue(usage.waitForExistence(timeout: 5)) - usage.tap() + func testUsageFromSettingsReturnsWhereItWasOpened() throws { + let app = makeApp() + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.landing", "chats"] + app.launch() + XCTAssertTrue(app.descendants(matching: .any)["chats.inbox"].firstMatch.waitForExistence(timeout: 15)) + openSettings(in: app) + // Settings closes and Usage opens over the screen it was opened from. + settingsRow("simple-bots.settings.usage", in: app).tap() XCTAssertTrue(app.descendants(matching: .any)["usage"].firstMatch.waitForExistence(timeout: 8)) - save("from-menu", app) + save("from-settings", app) let back = app.navigationBars["Usage"].buttons.element(boundBy: 0) XCTAssertTrue(back.waitForExistence(timeout: 5), "Usage has its top bar with Back") back.tap() - XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 5), "Back returns to the chat") - save("menu-back", app) + XCTAssertTrue(app.descendants(matching: .any)["chats.inbox"].firstMatch.waitForExistence(timeout: 5), + "Back returns to Chats") + save("settings-back", app) } @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat"] app.launch() return app } diff --git a/BighelpUITests/VoiceSettingsUITests.swift b/BighelpUITests/VoiceSettingsUITests.swift index a1a0ebcb..76c74563 100644 --- a/BighelpUITests/VoiceSettingsUITests.swift +++ b/BighelpUITests/VoiceSettingsUITests.swift @@ -188,28 +188,31 @@ final class VoiceSettingsUITests: BighelpUITestCase { XCTAssertLessThanOrEqual(restart.frame.maxX, screen.maxX, "Restart sound runs off screen") } if let name { save(name, app) } - app.navigationBars.buttons.firstMatch.tap() + // The sheet's own Back: the screen behind Settings has a navigation bar too. + app.buttons["BackButton"].firstMatch.tap() let done = app.buttons["settings.done"].firstMatch XCTAssertTrue(done.waitForExistence(timeout: 5)) done.tap() + // Back into the chat Settings was opened from, for its call. + let chat = chatRow("demo-finance", in: app) + XCTAssertTrue(chat.waitForExistence(timeout: 10), "Chats lists the demo chat") + chat.tap() } @MainActor private func launch(_ appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-start-chat", "-voice-settings-fixture", - "-bighelp.settings.simple-bots", "NO", "-loopdy.demo.appearance", appearance] + extra + "-loopdy.demo.appearance", appearance] + extra app.launch() return app } @MainActor private func openVoiceSettings(_ app: XCUIApplication) { - app.buttons["chat.menu"].tap() - XCTAssertTrue(app.buttons["menu.done"].waitForExistence(timeout: 5)) - let settingsEntry = app.buttons["menu.settings"] - for _ in 0..<4 where !(settingsEntry.exists && settingsEntry.isHittable) { app.swipeUp() } - settingsEntry.tap() + // Settings opens from the home's circle: Back out of the chat first. + goBackFromChat(in: app) + openSettings(in: app) let voice = settingsRow("settings.chat.voice-settings", in: app) XCTAssertTrue(voice.waitForExistence(timeout: 5)) voice.tap() diff --git a/BighelpUITests/VoiceStepLineUITests.swift b/BighelpUITests/VoiceStepLineUITests.swift index c8afbd89..2813c737 100644 --- a/BighelpUITests/VoiceStepLineUITests.swift +++ b/BighelpUITests/VoiceStepLineUITests.swift @@ -9,7 +9,7 @@ final class VoiceStepLineUITests: BighelpUITestCase { func testVoiceShowsTheAgentsStepOneAtATime() throws { let app = makeApp() app.launchArguments += ["-use-demo-fixtures", "-disable-demo-delays", "-test-voice-steps", - "-test-voice-partial", "-loopdy.home.opens-chat", "YES", + "-test-voice-partial", "-start-chat", "-loopdy.voice.conversation-mode", "turnBased", "-bighelp.voice.transcription", "hermes"] app.launch() diff --git a/BighelpUITests/WeatherCardsUITests.swift b/BighelpUITests/WeatherCardsUITests.swift index b973c307..9b551e58 100644 --- a/BighelpUITests/WeatherCardsUITests.swift +++ b/BighelpUITests/WeatherCardsUITests.swift @@ -94,7 +94,7 @@ final class WeatherCardsUITests: BighelpUITestCase { private func launch(appearance: String, extra: [String] = []) -> XCUIApplication { let app = makeApp() app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-test-weather-cards", - "-loopdy.home.opens-chat", "YES", "-loopdy.settings.nerd-mode", "NO", + "-start-chat", "-loopdy.settings.nerd-mode", "NO", "-loopdy.demo.appearance", appearance] + extra app.launch() return app diff --git a/BighelpUITests/WidgetLinkHostUITests.swift b/BighelpUITests/WidgetLinkHostUITests.swift index 93756b46..b7085d32 100644 --- a/BighelpUITests/WidgetLinkHostUITests.swift +++ b/BighelpUITests/WidgetLinkHostUITests.swift @@ -13,13 +13,16 @@ final class WidgetLinkHostUITests: BighelpUITestCase { let probe = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: URL(fileURLWithPath: path))) guard probe["mode"] == "widgets" else { throw XCTSkip("This host runs the \(probe["mode"] ?? "?") mode") } let app = makeApp() - app.launchArguments = ["-loopdy.home.opens-chat", "YES"] app.launch() try onboardOpenHost(app, address: try XCTUnwrap(probe["address"])) - // A chat with a reply, like the ones a widget lists. + // A chat with a reply, like the ones a widget lists: the primary bot's, from Bots. + showBots(in: app) + let primary = app.primaryBot + XCTAssertTrue(primary.waitForExistence(timeout: 30), "Bots shows the primary bot") + primary.tap() let composer = app.textViews["chat.composer.text"] - XCTAssertTrue(composer.waitForExistence(timeout: 30), "The agent's chat opens") + XCTAssertTrue(composer.waitForExistence(timeout: 30), "The bot's chat opens") composer.tap() composer.typeText("Widget link fixture message") app.buttons["chat.send"].tap() @@ -66,29 +69,28 @@ final class WidgetLinkHostUITests: BighelpUITestCase { "The widget's chat opens after a relaunch") save("widget-5-relaunch", app) - // A chat that's gone, at launch: the error closes onto a screen with ☰, never a dead end. + // A chat that's gone, at launch: the error closes onto the home and its bar, never a dead end. app.terminate() app.open(chatURL("native-session-v1:missing:bWlzc2luZw:bWlzc2luZw")) let alert = app.alerts.firstMatch XCTAssertTrue(alert.waitForExistence(timeout: 30), "A missing chat explains itself") sleep(3) // the agent's chat would open under the alert here alert.buttons["OK"].tap() - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 10), "☰ is there after the error") - XCTAssertTrue(menu.isHittable) + let newChat = app.buttons["home.new-chat"].firstMatch + XCTAssertTrue(newChat.waitForExistence(timeout: 10), "The home is there after the error") + XCTAssertTrue(newChat.isHittable) save("widget-6-after-error", app) } - /// The first row in All chats, as the widget stores it (`session.row.`). + /// The first row in Chats, as the widget stores it (`chats.row.here/` for the computer in use). @MainActor private func recentChatID(_ app: XCUIApplication) throws -> String { - app.buttons["chat.menu"].tap() - let chats = app.buttons["menu.chats"] - XCTAssertTrue(chats.waitForExistence(timeout: 5)) - chats.tap() + goBackFromChat(in: app) + showChats(in: app) + let prefix = "chats.row.here/" let row = app.descendants(matching: .any) - .matching(NSPredicate(format: "identifier BEGINSWITH %@", "session.row.")).firstMatch + .matching(NSPredicate(format: "identifier BEGINSWITH %@", prefix)).firstMatch XCTAssertTrue(row.waitForExistence(timeout: 20), "The chat is listed") - let id = String(row.identifier.dropFirst("session.row.".count)) + let id = String(row.identifier.dropFirst(prefix.count)) // Back to the agent's chat, where the app sits when someone leaves it. row.tap() XCTAssertTrue(app.textViews["chat.composer.text"].waitForExistence(timeout: 20)) diff --git a/BighelpUITests/WorkflowPublishUITests.swift b/BighelpUITests/WorkflowPublishUITests.swift index 57fc94f7..ffba6aca 100644 --- a/BighelpUITests/WorkflowPublishUITests.swift +++ b/BighelpUITests/WorkflowPublishUITests.swift @@ -52,10 +52,10 @@ final class WorkflowPublishUITests: BighelpUITestCase { @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] app.launch() - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])) - .firstMatch.waitForExistence(timeout: 15)) + // The home is up before the link comes in. + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 15)) return app } diff --git a/BighelpUITests/WorkflowsEditingUITests.swift b/BighelpUITests/WorkflowsEditingUITests.swift index 7d54fa10..b983d21e 100644 --- a/BighelpUITests/WorkflowsEditingUITests.swift +++ b/BighelpUITests/WorkflowsEditingUITests.swift @@ -315,8 +315,7 @@ final class WorkflowsEditingUITests: BighelpUITestCase { @MainActor func testAWorkflowLinkOpensItOrItsRunSheet() throws { let app = launch() - XCTAssertTrue(app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])) - .firstMatch.waitForExistence(timeout: 15)) + XCTAssertTrue(app.buttons["home.new-chat"].firstMatch.waitForExistence(timeout: 15)) app.open(URL(string: "loopdy://workflows/wf-morning")!) let pad = app.userInterfaceIdiom == .pad let make = element(pad ? "workflows.canvas.node.make" : "workflows.flow.stage.make", app) @@ -470,10 +469,10 @@ final class WorkflowsEditingUITests: BighelpUITestCase { @MainActor func testAComputerThatCantRunWorkflowsSaysWhyInPlainWords() throws { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-demo-workflows-unavailable", "chat_runner_missing"] app.launch() - openMenuRow(app) + openWorkDoor("workflows", in: app) let explanation = element("workflows.cant-run", app) XCTAssertTrue(explanation.waitForExistence(timeout: 8), "The screen explains instead of failing") let words = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS 'Update Hermes'")).firstMatch @@ -511,7 +510,7 @@ final class WorkflowsEditingUITests: BighelpUITestCase { @MainActor private func launch(_ extra: [String] = []) -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES"] + extra + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] + extra app.launch() return app } @@ -521,19 +520,9 @@ final class WorkflowsEditingUITests: BighelpUITestCase { if app.userInterfaceIdiom != .pad { throw XCTSkip("The free canvas is for regular width") } } - @MainActor - private func openMenuRow(_ app: XCUIApplication) { - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - let row = app.buttons["menu.workflows"] - XCTAssertTrue(row.waitForExistence(timeout: 8), "☰ lists Workflows") - row.tap() - } - @MainActor private func openWorkflows(_ app: XCUIApplication) { - openMenuRow(app) + openWorkDoor("workflows", in: app) XCTAssertTrue(element("workflows.home", app).waitForExistence(timeout: 8)) XCTAssertTrue(app.buttons["workflows.workflow.wf-research"].waitForExistence(timeout: 8)) } diff --git a/BighelpUITests/WorkflowsStagesAndTriggersUITests.swift b/BighelpUITests/WorkflowsStagesAndTriggersUITests.swift index 9321bb00..fc837d76 100644 --- a/BighelpUITests/WorkflowsStagesAndTriggersUITests.swift +++ b/BighelpUITests/WorkflowsStagesAndTriggersUITests.swift @@ -1,9 +1,9 @@ import XCTest /// Demo data: a run's stage opens what it used, made and decided; a workflow's trigger goes from -/// Manual to a schedule; Settings › Notifications has the workflow switches; the all-hosts Agents -/// screen asks which computer before New agent. BIGHELP_WORKFLOWS_EVIDENCE (TEST_RUNNER_…) saves -/// screenshots; BIGHELP_WORKFLOWS_APPEARANCE picks light or dark. +/// Manual to a schedule; Settings › Notifications has the workflow switches; the scheduled task +/// editor keeps its picker. BIGHELP_WORKFLOWS_EVIDENCE (TEST_RUNNER_…) saves screenshots; +/// BIGHELP_WORKFLOWS_APPEARANCE picks light or dark. final class WorkflowsStagesAndTriggersUITests: BighelpUITestCase { @MainActor func testARunStageShowsWhatItUsedMadeAndDecided() throws { @@ -79,31 +79,6 @@ final class WorkflowsStagesAndTriggersUITests: BighelpUITestCase { save("35-notification-workflows", app) } - @MainActor - func testAllHostsNewAgentAsksWhichComputerFirst() throws { - let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-use-multi-host-fixtures", - "-bighelp.hosts.all-hosts", "NO", "-loopdy.demo.appearance", appearance] - app.launch() - let menu = app.buttons["home.drawer.open"] - XCTAssertTrue(menu.waitForExistence(timeout: 10)) - menu.tap() - app.buttons["menu.all-hosts"].tap() - XCTAssertTrue(element("fleet.home", app).waitForExistence(timeout: 5)) - let organize = app.buttons["fleet.organize"] - XCTAssertTrue(organize.waitForExistence(timeout: 5)) - organize.tap() - let newAgent = app.buttons["fleet.organize.new-agent"] - XCTAssertTrue(newAgent.waitForExistence(timeout: 5)) - newAgent.tap() - let host = app.buttons["fleet.gate.host.Home Hermes"] - XCTAssertTrue(host.waitForExistence(timeout: 5), "It asks which computer") - save("36-new-agent-which-computer", app) - host.tap() - XCTAssertTrue(app.buttons["agent.editor.cancel"].waitForExistence(timeout: 15), "That computer's new-agent editor opens") - save("37-new-agent-editor", app) - } - /// The scheduled task editor's "When?" is the same picker the workflow trigger uses. @MainActor func testScheduledTaskEditorKeepsItsPicker() throws { @@ -130,20 +105,14 @@ final class WorkflowsStagesAndTriggersUITests: BighelpUITestCase { @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-loopdy.demo.appearance", appearance] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.demo.appearance", appearance] app.launch() return app } @MainActor private func openWorkflows(_ app: XCUIApplication) { - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - let row = app.buttons["menu.workflows"] - XCTAssertTrue(row.waitForExistence(timeout: 8)) - row.tap() + openWorkDoor("workflows", in: app) XCTAssertTrue(app.buttons["workflows.waiting.run-14"].waitForExistence(timeout: 8)) } diff --git a/BighelpUITests/WorkflowsUITests.swift b/BighelpUITests/WorkflowsUITests.swift index 12ee21b7..b7c7a49c 100644 --- a/BighelpUITests/WorkflowsUITests.swift +++ b/BighelpUITests/WorkflowsUITests.swift @@ -1,11 +1,11 @@ import XCTest -/// ☰ › Workflows on demo data: home, the run waiting for you, its sign-off and Approve. +/// Work › Workflows on demo data: home, the run waiting for you, its sign-off and Approve. /// BIGHELP_WORKFLOWS_EVIDENCE (TEST_RUNNER_…) saves each screen as a PNG; run once in /// light and once in dark appearance for both sets. final class WorkflowsUITests: BighelpUITestCase { @MainActor - func testMenuOpensWorkflowsAndApprovingTheWaitingRunFinishesIt() throws { + func testWorkOpensWorkflowsAndApprovingTheWaitingRunFinishesIt() throws { let app = launch() openWorkflows(app) save("01-home", app) @@ -37,8 +37,7 @@ final class WorkflowsUITests: BighelpUITestCase { func testTokenCountsAreNerdModeOnly() throws { for nerd in ["NO", "YES"] { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES", - "-loopdy.settings.nerd-mode", nerd] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.settings.nerd-mode", nerd] app.launch() openWorkflows(app) let running = app.buttons["workflows.run.run-15"] @@ -102,19 +101,15 @@ final class WorkflowsUITests: BighelpUITestCase { @MainActor private func launch() -> XCUIApplication { let app = makeApp() - app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays", "-loopdy.home.opens-chat", "YES"] + app.launchArguments = ["-use-demo-fixtures", "-disable-demo-delays"] app.launch() return app } @MainActor private func openWorkflows(_ app: XCUIApplication) { - let menu = app.buttons.matching(NSPredicate(format: "identifier IN %@", ["home.drawer.open", "chat.menu"])).firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 15)) - menu.tap() - let row = app.buttons["menu.workflows"] - XCTAssertTrue(row.waitForExistence(timeout: 8), "☰ lists Workflows after Kanban on a host that has them") - row.tap() + // Work's Workflows door, on a host that has them. + openWorkDoor("workflows", in: app) XCTAssertTrue(element("workflows.home", app).waitForExistence(timeout: 8)) XCTAssertTrue(app.buttons["workflows.waiting.run-14"].waitForExistence(timeout: 8)) } diff --git a/BighelpUITests/WorkspaceNavigationUITestSupport.swift b/BighelpUITests/WorkspaceNavigationUITestSupport.swift index 4b8f01cd..5ff95ea7 100644 --- a/BighelpUITests/WorkspaceNavigationUITestSupport.swift +++ b/BighelpUITests/WorkspaceNavigationUITestSupport.swift @@ -1,31 +1,198 @@ import XCTest +/// The one home's doors: three tabs (Bots or Chats, Today, Work) with New chat beside the bar, +/// Settings behind the person's circle, and every chat, bot page and door a pushed page with Back. extension BighelpUITestCase { + // MARK: The one home + + /// Leaves whatever covers the home (Settings, a chat, a bot page, a pushed page) until the bar shows. + @MainActor + func returnToHome(in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + let newChat = app.buttons["home.new-chat"].firstMatch + let deadline = Date.now.addingTimeInterval(timeout) + while !(newChat.exists && newChat.isHittable), Date.now < deadline { + if !stepBackTowardHome(in: app) { _ = newChat.waitForExistence(timeout: 1) } + } + XCTAssertTrue(newChat.exists && newChat.isHittable, "The home's bar must show", file: file, line: line) + } + + /// One step back toward the home: closes Settings or taps the Back of what is on top. False when + /// nothing could be tapped. + @MainActor + private func stepBackTowardHome(in app: XCUIApplication) -> Bool { + if app.buttons["settings.done"].firstMatch.exists { + leaveSettings(in: app) + return true + } + for identifier in ["chat.back", "simple-bots.profile.back", "today.board-page.back"] { + let back = app.buttons[identifier].firstMatch + if back.exists, back.isHittable { back.tap(); return true } + } + // A door's page or Sessions has the system Back, top left. + let back = app.navigationBars.buttons.firstMatch + if back.exists, back.isHittable, back.frame.minX < 60 { back.tap(); return true } + return false + } + + /// Opens one of the home's three tabs, "conversations", "today" or "work" (`home.tab.`). + @MainActor + func openHomeTab(_ tab: String, in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + let button = app.buttons["home.tab.\(tab)"].firstMatch + if !(button.exists && button.isHittable) { returnToHome(in: app, timeout: timeout, file: file, line: line) } + XCTAssertTrue(button.waitForExistence(timeout: 5) && button.isHittable, "Missing home.tab.\(tab)", + file: file, line: line) + guard button.exists else { return } + button.tap() + } + + /// The first tab on its Bots view (`simple-bots.home`). + @MainActor + func showBots(in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + showConversations("bots", root: "simple-bots.home", in: app, timeout: timeout, file: file, line: line) + } + + /// The first tab on its Chats view (`chats.inbox`). + @MainActor + func showChats(in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + showConversations("chats", root: "chats.inbox", in: app, timeout: timeout, file: file, line: line) + } + + @MainActor + private func showConversations(_ view: String, root: String, in app: XCUIApplication, timeout: TimeInterval, + file: StaticString, line: UInt) { + openHomeTab("conversations", in: app, timeout: timeout, file: file, line: line) + let screen = app.descendants(matching: .any)[root].firstMatch + if !screen.waitForExistence(timeout: 2) { + let toggle = app.buttons["home.switch.\(view)"].firstMatch + if toggle.waitForExistence(timeout: 5) { toggle.tap() } + } + XCTAssertTrue(screen.waitForExistence(timeout: timeout), "The first tab shows \(view)", file: file, line: line) + } + + /// Today's Feed, Ideas and Goals panel on one board: "feed", "ideas" or "goals". + @MainActor + func openTodayPanel(_ kind: String, in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + openHomeTab("today", in: app, timeout: timeout, file: file, line: line) + let picker = app.descendants(matching: .any)["today.boards.kind"].firstMatch + let home = app.descendants(matching: .any)["today.home"].firstMatch + XCTAssertTrue(picker.waitForExistence(timeout: timeout), "Today has its boards panel", file: file, line: line) + for _ in 0..<4 where !picker.isHittable { home.swipeUp() } + let titles = ["feed": "Feed", "ideas": "Ideas", "goals": "Goals"] + let segment = picker.buttons[titles[kind] ?? kind].firstMatch + XCTAssertTrue(segment.waitForExistence(timeout: 5), "The panel has \(kind)", file: file, line: line) + if segment.exists, !segment.isSelected { segment.tap() } + } + + /// Today › the panel's board ("feed", "ideas" or "goals") › See all: the whole board (`today.board-page`). + @MainActor + func openTodayBoard(_ kind: String, in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + openTodayPanel(kind, in: app, timeout: timeout, file: file, line: line) + // See all shows once the board has something on it. + let seeAll = app.buttons["today.boards.see-all"].firstMatch + let home = app.descendants(matching: .any)["today.home"].firstMatch + _ = seeAll.waitForExistence(timeout: timeout) + for _ in 0..<4 where seeAll.exists && !seeAll.isHittable { home.swipeUp() } + XCTAssertTrue(seeAll.exists && seeAll.isHittable, "\(kind) has See all", file: file, line: line) + guard seeAll.exists else { return } + seeAll.tap() + XCTAssertTrue(app.descendants(matching: .any)["today.board-page"].firstMatch.waitForExistence(timeout: 10), + "See all opens the board", file: file, line: line) + } + + /// Work › one of its doors: "projects", "tasks" (Kanban), "workflows" or "schedules". + @MainActor + func openWorkDoor(_ door: String, in app: XCUIApplication, timeout: TimeInterval = 20, + file: StaticString = #filePath, line: UInt = #line) { + openHomeTab("work", in: app, timeout: timeout, file: file, line: line) + let screen = app.descendants(matching: .any)["work.screen"].firstMatch + XCTAssertTrue(screen.waitForExistence(timeout: timeout), "Work opens", file: file, line: line) + let button = app.buttons["work.door.\(door)"].firstMatch + for _ in 0..<6 where !(button.exists && button.isHittable) { screen.swipeUp() } + XCTAssertTrue(button.exists && button.isHittable, "Work has the \(door) door", file: file, line: line) + guard button.exists else { return } + button.tap() + } + + /// The bar's New chat, then `new-chat.bot.`: a new chat with that bot in its To row. + @MainActor + func startNewChat(with botID: String, in app: XCUIApplication, + file: StaticString = #filePath, line: UInt = #line) { + returnToHome(in: app, file: file, line: line) + app.buttons["home.new-chat"].firstMatch.tap() + XCTAssertTrue(app.descendants(matching: .any)["new-chat.to"].firstMatch.waitForExistence(timeout: 15), + "New chat has its To row", file: file, line: line) + let bot = app.buttons["new-chat.bot.\(botID)"].firstMatch + XCTAssertTrue(bot.waitForExistence(timeout: 10), "New chat lists \(botID)", file: file, line: line) + guard bot.exists else { return } + bot.tap() + XCTAssertTrue(app.descendants(matching: .any)["new-chat.to.chip.\(botID)"].firstMatch.waitForExistence(timeout: 10), + "\(botID) is in the To row", file: file, line: line) + } + + /// A chat on the computer in use in the Chats list, by its session ID (`chats.row.here/`; + /// the old Sessions list's `session.row.`). + @MainActor + func chatRow(_ sessionID: String, in app: XCUIApplication) -> XCUIElement { + app.buttons["chats.row.here/\(sessionID)"].firstMatch + } + + /// Leaves a pushed chat by its Back (`chat.back`). + @MainActor + func goBackFromChat(in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { + let back = app.buttons["chat.back"].firstMatch + XCTAssertTrue(back.waitForExistence(timeout: 10), "The chat has Back", file: file, line: line) + guard back.exists else { return } + back.tap() + } + + /// The open chat's bot pill (`chat.identity`) opens the bot's page (`simple-bots.profile`). + @MainActor + func openBotPage(fromChatIn app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { + let identity = app.buttons["chat.identity"].firstMatch + XCTAssertTrue(identity.waitForExistence(timeout: 10), "The chat names its bot", file: file, line: line) + guard identity.exists else { return } + identity.tap() + XCTAssertTrue(app.descendants(matching: .any)["simple-bots.profile"].firstMatch.waitForExistence(timeout: 10), + "The pill opens the bot's page", file: file, line: line) + } + + // MARK: Old names, new doors + + /// An old ☰ destination by its row (`menu.chats`, `menu.agents`, `menu.scheduled-tasks`, + /// `menu.kanban`, `menu.workflows`, `menu.projects`, `menu.feed|ideas|goals`, `menu.settings`) + /// through the one home. Files (`menu.files`) lives on each bot's page now and has no door here. @MainActor func openRootDestination(_ destination: String, sidebarIdentifier: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { - // iPad and iPhone share ☰; there's no always-open sidebar. openSidebarDestination(sidebarIdentifier, in: app, file: file, line: line) } + /// The Bots view of the first tab, where the Agents screen's bots are now. @MainActor func openAgents(in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { - openRootTab("tab.agents", in: app, timeout: 10, file: file, line: line) - XCTAssertTrue(app.descendants(matching: .any)["agents.screen"].firstMatch.waitForExistence(timeout: 5), - "Agents must remain reachable through the current native navigation.", - file: file, line: line) + showBots(in: app, timeout: 10, file: file, line: line) } + /// Settings, a sheet from the person's circle (`simple-bots.settings`) on each of the three tabs. @MainActor func openSettings(in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { // Already open: Settings is a sheet over the screen it was opened from. if app.descendants(matching: .any)["settings.screen"].firstMatch.waitForExistence(timeout: 1) { return } - // Settings sits in ☰ on iPhone and iPad. - openRootTab("tab.profile", in: app, timeout: 10, file: file, line: line) + let circle = app.buttons["simple-bots.settings"].firstMatch + if !(circle.exists && circle.isHittable) { returnToHome(in: app, file: file, line: line) } + XCTAssertTrue(circle.waitForExistence(timeout: 10), "The circle is on the home", file: file, line: line) + guard circle.exists else { return } + circle.tap() XCTAssertTrue(app.descendants(matching: .any)["settings.screen"].firstMatch.waitForExistence(timeout: 5), - "The Settings destination must open through ☰.", file: file, line: line) + "The circle opens Settings.", file: file, line: line) } /// Settings › Connections, then one of its rows: Device access (`settings.connections.device-access`) @@ -117,43 +284,35 @@ extension BighelpUITestCase { if done.exists, done.isHittable { done.tap() } } + /// There is no ☰ any more: a chat's places are the home's, so this leaves the chat for the home. @MainActor func openChatWorkspaceMenu(in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { - // A chat's ☰ is the one menu, top left in its header. - let menu = app.buttons["home.drawer.open"].firstMatch - XCTAssertTrue(menu.waitForExistence(timeout: 8), "The chat header must expose ☰.", file: file, line: line) - guard menu.exists else { return } - menu.tap() + returnToHome(in: app, file: file, line: line) } + /// An old ☰ row (`menu.`) through the one home's door for that place. @MainActor func openSidebarDestination(_ identifier: String, in app: XCUIApplication, file: StaticString = #filePath, line: UInt = #line) { - let destinations = app.buttons.matching(identifier: identifier) - // A persistent iPad sidebar already exposes the same destination. - if !destinations.allElementsBoundByIndex.contains(where: \.isHittable) { - let rootMenu = app.buttons["home.drawer.open"].firstMatch - let chatOptions = app.buttons["chat.options"].firstMatch - let nestedMenu = app.buttons["workspace.menu"].firstMatch - if !(rootMenu.exists && rootMenu.isHittable) && chatOptions.exists && chatOptions.isHittable { - openChatWorkspaceMenu(in: app, file: file, line: line) + let doors = ["menu.scheduled-tasks": "schedules", "menu.kanban": "tasks", + "menu.workflows": "workflows", "menu.projects": "projects"] + let boards = ["menu.feed": "feed", "menu.ideas": "ideas", "menu.goals": "goals"] + switch identifier { + case "menu.chats", "menu.sessions": showChats(in: app, file: file, line: line) + case "menu.agents": showBots(in: app, file: file, line: line) + case "menu.settings": openSettings(in: app, file: file, line: line) + case "menu.new-chat": + returnToHome(in: app, file: file, line: line) + app.buttons["home.new-chat"].firstMatch.tap() + default: + if let door = doors[identifier] { + openWorkDoor(door, in: app, file: file, line: line) + } else if let board = boards[identifier] { + openTodayPanel(board, in: app, file: file, line: line) } else { - let menu = rootMenu.exists && rootMenu.isHittable ? rootMenu : nestedMenu - XCTAssertTrue(menu.waitForExistence(timeout: 8), "The visible screen must expose its sidebar.", - file: file, line: line) - guard menu.exists else { return } - menu.tap() + XCTFail("\(identifier) has no place in the one home", file: file, line: line) } } - let nativeMenu = app.descendants(matching: .any)["navigation.menu"].firstMatch - for _ in 0..<8 where !destinations.allElementsBoundByIndex.contains(where: \.isHittable) { - if nativeMenu.exists { nativeMenu.swipeUp() } - } - let destination = destinations.allElementsBoundByIndex.first(where: \.isHittable) - XCTAssertNotNil(destination, "Sidebar destination must be reachable: \(identifier)", - file: file, line: line) - guard let destination else { return } - destination.tap() } } diff --git a/DESIGN.md b/DESIGN.md index ba66b36a..e8f47e17 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -3,7 +3,7 @@ ## Authority and scope The current authority is the **Noodle brand kit** (`BighelpBrand`, the Ember palette) and its blended direction: -1a "Messages, evolved" structure, in the **Ink** look Bots mode started (#622): white by day, black at night, ink +1a "Messages, evolved" structure, in the **Ink** look the Bots view started (#622): white by day, black at night, ink controls in the person's own color. Cream ("Center stage") and Graphite ("After dark") stay as page choices. The app is a simple messaging experience for personal assistant agents. Earlier bighelp/iOS 27 Builder references are historical (`docs/ui-v3-design.md`). @@ -27,7 +27,7 @@ are historical (`docs/ui-v3-design.md`). lowercase b and kicks out at the bottom left as a chat-bubble tail. It appears in chrome (root nav bars, icon, setup) and as the app's loaders, never as a chat participant and never in an agent color. In the wordmark the mark stands in for the b, then "ighelp" in the kit's outlined Nunito: ink by day, cream after dark. See **Noodle** below. -- **Ink** is the default look, the one Bots mode always had: Classic's Paper page (#FFFFFF) by day and Black at night, +- **Ink** is the default look, the one the Bots view always had: Classic's Paper page (#FFFFFF) by day and Black at night, black bubbles by day (dark gray #3A3A3F after dark), and buttons and tinted text in the page's ink. Its switches are green, since an ink switch would be white on white after dark. Every control that acts (New chat, the selected tab, buttons, chips, row icons) takes the color picked in Appearance (`theme.action` and @@ -76,12 +76,12 @@ are historical (`docs/ui-v3-design.md`). talking, happy, sleeping) plus extra moves for its current work. The look is saved as the agent's avatar picture. - Every surface draws an agent's face in one order (`AgentFace`): its kit character, its petdex pet, its Hermes face or shape (the look Hermes keeps in its profile, drawn live and played with the avatar designer's states), its - Bots mode mark, then its picture. Each agent's pet companion is that same face (`AgentPet`); Settings › Appearance › + mark, then its picture. Each agent's pet companion is that same face (`AgentPet`); Settings › Appearance › Companion pet holds only Show pet companion, Pet size and Adventurous Pet. - Menu and Settings icons are bighelp's own line glyphs (`Design/Glyphs`, `BighelpGlyph`): a 24-pt grid, round 2-pt strokes and the brand's dot, with agents drawn as the orb with two eyes. Call sites still name SF Symbols; ones without a glyph fall back to the symbol. Edit `glyphs.py`, then run `export_assets.py`. -- Product type is SF Pro. Root screens use large titles; section captions are small, bold, letterspaced and muted. +- Product type is SF Pro. Root screens put a bold title (Today, Work) or the Bots | Chats switch in the home header; section captions are small, bold, letterspaced and muted. - The message box: + beside it, and one pill inside it at its end: voice mode (a waveform) while it's empty, Send once there's text, Stop while the agent works. No other microphone button. Once a draft has three lines, a small, quiet rail shows centered above the box: the expand icon and "Expand", in a glass pill @@ -102,8 +102,8 @@ are historical (`docs/ui-v3-design.md`). editable, an app-owned box of what to check (Missing, Check, Guess, You changed beside each field), where it goes (iOS's own pop-up menu of accounts or calendars, or the default one until bighelp may list them), anything already saved that looks like it (read only), and Discard and Save in the bar. The agent's review note sits at the top as - its quote. After a decision the same card says what happened. Each agent's Photo actions page (beside its - Instructions in Agent Studio, in What it can use on a bot's profile) sets the offer, how to read each kind, the question for unclear pictures and the review messages, + its quote. After a decision the same card says what happened. Each agent's Photo actions page (in What it can use on a + bot's profile) sets the offer, how to read each kind, the question for unclear pictures and the review messages, with Preview and Reset to defaults ([Image drafts](docs/IMAGE_DRAFTS.md)). - Agents' apps: an app an agent made is a card in the chat, never its page: an icon tile in the action color, the title, the agent's description, small "Sends answers" and "Live data" tags, and a full-width Open App. Open App @@ -118,35 +118,71 @@ are historical (`docs/ui-v3-design.md`). ## Navigation and simplicity -iPhone is an agent home. The bottom bar is **Chat, Feed, New chat, Ideas, Goals**, all for the selected agent; Files -(the Apps page) is in ☰. It is always open and names each tab under its icon; the current one is a pill in the -picked color. New chat is a round button in the middle, in the picked color, on every place the bar holds: a tap -starts a chat with the agent in use, touch and hold (right-click on the Mac) picks agents, one for a 1:1 chat or -several for a group. The bar holds Chat and three places (Appearance › App layout). In a chat, Chat is the lit tab and tapping it does nothing. -With Sessions in the bar (App layout), every chat's list and a chat picked from it light Sessions instead, and -Chat there opens the agent's own chat. A tab keeps its place: leave a chat for another place and the tab it was -under (Chat, or Sessions for a chat picked from its list) opens that chat again (`HeldChat`), until another chat -opens. Once another agent is in use, Chat opens that agent's chat instead. -Chat opens that agent's canonical Bot Chat (the same conversation as Hermes Desktop's bot entry) with its live avatar big at the top: tap the avatar for its profile (This chat's -model and reasoning, then Activity, Approvals, Schedules, Identity), tap the name to switch agents or open a group -chat, and ☰ for everything else. ☰'s first screen fits without -scrolling: the host as one switcher row on top, then New chat (Group beside it), Agents, Sessions (every chat), Projects, Kanban, Workflows -(where the computer's plugin has them or says why it can't run them; with All hosts on it asks which computer), -Scheduled tasks, Usage and Settings, then Recent chats with See all. Advanced options' Folder sits under More at the -bottom; the credential vault is in Settings › Apps & skills, with the apps and Device access. -Keep it that short: a new destination goes where people already look, not on the first screen. Headers keep their -own New chat only where there's no bar to hold it: Code mode, the iPhone Duo's side strip, Vision Pro's tab -ornament, and a board opened with Back. The chat list (and the all-hosts view's All sessions) searches from the system -glass search bar along the bottom, like All agents; it matches titles and previews, and a scroll puts the keyboard away. -A chat with something new since it was last read has a bold title and Bots mode's dot after its time, and a chat -whose message box holds an unsent message shows Draft before its preview. With Settings › Chat › Projects in the chat -list on (on by default, saved on each device), a chat in a project shows the project's name on a line of its own -under the preview, never beside it, so the preview stays whole at large text; a list grouped by project leaves it out. -The row's menu shows the chat's project beside Move to Project…, and the move sheet lists that project first, then -the rest by name. Projects sorts by Recently used or Name, saved on the device. Where the computer keeps read state, the -row's menu and leading swipe have Mark Read and Mark Unread. Feed, Ideas, Goals and Apps keep the Chat tab's header: ☰ and ⋯ (the agent's profile, -then Files, Memory, Skills & tools and Scheduled tasks). The root's edge-swipe zones -start below that row, so its corner buttons always get the tap. The avatar reacts to what the agent is doing (thinking, writing code, browsing, making +bighelp is one home with three places and no modes. The bottom bar is the same for everyone: **the first tab, Today and +Work**, with the round New chat button beside it. The first tab shows the Bots view or the Chats view and takes the name +of the person's default view; the header's Bots | Chats switch changes the view for this run. The bar is always open and +names each place under its icon; the current one is a pill in the picked color, and a dot on Today means something +needs you. New chat is a round button in the picked color. The bar shows on roots only and goes while the keyboard is +up: a pushed page, a chat included, has Back and no bar. The app opens on Settings › Chat › Opens on (Bots, Chats, +Today or Work), when it starts and not when it comes back, and a link, widget or notification that opens the app wins. +No chat opens by itself. + +Every root draws the same header and no navigation bar, so nothing moves between places: the person's circle at the +left, which opens Settings (iPhone has no menu and no sidebar); in the middle the Bots | Chats switch, or the title +(Today, Work); at the right search, the computer menu (Today and Work, with two or more computers), the place's own +control (Today's Edit) and +. When the switch or the title doesn't fit beside the buttons (large text), it takes a row +of its own. The root's edge-swipe zones start below that row, so its corner buttons always get the tap. + +**Bots** is one row per bot and group chat (Bots view, below). **Chats** is every chat on every computer in one list, +newest first, Pinned on top, then Today, Yesterday and Earlier, with search over it and one row of chips: All, Unread +and, with two or more computers, one for each. Touch and hold a chat for Pin, Mark read or unread, Rename and +Archive; only the computer in use's chats pin or mark read, while another computer's rename and archive. A chat with +something new since it was last read has a bold title and a dot after its time, and a chat whose message box holds +an unsent message shows Draft before its preview. Chats › This computer opens that computer's own Sessions page: +its projects, imports from other apps and one bot's chats. There, with Settings › Chat › Projects in the chat list on +(on by default, saved on each device), a chat in a project shows the project's name on a line of its own under the +preview, never beside it, so the preview stays whole at large text; a list grouped by project leaves it out. The +row's menu shows the chat's project beside Move to Project…, and the move sheet lists that project first, then the +rest by name. Projects sorts by Recently used or Name, saved on the device. Where the computer keeps read state, the +row's menu and leading swipe have Mark Read and Mark Unread. + +**Today** is a grid of panels under the header: Needs you on top while something waits (a card with the count and the +first entry, which opens the Needs you deck), the Shared with bighelp card while a share waits, then the person's +panels in three sizes (Small, Wide, Tall), and a Make a space box below them that starts a chat with a bot to draft +one. One panel holds Feed, Ideas and Goals for every bot (See all opens a page with a chip for each bot); each space +is a panel of its own ([Spaces](docs/SPACES.md)). Edit turns the grid into a list where each panel is moved, hidden +and sized; hidden panels come back from there. **Work** is one list of what the bots are doing, each row from the +store that holds it: coding sessions, chats and background work running now, workflow runs, Kanban tasks and +scheduled tasks. Chips filter it: All, Needs you, Working, Done. Four doors lead on: Projects, Tasks (Kanban), +Workflows and Schedules, each only where the computer has it. Today and Work show the computer in use; with two or +more computers the header's computer menu switches it. A project's page is Work filtered to that project, with Back, +its name and ⋯ (pull requests, worktrees, Dev Factory). + +**New chat** is the new chat's own screen: the ordinary chat with a To row under Back and ⋯, where the bot's name +would be. Picked bots are chips, and a field filters the list of bots and group chats over the empty messages. One +bot is a chat, two to six are a group chat, and a group chat the person already has can be picked at the end of the +list. With nobody picked the message box is the primary bot's; picking another single bot makes it that bot's. For one +bot on a computer that can run coding sessions, one row under the message box scrolls sideways and never wraps: +Project (none is an ordinary chat), then, once a project is picked, where it runs (a new worktree or local), the +branch, the mode (Default, Plan, YOLO) and Stage. A project makes Send start a coding session, which Work lists; +Stage keeps the message as a job, and Send all starts the staged jobs as one batch. A group chat and a coding +session take text only, so + offers no attachments for them. The To row, the list and the choices row leave once the +first message is sent. + +A chat is a pushed page with one header: Back, the bot (its face and name; a tap opens its bot page) and ⋯. Tapping a +bot on the Bots view opens what Settings › Chat › A bot opens says: its ongoing Bot Chat (the same conversation as +Hermes Desktop's bot entry), your last chat with it, or a new chat; Ask and Needs you open the Bot Chat. A group +chat's name opens its Group Settings (Chat Info for a group Hermes doesn't run). The line under the name says the +agent's activity while it works, and otherwise the chat's title when Settings › Chat › Chat title is on (off by +default; never "New chat" or "Bot Chat"). The bot page is the same for every bot from every door: a chat's header, +Bot Profile in a bot's menu, a bot chip on a Today board. + +iPad at regular width works the same way, with a sidebar behind a button in the header: it slides in from the +leading edge, and chats use the width of the screen. The sidebar lists the three places, Settings, New chat, recent +chats (See all opens Chats) and More: Needs you while something waits, Shared with bighelp while a share waits, and +Usage. The Mac and Vision Pro keep that sidebar open as a column beside the page. + +A bot's face reacts to what the agent is doing (thinking, writing code, browsing, making images…), driven by the running tool (`AgentActivityKind`, shared with the island as `BighelpActivityPose`). On phones with a Dynamic Island, the island names the work. In the app it grows into a stage (`AgentActivityIsland` + `IslandStage`): the name and the work beside the camera, and underneath, the pet acting @@ -155,24 +191,20 @@ planes…). The status bar hides while it shows, and the app moves down (root `a is covered. Tap for a compact pill, touch and hold to open the chat. Settings › Chat › Dynamic Island turns it off. Outside the app, one Live Activity holds the active chats as compact rows: title, agent and a fixed status icon. Chats needing attention come first. Each row opens its own chat; extra chats show as a count. -The expanded Dynamic Island shows three rows, while the compact island keeps a quiet work or attention symbol. Every phone chat uses this big-avatar header and keeps the tab bar under its message box (All -agents' chats excepted). Every chat has ☰ in the top left, like the other root screens; a chat opened from the -list, Agents, Feed or a task goes back to it with the edge swipe. A group chat's name opens its Group Settings (Chat Info for a group Hermes doesn't run). The line under -the name says the agent's activity while it works, and otherwise the -chat's title when Settings › Chat › Chat title is on (off by default; never "New chat" or "Bot Chat"). iPad works the same way, with no always-open sidebar: -☰ slides the menu in from the leading edge, and chats use the width of the screen. The iPhone Duo follows how it's -held (`BighelpScreenPosture`). Folded, the cover screen is wide and short, with the camera and status in a column on -its trailing edge: the bar's places go down that column as iOS's own toolbar items (`BighelpStripTabs`), under the -screen's own buttons (☰, the brand, a filter), which iOS moves there too, so chats get their height back, and in Bots and Code mode the column holds the chat switcher instead (`BighelpChatSwitcher`: the bots on top -of the home, or the running sessions, each with its live state; Settings › Modes › Chat switcher, on by default -there and opt-in on iPad and Mac in landscape). Open and held wide, the list (Bots mode's home, the chat list, or -Code's home) sits left of the fold and what it opens sits right of it, like a book (`BighelpSplitColumn`); nothing -crosses the fold. Held upright it's a big phone, never the cover screen's layout, and half-folded like a small -laptop a chat keeps its messages above the fold and its message box and keyboard below it. Half of the open screen -in iOS's Split View gets the cover screen's layout. On Vision Pro bighelp always -starts in its own window. The tabs sit in a strip beside the window (`VisionTabOrnament`), clear of the system's -move and close controls under it; ☰ opens the menu as a column inside the window and the page beside it narrows -(`VisionSideMenu`). Everything you look at and pinch is at least 56pt, and Appearance › Transparency sets how much +The expanded Dynamic Island shows three rows, while the compact island keeps a quiet work or attention symbol. + +The iPhone Duo follows how it's held (`BighelpScreenPosture`). Folded, the cover screen is wide and short, with the +camera and status in a column on its trailing edge: the places go down that column as iOS's own toolbar items +(`HomeStripTabs`), under the screen's own buttons, which iOS moves there too, so chats get their height back, and +a chat's column holds the chat switcher instead (`BighelpChatSwitcher`: the bots on top of the Bots view, or a coding +session's other sessions, each with its live state; Settings › Chat › Chat switcher, on by default there and opt-in on +iPad and Mac in landscape). Open and held wide, the first tab's list (the Bots view or the Chats view) sits left of the +fold and what it opens sits right of it, like a book (`BighelpSplitColumn`); nothing crosses the fold. Held upright +it's a big phone, never the cover screen's layout, and half-folded like a small laptop a chat keeps its messages +above the fold and its message box and keyboard below it. Half of the open screen in iOS's Split View gets the cover +screen's layout. On Vision Pro bighelp always starts in its own window. The three places sit in a strip beside the +window (`HomeTabOrnament`), clear of the system's move and close controls under it; the sidebar opens as a column +inside the window and the page beside it narrows. Everything you look at and pinch is at least 56pt, and Appearance › Transparency sets how much of the room shows through the window. Titles and toolbar buttons use the app's ink in light mode, since the system draws them white. The agent can also stand in the room as a 3D character in its own volume (Settings › In your space): kit characters are sculpted from their own art like vinyl toys, round bodies with faces laid on them @@ -180,7 +212,7 @@ space): kit characters are sculpted from their own art like vinyl toys, round bo It opens within reach; pinch it to make it hop, drag to turn it, and drag a corner of its volume to make it bigger or smaller. It wears the Agent Studio headwear and pattern and plays the chosen moves. The avatar designer shows the same 3D character beside its choices, with moods to try (listening, thinking, talking, happy, sleepy) -and See it in your room, which puts the look being designed into the room at full size. ☰ › More › Simple mode leaves just +and See it in your room, which puts the look being designed into the room at full size. The sidebar's More › Simple mode leaves just the agent, with Open bighelp under it to come back. The avatar never opens by itself. Widgets (`BighelpActivityShared`, rendered by the Live Activity extension) use the Colors picks through @@ -195,14 +227,14 @@ agent or board; tapping a card opens it in the app. **Feed**, **Ideas** and **Go agent picked in the widget or Auto (the agent picked in the app). The app reads only the boards widgets are set to (`BighelpWidgetBoardLoader`, a few agents at most) and the widget says so until it has. **Pinned Agents** is a grid of faces with names under them, like contacts: Current Gateway shows the computer in use's pinned agents, -Multi Gateway every computer's (All agents' pinned row), with a small computer name under each when they're on +Multi Gateway every computer's (the Bots view's pinned row), with a small computer name under each when they're on more than one. A tap opens that agent's canonical Bot Chat (`loopdy://agent-chat?agent=…&host=…`), switching -computers first like All agents. Pictures are copied per agent and computer (`BighelpPinnedAvatarStore`), and a +computers first, as the Bots view does. Pictures are copied per agent and computer (`BighelpPinnedAvatarStore`), and a computer called only by its address shows as "Computer 2". **Bots** shows one, two or four chosen bots (small, medium, large) on a chosen gateway, on the plain page color: each bot's face (a Simple Bot shape standing free, a photo in a circle, its default shape without a picture) over its name, and a tap opens its Bot Chat on that gateway. The app writes every gateway's bots and faces into the app group (`BighelpBotsWidgetFeed`, the computer in use live -and the others from All agents), so the widget keeps them with bighelp closed. **Usage** shows each plan's limits as +and the others from their all-hosts copies), so the widget keeps them with bighelp closed. **Usage** shows each plan's limits as the plugin reports them, for the gateway in use or a chosen one. Each size lists only its own styles: small (Ring, Two meters, What's left, Four plans, Closest to limit), medium (One plan, Every plan, Next resets, Side by side), large (Every plan, One plan), extra large (a column per plan), Cost and tokens in the first three, and the Lock @@ -213,11 +245,8 @@ provider's color shows in full color only; tinted, clear and Lock Screen looks d carry the meaning. It shows only what Hermes and the plugin report: no pace, no daily share of a limit, no API-rate value. On Vision Pro the same widgets sit on a wall or table as glass, without the Lock Screen sizes. -Apps: **Artifacts** lists what the agent made or changed lately, newest first, from one plugin request -(`files.recent`, plugin 2.15+): its `write_file`/`patch` history and deliveries plus new top-level files. It never -walks the whole workspace (a real one holds over a million files); older plugins get a shallow, bounded scan that -skips tooling folders and shows files as it goes. **Media** shows the pictures and videos the agent sent or -generated (`attachments.recent`), then pictures from its posts; tap one for the native preview. +**Media** (a bot page's tab) shows the pictures and videos the agent sent or generated (`attachments.recent`), then +pictures from its posts; tap one for the native preview. The app icon badge means "something arrived while you were away": pushes set it, opening bighelp clears it (`BighelpAppBadge`). The app never sets a count of its own, so it can't get stuck on items the user can't see. @@ -306,18 +335,18 @@ category with a +, which starts a chat asking the agent to plan a goal in that c category's blueprints). Goals carry the category in the plugin (`native-agent-board-goal-categories-v1`); without it every goal shows under Other and the page says to update the plugin. -**Projects** (☰ › Projects) are Hermes projects shown the way Claude shows them: cards with the project's emoji +**Projects** (Work › Projects) are Hermes projects shown the way Claude shows them: cards with the project's emoji and color, description and recent use; a project page with **New chat in this project**, its chats and its folders. A chat started there runs in the project's folder (Hermes files chats by folder, and the project becomes the current one). With Advanced options on, a project's ⋯ menu has Folders and Git for the folder and Git pages. -**Usage** (☰ › Usage, above Settings) is the one place for what the agents use. Limits come first: each plan, +**Usage** (the first group of Settings, and the sidebar's More) is the one place for what the agents use. Limits come first: each plan, limit and balance the plugin finds (Choose hides one), with what the agents used through it in the range. With -several computers (All hosts on) a menu beside Choose shows the computer in use, another one, or All computers, where +several computers (Show every computer on) a menu beside Choose shows the computer in use, another one, or All computers, where each computer's plans sit under its own name; it changes only Limits and is remembered on the device. Then 7, 30 or 90 days of Hermes' own numbers (`/api/analytics/usage` and `/api/analytics/models`, per agent): estimated cost or processed tokens per day as bars (tap one for its day), totals with the cache rate, when you use it (weekdays, and -hours with the plugin's `usage/activity`), and ranked rows by model, by agent and, with All hosts on, by computer. +hours with the plugin's `usage/activity`), and ranked rows by model, by agent and, with Show every computer on, by computer. Tap a row to chart it against everything else. Chat ⋯ › Usage › Usage and the context window open the same page; there is no overlay or Settings copy. Subscriptions report no cost, so a host where nothing cost money opens on Tokens. Share (top right, beside Refresh) sends the page as a PDF (paged, never cutting a card in two), a PNG (one tall @@ -325,7 +354,7 @@ picture), a web page (one file, inline styles and SVG charts, nothing loaded) or numbers: days, models, agents, computers, totals, limits), always light, in the range, Cost or Tokens and Limits computers on screen, with every row listed and the date range and time it was made at the top. -**Kanban** (☰ › Kanban, above Scheduled tasks) is Hermes' Kanban plugin, shown only when the host has it. Five lanes +**Kanban** (Work › Tasks) is Hermes' Kanban plugin, shown only when the host has it. Five lanes in plain words: Later (triage, to-do, scheduled), Ready (an agent picks these up next), Working (only Hermes starts work, so nothing is dropped here), Needs you (blocked or waiting for review) and Done. Cards show who has them with their avatar, a pulse while they work, and why they need you ("Has a question", "Ready for review", "Got stuck"). @@ -337,11 +366,10 @@ the AI provider. On iPhone the board opens on Needs you as one lane at a time; i the board in its own glass window beside bighelp: look at a card, pinch and drag it, and it lifts toward you while the lane under it lights up. -**Workflows** (☰ › Workflows, after Kanban) are the bighelp plugin's: stages that agents run one at a time on the -computer, with your sign-off at the end. The row shows when the computer's plugin has them (`native-workflows-v1`) +**Workflows** (Work › Workflows) are the bighelp plugin's: stages that agents run one at a time on the +computer, with your sign-off at the end. The door shows when the computer's plugin has them (`native-workflows-v1`) or lists them under `unavailable` with a reason; then the screen says in plain words why this computer can't run -them and what to do, never the code. Plugins with neither keep the row hidden. With All hosts on the row asks which -computer first, then opens that one's Workflows. An older plugin gets "Update the bighelp plugin to use Workflows". +them and what to do, never the code. Plugins with neither keep the door hidden. An older plugin gets "Update the bighelp plugin to use Workflows". Home leads with the service line, then Waiting for you (Review or Later), Active runs (All runs), Your workflows (pinned first; Run, or Set up while a role has no agent) and Templates: Create from scratch on top, then Built-in and Yours. Touch and hold a workflow for Open, Run, Pin or Unpin, Save as template and Archive; Archived workflows @@ -377,24 +405,22 @@ the top bar stays on one line. Token counts, attempts, full fingerprints, the se are Advanced options only, and runs on Hermes' fallback runner (which can't count tokens) show none rather than 0. Stage chats (source `workflow`) stay out of Sessions, recents and widgets. -**All hosts** (the stack button beside ☰'s host switcher) turns home into one list of every agent on every -host, like Messages: pinned agents up top as big pictures with their name and role (no host name; touch and hold -to drag them into a new order, kept on this device across hosts), host filter chips, then each agent with its host's -name, its role and its latest chat, newest first. One big round New chat sits bottom right, above the search bar, -where a thumb rests. A tap opens that agent's canonical Bot Chat (☰ top left, the edge swipe goes back); if it's on another host, the app switches hosts -first while the list stays up. ☰'s recent chats, All chats and Scheduled tasks then list every host's, each with -its host's name. Screens that belong to one host (Settings, Agents, Projects, Kanban, Workflows, the credential -vault, the folder, New group) ask which host first; Usage instead adds up every host, with a row for each; Settings' Your computers group also has **Update every computer** (with two or more), one page -for every host: Update Hermes (each host's commits behind), Update bighelp Plugin (each host's version → the new -one) and Restart Hermes Gateway, all at once with each host's live status and its own Restart when it needs one. -Each host runs the same flows as its own computer page (`HostOperationsStore`, `HostPluginUpdateModel`); hosts that -are offline or signed out say so and are skipped (`Bighelp/Fleet/FleetMaintenance.swift`). The tab bar hides, ☰ › All agents is home, and the button in the list's top bar -turns it off. Other hosts are read at most once a minute over their own saved sign-ins (`Bighelp/Fleet`); one -that can't be reached says so and keeps showing what it had last time. While it's on and the app is open, every -host stays connected, so a switch opens the agent's chat at once from the copy saved on the phone while that -host's details finish loading. - -Group chats (Hermes hosted rooms / Bot Mode) live in the switcher, ☰ and Agents. A group's **Group Settings** +**Show every computer** (Settings › Your computers, on until turned off) puts every computer's bots and chats in the +Bots view, the Chats view and New chat's list of bots, like Messages with several accounts: each chat says which +computer it is on, and the Chats view's chips filter by computer. A tap on another computer's bot or chat makes that +computer the one in use first, while the list stays up (the Bots view shows the Noodle loader, with Cancel, until the +bot opens). Today and Work show the computer in use, and their header's computer menu switches it. Usage instead adds +up every host, with a row for each. Settings' Your computers group also has **Update every computer** (with two or +more), one page for every host: Update Hermes (each host's commits behind), Update bighelp Plugin (each host's +version → the new one) and Restart Hermes Gateway, all at once with each host's live status and its own Restart when +it needs one. Each host runs the same flows as its own computer page (`HostOperationsStore`, +`HostPluginUpdateModel`); hosts that are offline or signed out say so and are skipped +(`Bighelp/Fleet/FleetMaintenance.swift`). Other hosts are read at most once a minute over their own saved sign-ins +(`Bighelp/Fleet`); one that can't be reached says so and keeps showing what it had last time. While it's on and the +app is open, every host stays connected, so a switch opens the agent's chat at once from the copy saved on the phone +while that host's details finish loading. + +Group chats (Hermes hosted rooms / Bot Mode) live in the Bots view and the Chats view. A group's **Group Settings** (`GroupSettingsView`, a pushed page any screen can open: `AppRoute.groupSettings`) shows its name and "3 bots", its members' faces with a small Lead badge on the lead, then, where Hermes keeps settings for the room (`groups.state` has `context`): WHEN A MESSAGE NAMES NOBODY, three radio rows with a hint each (Everyone answers; @@ -406,14 +432,12 @@ group Hermes doesn't run shows only its name and members. New Group Chat offers In the chat, Hermes' picks are one quiet centered line ("Pixel gave this to Scout", "Assigned to Scout and Echo", "Couldn’t choose who answers, so everyone will"), the header says "Lead: Pixel" under the name, and a discussion Hermes paused at its cap is a small card ("Paused after 10 messages.") with Continue and Stop until -something moves it on or it has used every Continue. Agents opens on the -**Pinned** agents: each shows its role under the name (one line, trailing off), or what it's doing when it's busy. -Touch and hold lifts an agent: drag it to reorder (the order is kept per host), or let go to see its actions. +something moves it on or it has used every Continue. -**Settings** is one short list where every row opens one page, and it is the same tree in every mode (Bots mode's -circle opens it too, with no Settings of its own). The first screen has you (name and photo), Usage and, while a +**Settings** is one short list where every row opens one page, and the person's circle in every root's header opens +it. The first screen has you (name and photo), Usage and, while a share waits, Shared with bighelp; **Your bots** (Models, Apps & skills, Voice, Personality and the Teamwork -switch); **This app** (Appearance, Chat, Notifications, Modes); on Vision Pro, In your space; **Your computers** +switch); **This app** (Appearance, Chat, Notifications); on Vision Pro, In your space; **Your computers** (one row per computer, Add a computer, Show every computer, Time zone and, with two or more computers, Update every computer); then Help & feedback and the Advanced options switch. Don't add sections that compete with these; add to the page a row already opens (Help & feedback also holds Share usage and diagnostics, on by default, and @@ -421,18 +445,16 @@ the Apple Watch's status). Settings › Models is the AI providers first, then **Default model** with one row per bot (its face, its name and its model under it); a row opens that bot's own Default Model page, the one its profile opens. Advanced comes last. Settings › Chat reads in named groups: **Opening**, **A bot's work**, **In a chat** and **Chat list**, then the -Advanced groups. Opening has Opens on (Agents, Agents (multi), Last chat, Feed, Ideas, Goals, -Kanban, Projects; Last chat, the agent's latest chat, until you pick), Start with (Last bot used, or one of this -computer's agents, kept per computer; Agents (multi) has none) and A bot opens. It applies when the app starts, -not when it comes back; a link, widget or notification that opens the app wins, and Kanban or Projects where the -computer can't open them fall back to Last chat (`BighelpLanding`). +Advanced groups. Opening has Opens on (Bots, Chats, Today, Work; Chats until you pick), First tab shows (Bots or Chats, only +when Opens on is Today or Work) and A bot opens (Its ongoing chat, Your last chat, A new chat). It applies when the +app starts, not when it comes back; a link, widget or notification that opens the app wins. **Apps & skills** (Settings › Your bots) is for everyone: This device (Device access) first, then Apps (Built-in apps and Composio), Skills and plugins (with this week's featured plugin, the pick Hermes' marketplace and Desktop show), Talk anywhere (Messaging apps) and Logins (the credential vault); with Advanced options on, an Advanced group adds MCP servers and Toolsets. Each bot's profile has its own **Marketplace** with the same pages for that bot, and its own Connections. A bot's profile also lists **Core Files** (SOUL.md, USER.md, MEMORY.md and the AGENTS.md Hermes loads for its chat, each opening in the Markdown viewer to read or edit) and **Active Project** (the project its new -chats start in, a checked list; also in Bots mode, where ☰ › Projects isn't). Host administration is hidden until +chats start in, a checked list). Host administration is hidden until **Advanced options** is on, and each part sits on the page it tunes: a computer's page, Chat, Models, Apps & skills and a bot's Advanced Options. There is no Hermes tools list and no System page. Pages lead with the action people come for (`BighelpActionRow`) and keep explanations to one line. **Your computers** lists each computer (the one in use @@ -447,21 +469,20 @@ inside everyday screens: the chat Info sheet's visibility toggles and host detai Skills/Session rows in the + sheet, Agent Studio's Advanced page and templates, the task editor/detail Advanced groups, and the extra sections on Settings › Chat. Everyday controls must never live only behind it. -The chat's ⋯ menu is one list, the same with Advanced options on or off: New Bot Chat in an agent's Bot Chat (Switch agent -in the home chat); then This chat (a group chat's Group Settings and Chat info, where its members are, Rename…, Move to Project… with -the chat's project, Files, and File changes when available); then Model (Model & speed, Usage); then More (Edit -agent, Advanced). Model & speed contains Model settings and Fast Mode. Usage contains provider usage, Context +The chat's ⋯ menu is one list, the same with Advanced options on or off: New Bot Chat in an agent's Bot Chat; then This chat (a group chat's Group Settings and Chat info, where its members are, Rename…, Move to Project… with +the chat's project, Files, and File changes when available); then Model (Model & speed, Usage); then More (Bot +page, Advanced). Model & speed contains Model settings and Fast Mode. Usage contains provider usage, Context window and Compact. Existing technical controls stay in Advanced. The groups have lines between them, not titles: iOS keeps a menu under about 60% of the screen's height, and titles made the list scroll. Keep every level short enough to navigate without scrolling, File changes included (`CompactChatMenuUITests`). iOS draws the menu at the device's text size, not bighelp's, and the whole list fits at the default size; from the device's XL, keep the full font size and fold the top level into Model (Model & speed), This chat (Rename…, Move…, Files; a group's Chat -info), Agent (New Bot Chat, Switch agent, Edit agent) and More (File changes, Usage and Advanced). At accessibility +info), Agent (New Bot Chat, Bot page) and More (File changes, Usage and Advanced). At accessibility sizes, Advanced also groups its visibility switches under Display, and secondary summaries are left out and labels shortened. -Move to Project… (`MoveChatToProjectSheet`) also sits in a chat's hold menu in Chats and a pinned chat's -right-click menu on the Mac, wherever the computer can move chats (`sessionWorkspaceEdit`). It lists the agent's +Move to Project… (`MoveChatToProjectSheet`) also sits in a chat's hold menu on a computer's Sessions page, +wherever the computer can move chats (`sessionWorkspaceEdit`). It lists the agent's projects with a tick on the chat's own, and moves the chat only once Hermes confirms it; then Chats, the open chat and File changes show the new project. Chats have no backgrounds of their own: Settings › Appearance sets the look of every screen. @@ -471,11 +492,11 @@ selected agent's default for new chats. Fast Mode may cost more. Read the host's unknown modes stay labeled as host-managed. A model/provider without verified support shows Unavailable and a reason, not an effective On switch. A running reply locks chat speed changes just like model and reasoning. -Agent entries (including Agents → Message and All hosts) use the canonical Bot Chat resolver. New chat still +Agent entries (including the Bots view and Show every computer) use the canonical Bot Chat resolver. New chat still creates an ordinary conversation, and picking a saved chat still opens that exact conversation. A failed Bot Chat lookup offers a retry rather than silently falling back to an unrelated chat; stale navigation results are ignored. -A chat's model and thinking level (`ChatModelSummaryRow`) show in the avatar's profile, at the top of Info and at the top of +A chat's model and thinking level (`ChatModelSummaryRow`) show at the top of a chat's Info and at the top of the context pop-up, each with Change into Model settings. Showing them reads the level once, never while the agent is replying. Deleting an agent stops its reply and clears its unsent drafts on this device instead of refusing; only a group chat that includes it holds the delete back, by name. @@ -485,8 +506,7 @@ messages and answers other agents send in) are one quiet centered line in the ch (`ChatAgentTalkRail`): the agents' faces stacked, then "4 messages with Nova", "Asking Nova…" or, from the plugin's `agents/talk` feed, "Nova is searching the web…". Back-to-back messages share one line. It stays out of the finished-turn fold and shows with tool calls and reasoning hidden, because it's conversation. A tap -opens what they said as a short chat between them, with "What Nova did" from Nova's own chat. Simple Bot -mode draws the faces as marks. A `message_agent` message and its later answer are two lines, each where it +opens what they said as a short chat between them, with "What Nova did" from Nova's own chat. A `message_agent` message and its later answer are two lines, each where it happened: "Asked Nova" and "Nova answered"; the delivery notice that only repeats the answer stays out. Hermes runs some turns on its own (another agent wrote in, a background process finished), and other Hermes processes write some messages, so neither streams here: the chat reads what Hermes saved when such a turn ends, and while @@ -568,14 +588,15 @@ Long instructions (an agent's SOUL, a personality) have an expand icon that open form. Present that editor from the form's root: a full-screen cover hung on a list section header never got the keyboard. -## Bots mode +## Bots view -An opt-in calm home (Settings › Modes › Bots mode): just your bots and their chats. No tab bar -and no ☰. The page is the light and dark theme picked in Appearance, your bubbles are black (ink after dark) unless you -picked a bubble color in Appearance, and buttons and tinted text are the page's ink (white after dark). The -text is SF Pro, as everywhere. +The first tab's calm view: just your bots and their chats (the default for people who pick "With a bot" at first run; +the header's switch moves between it and Chats). The page is the light and dark theme picked in Appearance, your +bubbles are black (ink after dark) unless you picked a bubble color in Appearance, and buttons and tinted text are the +page's ink (white after dark). The text is SF Pro, as everywhere. -- **Home**: your circle top left opens Settings; search and + top right. + is a short menu: New Bot, New Group +- **Home**: the home header (your circle top left, the Bots | Chats switch, then search, a round button that opens a + search page, and +). + is a short menu: New Bot, New Group Chat and New Section, each only where it can work (a computer that can't make group chats leaves New Group Chat out). The primary bot (no badge), pinned bots and pinned group chats (up to three of their members' faces) share the top, all the same size: one large, else two or three across, six at most in two rows. Only pins the top @@ -611,13 +632,12 @@ text is SF Pro, as everywhere. "On Home Mac and Studio Mac" when its members are on more than one computer), ⋯ (Rename, Edit Members, Delete Section), a big folder of faces, its members as home rows (their role line names the computer when the section spans several), then Add Bots or Group Chats. New Section and Edit Members are one sheet: the name, then every - bot and group chat with a check (by computer with Multi-gateway; "In Work", or "Moves from Work" once picked). + bot and group chat with a check (by computer with Show every computer; "In Work", or "Moves from Work" once picked). A bot is in one section at a time. Edit Sections (a card's menu, search's filter) renames, drags into order - and deletes; Done keeps it all, and Delete asks first and keeps every member, in No section. With Multi-gateway - a section holds any computer's bots and group chats; with it off (or one gateway filtered) a section shows only - that computer's members, and one with all its members elsewhere doesn't show. Bots' sections are Hermes - Desktop's own field, so Desktop shows them too; Chat mode's Agents screen shows the same cards under Pinned, and - Code mode's agent picker lists agents under their sections. + and deletes; Done keeps it all, and Delete asks first and keeps every member, in No section. With Show every + computer on, a section holds any computer's bots and group chats; with it off (or one computer filtered) a + section shows only that computer's members, and one with all its members elsewhere doesn't show. Bots' sections + are Hermes Desktop's own field, so Desktop shows them too. - **Marks**: thirteen shapes in eleven colors with two white eyes (`SimpleBotMark`), from before Bot Studio. A bot that has one keeps it until another avatar is saved; one with no picture, character or pet shows a mark made from its ID. @@ -626,14 +646,9 @@ text is SF Pro, as everywhere. open Bot Studio over it, on Body or Eyes; its Done brings the look back. Templates, top right, fills in the role and instructions. Create saves the look as Edit avatar does: the picture on its computer and the Bot Studio look beside it (`SimpleBotCreation.use`). -- **Chat**: Back, the bot's name (its profile) and ⋯; no New chat button. Voice is a bar over the chat, under - its header (`SimpleBotVoiceBar`), and the chat stays in use: the bot's face, a visualizer from the real audio - levels (your voice in the page's ink, the bot's in its color, dots while nobody speaks), voice choices (Live - or Take turns, the bot's voice on or off), the microphone and End. The bot's work shows as Settings › Chat › Agent's - work says, as in every one-to-one chat: the notes it writes on the way to its answer go with its steps, in - order, and the answer always shows. -- **Swipes**: from the left edge back to your bots; from the right, this bot's profile (the primary bot's on - the home). The full app's swipe choices lead to places this mode hides, so they don't apply here. +- **Chat**: the one chat header (Back, the bot's name, which opens its bot page, and ⋯; see Navigation). The bot's + work shows as Settings › Chat › A bot's work says, as in every one-to-one chat: the notes it writes on the way to + its answer go with its steps, in order, and the answer always shows. - **Dashboard** opens with **Activities**, one line ("2 running · 4 done today") until it's tapped, so Feed, Ideas and Goals stay where they were. Open, it lists the bot's subagents and background commands of the last seven days by day (Today, Yesterday, then weekdays), running first, each with how it went and when (`DashboardTodaySection`, @@ -650,9 +665,12 @@ text is SF Pro, as everywhere. password is asked once and kept in this phone's Keychain. Without a VNC server it says how to turn one on. Pinch zooms whether watching or in control; zoomed in while in control, two fingers move the view. - **Profile**: the mark, name and role over every tab (Dashboard too), then the tabs: Dashboard, Info, Computer (its - screen, when the host has one), Files and Media. Info is in named groups: Personality (Character, Instructions, - Core Files), Defaults (Default Model, Default Voice, Active Project), What it can use (Connections, Marketplace, - Credential Vault, Photo actions) and Routines (Add routine first, then the bot's routines), with Advanced Options + screen, when the host has one), Files and Media. It is the same page for every bot, from a chat's header, a bot's + menu or a Today board. ⋯ holds what is done to the bot: New chat, Chats with this bot, Pin, Use with Siri, + Duplicate, Manage bots and Delete bot (Show routines is on the Dashboard tab). Info is in named groups: About + (Name, Role and Summary, each edited in place, and the Handle, which is only read), Personality (Character, + Instructions, Core Files), Defaults (Default Model, Default Voice, Active Project), What it can use (Connections, + Marketplace, Credential Vault, Photo actions, Approvals) and Routines (Add routine first, then the bot's routines), with Advanced Options alone at the end. A group shows only the rows the computer offers. Holding a tab shows a glass bar above it with Set Default (the tab profiles open on; Dashboard until one is set; a note confirms it) and Rearrange (the tabs become glass chips to drag where they are, the tab below fades, Done in the header). Both are one choice for every bot (`SimpleBotProfileTabs`); the @@ -672,8 +690,7 @@ text is SF Pro, as everywhere. computer, never typed again. If one part doesn't save, the others show Saved and only that part stays open, its fields kept. A website's page lists what's there, Add to this website and Remove this website; a card's or address's page shows its face, Used on (Stop beside each but the last) and Use on another website. -- **Settings**: the person's circle opens the same Settings as ☰ does in Chat and Code (see Settings above), so - Bots mode has no short Settings of its own. Modes, under This app, switches the homes. +- **Settings**: the person's circle opens Settings (see Settings above). ## An agent showing the way @@ -694,27 +711,24 @@ When the person asks where something is, the agent can open it (`iphone_navigati - Return to chat puts back exactly the tab and pages the person had; the chat's draft and place are its own and never change. -## Code mode - -An opt-in second home for coding (Settings › Modes › Code mode; Chat stays the default). Its home is the -Launchpad: filter chips (All, Running, Needs you, Ready), one card per session (a still status dot, its name, its -branch in code type, what it's doing now) and a message box pinned at the bottom in place of the bottom bar. Under -the box, three chips choose the project, where it runs (New worktree, the default, or Local checkout) and the -branch; they stay set, so each send starts the next session at once and adds its card. Inside the box, the agent's -face, a model chip (model, reasoning, fast mode; a long name truncates, never the buttons beside it) and a mode -button (Default, Plan, YOLO) set what new sessions run on. A card opens the session's ordinary -chat, where steer, queue and approvals work as in every chat; it has no bottom bar while Code mode is the home. -Touch and hold a card (right-click on the Mac) for Changes: uncommitted files, then the branch's commits, and Ship -(commit, push, pull request). ☰ keeps one menu: a Chat / Code mode switch on top, then Sessions, Projects, Pull -requests, Worktrees, Kanban and Settings. Nothing animates on the cards. - -Orchestration mode: Stage (beside Send; an icon once something is staged) keeps the message, with the chips as -they are, in a tray over the box, and Send all with its count starts them all as one batch. A batch is one card -on the home with a line per session, and opens one chat for all of them: colored pills (each opens that session's -own chat), your messages on the right, and under each one every session's answer in a single block. `#` lists -the batch's sessions, then the project's open pull requests; the chip and a line over the box say who gets it. - -Dev Factory (☰ › Dev Factory in Code mode): coding recipes across projects. Its home lists what runs now +## Coding sessions + +There is no Code mode. A coding session starts from New chat: pick one bot, pick a project in the choices row under the +message box, and Send starts it. Under the box the row's chips choose the project, where it runs (New worktree, the +default, or Local checkout), the branch and the mode (Default, Plan, YOLO); they stay set, so each send starts the next +session at once. The box's own model chip (model, reasoning, fast mode; a long name truncates, never the buttons beside +it) sets what the new session runs on. Work lists the sessions with the rest of the bots' work: one card per session +(a still status dot, its name, its branch in code type, what it's doing now), and a card opens the session's ordinary +chat, where steer, queue and approvals work as in every chat. Touch and hold a card (right-click on the Mac) for +Changes: uncommitted files, then the branch's commits, and Ship (commit, push, pull request). A project's page is Work +filtered to that project, with ⋯ for pull requests, worktrees and Dev Factory. Nothing animates on the cards. + +Stage (the last chip) keeps the message, with the chips as they are, in a tray above the choices row, and Send all with its count starts them all as one batch. A batch is one card on Work with a line per +session, and opens one chat for all of them: colored pills (each opens that session's own chat), your messages on the +right, and under each one every session's answer in a single block. `#` lists the batch's sessions, then the +project's open pull requests; the chip and a line over the box say who gets it. + +Dev Factory (a project's ⋯ on Work): coding recipes across projects. Its home lists what runs now (one card per start, a line per project), the recipes (projects as small code chips, a Run button), then the templates new recipes start from. A start's screen has one card per project: its step track, what it does now in the computer's own words, and only the buttons it needs (Approve and Look at changes, Try again, the pull @@ -757,9 +771,9 @@ iPhone, iPad and Vision Pro stay exactly as they are. - **Hover.** The highlight shows in plain SwiftUI layouts: the tab bar, headers, cards, chips. List and Form rows, menus, toolbar items and views with a `.contextMenu` are UIKit on the Mac and don't report hover; they rely on their click area. -- **Keys.** ⌘N new chat, ⌘, Settings, ⌃⌘S sidebar, ⌘1–⌘5 the bottom bar's tabs (`BighelpMenuCommands`). +- **Keys.** ⌘N new chat, ⌘, Settings, ⌃⌘S sidebar, ⌘1–⌘3 the three places (`BighelpMenuCommands`). - **Sidebar.** A sidebar button sits in the title bar right after the window controls, as in Mail and Finder, so - the sidebar opens and closes from every screen, including pages with no ☰. Drag the line between the sidebar + the sidebar opens and closes from every screen. Drag the line between the sidebar and the page to make it narrower or wider (the page keeps at least 380 points); the width is remembered, and a double-click on the line goes back to the usual width. diff --git a/PRODUCT.md b/PRODUCT.md index 7fcb591d..e6720e9b 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -10,6 +10,22 @@ ios bighelp is a native client for conversations with agents, including model selection, reasoning and tool activity, rich generated cards, files, code/project changes and voice interaction. +## The Shape of the App + +bighelp is one home with three places and no modes, the same for everyone: + +- **Bots or Chats.** The first tab shows one row per bot and group chat (Bots), or every chat on every computer, + newest first (Chats). The person picks which opens first, and a switch in the header changes it. Every chat is a + page pushed over a place, with Back. +- **Today.** What needs the person now (answers a bot waits for, shares from other apps), Feed, Ideas and Goals for + every bot, and spaces: live panels a bot drafts in a chat and the person adds. See [Spaces](docs/SPACES.md). +- **Work.** What the bots are doing: coding sessions, chats and background work, workflow runs, Kanban tasks and + scheduled tasks in one list, with Projects, Tasks, Workflows and Schedules one tap away. +- **New chat** is one screen. The person picks who it is to: one bot is a chat, two to six are a group chat, and with + one bot and a project it starts a coding session. +- Settings opens from the person's circle in the header of every place. The same app runs on iPhone, iPad, Mac and + Vision Pro; iPad, Mac and Vision Pro add a sidebar. + ## Runtime Direction bighelp supports Hermes and is also building **bighelp Native**, its own native @@ -37,7 +53,7 @@ This work does not depend on the unfinished Native harness. ## Operating Context -Users return to existing sessions, continue live work, switch agents and workspaces, inspect project changes, and personalize appearance. Conversation continuity and readable long-form output remain essential when the presentation changes. +Users return to existing sessions, continue live work, switch bots and computers, see what is waiting for them, inspect project changes, and personalize appearance. Conversation continuity and readable long-form output remain essential when the presentation changes. ## Experience Vision @@ -51,15 +67,15 @@ the baseline for future work. New features, themes, and visual redesigns must preserve the [Chat interaction contract](docs/CHAT_INTERACTION_CONTRACT.md). This is an ongoing product requirement, not a completed performance initiative. -Opening Home with no active chat must also feel immediate. Catching up on old +Opening the home with no active chat must also feel immediate. Catching up on old answers must not replay completed work as new activity, repeatedly rebuild the -menu, or stall navigation. Preserve the [idle startup contract](docs/IDLE_STARTUP_RELIABILITY.md). +sidebar or the lists, or stall navigation. Preserve the [idle startup contract](docs/IDLE_STARTUP_RELIABILITY.md). ## Capabilities and Constraints - V3 is the only shipping interface. Legacy V1/V2 preference values remain decodable for migration; they do not define alternate production chat engines. -- Preserve established model/reasoning controls, side menu, theme picker, Project Changes, rich drafts, slash commands, attachment flows and voice modes. +- Preserve established model/reasoning controls, sidebar, theme picker, Project Changes, rich drafts, slash commands, attachment flows and voice modes. - Preserve transcript identity, ordering, hydration, grouping, reader-controlled scrolling, native input continuity, and request-scoped drafts in every redesign. - Large-history efficiency must preserve messages and tool results. Reducing diff --git a/README.md b/README.md index 80ed734d..7ed6b209 100644 --- a/README.md +++ b/README.md @@ -18,26 +18,32 @@ makes work with your agents feel like texting a friend. ## What it does -- **Three ways to use it.** You choose one at the end of setup, and you can change it later in Settings: - - **Bots:** a calm home with only your bots, like a messaging app. - - **Chat:** the full app, with every chat, tool and setting. - - **Code:** each message starts a coding session in its own worktree. Then you look at the changes and ship - them. -- **Chat** with one agent, or with a group of agents, also agents on your other computers. Replies stream in +- **One home with three places,** the same for everyone: + - **Bots or Chats:** the first place shows your bots like a messaging app, or every chat from every computer. + You pick the view at the end of setup, and a switch in the header changes it. + - **Today:** your Feed, Ideas and Goals, and Spaces. A space is a live panel that an agent makes and keeps + current, after you add it. + - **Work:** what your agents do now: coding sessions, running chats, workflows, tasks and scheduled + tasks. +- **Chat** with one agent, or with a group of agents, also agents on your other computers. A new chat can also + start a coding session in its own worktree. Then you look at the changes and ship them. Replies stream in live. You can react to messages, see the agent's reasoning and tool use, and send files and photos. - **Agents** that you make from templates, or save as templates. Each agent has an avatar from the catalog or your own design, and a profile with its files and media. - **Approvals and questions,** so an agent asks before it acts. - **Feed, Ideas and Goals.** Your agent fills them, but only after you ask it to. -- **Projects, Kanban, Workflows and Scheduled tasks** for longer work, and **Usage** for your AI plans and limits. +- **Projects, Kanban, Workflows and Scheduled tasks** for longer work (Work opens them), and **Usage** for your AI + plans and limits. - **Voice:** talk in turns, or live. -- **Apps:** connect apps for your agents through Composio or Hermes' own connectors (Settings › Connections). +- **Apps and skills:** connect apps for your agents through Composio or Hermes' own connectors (Settings › Apps & + skills). - **Device tools:** let agents use Calendar, Reminders, Contacts, Photos, Health, Location and more (Settings › - Connections › Device access). Each one is off until you turn it on. -- **Several computers:** see the agents of all your computers in one list. + Apps & skills › Device access). Each one is off until you turn it on. +- **Several computers:** Show every computer puts the bots and chats of all your computers in one list. - **Notifications, Live Activities, widgets, Shortcuts, CarPlay and an Apple Watch app.** - **Apple Vision Pro:** your agent can stand in the room with you, in 3D. -- **Themes** with light and dark modes, and **Nerd Mode** for host tools such as files, plugins, MCP and logs. +- **Themes** with light and dark modes. One Settings holds everything, and **Advanced options** adds host tools + such as files, MCP servers and logs. ## How it works diff --git a/Scripts/AppStorePosters.py b/Scripts/AppStorePosters.py index ed5b1ace..dd96ba67 100644 --- a/Scripts/AppStorePosters.py +++ b/Scripts/AppStorePosters.py @@ -38,11 +38,11 @@ PANELS = [ ("01-chat", "01-spending", "Chat", ("Your bots.", "One simple chat."), ("Text your own AI agents like you'd text a friend.", "Answers come back as clear cards.")), - ("02-bots", "11-bots", "Bots mode", ("Just your bots.", "A text away."), + ("02-bots", "11-bots", "Bots", ("Just your bots.", "A text away."), ("A calm home for the bots you talk to most.", "Tap one and chat.")), ("03-feed", "03-feed", "Feed", ("A Feed that fills", "when you ask."), ("Your bots post what you asked for.", "Nothing runs until you say so.")), - ("04-code", "12-code", "Code mode", ("Code anywhere.", "Just describe it."), + ("04-code", "12-code", "Work", ("Code anywhere.", "Just describe it."), ("Each message starts its own coding session.", "Check the changes when it's done.")), ("05-ideas", "08-ideas", "Ideas", ("Ideas it noticed.", "You decide."), ("Your bot offers to take things off your plate.", "Tap Let's do it, or don't.")), diff --git a/Scripts/AppStoreScreenshots.sh b/Scripts/AppStoreScreenshots.sh index 7db1edf3..405933ab 100755 --- a/Scripts/AppStoreScreenshots.sh +++ b/Scripts/AppStoreScreenshots.sh @@ -45,16 +45,16 @@ for kind in ${=BIGHELP_STORE_DEVICES:-iphone ipad}; do -only-testing:BighelpUITests/AppStoreScreenshotUITests || echo "$kind: some screens failed" kill $host; wait $host 2>/dev/null || true rm -f $log - # Code mode's home for the Code poster: its own UI test on the demo projects. The shot holds - # session cards, not chats. + # Work's coding session card for the Code poster: its own UI test on the demo projects. The shot + # holds the card a coding send makes on Work, not a chat. if [[ $kind != duo ]]; then code=$(mktemp -d -t bighelp-store-code) TEST_RUNNER_BIGHELP_CODE_MODE_EVIDENCE=$code TEST_RUNNER_BIGHELP_CODE_MODE_APPEARANCE=light \ xcodebuild test-without-building -project "$repo/Bighelp.xcodeproj" -scheme Bighelp -destination "id=$udid" \ -derivedDataPath "$derived" \ - -only-testing:BighelpUITests/CodeModeUITests/testSendsStartSessionsBackToBackAndMenuSwitchesModes \ - || echo "$kind: Code mode failed" - cp "$code/02-two-sessions.png" "$output/$kind-12-code.png" 2>/dev/null || echo "$kind: no Code mode shot" + -only-testing:BighelpUITests/CodeModeUITests/testACodingSendOpensItsProjectOnWork \ + || echo "$kind: coding session test failed" + cp "$code/02-session-card.png" "$output/$kind-12-code.png" 2>/dev/null || echo "$kind: no coding session shot" rm -rf $code fi xcrun simctl shutdown $udid diff --git a/Scripts/HostSignInMatrixProbe.py b/Scripts/HostSignInMatrixProbe.py index 1c6e0fe6..fbfd7622 100644 --- a/Scripts/HostSignInMatrixProbe.py +++ b/Scripts/HostSignInMatrixProbe.py @@ -20,9 +20,10 @@ installer from GitHub: the app finds the latest GitHub Release and updates to it (PluginReleaseUpdateHostUITests; needs the internet) fleet two hosts with the bighelp plugin (--plugin) and different agents: - the all-hosts view lists both and opens an agent on the host that - isn't selected (AllHostsHostUITests), and Ask an agent on the gateway - that isn't in use (ShortcutGatewaySwitchHostUITests) + Ask an agent on the gateway that isn't in use + (ShortcutGatewaySwitchHostUITests). The tests that opened another + computer's agent from the all-hosts view are gone with that view, + and none replaces them here media no sign-in, with the bighelp plugin (--plugin) and the test-only Scripts/HostProbePlugin: a generated image stays in the chat after the turn ends, two pictures an agent saved outside its folder show @@ -39,7 +40,7 @@ original call got back (DeviceAccessHostUITests; Reminders is granted to the app on the simulator first, so iOS doesn't ask) appstate no sign-in, with the bighelp plugin (--plugin) and two more agents: Bots - mode's top is rearranged and saved, the app is deleted from the + view's top is rearranged and saved, the app is deleted from the simulator and installed again, and the new install shows the same top from the computer (BotsAppStateHostUITests, run twice) drafts no sign-in, with the bighelp plugin (--plugin) and a scripted model: @@ -97,11 +98,7 @@ "ProjectsAndBoardHostUITests/testAppsShowsTheAgentsFilesWithNoWorkingFolderSet", "ProviderUsageHostUITests/testUsageLoadsFromTheChatTheAppOpensWith"], "update": ["PluginReleaseUpdateHostUITests/testUpdatesToTheLatestReleaseOnARealHost"], - "fleet": ["AllHostsHostUITests/testAllHostsListsBothHostsAndOpensTheOther", - "AllHostsHostUITests/testProviderUsageLoadsInAChatOnTheOtherHost", - "AllHostsHostUITests/testUsageOpensFromTheMenuWithAllHosts", - "AllHostsHostUITests/testSecureInputAndQuestionsWorkInAChatOnTheOtherHost", - "ShortcutGatewaySwitchHostUITests/testAskAnAgentSwitchesToItsGatewayAndGetsTheAnswer"], + "fleet": ["ShortcutGatewaySwitchHostUITests/testAskAnAgentSwitchesToItsGatewayAndGetsTheAnswer"], "drafts": ["ImageDraftsHostUITests/testAContactDraftFromAPhotoSavesOnceAndTheAgentHearsIt", "ImageDraftsHostUITests/testAPhotoAloneGetsTheOfferAndTheAgentCantAddTheContactItself"], "apps": ["HTMLAppsHostUITests/testABigAppFromTheAgentOpensAndItsAnswerReachesTheAgent"], @@ -669,8 +666,7 @@ def session_sources(home: Path) -> list[str]: def run_fleet(args, repo: Path) -> int: """Two open hosts with the plugin: "Desk agent" on one; "Lab agent" and "researcher" on the other. - The scripted tool model answers plain messages like the synthetic one, and its secure input and - question turns check prompts in a chat on the host the all-hosts view switched to.""" + The scripted tool model answers plain messages like the synthetic one.""" if not args.plugin: raise SystemExit("fleet mode needs --plugin ") with tempfile.TemporaryDirectory(prefix="signin-fleet-", dir="/tmp") as temporary: @@ -746,10 +742,6 @@ def run_fleet(args, repo: Path) -> int: timeout=1500) for label, _, _, _, home, _ in hosts: print(json.dumps({"host": label, "session_sources_on_host": session_sources(home)}), flush=True) - timings = args.results / "fleet" / "fleet-timings.json" - if timings.exists(): - print(json.dumps({"switch_seconds": json.loads(timings.read_text()), - "latency_ms": args.latency_ms}), flush=True) print(json.dumps({"mode": "fleet", "exit_code": result.returncode}), flush=True) return result.returncode finally: @@ -784,7 +776,7 @@ def app_state_on_host(home: Path) -> dict: def run_appstate(args, repo: Path) -> int: - """One open host with the plugin and three agents. The app saves a Bots mode order, is deleted + """One open host with the plugin and three agents. The app saves a Bots view order, is deleted from the simulator and installed again, and gets the order back from the host.""" if not args.plugin: raise SystemExit("appstate mode needs --plugin ") diff --git a/Scripts/RoomLinkProbe.py b/Scripts/RoomLinkProbe.py index 57c4e9e8..828cdeeb 100644 --- a/Scripts/RoomLinkProbe.py +++ b/Scripts/RoomLinkProbe.py @@ -16,11 +16,8 @@ the home's agent, and on the second host for its agent in a room homed elsewhere (native-room-peer-typing-v1). -With --simulator-id it runs the app's own UI test instead -(AllHostsHostUITests/testGroupChatWithAnAgentFromEachHostAnswers): the app adds -both hosts, starts the group from All agents and gets both answers. Then the -probe reads the home's room to show the link and both replies. Build the app -for testing first (into --derived-data). +The app has no UI test for a group chat across two computers, so this probe +makes the protocol calls only. Run it with the Hermes checkout's own Python (it needs `websockets`). HERMES_DISABLE_LAZY_INSTALLS=1 keeps Hermes from "finishing a source update" @@ -98,7 +95,7 @@ def free_port() -> int: class Host: """One isolated Hermes: dashboard and gateway sharing a throwaway home.""" - def __init__(self, label: str, root: Path, hermes: str, model_port: int, logs: Path, display: str | None = None, + def __init__(self, label: str, root: Path, hermes: str, model_port: int, logs: Path, plugin: Path | None = None): self.label = label self.home = root / label / "home" @@ -132,9 +129,6 @@ def __init__(self, label: str, root: Path, hermes: str, model_port: int, logs: P API_SERVER_KEY=secrets.token_urlsafe(48), API_SERVER_HOST="127.0.0.1", API_SERVER_PORT=str(self.api_port), # Plain http is allowed only on this machine's loopback, as here. HERMES_ROOM_LINK_URL=f"http://127.0.0.1:{self.api_port}") - if display: - subprocess.run([hermes, "profile", "rename", "default", display], cwd=self.project, env=self.env, - check=True, timeout=120, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.logs = [(logs / f"{label}-serve.log").open("w"), (logs / f"{label}-gateway.log").open("w")] self.processes = [ subprocess.Popen([hermes, "serve", "--host", "127.0.0.1", "--port", str(self.dashboard_port), @@ -328,56 +322,13 @@ async def exercise(home_host: Host, peer_host: Host, reply_timeout: float, plugi return evidence -async def read_back(home_host: Host) -> dict: - """What the home recorded for the group the app made: its link and its replies.""" - async with RPC(home_host) as home: - rooms = (await home("groups.list", {"limit": 50}))["rooms"] - mixed = [room for room in rooms if any(m.get("target", {}).get("kind") == "peer" for m in room["members"])] - assert len(mixed) == 1, f"expected one group with an agent from the other host, found {len(mixed)}" - room = mixed[0] - state = await home("groups.state", {"room_id": room["room_id"]}) - page = await home("groups.log", {"room_id": room["room_id"], "since_seq": 0, "limit": 100}) - return {"members": [(m["member_id"], m["target"]["kind"]) for m in room["members"]], - "peer_routes": [r["status"] for r in state.get("driver_status", {}).get("peer_routes", [])], - "replies_from": sorted({e["payload"]["member_id"] for e in page["events"] - if e["kind"] == "message.member"})} - - -def run_ui(args, hosts: list[Host], root: Path) -> int: - repo = Path(__file__).resolve().parent.parent - probe = root / "probe.json" - probe.write_text(json.dumps({"mode": "roomlink", "address_a": hosts[0].origin.removeprefix("http://"), - "address_b": hosts[1].origin.removeprefix("http://"), - "plugin": "yes" if args.plugin else "no"})) - probe.chmod(0o600) - args.results.mkdir(parents=True, exist_ok=True) - env = dict(os.environ, TEST_RUNNER_BIGHELP_SIGNIN_PROBE=str(probe), - TEST_RUNNER_BIGHELP_SIGNIN_EVIDENCE=str(args.results / "roomlink")) - command = ["xcodebuild", "test-without-building", "-project", str(repo / "Bighelp.xcodeproj"), - "-scheme", "Bighelp", "-destination", f"platform=iOS Simulator,id={args.simulator_id}", - "-derivedDataPath", str(args.derived_data), "-parallel-testing-enabled", "NO", - "-resultBundlePath", str(args.results / "roomlink.xcresult"), - "-only-testing:BighelpUITests/AllHostsHostUITests/testGroupChatWithAnAgentFromEachHostAnswers"] - with (args.results / "xcodebuild-roomlink.log").open("w") as output: - result = subprocess.run(command, env=env, cwd=repo, stdout=output, stderr=subprocess.STDOUT, timeout=1500) - print(json.dumps({"ui_test_exit_code": result.returncode}), flush=True) - if result.returncode == 0: - print(json.dumps(asyncio.run(read_back(hosts[1])), indent=2), flush=True) - return result.returncode - - def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--hermes", required=True, help="the separate Hermes checkout's hermes launcher") parser.add_argument("--logs", type=Path, help="keep both hosts' logs in this folder") parser.add_argument("--reply-timeout", type=float, default=240) parser.add_argument("--plugin", type=Path, help="the bighelp plugin folder to run on both hosts") - parser.add_argument("--simulator-id", help="run the app's UI test on this simulator instead of the RPC calls") - parser.add_argument("--derived-data", type=Path, help="where the app was built for testing") - parser.add_argument("--results", type=Path, default=Path("/private/tmp/roomlink-results")) args = parser.parse_args() - if args.simulator_id and not args.derived_data: - parser.error("--simulator-id needs --derived-data") model = ThreadingHTTPServer(("127.0.0.1", 0), ScriptedModel) threading.Thread(target=model.serve_forever, daemon=True).start() with tempfile.TemporaryDirectory(prefix="roomlink-", dir="/private/tmp") as temporary: @@ -386,13 +337,10 @@ def main() -> int: logs.mkdir(parents=True, exist_ok=True) hosts = [] try: - for label, display in (("desk", "Desk agent"), ("lab", "Lab agent")): - hosts.append(Host(label, root, args.hermes, model.server_port, logs, - display=display if args.simulator_id else None, plugin=args.plugin)) + for label in ("desk", "lab"): + hosts.append(Host(label, root, args.hermes, model.server_port, logs, plugin=args.plugin)) for host in hosts: host.wait_ready() - if args.simulator_id: - return run_ui(args, hosts, root) evidence = asyncio.run(exercise(hosts[0], hosts[1], args.reply_timeout, plugin=args.plugin is not None)) evidence["model_calls"] = ScriptedModel.calls print(json.dumps(evidence, indent=2)) diff --git a/Scripts/check-localization.py b/Scripts/check-localization.py index 7ce69e59..7208d89c 100644 --- a/Scripts/check-localization.py +++ b/Scripts/check-localization.py @@ -12,7 +12,7 @@ # Representative boundaries; this is intentionally not a whole-app coverage claim. REQUIRED = { "Your agents, right at home.", "Get Started", "Connect your computer", - "Add the bighelp plugin", "Choose your mode", "Use %@", "Chat", "Feed", + "Add the bighelp plugin", "Use %@", "Chat", "Feed", "Ideas", "Goals", "Files", "Agents", "Settings", "New chat", "Send message", "Stop response", "Message %@", "Ask %@", "Appearance", "Your name", "Done", "Advanced options", "Default model", "AI providers", "Help & feedback", @@ -21,35 +21,54 @@ "PDF pages require a current native Hermes conversation.", "hermes.example.com or 192.168.1.20", } -# Simple Bot mode, Teamwork and the Settings pages they open (#527). +# The Bots view, Teamwork and the Settings pages they open (#527). SIMPLE_BOTS_AND_TEAMWORK = { "Search bots", "New Bot", "New Group Chat", "Mark Unread", "Mark Read", "Pin", "Unpin", "Make Primary Bot", "Replace Primary Bot…", "Rearrange", "Hide", "Bot Profile", "Templates", "Drag your bots and group chats into the order you want, then tap Save.", "No bots yet", "Create New Bot", "Instructions", "Default Model", "Routines", "Computer", "Media", "Character", - "Your computer isn't connected", "Saved. This is how %@ looks everywhere.", "End voice", - "Auto-review", "Multi-gateway", "Your computers", "Your bots see your name.", + "Your computer isn't connected", "Saved. This is how %@ looks everywhere.", + "Auto-review", "Your computers", "Your bots see your name.", "Asked %@", "%@ answered", "%@ didn't answer", "Asking %@…", "Waiting for %@", "%@ is working on it…", "%lld messages with %@", "%@ and %@", "%@, %@ and %@", "What %@ did", "Bots ask each other for help", "The computer didn't save it for %@. Try again.", "Bots messaging each other", "Quiet hours", "Notify me about", "Send a test", "Turn off notifications", "Channels", "Opens on", "Return sends", "A bot opens", - "Chat layout", "App layout", "Light mode", "Dark mode", "Text and buttons", "Bottom bar", - # The modes after their 2.6.11 rename (#528). - "Bots", "Chat", "Code", "Bots mode", "Chat mode", "Code mode", "Next mode", "Header mode switcher", - "Switch between Bots, Chat and Code from the top of each home.", + "Chat layout", "Light mode", "Dark mode", "Text and buttons", + "Bots", "Chat", "Code", +} +# The one home's screens: the header and bar, Chats, New chat, Today, Work, spaces, the bot page +# and the first-run question (#977). +ONE_HOME = { + "Today", "Work", "Chats", "Sidebar", "Recent chats", "Bot page", "Pick a chat, or start a new one.", + "Search chats", "Chat name", "Mark unread", "Archive", "No chats yet", "No chats on %@", + "%@ isn't connected. Showing its last chats.", + "Add a bot", "Group chats", "Where should this chat run?", "How should this chat work?", "Stage", + "Send all %lld", "Group chat · %lld bots", "%lld coding sessions in %@", + "Group chats start with text only", "Starting the chat…", + "How do you want to start?", "With a bot", "Across chats", "First tab shows", + "Approvals", "Handle", "Delete bot", "Chats with this bot", + "Make a space", "Add to Today", "Delete this space?", "Updated %@", "Try again in a minute", + "Hide from Today", "Every panel is hidden. Tap Edit to show one.", + "Nothing needs you", "Open a board", "Pull requests (%lld)", "step %lld of %lld", + "Open Work, then try again.", } PLURALS = {"%lld messages with %@"} # These screens' plain-String parameters show text verbatim, so app copy handed to them has to be # resolved with String(localized:) first. A bare English literal here never reaches the catalog. SCOPED_SOURCES = [ *sorted((ROOT / "Bighelp/SimpleBots").glob("*.swift")), + *sorted((ROOT / "Bighelp/Home").rglob("*.swift")), + *sorted((ROOT / "Bighelp/Today").glob("*.swift")), + *sorted((ROOT / "Bighelp/Work").glob("*.swift")), + *sorted((ROOT / "Bighelp/Spaces").glob("*.swift")), + ROOT / "Bighelp/Chat/ChatNewChatSlot.swift", ROOT / "Bighelp/Hosts/FirstRunOnboardingSteps.swift", ROOT / "Bighelp/App/RootSimpleBots.swift", ROOT / "Bighelp/Agents/Teamwork.swift", ROOT / "Bighelp/Chat/ChatAgentTalkRail.swift", ROOT / "Bighelp/Settings/SettingsView.swift", ROOT / "Bighelp/Settings/SettingsView+Preferences.swift", ROOT / "Bighelp/Settings/SettingsView+Identity.swift", ROOT / "Bighelp/Settings/ChatLayoutSettingsView.swift", ROOT / "Bighelp/Settings/AppearanceStudioView.swift", - ROOT / "Bighelp/Settings/AppearanceSizeControls.swift", ROOT / "Bighelp/Settings/AppLayoutSettingsView.swift", + ROOT / "Bighelp/Settings/AppearanceSizeControls.swift", ROOT / "Bighelp/Settings/BighelpNotificationSettingsView.swift", ] VERBATIM = re.compile( @@ -61,7 +80,9 @@ r'|\?\?\s*"[A-Z][a-z]+[ .…’\']' r'|\breplacingOccurrences\(of:\s*"agents?"', re.S) # A new bot's fallback role and instructions are saved on the host as the bot's own words, not shown as app copy. -SAVED_DATA = {("SimpleBotTemplates.swift", '?? "You '), ("SimpleBotTemplates.swift", '?? "Everyday ')} +# New chat's `note(_:)` takes a LocalizedStringKey, unlike the Settings helper of the same name. +SAVED_DATA = {("SimpleBotTemplates.swift", '?? "You '), ("SimpleBotTemplates.swift", '?? "Everyday '), + ("NewChatView.swift", 'note("')} def units(node): @@ -103,6 +124,14 @@ def test_simple_bots_teamwork_and_their_settings_have_chinese(self): self.assertTrue(values) self.assertTrue(all(unit["value"].strip() for unit in values)) + def test_one_home_screens_have_chinese(self): + for key in ONE_HOME: + with self.subTest(key=key): + self.assertTrue(key in self.strings, f"{key!r} is missing from the catalog") + values = list(units(self.strings[key]["localizations"]["zh-Hans"])) + self.assertTrue(values) + self.assertTrue(all(unit["value"].strip() for unit in values)) + def test_counts_use_plural_variations(self): for key in PLURALS: with self.subTest(key=key): diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f5373165..a8362c5c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -63,6 +63,7 @@ Start at the owner of a behavior, then follow its typed boundary: | Change | Start here | Boundary to preserve | |---|---|---| | App construction and account separation | `Bighelp/App/BighelpAppComposition.swift` | Native host authority is independent of the optional account. | +| The home: bar, header, Chats, New chat, Today, Work | `Bighelp/App/RootHome.swift`, `Bighelp/Home/`, `Bighelp/Today/`, `Bighelp/Work/` | Each computer has its own `AppState` and stores; what sits above them lives in `HomeSelection`. Spaces are in [Spaces](SPACES.md). | | Chat presentation and actions | `Bighelp/Chat/ChatView.swift`, `ChatModel.swift`, `ChatComposer.swift` | The retained model owns drafts and submissions; the native timeline owns scrolling. | | Rail, goal, tasks and subagent sheets | `Bighelp/Chat/SessionStatusRailView.swift`, `SessionGoalSheet.swift`, `SessionTasksSheet.swift`, `SessionSubagentRosterSheet.swift` | Presentation does not invent execution or session authority. | | Local appearance | `Bighelp/DesignSystem/BighelpThemeReader.swift` | Resolve the consuming view's traits, including sheet and hosted-row overrides. | @@ -206,7 +207,8 @@ never authorize adoption. Explicit host removal does not select another host. The top-level objects include: -- `AppState` for selected tab, navigation path, and active conversation. +- `AppState` for the selected tab, navigation path, and active conversation, and `HomeSelection` (one for the app) for + what stays when the computer in use changes. - `SettingsStore` for local preferences. - `UserIdentityStore` for the local display identity and avatar reference. - `AgentDirectoryStore` for agent metadata. @@ -228,8 +230,9 @@ against fixture implementations in tests. Native host selection belongs to the independently authenticated host registry. `NativeWorkspaceSelectionStore` binds the selected host and exact owner to one runtime, retires changed authority, and preserves same-authority recovery. -The all-hosts view (`Bighelp/Fleet`) lists every configured host's agents, -direct chats and scheduled tasks without changing that selection model. +Show every computer (`Bighelp/Fleet`) lists every configured host's agents, +direct chats and scheduled tasks in the Bots view, the Chats view and New chat's list of bots, without changing that +selection model. `FleetStore` keeps one snapshot per host in Application Support (`BighelpFleet`, complete file protection): the selected host's comes from its live runtime stores; `RegistryFleetReader` reads the others at most once a @@ -242,8 +245,8 @@ connected: a switch doesn't suspend the previous host's store, and the reader keeps the others open. Turning it off or going to the background closes all but the selected one, as before. Opening an agent, chat or task on another host selects that host and runs the open as soon as its runtime exists with its saved -catalog, before the runtime's refresh finishes (the same point the home chat -opens at launch); host-only screens ask which host first. Removing a host +catalog, before the runtime's refresh finishes; Today and Work show the host in +use, and their header's computer menu switches it. Removing a host deletes its snapshot. Resetting the optional notification installation clears its scoped @@ -318,20 +321,28 @@ known session after refreshing the catalog if necessary. ## 4. User interface shell -The main shell presents Agents, Sessions, Scheduled Tasks and Workspace. -Sessions remains the root of the initial landing destination: by default a cold -launch opens the agent's latest chat on it, and Settings › Chat › Opens on can pick -another screen and agent instead (`BighelpLanding`). Activity, preferences, -account/device management and connectivity live inside Workspace. New chat is a -separate action, not another tab. Existing route identities and legacy +The shell is one home with three places (`HomeTab`): the first tab shows the Bots view (`SimpleBotsHomeView`) or the +Chats view (`ChatsInboxView`), then Today (`TodayView`) and Work (`WorkView`). There are no modes. `RootShellView` +switches the root itself and each root draws its own header (`HomeHeaderBar`); everything else, a chat included, is a +page pushed on the one navigation stack (`AppState.path`, `AppRoute`) with Back. The bar (`HomeTabBar`; `HomeTabOrnament` +on Vision Pro, `HomeStripTabs` on the iPhone Duo) shows on roots only, and Settings is a sheet opened by the person's +circle in the header. `HomeSelection` holds what is above any one computer: the tab, the first tab's view, New chat's +picks (`NewChatSession`) and Today's layout and boards. Each computer has its own `AppState`, stores and chats +(`NativeWorkspaceRuntime`), so these stay put when the computer in use changes. `settings.homeLanding` (Settings › Chat › +Opens on: Bots, Chats, Today, Work) decides where a cold launch opens, applied once by `HomeSelection.land`; no chat +opens by itself. `HomeSettingsMigration` reads the older mode settings once. Existing route identities and legacy Inbox-to-Activity links remain compatible. +New chat is the new chat's own screen: the ordinary chat with a To row and a list of bots over the empty messages +(`ChatNewChatSlot`), and for one bot a row of coding choices under the message box. Work lists coding sessions with the +other work the bots are doing. Spaces (`Bighelp/Spaces/`, [Spaces](SPACES.md)) are panels on Today. + The native chat canvas and unified composer serve production and isolated fixtures. The verified Codex presentation, typography, native editor and disclosure behavior are retained; native transport selection does not reconstruct them. -Configurable edge gestures can open the quick workspace, create a chat, or -navigate to a selected area. The quick workspace surfaces recent sessions and -common actions without owning duplicate session state. +Configurable edge gestures can open the sidebar (on iPhone, which has none, they go to Chats), create a chat, or +navigate to a selected area. The sidebar (`HomeSidebar`) surfaces the three places, recent sessions and a few common +actions without owning duplicate session state. ## 5. Feature architecture @@ -407,9 +418,9 @@ protected-file replacement. A strict reference save or authority change cancels older checkpoints; changes arriving during encoding remain dirty for the next checkpoint. Catch-up must never turn this into a synchronous save per event. Queued final answers and child discovery/termination belong to that same batch. -Home, sidebar and Sessions observe the catalog's stable `presentedRecords` +The Chats view, the sidebar and Sessions observe the catalog's stable `presentedRecords` during catch-up; canonical routing and persistence continue to use `records`. -Publish the latest presentation and one deferred automatic Home refresh at +Publish the latest presentation and one deferred automatic home refresh at catch-up completion. Account reset clears both presentation and pending reload ownership. See [idle startup reliability](IDLE_STARTUP_RELIABILITY.md). Unchanged reference state does not repeat its synchronous durability write on @@ -852,7 +863,7 @@ UserDefaults stores non-secret preferences such as theme, appearance, selected and pinned agents, pinned sessions, user-facing identity, and gesture choices. Those explicit preferences survive sign-out and app updates until the user changes them. Project-section order and collapse state are device-local too, -shared by the Sessions screen and Quick Workspace. Their versioned settings +kept for the Sessions page. Their versioned settings payload is keyed by the sign-in scope and selected host ID, so a fresh sign-in starts a new layout scope. Layout is not synced to other devices. Project names are display labels; stable project IDs own the @@ -933,16 +944,14 @@ only at the native authority boundary. `BighelpHostSelectionChangeRelay` remains for demo mode's host switch (`DemoHosts`): it synchronously retires fixture models and changes their cache scope. It cannot retarget production native chat. -### Quick Workspace overview +### Sidebar overview -`QuickWorkspaceDrawer` uses one native list, embedded or inside a navigation -stack. Conversations contains New chat, Chats and Agents. Work contains Activity, -Scheduled tasks and Skills & tools. Workspace contains Workspace features, -Folder, Switch instance and Settings. Saved content follows in Recent chats and -Pinned agents disclosures. Scratchpad and Wiki are absent. Retain 44-point -targets and allow accessible text sizes to scroll rather than clipping or -shrinking text. Native navigation toolbars own their Liquid Glass buttons; do -not wrap a toolbar button in a second glass circle. +`HomeSidebar` uses one native list: the three places, Settings and a New chat button; Recent chats (eight, with See +all); and More (Needs you while something waits, Shared with bighelp while a share waits, Usage, and Simple mode on +Vision Pro). iPad at regular width slides it in behind a header button, and the Mac and Vision Pro keep it as a column +(`BighelpSideMenu`). Scratchpad and Wiki are absent. Retain 44-point targets and allow accessible text sizes to scroll +rather than clipping or shrinking text. Native navigation toolbars own their Liquid Glass buttons; do not wrap a +toolbar button in a second glass circle. ### Hermes scheduler compatibility diff --git a/docs/BIGHELP_CARDS.md b/docs/BIGHELP_CARDS.md index 75f58ef3..2316f1a6 100644 --- a/docs/BIGHELP_CARDS.md +++ b/docs/BIGHELP_CARDS.md @@ -225,6 +225,21 @@ full contract is [HTML apps](HTML_APPS.md). The app adds `html_app` to `renders` only when `/native/context` lists `native-html-apps-v1` (and `native-card-objects-v1`). +## Space drafts + +Plugin feature `native-spaces-v1` adds `space_draft`: a live panel for Today that +the agent drafted with `bighelp_draft_space`. Only that tool makes one, and it +is its card's only element. The card shows a preview of the panel, how often it +updates, whether that uses AI, a size, and Add to Today. Nothing runs on the +computer until the person taps Add. The app adds `space_draft` to `renders` +only when `/native/context` lists `native-spaces-v1` (and +`native-card-objects-v1`). The full contract is [Spaces](SPACES.md). + +A space's own card is an ordinary card drawn in a panel on Today. The panel +draws less of it than a chat would (`BighelpCardLimits`): fewer list items, +table rows and columns, a shorter chart and fewer lines of text, and no root +title, since the panel names the space. In a chat nothing changes. + ## Weather backgrounds A `card` element may carry an animated weather background beside its `props`: diff --git a/docs/CACHE_FIRST_SESSIONS.md b/docs/CACHE_FIRST_SESSIONS.md index c8fdd809..b9988df8 100644 --- a/docs/CACHE_FIRST_SESSIONS.md +++ b/docs/CACHE_FIRST_SESSIONS.md @@ -74,7 +74,7 @@ scoped and defaults to empty for clients without this native provenance. ## Document scanning -`Scan document` in the attachment drawer uses Apple's +`Scan document` in the attachment menu uses Apple's `VNDocumentCameraViewController`. Camera access is requested only on explicit use; unsupported devices show an unavailable action. The system scanner handles capture, page correction and ordering. Saving creates one local PDF containing all selected diff --git a/docs/CHAT_INTERACTION_CONTRACT.md b/docs/CHAT_INTERACTION_CONTRACT.md index 3503419c..c52ca828 100644 --- a/docs/CHAT_INTERACTION_CONTRACT.md +++ b/docs/CHAT_INTERACTION_CONTRACT.md @@ -48,7 +48,7 @@ canonical data, reader state, and disposable views: | Reader choices and drafts | The prepared chat's disclosure store owns explicit tool/fold choices. `DashboardModel` owns clarification drafts by item, session, and request; removal/account reset prunes them. These are local presentation state, not a new transcript authority. | | Hosted SwiftUI content | `HostedRow.body` preserves Observation, and `.id(row.id)` scopes recycled local state. Propagate public presentation values and app dependencies without replacing the hosting configuration's private layout/accessibility environment. | | Persistence | Existing bounded checkpoints coalesce draft/tool writes. A pause in typing writes the plain draft to `ChatDraftJournal`, never the catalog; the chat's next save takes it, and a relaunch restores it only while the saved draft is one the journal saw. Reference drafts keep their own checkpoint. Live final-turn, stop, navigation, and lifecycle paths retain explicit flushes. Historical final answers and subagent lifecycle updates share the catch-up checkpoint; a terminal tool must not synchronously rewrite the entire retained session. | -| Idle startup | Home, sidebar and Sessions hold stable presentation during catch-up and publish the accumulated state once. Routing and actions continue to resolve canonical records. See [idle startup reliability](IDLE_STARTUP_RELIABILITY.md). | +| Idle startup | The Chats view, sidebar and Sessions page hold stable presentation during catch-up and publish the accumulated state once. Routing and actions continue to resolve canonical records. See [idle startup reliability](IDLE_STARTUP_RELIABILITY.md). | Tail following occurs after UIKit layout and yields during tracking, dragging, and deceleration. The deferred publication of the bottom-state Boolean is for @@ -117,7 +117,7 @@ cover these boundaries: | Typed drafts survive a relaunch without catalog writes | `ChatDraftJournalTests` | Run [ChatStreamingAnchorUITests](../BighelpUITests/ChatStreamingAnchorUITests.swift) -for the three short/long/expanded stress scenarios, growing-tail following, +for the short and large-tool stress scenarios, growing-tail following, reading during a stream, consecutive tool turns, sending from history, and first short-response placement. Run [ToolDisclosureUITests](../BighelpUITests/ToolDisclosureUITests.swift) for expanded @@ -176,6 +176,27 @@ or successful TestFlight processing cannot replace interaction evidence. The user's acceptance of build 2.0.1 (8) establishes the product baseline; physical-device frame-rate claims still require device measurements. +## What surrounds the message box + +A chat is a pushed page. Its header is Back, the bot (a tap opens its bot page) and ⋯ (`ChatPushedHeader`). No bar +sits under the message box. None of this changes scrolling, drafts, streaming, keyboard control or history. The chat +table stays full height, and the header and the message box overlay it as described below. + +New chat's own blank chat adds three parts through `ChatNewChatSlot`. A To row sits in the header, where the bot's +name would be. A people list sits over the empty messages. For one bot, one row of coding choices sits under the +message box. + +These parts draw only while nothing is sent in that chat. From its first message on (staged, sending or sent) the chat +is an ordinary chat. The shell decides which chat gets the parts from the chat's ID, never from its messages. Each part +is the shell's own view with its own state, so a change in one redraws that part and not the chat. + +The Send hook (`ChatComposerActions.sendOverride`) is asked before the chat's own send. True means the message went +elsewhere (a group chat, a coding session), and whoever took it empties the box. False sends in this chat as usual. +The hook must not capture a view, because `ChatComposerHost` keeps it for as long as the chat is open. The message box +must not redraw for it. `ChatComposer` is `Equatable`: a new input that changes how the box looks goes in its `==`. +The choices row is `Equatable` too. It reads `ChatModel.draftShape` in a small host view of its own, never in the +shell or the route, or every key press redraws the shell. + ## Glass, startup and suggested prompts Native Liquid Glass controls need the scrolling content behind them. Keep the @@ -191,11 +212,11 @@ the available width. Verify default and accessibility Dynamic Type; a label in the accessibility tree does not prove the title is visibly rendered. Selecting a prompt retains the established quick-action behavior. -Home may appear from cached admission before the host is ready. Dashboard loads +The home may appear from cached admission before the host is ready. Dashboard loads must wait for the verified connection and reject results from a replaced connection. Navigation cancellation must not become a visible load failure. -Long-pressing the bighelp logo in every workspace sidebar presents the same +The header's computer menu on Today and Work switches the computer in use through the same loaded host selection state. @@ -235,9 +256,8 @@ the canonical byte-preservation, uncertain-delivery and failed-checkpoint cases. ## Sidebar and optional project context -Home, Scratchpad, Wiki, Scheduled Tasks, Skills & Tools and Settings form one -continuous navigation group: do not add a divider after Wiki. Pinned agent previews -follow the navigation, with sessions below; preserve the existing bounded previews +The three places and Settings form one continuous navigation group: do not add a divider +between them. Recent chats follow, bounded to eight, then More; preserve the bounded list so navigation and some content remain visible together. A selected non-repository folder remains valid chat context. Its Changes rail reads diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 1333723b..820c6c11 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -183,8 +183,7 @@ chat_stress_args=( -destination "platform=iOS Simulator,id=$CHAT_SIMULATOR_ID" -derivedDataPath "$CHAT_DERIVED_DATA" -parallel-testing-enabled NO -only-testing:BighelpTests/ChatTimelineRenderPartitionTests - -only-testing:BighelpUITests/ChatStreamingAnchorUITests/testExpandedLongToolStreamKeepsMainThreadResponsive - -only-testing:BighelpUITests/ChatStreamingAnchorUITests/testLongToolStreamKeepsMainThreadResponsive + -only-testing:BighelpUITests/ChatStreamingAnchorUITests/testConsecutiveLargeToolsKeepMainThreadResponsive -only-testing:BighelpUITests/ChatStreamingAnchorUITests/testShortToolStreamKeepsMainThreadResponsive ) xcodebuild build-for-testing "${chat_stress_args[@]}" && \ @@ -292,6 +291,14 @@ The app can run without production services: Additional launch arguments used by UI tests can select an initial screen. Keep fixture content synthetic and never copy production data into tests. +- `-loopdy.home.landing bots|chats|today|work` sets where the app opens, and `-bighelp.home.view bots|chats` sets the + first tab's view when it is today or work. Demo runs also take `-initial-tab` with a place's name. +- `-bighelp.home.migrated-v1 YES` skips the one-time read of the older mode settings (`NO` runs it at every launch). +- `-bighelp.hosts.all-hosts YES|NO` sets Show every computer. +- DEBUG builds with `-use-demo-fixtures` show one new screen alone on made-up data: `-test-home-chrome`, + `-test-chats-inbox`, `-test-new-chat`, `-test-today-home`, `-test-work-screen` (add `-test-work-project` for a + project's page), `-test-spaces-today`, and `-test-spaces` for a chat with a space draft. + ## Runtime configuration The notification service's address (`https://link.loopdy.app`) is fixed in @@ -482,7 +489,7 @@ in portrait/landscape/accessibility sizes, Hosts and long-press instance switchi from immediate selection. Preserve the chat performance gate alongside this work. -## Draft, account recovery and drawer regression checks +## Draft, account recovery and sidebar regression checks For composer ownership or account recovery changes, run these actual suites: `ReferenceDeliveryAcceptanceTests`, `ReferenceNativeEditorAcceptanceTests`, @@ -505,9 +512,10 @@ Native row alongside an existing phone and Hermes host. Verify that v1 returns its supported kinds and that all persisted rows, grants and schema are unchanged. Do not fix this by revoking devices, changing keys or coercing Native to Hermes. -For drawer changes, run `BighelpMenuUITests` and look at the drawer on screen, light and -dark, checking hit targets as well as layout. Keep navigation before the bounded pinned-agent preview and sessions; -verify the full Agents route remains reachable with more pins than the preview. +For changes to the home shell or the sidebar, run `HomeShellUITests` (the places, the header, a pushed chat, New chat, +Today and Work) and look at the sidebar on screen on iPad, light and dark, checking hit targets as well as layout. +Keep the three places before the bounded list of recent chats; verify See all still reaches every chat with more +chats than the sidebar lists. For scheduler compatibility, run the bighelp plugin contract, workspace-control and portability suites with the installed Hermes source on `PYTHONPATH`, followed diff --git a/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md b/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md index 2cad25f8..2e3719cd 100644 --- a/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md +++ b/docs/DIRECT_STREAMING_AND_LIVE_VOICE.md @@ -78,8 +78,8 @@ cut itself off and the player stopped. Each call keeps a call audio report: what scheduled and finished, the main mixer's output level, the engine, the session and the route, and each change with its time (`GeminiLiveAudioDiagnostics`, also in the `LiveVoiceAudio` log every 10 s). Settings › Voice › Advanced, with Advanced options (`settings.nerdModeEnabled`) on, has a switch for each part the call screen shows (`LiveVoiceDebug`, both off at -first): Call sound report shows it once a second, and Copy report button puts Copy report there and in -Bots mode's voice bar menu. Its Restart sound stops and starts the player of the Gemini Live call in progress +first): Call sound report shows it once a second, and Copy report button puts Copy report there. +Restart sound, on the same page, stops and starts the player of the Gemini Live call in progress only (`LiveVoiceCurrentCall`, a weak reference the call clears as it ends). When Gemini interrupts a reply, the report keeps the last ten microphone-gate decisions at that moment: diff --git a/docs/HERMES_BOT_MODE.md b/docs/HERMES_BOT_MODE.md index 15f62d23..d9af7cdb 100644 --- a/docs/HERMES_BOT_MODE.md +++ b/docs/HERMES_BOT_MODE.md @@ -4,6 +4,10 @@ > the app's native WebSocket connection to the dashboard. The retired bighelp Link relay plays no part. Some type > names still say `Link` (for example `BighelpLinkHermesBotModeClient`, aliased as `HermesHostedRoomClient`); they > are legacy names only. +> +> The name: "Bot Mode" is Hermes' word for its hosted group chats, and file and type names keep it (`BotModeRoom`, +> `BotModeRoomStore`). It is not the app's old Bots mode, which is gone. Today the first tab's Bots view lists bots +> and group chats, and every group chat is also a row in the Chats view. ## Product boundary @@ -89,8 +93,8 @@ never truncated to fit transport. A room can hold agents from any number of the person's computers (Hermes RoomLink). Cross-gateway links are direct gateway-to-gateway connections; the -app only carries the setup. New chat › Group chat in the all-computers view -takes agents from any computer, and the first agent's computer is the room's +app only carries the setup. New chat's To row takes two to six bots from any computer +while Show every computer is on, and the first bot's computer is the room's home. For each agent on another computer: 1. That computer: `groups.capabilities {profile}` gives `room_link.catalog` @@ -112,8 +116,8 @@ sign-ins (`RegistryRoomPeerHosts`). A peer member never takes a local profile's name or picture, even one with the same profile ID. `Scripts/RoomLinkProbe.py` checks the whole flow on two isolated real hosts. -A peer member shows its own computer's current name and picture: the -all-computers view keeps a copy of each computer's agents +A peer member shows its own computer's current name and picture: Show every computer +keeps a copy of each computer's agents (`FleetStore.peerAgent`, found by `peer_id`), and a room with peers on screen reads those computers again when the copy is old. While such a room is on screen, the app holds a connection to each of those computers diff --git a/docs/IOS27_DESIGN_CONTRACT.md b/docs/IOS27_DESIGN_CONTRACT.md index a639f0a5..d1e2fdc9 100644 --- a/docs/IOS27_DESIGN_CONTRACT.md +++ b/docs/IOS27_DESIGN_CONTRACT.md @@ -14,14 +14,14 @@ The retained Figma design-context responses establish native toolbar, sheet tool A new user should understand how to connect and chat in roughly 30 seconds, with the low effort of Muse AI or similar chat apps. This is a comprehension target, not an unmeasured authentication-time guarantee. Keep one obvious primary action, group related settings in clear menus, and keep those settings editable. A setting does not need a separate screen. The source inventory preserves capabilities; it is not a page quota. Use progressive disclosure for advanced choices and recovery mechanics without hiding safety consequences. -The first-run path (`FirstRunOnboardingView`) is Welcome → Connect → Choose your mode, with optional steps between them. The progress bar counts four steps: Welcome, Connect, Plugin or Notifications, and Your mode. +The first-run path (`FirstRunOnboardingView`) is Welcome → Connect → How to start, with optional steps between them. The progress bar counts four steps: Welcome, Connect, Plugin or Notifications, and How to start. 1. **Welcome.** Get Started goes on to Connect. A small Appearance options button under it opens the optional Appearance step (System, Light or Dark, and the bubble color). That step has Back and Skip, is not counted in the progress bar, and goes on to Connect. Appearance stays editable in Settings. 2. **AI data agreement.** Before Connect, anyone who hasn't agreed yet is asked once (`AIDataConsent`). 3. **Connect.** Host setup. It has no Skip. 4. **Plugin.** Optional, with Skip. It installs the bighelp plugin on the computer. -5. **Notifications.** Optional, with Skip. It shows only after the plugin is installed and running. Skip on the plugin step, or a plugin that still needs Hermes restarted, goes straight to the mode. -6. **Choose your mode.** No Skip. The cards are Bots, Chat and Code (`FirstRunMode` `.bots`, `.sessions`, `.code`). Tapping a card shows its preview large, with its Use button. The screen says the choice can be changed later. +5. **Notifications.** Optional, with Skip. It shows only after the plugin is installed and running. Skip on the plugin step, or a plugin that still needs Hermes restarted, goes straight to How to start. +6. **How do you want to start?** No Skip. Two cards, With a bot (opens on Bots) and Across chats (opens on Chats) (`FirstRunHome` `.bots`, `.chats`), each with a small drawn sketch of that home, and Continue. The choice sets Opens on. The screen says it can be changed in Settings › Chat. ## Visual system @@ -39,7 +39,7 @@ Use native navigation, toolbars, search, lists, forms, sections, menus, alerts, ## Conversation hierarchy -- Conversations are the primary root. Search, existing filters, pins, groups and compose remain reachable. +- Conversations are the first tab (the Bots and Chats views). Search, existing filters, pins, groups and compose remain reachable. - Direct identity is centered in the conversation toolbar and opens genuine details. Group headers use actual participant identities; incoming group messages identify their real speaker. - Incoming prose uses neutral bubbles. Outgoing bubbles carry the selected accent. Rich content retains a wider bounded lane and its existing renderer. - Work trails expose actual ordered events, delegated identity, lifecycle and detail disclosure. No timer-generated success or synthetic progress. diff --git a/docs/LOCALIZATION.md b/docs/LOCALIZATION.md index f341247b..2cb7689a 100644 --- a/docs/LOCALIZATION.md +++ b/docs/LOCALIZATION.md @@ -9,37 +9,35 @@ not a claim that the whole app is translated. - First-run welcome, optional appearance controls, AI data consent, connection headings and sign-in controls, plugin introduction, notification introduction, - and mode selection. -- Main bottom-bar labels, menu destinations, host-switcher controls, recent-chat - controls, and the equivalent Mac menu-bar tab names. + and how to start. +- Main bottom-bar labels, host-switcher controls, recent-chat controls, and the + equivalent Mac menu-bar place names. - Core chat composer placeholders and accessibility labels, send/stop/voice controls, mid-turn send choices, and attachment/action-menu labels. -- Top-level Settings rows, identity controls, experience switches, appearance - summary, assistant rows, and the Advanced options entry (Nerd Mode in code). +- Top-level Settings rows, identity controls, appearance + summary, bot rows, and the Advanced options entry (the code name is Nerd Mode). The second stage (#527) adds: -- Bots mode (Simple Bot mode before 2.6.11): the home (pinned bots, the list, search, - the + menu, a bot's long-press menu, Rearrange, the gateway filter), New Bot and its +- The Bots view (the first tab's view, once called Bots mode): the home (pinned bots, the list, search, + the + menu, a bot's long-press menu, Rearrange, the computer filter), New Bot and its Templates sheet, New Group Chat, a bot's profile (Info, Computer, Files and Media tabs, - Instructions, Default Model, Routines), the voice bar, the opening loader, and its - Settings entry (the person's circle, which now opens the one Settings). + Instructions, Default Model, Routines), the voice bar, the opening loader, and the person's + circle, which opens the one Settings. - Teamwork: the line where agents talk to each other ("Asked …", "… answered", "N messages with …"), its sheet, the working and typing states, and the Teamwork - switch with its line. In Bots mode the switch says bots in sentences of its own. -- The Settings pages these lead to: Experience, Assistants, Notifications (topics, + switch with its line. Where the Bots view reaches it, the switch says bots in sentences of its own. +- The Settings pages these lead to: Models, Voice, Notifications (topics, "Bots messaging each other", channels, workflows, Quiet hours, test and turn-off), - Chat (with the Advanced options sections), and Appearance with Chat layout and App layout. -- The modes after their 2.6.11 rename: Bots, Chat and Code, Settings › Modes (its picker and the - Header mode switcher), and the mode edge swipes. + Chat (with the Advanced options sections), and Appearance with Chat layout. - Needs you and a blueprint's chips in the message box. The Chinese text is an AI-assisted draft and remains `needs_review` in the catalog. It has not received professional or fluent-speaker approval. Screenshots and automated checks establish rendering and lookup, not linguistic certification. Keep `bighelp`, `Hermes`, provider/model names, and product names intact. Terminology: -the modes are Bots = 机器人, Chat = 聊天 and Code = 代码 (Bots mode = 机器人模式, -Code mode = 代码模式; the Chat mode was called Sessions before 2.6.11). A list of +Bots = 机器人 and Chat = 聊天 (the first tab's two views; they were the modes Bots mode = 机器人模式 +and Chat mode, which was called Sessions before 2.6.11). A list of chats is still Sessions = 会话. Agents = 智能体, Feed = 动态, Ideas = 灵感, Goals = 目标, host/computer = 电脑, Teamwork = 团队协作, primary bot = 主机器人, gateway = 网关, template = 模板, routine = 例行任务, pin = 置顶, Quiet Hours = 勿扰时段, @@ -50,7 +48,7 @@ channel = 渠道, Live Activities = 实时活动, Dynamic Island = 灵动岛. Use a SwiftUI localized literal where the API accepts one: ```swift -Text("Choose your mode") +Text("How do you want to start?") Button("Continue", action: next) ``` @@ -84,7 +82,7 @@ existing "A, B and C" without a serial comma. A word swap can't be translated. When one screen says bots where another says agents, give it whole sentences of its own (Teamwork's `detail(saysBots:)`). When the same English means two things, give one of them its own key and keep the -English with `defaultValue:` (the Bots mode + button's "New" is not the unread +English with `defaultValue:` (the Bots view's + button's "New" is not the unread badge's "New"). ## Catalog and build workflow @@ -134,9 +132,9 @@ Notifications › Advanced › Provider details and the notification setup's sta and error messages, catalog template text, and chat tool phrases (so a running agent-talk line reads "Nova:searching the web…"). The notification service names its topics in English; every language, English too, shows the app's own words for -those topics (Replies, Questions and approvals, Helper results). Onboarding mode-preview images still contain English -demo text; localize those assets in a later screenshot pass. A translated menu -entry does not imply its entire destination is translated. +those topics (Replies, Questions and approvals, Helper results). The one home's own screens (the Chats view, +Today, Work, New chat's To row and choices, spaces) are English until their copy is added to the catalog. A translated +menu entry does not imply its entire destination is translated. Watch, widgets, Live Activities, notification extension copy, Shortcuts, CarPlay, spatial-only controls, privacy usage descriptions in Info.plist, and App Store diff --git a/docs/SECURITY_AND_PRIVACY.md b/docs/SECURITY_AND_PRIVACY.md index 64e95ccf..89bf9c43 100644 --- a/docs/SECURITY_AND_PRIVACY.md +++ b/docs/SECURITY_AND_PRIVACY.md @@ -83,7 +83,7 @@ gzip-compressed when that is smaller, with a 5-second timeout. It holds: | Event | What it carries | |---|---| | `app.opened`, `app.backgrounded`, `session.ended` | whether it was a cold start; time in the foreground; session length | - | `feature.used` | which of 14 fixed features was used: chat sent, card drawn, card answered, voice turn, live voice, workflow run, mode switched, agent opened, file opened, Shortcut run (counted after the AI-data agreement), widget opened (any `loopdy://` link the system opens: mostly widgets, also Live Activity and alert links), CarPlay voice, Watch chat, notification opened | + | `feature.used` | which of 13 fixed features was used: chat sent, card drawn, card answered, voice turn, live voice, workflow run, agent opened, file opened, Shortcut run (counted after the AI-data agreement), widget opened (any `loopdy://` link the system opens: mostly widgets, also Live Activity and alert links), CarPlay voice, Watch chat, notification opened | | `perf.first_token_ms`, `perf.reconnect` | milliseconds from Send to the first streamed word; how long a reconnect took and whether it worked | | `perf.launch` | MetricKit's launch histograms: the middle bucket and how many launches | | `hang`, `crash` | MetricKit's reports: exception type, code and signal as numbers, and up to 64 stack frames as a binary UUID, an offset and the binary's name | @@ -419,8 +419,8 @@ Nothing leaves the device until the person opens bighelp, picks the agent and chat, and taps Send there: the share goes into that chat's message box, and the usual AI data agreement, computer and attachment checks apply. bighelp deletes a share from the device only once Hermes takes the message that carries it, or when -the person deletes it (☰ › Shared with bighelp, or the first screen of Settings, lists -every waiting share). Before a message carrying a share goes, bighelp saves that +the person deletes it (Today's Shared with bighelp card, the first screen of Settings and the +sidebar's More open the list of every waiting share). Before a message carrying a share goes, bighelp saves that it's being sent; if it can't, the message isn't sent. Once Hermes takes it, the share is marked spent first, so it's never offered again even if deleting it has to wait. A message still waiting for its connection or refused keeps the share as @@ -627,8 +627,8 @@ Authorized Wiki metadata can disclose the chosen absolute source folder to the a ## Group presentation preferences -The Agents screen keeps pinned and archived group preferences locally on this -device, scoped to the authenticated workspace. Archiving here hides the group -from the active Agents list; Archived groups can restore it. This does not stop -Hermes work or delete its transcript. Delete is a separate confirmed action through Hermes' native +The Bots view keeps each group chat's pin, hidden state and section on this device, by +computer, and also on the person's computers (`bots.layout`, plugin `native-app-state-v1`). +Hiding a group removes it from the Bots view's list, and search's filter can show it again. +This does not stop Hermes work or delete its transcript. Delete is a separate confirmed action through Hermes' native `groups.disband` operation, which stops the room and permanently retires its ID. diff --git a/docs/SPACES.md b/docs/SPACES.md new file mode 100644 index 00000000..98a45d8d --- /dev/null +++ b/docs/SPACES.md @@ -0,0 +1,141 @@ +# Spaces + +A space is a live panel on Today. A bot drafts it in a chat. The person adds it with **Add to +Today**. A routine on the computer then keeps it current. Each space has a card (what the panel +shows) and an HTML page (what a tap opens). + +The plugin feature is `native-spaces-v1`. This page is the app's side. The wire contract (routes, +the space object, errors, the routine) is bighelp-plugin's docs/SPACES.md. Do not copy it here. + +The code is in `Bighelp/Spaces/`. Today's grid is in `Bighelp/Today/`. + +## Where the spaces come from + +- `SpacesHost` lists the person's computers (`SpacesComputer`). The computer in use is first. The + app sets it up in `BighelpApp.wireSpaces`. +- The computer in use, and the others that Show every computer keeps connected, are + read live. Every other computer shows what the phone kept. +- Each computer has one `SpacesStore`, kept by its cache scope (`WorkspaceAuthority.cacheScopeID`). + A reconnect is a new owner with the same scope, so it keeps the same store. +- `TodaySpacesModel` reads all the stores together, in one order: by position, then the computer, + then the title. +- Demo mode uses `DemoSpacesClient` for the spaces and `DemoHTMLAppsClient` for their pages. + +## Reading + +- Today reads every computer when it shows, when the app comes back, and every minute while it + shows (`TodaySpacesModel.watch`). +- A read names the computer's bots (64 at most a call). Before the bots are known, nothing is read. +- The read sends the card hashes the phone has (`known`). The computer leaves those cards out. + Cards it left out to keep the answer small (`cardOmitted`) are read with `get`, 24 at most a read. +- The phone keeps a copy of each computer's spaces in Caches (`BighelpSpaces`). Today draws it at + once. A copy over 6 MiB is kept without its cards. +- A computer that is not connected keeps its panels. Each panel says "Not connected". +- Only the plugin's own context says the feature is missing. Then Today shows "Update the plugin on + to see its spaces." A refused route during a reconnect never says that. + +## Adding + +- The chat draws the `space_draft` card (`SpaceDraftCardView`). It reads the draft with `get` and + shows the panel as Today will draw it. +- The person picks Small, Wide or Tall. Add sends the revision the card shows. +- Add puts the space after every space on Today. If Today did not show yet, the model reads the + computer first, so the space is on Today at once. +- The answers the card acts on: + +| Answer | The card | +|---|---| +| The space | On Today, with Open Today | +| `draft_changed` | Reads the draft again: "The bot changed this space. Check it, then add it." | +| `invalid_request` (422) | "This space's script is missing. Ask the bot to make it again." | +| `spaces_full` | "This bot has as many spaces as it can keep. Delete one on Today first." | +| `schedules_unavailable` | "Your computer can't run scheduled tasks right now." | +| `space_not_found` | Removed | +| No answer | "Could not reach your computer. Try again." | + +- Open Today calls `SpaceDraftCardHost.openToday`. The shell sets it. + +## Size, hide and order + +- A space's size, hidden state and place belong to its computer, not to this phone. Its panel + descriptor has `keepsOwnLayout`, and `TodayPanelLayoutStore.ownedChanges` sends the person's + changes to `SpacesTodayBridge`. +- A change shows at once (`SpacesStore.stage`), then goes to the computer with `update`. +- A refusal undoes it. No answer keeps it, and the next read sends it again. +- A change waiting for its answer is sent again only as the same request, with the same + `operationId`. A change on top of it is a new request with a new `operationId`. The plugin refuses + an `operationId` it saw with another body. +- Changes to one space go to the computer one at a time (`SpacesStore.send`). A change made while + one is on its way goes when that one ends, so the computer ends on the last choice. +- Edit's drag gives every space a new place, 1,024 apart. The new order shows before any computer + answers, so a panel never jumps back. +- A hidden space keeps updating. Edit lists it under Hidden. + +## Update now + +- Update now (the panel's menu) and Try again (a stopped panel) call `refresh`. +- A script runs at once (`ran: "now"`). An AI routine runs on the computer's next tick (`queued`). +- A paused AI routine runs nothing (`paused`). The panel says "Paused in Scheduled tasks". +- `routine_failed` (502): the run failed. The panel shows the space as the computer read it, with + "Its update failed". +- `refresh_too_soon`: "Try again in a minute". +- A refusal of the menu's Update now shows as one line under Today's header (`TodayNotice`), which + VoiceOver also speaks. + +## Deleting + +- Delete asks first ("Delete this space?"). The space goes off Today at once. +- No answer, no connection, or `schedules_unavailable` (503): the computer has not finished. The + space stays off Today, and the same request (same `operationId`) goes again at each read until + the computer answers. The phone keeps the waiting delete across launches. +- A definite refusal brings the space back, in its place, and a line under Today's header says so. +- Edit has a Delete button on each space's row. VoiceOver reaches Open, Update now and Delete from + the panel's Actions menu. + +## What keeps a space, and what removes it + +- A read asks about every bot in the computer's list and every bot the phone holds spaces for. +- Only the computer's answer removes a space: the space is not in the list any more, or the bot is + gone (`profile_not_found`). A bot list that is short for a moment (a reconnect, a computer + switch) removes nothing. +- Removing a computer in Settings erases its spaces from the phone (`TodaySpacesModel.forget`). + +## A space's page + +- The page loads from its own `bighelp-app:///` origin and reads only its own data. +- It never sends a message, whatever the plugin says the page may do. +- Only a link the person taps, to an `http` or `https` address, opens outside. The app drops every + other navigation off the page: a script's own navigation or `window.open`, and every other + scheme, bighelp's own links included (`HTMLAppNavigationPolicy`). +- The title and description a bot writes are cut to the wire maximums as they are read. + +## What a panel shows + +`SpacePanelView` draws the title, the bot (and the computer with two or more), the card at the +panel's size in a fixed frame, and one footer line (`SpacePanelFooter`): + +| State | Footer | +|---|---| +| Fresh or stale | "Updated 2:14 PM" (the space's own `updatedAt`), and "Uses AI" when it does | +| Stopped (`missing`, `failed`, `late`, unknown) | "Stopped updating" and Try again | +| Paused in Scheduled tasks | "Paused in Scheduled tasks", no Try again | +| `script_changed` | "Stopped: its script changed", no Try again. The bot drafts it again and the person adds it again. | +| Not connected | "Not connected"; the last card stays | +| Card not read yet | A still placeholder | +| Card the app can't draw | "Can't show this" | + +A tap opens the space's page in `HTMLAppScreen`, on the space's own computer +(`TodaySpacesModel.pageConnection`). A space's page never sends a message. + +## Demo and tests + +- `-use-demo-fixtures -test-spaces` opens the finance bot's chat with a space draft. +- `-test-spaces-today` shows Today's grid alone with the demo computer's spaces + (`SpacesTodayFixture`). +- `DemoSpacesClient` answers as the plugin does: the draft's revision, an `operationId` that only + repeats the same request, the refresh gap, a paused AI routine, a changed script, a script that is + gone (`missingScripts`) and a delete Hermes can't finish yet (`stuckTasks`). +- Unit tests: `SpacesWireTests`, `SpacesStoreTests`, `TodaySpacesModelTests`, + `SpacePanelStateTests`, `SpaceDraftCardStateTests` and `TodayPanelLayoutTests`. The shared card + example is `BighelpTests/Fixtures/CardExamples/static-space-draft.json`, the same bytes as the + plugin's. diff --git a/docs/WORKSPACE_MANAGEMENT.md b/docs/WORKSPACE_MANAGEMENT.md index d98aab27..b03cd6b3 100644 --- a/docs/WORKSPACE_MANAGEMENT.md +++ b/docs/WORKSPACE_MANAGEMENT.md @@ -15,7 +15,7 @@ logs, webhooks, tool backends, diagnostics, backups and the other host pages on computer's page (Advanced groups, with Advanced options on); Clean up chats in Settings › Chat; Toolsets and Manage bots in a bot's Advanced Options. Scratchpad, GitHub and Wiki remain retired from app navigation, and the contract also leaves -out Usage (☰ › Usage) and the destinations for this app's own settings, which +out Usage (the first group of Settings, and the sidebar's More) and the destinations for this app's own settings, which live in Settings. Native Wiki contracts and clients remain for older hosts that still list `native-wiki-v1` (current plugin releases no longer have the Wiki routes), without adding a diff --git a/docs/hermes/CHAT.md b/docs/hermes/CHAT.md index 3cfcb0c6..ae500f69 100644 --- a/docs/hermes/CHAT.md +++ b/docs/hermes/CHAT.md @@ -220,9 +220,9 @@ The response consumed here has `pairs:[["/name","description"],...]` (at most 2, A dispatcher may return `{type:"skill"|"send",message:}`. That is an instruction to the client, not proof that a turn started. Submit those exact bytes once through `prompt.submit` with `queued:true`, then use normal admission/terminal rules. `/plan` and skills can depend on this expansion. If a command returns `output` and is not `streaming`/`queued`, show that output once as a command result and settle immediately. A command whose expansion/submit outcome is unknown must not be rerun. -The first message in Code mode must use the same command router; sending a leading slash directly as `prompt.submit.text` bypasses command expansion. The menu selection is validated against the current text before dispatch, so editing the command cannot execute a stale selected entry. +The first message of a coding session (New chat with a project) must use the same command router; sending a leading slash directly as `prompt.submit.text` bypasses command expansion. The menu selection is validated against the current text before dispatch, so editing the command cannot execute a stale selected entry. -Sources: [catalog decoder](../../Bighelp/Chat/SlashCommands.swift), [command dispatcher and fallback](../../Bighelp/DirectHermes/DirectHermesConversationClient+Submission.swift), [command tests](../../BighelpTests/DirectHermesConversationTests.swift), [Code mode guidance](../../AGENTS.md). +Sources: [catalog decoder](../../Bighelp/Chat/SlashCommands.swift), [command dispatcher and fallback](../../Bighelp/DirectHermes/DirectHermesConversationClient+Submission.swift), [command tests](../../BighelpTests/DirectHermesConversationTests.swift), [coding sessions guidance](../../AGENTS.md). ## 7. Live event envelopes and payloads diff --git a/scripts/ci_release_validation.py b/scripts/ci_release_validation.py index 37601fcb..71df0db8 100644 --- a/scripts/ci_release_validation.py +++ b/scripts/ci_release_validation.py @@ -8,15 +8,15 @@ from pathlib import Path from urllib.request import Request, urlopen -PROFILE = "release-smoke-v2" +PROFILE = "release-smoke-v3" WORKFLOW = ".github/workflows/ios-ci.yml" UI_TESTS = ( "ReferenceHubUITests/testMiddleSlashCommandWorksWithoutRetiredProviders", "ReferenceHubUITests/testDarkLargeTextDrawerPreservesKeyboardAndDraft", "ReferenceHubUITests/testSendKeepsKeyboardClosedWhileChatUpdates", - "AgentsUITests/testChatsOpenedFromAgentsKeepTheTabBar", - "BoardSwipeBlueprintsUITests/testBlueprintsAskForTheBlanksThenSendOrEdit", - "DefaultModelUITests/testDefaultModelSurvivesProviderKeysAndComingBack", + "HomeShellUITests/testAChatIsAPushedPageWithBackTheBotAndNoBar", + "BoardSwipeBlueprintsUITests/testBlueprintsGoToTheMessageBoxWithTheirBlanksAsChips", + "DefaultModelUITests/testModelsSurvivesABotsPageAndComingBack", ) diff --git a/scripts/ci_ui_test_shard.py b/scripts/ci_ui_test_shard.py index 7331f652..d38e830d 100644 --- a/scripts/ci_ui_test_shard.py +++ b/scripts/ci_ui_test_shard.py @@ -7,8 +7,10 @@ from pathlib import Path +# The one test that rotates an iPad and checks a chat's header. The Duo's other tests skip on an iPad +# or run on the Duo's own simulator. IPAD_TESTS = ( - "AgentsUITests/testLastRowClearsSearchAndNavigationInPortraitAndLandscape", + "DuoLayoutUITests/testIPadBotSwitcherStaysBelowStatusBar", ) SELECTOR_PREFIX = "-only-testing:BighelpUITests/" diff --git a/scripts/test_ci_release_validation.py b/scripts/test_ci_release_validation.py index da132c47..6e6a67a7 100644 --- a/scripts/test_ci_release_validation.py +++ b/scripts/test_ci_release_validation.py @@ -52,7 +52,7 @@ def test_current_shards_cover_every_test_once_and_have_real_ipad_assignments(sel self.assertEqual(len(assigned), len(set(assigned))) self.assertEqual(set(assigned), set(selectors(root))) self.assertIn( - "-only-testing:BighelpUITests/AgentsUITests/testLastRowClearsSearchAndNavigationInPortraitAndLandscape", + "-only-testing:BighelpUITests/DuoLayoutUITests/testIPadBotSwitcherStaysBelowStatusBar", shards["ui-ipad"], )