From f6be2902916042e3c01c20c547f7ea5ae7d4d1d5 Mon Sep 17 00:00:00 2001 From: Ryan Cartwright Date: Thu, 5 Nov 2026 11:16:42 +1100 Subject: [PATCH 1/2] feat(ios): add a native iPhone app that copies the phone web, signing in to a workspace by its own server --- .github/workflows/ios.yml | 41 + apps/codegen/generate-trigger-kinds.ts | 69 + apps/codegen/generate.ts | 2 + apps/ios/.gitignore | 3 + apps/ios/README.md | 86 ++ apps/ios/Sugabots.xcodeproj/project.pbxproj | 850 ++++++++++++ .../xcshareddata/IDEWorkspaceChecks.plist | 8 + apps/ios/Sugabots/API/ArtifactModels.swift | 57 + apps/ios/Sugabots/API/EventStream.swift | 105 ++ apps/ios/Sugabots/API/SettingsModels.swift | 88 ++ apps/ios/Sugabots/App/DebugLaunch.swift | 181 +++ apps/ios/Sugabots/App/DebugOpenHome.swift | 97 ++ apps/ios/Sugabots/App/Invites.swift | 23 + apps/ios/Sugabots/App/Route.swift | 33 + apps/ios/Sugabots/App/Session.swift | 223 ++++ apps/ios/Sugabots/App/Slugify.swift | 16 + apps/ios/Sugabots/App/SugabotsApp.swift | 362 ++++++ .../Sugabots/App/WorkspacePreferences.swift | 59 + .../App/WorkspaceStore+Artifacts.swift | 36 + .../App/WorkspaceStore+Conversations.swift | 70 + .../App/WorkspaceStore+Routines.swift | 145 +++ .../App/WorkspaceStore+Settings.swift | 212 +++ apps/ios/Sugabots/App/WorkspaceStore.swift | 423 ++++++ .../Sugabots/Artifacts/ArtifactCards.swift | 206 +++ .../Sugabots/Artifacts/ArtifactFrame.swift | 175 +++ .../Sugabots/Artifacts/ArtifactsPage.swift | 309 +++++ .../AccentColor.colorset/Contents.json | 23 + .../AppIcon.appiconset/AppIcon.png | Bin 0 -> 39953 bytes .../AppIcon.appiconset/Contents.json | 14 + .../Sugabots/Assets.xcassets/Contents.json | 6 + .../Mark.imageset/Contents.json | 12 + .../Assets.xcassets/Mark.imageset/Mark.png | Bin 0 -> 4589 bytes .../Sugabots/Attention/ApprovalsScreen.swift | 253 ++++ apps/ios/Sugabots/Attention/InboxScreen.swift | 299 +++++ apps/ios/Sugabots/Attention/YouScreen.swift | 245 ++++ .../Sugabots/Conversation/ActivityState.swift | 54 + .../Sugabots/Conversation/ApprovalCard.swift | 462 +++++++ .../Conversation/BotDetailsSections.swift | 110 ++ apps/ios/Sugabots/Conversation/Composer.swift | 491 +++++++ .../Sugabots/Conversation/ComputerSheet.swift | 130 ++ .../Conversation/ConversationDetails.swift | 357 +++++ .../Conversation/ConversationHeader.swift | 371 ++++++ .../Conversation/ConversationModel.swift | 648 ++++++++++ .../Conversation/ConversationScreen.swift | 666 ++++++++++ .../Sugabots/Conversation/DesktopView.swift | 78 ++ .../Sugabots/Conversation/MentionEditor.swift | 231 ++++ .../Sugabots/Conversation/MessageFiles.swift | 258 ++++ .../Conversation/MessageMarkdown.swift | 238 ++++ .../Sugabots/Conversation/MessageRow.swift | 666 ++++++++++ .../Conversation/NewThreadScreen.swift | 218 ++++ .../Sugabots/Conversation/RoutineRun.swift | 91 ++ .../Conversation/SideThreadSheet.swift | 115 ++ apps/ios/Sugabots/Conversation/ToolLine.swift | 169 +++ apps/ios/Sugabots/Design/ColourSwatches.swift | 54 + .../Sugabots/Design/ConfirmDeleteDialog.swift | 104 ++ apps/ios/Sugabots/Design/ConnectionMark.swift | 177 +++ apps/ios/Sugabots/Design/Controls.swift | 338 +++++ apps/ios/Sugabots/Design/Faces.swift | 211 +++ apps/ios/Sugabots/Design/Icon.swift | 35 + apps/ios/Sugabots/Design/LookGlyphs.swift | 128 ++ apps/ios/Sugabots/Design/Palette.swift | 89 ++ apps/ios/Sugabots/Design/ProviderTile.swift | 31 + apps/ios/Sugabots/Design/SVGPath.swift | 242 ++++ apps/ios/Sugabots/Design/WebControls.swift | 1147 +++++++++++++++++ apps/ios/Sugabots/Emoji/EmojiData.swift | 176 +++ apps/ios/Sugabots/Emoji/EmojiPicker.swift | 173 +++ apps/ios/Sugabots/Fonts/JetBrainsMono.woff2 | Bin 0 -> 40404 bytes apps/ios/Sugabots/Fonts/OFL-JetBrainsMono.txt | 93 ++ apps/ios/Sugabots/Fonts/OFL-Rubik.txt | 93 ++ apps/ios/Sugabots/Fonts/Rubik.ttf | Bin 0 -> 359804 bytes apps/ios/Sugabots/Home/ChannelScreens.swift | 62 + apps/ios/Sugabots/Home/ConversationList.swift | 440 +++++++ apps/ios/Sugabots/Home/HomeScreen.swift | 153 +++ apps/ios/Sugabots/Home/HomeSheets.swift | 270 ++++ apps/ios/Sugabots/Info.plist | 17 + apps/ios/Sugabots/NewBot/ModelPicker.swift | 182 +++ apps/ios/Sugabots/NewBot/NewBotScreen.swift | 136 ++ .../Onboarding/OnboardingScreen.swift | 751 +++++++++++ .../Sugabots/Onboarding/WorkspaceSetup.swift | 43 + .../Sugabots/Routines/NewRoutineScreen.swift | 332 +++++ .../Sugabots/Routines/RoutineControls.swift | 49 + apps/ios/Sugabots/Routines/RoutinePanel.swift | 526 ++++++++ .../Sugabots/Routines/RoutinesScreen.swift | 150 +++ .../Sugabots/Routines/TriggerEditing.swift | 819 ++++++++++++ .../Routines/TriggerKinds.generated.swift | 46 + .../ios/Sugabots/Settings/AgentSettings.swift | 474 +++++++ .../Sugabots/Settings/ConnectionPage.swift | 537 ++++++++ .../Settings/ConnectionsSettings.swift | 380 ++++++ apps/ios/Sugabots/Settings/DebugOpen.swift | 22 + .../Sugabots/Settings/GeneralSettings.swift | 286 ++++ .../Sugabots/Settings/MembersSettings.swift | 336 +++++ .../Sugabots/Settings/ModelsSettings.swift | 216 ++++ .../Settings/NotificationsSettings.swift | 270 ++++ apps/ios/Sugabots/Settings/PodSettings.swift | 431 +++++++ .../Sugabots/Settings/ProviderSettings.swift | 872 +++++++++++++ .../Sugabots/Settings/SandboxSettings.swift | 519 ++++++++ .../Sugabots/Settings/SettingsControls.swift | 500 +++++++ .../Sugabots/Settings/SettingsRoutes.swift | 124 ++ .../ios/Sugabots/Settings/SettingsRules.swift | 299 +++++ .../ios/Sugabots/Settings/UsageSettings.swift | 353 +++++ .../Sugabots/Settings/WebSearchSettings.swift | 193 +++ apps/ios/Sugabots/SignIn/SignInScreen.swift | 595 +++++++++ 102 files changed, 23558 insertions(+) create mode 100644 .github/workflows/ios.yml create mode 100644 apps/codegen/generate-trigger-kinds.ts create mode 100644 apps/ios/.gitignore create mode 100644 apps/ios/README.md create mode 100644 apps/ios/Sugabots.xcodeproj/project.pbxproj create mode 100644 apps/ios/Sugabots.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 apps/ios/Sugabots/API/ArtifactModels.swift create mode 100644 apps/ios/Sugabots/API/EventStream.swift create mode 100644 apps/ios/Sugabots/API/SettingsModels.swift create mode 100644 apps/ios/Sugabots/App/DebugLaunch.swift create mode 100644 apps/ios/Sugabots/App/DebugOpenHome.swift create mode 100644 apps/ios/Sugabots/App/Invites.swift create mode 100644 apps/ios/Sugabots/App/Route.swift create mode 100644 apps/ios/Sugabots/App/Session.swift create mode 100644 apps/ios/Sugabots/App/Slugify.swift create mode 100644 apps/ios/Sugabots/App/SugabotsApp.swift create mode 100644 apps/ios/Sugabots/App/WorkspacePreferences.swift create mode 100644 apps/ios/Sugabots/App/WorkspaceStore+Artifacts.swift create mode 100644 apps/ios/Sugabots/App/WorkspaceStore+Conversations.swift create mode 100644 apps/ios/Sugabots/App/WorkspaceStore+Routines.swift create mode 100644 apps/ios/Sugabots/App/WorkspaceStore+Settings.swift create mode 100644 apps/ios/Sugabots/App/WorkspaceStore.swift create mode 100644 apps/ios/Sugabots/Artifacts/ArtifactCards.swift create mode 100644 apps/ios/Sugabots/Artifacts/ArtifactFrame.swift create mode 100644 apps/ios/Sugabots/Artifacts/ArtifactsPage.swift create mode 100644 apps/ios/Sugabots/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/AppIcon.png create mode 100644 apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 apps/ios/Sugabots/Assets.xcassets/Contents.json create mode 100644 apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Contents.json create mode 100644 apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Mark.png create mode 100644 apps/ios/Sugabots/Attention/ApprovalsScreen.swift create mode 100644 apps/ios/Sugabots/Attention/InboxScreen.swift create mode 100644 apps/ios/Sugabots/Attention/YouScreen.swift create mode 100644 apps/ios/Sugabots/Conversation/ActivityState.swift create mode 100644 apps/ios/Sugabots/Conversation/ApprovalCard.swift create mode 100644 apps/ios/Sugabots/Conversation/BotDetailsSections.swift create mode 100644 apps/ios/Sugabots/Conversation/Composer.swift create mode 100644 apps/ios/Sugabots/Conversation/ComputerSheet.swift create mode 100644 apps/ios/Sugabots/Conversation/ConversationDetails.swift create mode 100644 apps/ios/Sugabots/Conversation/ConversationHeader.swift create mode 100644 apps/ios/Sugabots/Conversation/ConversationModel.swift create mode 100644 apps/ios/Sugabots/Conversation/ConversationScreen.swift create mode 100644 apps/ios/Sugabots/Conversation/DesktopView.swift create mode 100644 apps/ios/Sugabots/Conversation/MentionEditor.swift create mode 100644 apps/ios/Sugabots/Conversation/MessageFiles.swift create mode 100644 apps/ios/Sugabots/Conversation/MessageMarkdown.swift create mode 100644 apps/ios/Sugabots/Conversation/MessageRow.swift create mode 100644 apps/ios/Sugabots/Conversation/NewThreadScreen.swift create mode 100644 apps/ios/Sugabots/Conversation/RoutineRun.swift create mode 100644 apps/ios/Sugabots/Conversation/SideThreadSheet.swift create mode 100644 apps/ios/Sugabots/Conversation/ToolLine.swift create mode 100644 apps/ios/Sugabots/Design/ColourSwatches.swift create mode 100644 apps/ios/Sugabots/Design/ConfirmDeleteDialog.swift create mode 100644 apps/ios/Sugabots/Design/ConnectionMark.swift create mode 100644 apps/ios/Sugabots/Design/Controls.swift create mode 100644 apps/ios/Sugabots/Design/Faces.swift create mode 100644 apps/ios/Sugabots/Design/Icon.swift create mode 100644 apps/ios/Sugabots/Design/LookGlyphs.swift create mode 100644 apps/ios/Sugabots/Design/Palette.swift create mode 100644 apps/ios/Sugabots/Design/ProviderTile.swift create mode 100644 apps/ios/Sugabots/Design/SVGPath.swift create mode 100644 apps/ios/Sugabots/Design/WebControls.swift create mode 100644 apps/ios/Sugabots/Emoji/EmojiData.swift create mode 100644 apps/ios/Sugabots/Emoji/EmojiPicker.swift create mode 100644 apps/ios/Sugabots/Fonts/JetBrainsMono.woff2 create mode 100644 apps/ios/Sugabots/Fonts/OFL-JetBrainsMono.txt create mode 100644 apps/ios/Sugabots/Fonts/OFL-Rubik.txt create mode 100644 apps/ios/Sugabots/Fonts/Rubik.ttf create mode 100644 apps/ios/Sugabots/Home/ChannelScreens.swift create mode 100644 apps/ios/Sugabots/Home/ConversationList.swift create mode 100644 apps/ios/Sugabots/Home/HomeScreen.swift create mode 100644 apps/ios/Sugabots/Home/HomeSheets.swift create mode 100644 apps/ios/Sugabots/Info.plist create mode 100644 apps/ios/Sugabots/NewBot/ModelPicker.swift create mode 100644 apps/ios/Sugabots/NewBot/NewBotScreen.swift create mode 100644 apps/ios/Sugabots/Onboarding/OnboardingScreen.swift create mode 100644 apps/ios/Sugabots/Onboarding/WorkspaceSetup.swift create mode 100644 apps/ios/Sugabots/Routines/NewRoutineScreen.swift create mode 100644 apps/ios/Sugabots/Routines/RoutineControls.swift create mode 100644 apps/ios/Sugabots/Routines/RoutinePanel.swift create mode 100644 apps/ios/Sugabots/Routines/RoutinesScreen.swift create mode 100644 apps/ios/Sugabots/Routines/TriggerEditing.swift create mode 100644 apps/ios/Sugabots/Routines/TriggerKinds.generated.swift create mode 100644 apps/ios/Sugabots/Settings/AgentSettings.swift create mode 100644 apps/ios/Sugabots/Settings/ConnectionPage.swift create mode 100644 apps/ios/Sugabots/Settings/ConnectionsSettings.swift create mode 100644 apps/ios/Sugabots/Settings/DebugOpen.swift create mode 100644 apps/ios/Sugabots/Settings/GeneralSettings.swift create mode 100644 apps/ios/Sugabots/Settings/MembersSettings.swift create mode 100644 apps/ios/Sugabots/Settings/ModelsSettings.swift create mode 100644 apps/ios/Sugabots/Settings/NotificationsSettings.swift create mode 100644 apps/ios/Sugabots/Settings/PodSettings.swift create mode 100644 apps/ios/Sugabots/Settings/ProviderSettings.swift create mode 100644 apps/ios/Sugabots/Settings/SandboxSettings.swift create mode 100644 apps/ios/Sugabots/Settings/SettingsControls.swift create mode 100644 apps/ios/Sugabots/Settings/SettingsRoutes.swift create mode 100644 apps/ios/Sugabots/Settings/SettingsRules.swift create mode 100644 apps/ios/Sugabots/Settings/UsageSettings.swift create mode 100644 apps/ios/Sugabots/Settings/WebSearchSettings.swift create mode 100644 apps/ios/Sugabots/SignIn/SignInScreen.swift diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml new file mode 100644 index 000000000..f5c270109 --- /dev/null +++ b/.github/workflows/ios.yml @@ -0,0 +1,41 @@ +name: iOS + +# Builds the iOS app whenever it or its generators change. The app builds +# against the generated files it last took, so a change to the web or the API +# doesn't run this; it reaches the app when someone regenerates them, which the +# Native apps workflow checks. + +on: + push: + branches: [main] + paths: + - "apps/ios/**" + - "apps/codegen/**" + - ".github/workflows/ios.yml" + pull_request: + paths: + - "apps/ios/**" + - "apps/codegen/**" + - ".github/workflows/ios.yml" + +concurrency: + group: ios-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: Build + # The app is written for a newer Swift than macOS 14's Xcode 15 builds; + # macOS 26's image has Xcode 26 by default. + runs-on: macos-26 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + + - name: Build for the simulator + run: >- + xcodebuild build + -project apps/ios/Sugabots.xcodeproj + -scheme Sugabots + -destination "generic/platform=iOS Simulator" + CODE_SIGNING_ALLOWED=NO diff --git a/apps/codegen/generate-trigger-kinds.ts b/apps/codegen/generate-trigger-kinds.ts new file mode 100644 index 000000000..5c254bba8 --- /dev/null +++ b/apps/codegen/generate-trigger-kinds.ts @@ -0,0 +1,69 @@ +/** + * Writes `Sugabots/Routines/TriggerKinds.generated.swift` from the words in + * `packages/web/src/lib/routine-trigger-words.ts`: each kind of trigger a + * routine may have, as the list of kinds offers it, and what each webhook + * source's sender must do to be let in. + */ +import { + TRIGGER_KINDS, + WEBHOOK_SOURCE_NOTES, +} from "../../packages/web/src/lib/routine-trigger-words.ts"; +import type { GeneratedFiles } from "./generated-files.ts"; + +const string = (text: string) => JSON.stringify(text); + +/** A snake_case value as the camelCase name of its Swift case, as the API's generated enums name them. */ +const swiftCase = (value: string) => + value.replace(/_([a-z0-9])/g, (_, letter: string) => letter.toUpperCase()); + +/** A `switch self` over every kind, each kind's case returning `caseValue` of it. */ +function switchOverKinds(caseValue: (choice: (typeof TRIGGER_KINDS)[number]) => string): string { + return TRIGGER_KINDS.map( + (choice) => `\t\tcase .${swiftCase(choice.kind)}: ${caseValue(choice)}`, + ).join("\n"); +} + +export function swift(): string { + return `// Generated by apps/codegen/generate-trigger-kinds.ts from packages/web/src/lib/routine-trigger-words.ts. Do not edit. + +/// A kind of trigger a routine may have, as \`TRIGGER_KINDS\` lists them: Sugabots' own first. +enum TriggerKind: String, CaseIterable, Identifiable { +${TRIGGER_KINDS.map((choice) => `\tcase ${swiftCase(choice.kind)}${swiftCase(choice.kind) === choice.kind ? "" : ` = ${string(choice.kind)}`}`).join("\n")} + + var id: String { rawValue } + + var label: String { + switch self { +${switchOverKinds((choice) => string(choice.label))} + } + } + + /// What it runs on, in the line under its label. + var sub: String { + switch self { +${switchOverKinds((choice) => string(choice.sub))} + } + } + + /// The kind of connection the bot's pod needs for it, for an integration's trigger. + var connection: ConnectionKind? { + switch self { +${switchOverKinds((choice) => (choice.connection ? `.${swiftCase(choice.connection)}` : "nil"))} + } + } +} + +extension WebhookAuthChoice { + /// What a caller must do to be let in, for each source that signs its own way, as \`WEBHOOK_SOURCE_NOTES\`. + static let sourceNotes: [String: String] = [ +${Object.entries(WEBHOOK_SOURCE_NOTES) + .map(([source, note]) => `\t\t${string(source)}: ${string(note)},`) + .join("\n")} + ] +} +`; +} + +export function generate(): GeneratedFiles { + return { files: new Map([["Sugabots/Routines/TriggerKinds.generated.swift", swift()]]) }; +} diff --git a/apps/codegen/generate.ts b/apps/codegen/generate.ts index 95569a6bf..a8e34463b 100644 --- a/apps/codegen/generate.ts +++ b/apps/codegen/generate.ts @@ -23,6 +23,7 @@ import * as lucideIcons from "./generate-lucide-icons.ts"; import * as nativeConstants from "./generate-native-constants.ts"; import * as palette from "./generate-palette.ts"; import * as providerLogos from "./generate-provider-logos.ts"; +import * as triggerKinds from "./generate-trigger-kinds.ts"; import { type Generator, iosOnly, targetRoots } from "./generated-files.ts"; /** Every generator, by the script that holds it; a test checks each `generate-*.ts` is here. */ @@ -40,6 +41,7 @@ export const generators: Record = { "generate-native-constants.ts": iosOnly(nativeConstants.generate), "generate-palette.ts": iosOnly(palette.generate), "generate-provider-logos.ts": iosOnly(providerLogos.generate), + "generate-trigger-kinds.ts": iosOnly(triggerKinds.generate), }; if (import.meta.main) { diff --git a/apps/ios/.gitignore b/apps/ios/.gitignore new file mode 100644 index 000000000..40e514a2c --- /dev/null +++ b/apps/ios/.gitignore @@ -0,0 +1,3 @@ +xcuserdata/ +*.xcuserstate +DerivedData/ diff --git a/apps/ios/README.md b/apps/ios/README.md new file mode 100644 index 000000000..a2728eb76 --- /dev/null +++ b/apps/ios/README.md @@ -0,0 +1,86 @@ +# Sugabots for iOS + +A native SwiftUI app for iPhone (iOS 17+) that copies the web app's phone layout (`packages/web`, below its `md` breakpoint) screen for screen: the same pages, words, sizes, colour tokens (light, dark or system, dark by default), Rubik and JetBrains Mono, and Lucide icons. It keeps iOS's own behaviour where the two differ: swipe back, sheets you drag down, the keyboard lifting the composer, and long-press menus where the web has hover toolbars. + +- **Home, Inbox, Approvals and You** sit under the web's floating tab bar. +- **Conversations** (a pod's channels, bots' channels, threads, routines' threads) stream live, with tool steps, approvals, files, reactions, replies, threads under their messages, side threads in a sheet, and Details. +- **Routines**: a pod's or a bot's list, New routine, and the panel beside a routine's thread, where its triggers are set up. +- **Artifacts**: a pod's list, each on a page of its own at any version, and cards in the messages that wrote them; a bot-made page runs in a web view that loads nothing else. +- **Settings**, **New bot**, **New thread** and the signed-out screens follow their web pages. +- A bot's **live desktop** is the web's own phone desktop page in a web view, signed in with the app's session cookie. + +When the web changes, compare the page in `packages/web/src` and change its Swift copy to match. The generated files below come straight from the web's packages and the API. Where the app deliberately differs from the web, [`apps/NATIVE.md`](../NATIVE.md) says how and why, and the values are in `apps/native-constants.json`. + +## The API + +The app reaches the server only through `Sugabots/API/API.generated.swift`, which is generated from `packages/contracts/openapi.json`, which is in turn generated from the API's definition in `@sugabots/contracts`. It has a Swift type for each schema the contracts export, named as they are (`podSchema` is `Pod`), and a typed request for each route, grouped as the web's client groups them: `api.threads.get(...)` on the web is `client.threads.get(threadId:)` here. + +The app keeps the API it was last generated from while the web moves on, so it can fall behind: a newer server's fields it doesn't know are ignored, and enum values and union members it doesn't know decode as `unknown`. To take the API's changes, before changing the app: + +```sh +node apps/codegen/generate.ts +``` + +On a change under `apps/`, the Native apps workflow's `codegen` tests fail until it has been run, and the app then fails to build wherever it relied on what changed. That is how a change to the API reaches this app: as compile errors, not as a decoding failure in someone's hands. + +What it decodes stays open to a newer server: an enum or a union decodes a value it doesn't know as `unknown`, and fields it doesn't know are ignored. A field that may be left out of a request and may also be sent as null to clear it is a double optional (`String??`): `nil` leaves it out, `.some(nil)` sends null. + +Add what the app needs on top of these types (labels, `Identifiable`, derived values) as extensions in `API/Models.swift` and its neighbours, never by editing the generated file. + +## Rules copied from the web + +Some of the web's rules are written again in Swift: how a tool step is named and described (`Conversation/ToolNames.swift`, `Conversation/ToolSteps.swift`), how names are listed (`Conversation/Names.swift`), how times are written (`Conversation/Times.swift`), how a routine's schedule is worded (`Routines/ScheduleWords.swift`), mentions (`Conversation/Mentions.swift`), message previews (`Conversation/Previews.swift`), how a thread groups its messages and which parts of one it draws (`Conversation/ChatGroups.swift`, `Conversation/Segments.swift`), markdown's blocks (`Conversation/MarkdownBlocks.swift`), file looks (`Conversation/FileLook.swift`), initials and Gravatar (`Design/Avatars.swift`), mutes (`Home/Mutes.swift`) and time zones (`Settings/TimeZoneChoices.swift`). + +Nothing checks these copies against the web's, so a change to one of these rules on the web needs the same change here. + +## Run it + +Open `Sugabots.xcodeproj` in Xcode and run the `Sugabots` scheme on an iPhone simulator. The app has no package dependencies. + +Sign-in asks for the workspace first, as Slack does: its name, which opens `https://[name].sugabots.ai`, or a name and another ending for a self-hosted server, such as `sugabots` + `.yourcompany.com`. The app talks to `/api` under that address. It signs in with better-auth's bearer plugin and keeps the token in the Keychain. Debug builds suggest `sugabots` + `.local`, that is `https://sugabots.local`, which Portless serves on your network in LAN mode. + +better-auth only accepts a sign-in whose `Origin` is in the server's trusted origins (`PUBLIC_URL`, `WEB_APP_URL`). The app sends the workspace address's origin, so sign in at the same address the web app uses. For a local server, the simulator also has to trust Portless's certificate: + +```sh +xcrun simctl keychain booted add-root-cert ~/.portless/ca.pem +``` + +## Layout + +| Folder | What it holds | +| --- | --- | +| `Sugabots/API` | The generated types and requests, what the app adds to them, the HTTP client, the event stream, the Keychain token | +| `Sugabots/App` | Entry point, routes, `Session` (server and sign-in), `WorkspaceStore` and its extensions (what each area loads and changes) | +| `Sugabots/Home` | Home: the pod rail and the pod's conversation list, with its sheets | +| `Sugabots/Conversation` | A conversation: live model, header, messages, tool steps, approvals, files, composer, Details, side threads, the computer | +| `Sugabots/Attention` | Inbox, Approvals and You | +| `Sugabots/Routines` | Routines: the list, New routine, the panel, and the sheets that set up a trigger | +| `Sugabots/Artifacts` | Artifacts: the list, an artifact's page, the cards in messages, and the web view a bot-made page runs in | +| `Sugabots/Settings`, `NewBot`, `SignIn` | Those pages, each as the web has it | +| `Sugabots/Emoji` | The emoji picker and shortcodes, over `Resources/Emoji.json` | +| `Sugabots/Design` | The web's colour tokens and type, Lucide icons, its controls as a phone draws them (`WebControls.swift`), bot faces, logos | +| `Sugabots/Fonts` | Rubik (TTF) and JetBrains Mono (the web's own woff2), under the SIL Open Font License (`OFL-*.txt`) | + +Debug builds can sign in and open a page at launch, for screenshots: set `SUGABOTS_SERVER`, `SUGABOTS_EMAIL` and `SUGABOTS_PASSWORD`, and `SUGABOTS_OPEN` (see `App/DebugLaunch.swift` and the `DebugOpen` files), with `SIMCTL_CHILD_` before each when launching with `xcrun simctl launch`. + +These files are generated, each by its script in `apps/codegen`, from the web's packages and the API. `node apps/codegen/generate.ts` from the repo root regenerates all of them, and on a change under `apps/` the `codegen` tests fail while any is out of date: + +| Script | Writes | From | +| --- | --- | --- | +| `generate-api.ts` | `API/API.generated.swift`, and Android's `apps/android/api` client | `packages/contracts/openapi.json`, read by `api/model.ts` and written by `api/swift.ts` and `api/kotlin.ts` | +| `generate-palette.ts` | `Design/Palette.generated.swift` | the colour tokens on `:root` in `packages/web/src/app.css` | +| `generate-built-in-tools.ts` | `Conversation/BuiltInTools.generated.swift` | `builtInToolCatalog` in `@sugabots/contracts` | +| `generate-limits.ts` | `API/Limits.generated.swift` | the limits in `@sugabots/contracts`, and the screens' own in `packages/web/src/lib` (`screen-limits.ts`, and the default quiet hours in `notification-choices.ts`) | +| `generate-catalogs.ts` | `API/Catalogs.generated.swift`, `Home/Mutes.generated.swift` | the search and computer provider catalogs, role labels and webhook prefixes in `@sugabots/contracts`; the web's words and lists in `packages/web/src/lib` (`notification-choices.ts`, `model-makers.ts`, `tool-access-labels.ts`, `routine-trigger-words.ts`, `provider-hues.ts`) | +| `generate-trigger-kinds.ts` | `Routines/TriggerKinds.generated.swift` | the kinds of trigger and each webhook source's note in `lib/routine-trigger-words.ts` | +| `generate-artifact-pages.ts` | `Artifacts/ArtifactPages.generated.swift` | `artifact-pages.ts` in `@sugabots/contracts`, `lib/page-frame.ts`, `app.css`'s colours and fonts, and `lib/artifact-kind-catalog.ts` | +| `generate-native-constants.ts` | `Design/NativeConstants.generated.swift` | `apps/native-constants.json` | +| `generate-bot-looks.ts` | `Design/BotLooks.generated.swift` | `@sugabots/avatars`, the pod palette | +| `generate-lucide-icons.ts` | `Design/Lucide.generated.swift` | every icon `packages/web` imports from `lucide-react` | +| `generate-connection-marks.ts` | `Design/ConnectionMarks.generated.swift` | `ui/connection-mark.tsx` | +| `generate-provider-logos.ts` | `Assets.xcassets/ProviderLogos`, `Design/ProviderLogos.generated.swift` | `@sugabots/provider-logos`, contracts | +| `generate-emoji.ts` | `Resources/Emoji.json` | `@sugabots/emoji` | + +The web modules these read are plain data, imported by the web's components and by the scripts, which Node runs as they are: they import nothing but types, so no React and no `@/` paths. Each script builds its data apart from the Swift it writes, so another app's copy can be written from the same data. + +The project file lists its sources. When you add a Swift file, add it in Xcode so it joins the target. diff --git a/apps/ios/Sugabots.xcodeproj/project.pbxproj b/apps/ios/Sugabots.xcodeproj/project.pbxproj new file mode 100644 index 000000000..81348ef61 --- /dev/null +++ b/apps/ios/Sugabots.xcodeproj/project.pbxproj @@ -0,0 +1,850 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + E14A4AAEEA74D2798887ABDA /* APIClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAFF3753A73D409BD8C6219E /* APIClient.swift */; }; + 88B4A6057C7C002463A28D17 /* EventStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD21706A0BFD0B507360D0A6 /* EventStream.swift */; }; + 466987204D75752F3C2BA6FD /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = A845C4A941EF4C62CC1B72BA /* Models.swift */; }; + A5DDB8E948166C443689BFD3 /* TokenStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AD65F3FB1C73D3097D5544B /* TokenStore.swift */; }; + D8749B7E5C9A8509CE4C62AB /* Route.swift in Sources */ = {isa = PBXBuildFile; fileRef = 061F596D31E4BA0BDA6983BF /* Route.swift */; }; + A3C5E888AA097EB072EFC794 /* WorkspacePreferences.swift in Sources */ = {isa = PBXBuildFile; fileRef = B988EB0CC10D6C4FCFC119FC /* WorkspacePreferences.swift */; }; + 09826E03DDC897C03CA8C071 /* Slugify.swift in Sources */ = {isa = PBXBuildFile; fileRef = B15E85FCE3C8F3302D41DA2A /* Slugify.swift */; }; + 44CCFB75ABF62910FB190573 /* Invites.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B9E4E5D6776C07BE193F6BE /* Invites.swift */; }; + 3907702C4F24DFE8E7A521C2 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C7F9FE44C3DA1D8C9681E29 /* Session.swift */; }; + 3F6DC11E23AE431016EF4A25 /* SugabotsApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 771379D6666B436844B2CC97 /* SugabotsApp.swift */; }; + 32682ABBD9A64F8D119FA672 /* WorkspaceStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CCDEE968E91A607D2491E3E /* WorkspaceStore.swift */; }; + 494CCFCDCB452298E19C9BD5 /* ApprovalsScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD2C3910E54E2E86F393F731 /* ApprovalsScreen.swift */; }; + 2801792AC0CA6EC3FAA7E8BE /* InboxScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1020A44A0C86DE2D9520F568 /* InboxScreen.swift */; }; + 9C216A6C86C34BDD8A25634F /* YouScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9126239CAE2BD0FA71AF54CD /* YouScreen.swift */; }; + F2227571606E4A3AF3546F8E /* ConversationModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D83A730B36A4354C35075EB /* ConversationModel.swift */; }; + 7D4D1DC292CC3DEA99BF9194 /* ConversationScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BEF89D5AF9F65699B2ABBF5 /* ConversationScreen.swift */; }; + A44EF09279B3B3415595620D /* ChatGroups.swift in Sources */ = {isa = PBXBuildFile; fileRef = F69069503089209E71755A2E /* ChatGroups.swift */; }; + 6856F0E8D319A3609E8C4687 /* ComputerSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BFED9759698A4C6228B7364 /* ComputerSheet.swift */; }; + 24D76B53130BC87F537F22D1 /* ToolNames.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2569580027B199748BFE2298 /* ToolNames.swift */; }; + 001DD58515BC4998332D5581 /* BotLooks.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3CF3D0257661908A10B1289 /* BotLooks.generated.swift */; }; + BBABD080951E1845220A26E8 /* Controls.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76F6F585620EC11CCDE525A6 /* Controls.swift */; }; + 56D6C924863DDEB7437F800F /* Faces.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB9AE8FE1CDBAFCE46BF578E /* Faces.swift */; }; + CC29E82252B5FE216850DDE9 /* Avatars.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F6B58CD306C531CFFC774F /* Avatars.swift */; }; + 6200298A0F341EEBB9CEC47F /* Palette.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B17129B8579BC8CF7E165FE /* Palette.swift */; }; + 5519534E4D310800FBD74534 /* SVGPath.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A1A8E67DCFD5C397203F038 /* SVGPath.swift */; }; + 90FE1ACDA6033F0CDD13BFE9 /* HomeScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AF57B4CF1C84550D1950112 /* HomeScreen.swift */; }; + B45C3394E1C301AF023CED1C /* JetBrainsMono.woff2 in Resources */ = {isa = PBXBuildFile; fileRef = ABED72F46CC97B327B1A2B9E /* JetBrainsMono.woff2 */; }; + 0553BA0E11818B87D31397D2 /* Rubik.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 598D2FB4341356F112931C01 /* Rubik.ttf */; }; + B0237D3616875AAE4DBEE4A3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = DCE498C0536AFA6C6A77EB68 /* Assets.xcassets */; }; + DF5C706020403B4BC8CF4043 /* Lucide.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 408EDC11EC2CA7283C513A41 /* Lucide.generated.swift */; }; + 3F1B39B0B0F2F193B3058325 /* Icon.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23CE8BE1CA6F1856CFA083DD /* Icon.swift */; }; + F49A6B37C174A83342DF222C /* ConversationList.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0C410CDD148CD91675A9414 /* ConversationList.swift */; }; + 156CE109B161B848CDAC638D /* HomeSheets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05527E8985E2286166609041 /* HomeSheets.swift */; }; + B0293DC10873EFD031D2F4E3 /* Mutes.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEE2BBA45144B7EB2E9BEB19 /* Mutes.swift */; }; + 70D9A4ACF92FEA3F47DECEB1 /* Mutes.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02742345AC712F500BBD22C1 /* Mutes.generated.swift */; }; + 128330ED532C9B24FC31C043 /* WebControls.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8E0D97BBFE3A7030B5AC9D1 /* WebControls.swift */; }; + F010B03F5C4A8D71A952421A /* ToolSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = 343115024B02F8B39DE8BA3A /* ToolSteps.swift */; }; + 7B7FBA065E1C20632EE3192E /* Previews.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5BEA6FC7A051708AED71BFA /* Previews.swift */; }; + 003D4B5B8C9B131030076509 /* ToolLine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2937D7959A0F3A95E8669D7C /* ToolLine.swift */; }; + 87630CC3F40AD712F923A612 /* ApprovalCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD21D5D43F8CA3FD7804B9A0 /* ApprovalCard.swift */; }; + ECE190D9BABE1D1FDF850C3B /* MessageMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B5643F53167BF6E1494838 /* MessageMarkdown.swift */; }; + EC77EAD976208E1428915D17 /* MarkdownBlocks.swift in Sources */ = {isa = PBXBuildFile; fileRef = 839E8934009A0D4A1516F613 /* MarkdownBlocks.swift */; }; + 9601D5A24437AEA5B5B7240B /* MessageRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = C32D3548CAD2D2050E423B07 /* MessageRow.swift */; }; + B5DA939D7B51FB165B391AD0 /* Segments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59F3E9AAB97BE3118ABCA11A /* Segments.swift */; }; + EB3361094F8F4A5A4C812EDA /* MessageFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DFBB9352631DD57ACB1E2FE /* MessageFiles.swift */; }; + F270E01F9A910443F30BDD75 /* FileLook.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA0E2FE73B74657967D20417 /* FileLook.swift */; }; + 37549AFC4C61033FA902F3B4 /* FileLook.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6A24149A3BEB7FFCC9310462 /* FileLook.generated.swift */; }; + F7716B1C4577DC5139268799 /* Composer.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB21A5D56BBEE882143AABD3 /* Composer.swift */; }; + E205780B7F664F3AA03D2408 /* ConversationHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EC56AFFDD7DF0B39B412DD8 /* ConversationHeader.swift */; }; + A080E6556BF3BCFF1A7ABEAE /* ConversationDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68168D1A99186730E5EB3C1B /* ConversationDetails.swift */; }; + 60DA7188734489205E79386B /* SideThreadSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1EA0CB6193C5DF0F5CC27B /* SideThreadSheet.swift */; }; + 065664D7ACEB8C0D8538752B /* RoutineRun.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2D62A2282BFDAC378FF09E2 /* RoutineRun.swift */; }; + 80698FDADA5E387160D635A7 /* ActivityState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 901F9A4C4D2BAE0536F086D5 /* ActivityState.swift */; }; + 803F7E434FCB9FA4A7CE5289 /* BotDetailsSections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18DF9D5AC4667D0090F56D50 /* BotDetailsSections.swift */; }; + FB3F17851A55B876FB3AF5AC /* WorkspaceStore+Conversations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0285C577E55CD98A04645EFA /* WorkspaceStore+Conversations.swift */; }; + C71CE8C25A6B0CBF00997E95 /* DebugLaunch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93D61877D383E2D2C771F3B0 /* DebugLaunch.swift */; }; + 42C13543D8327A71E4EEF04C /* SettingsModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0CB77A42DADE6C912766F2C8 /* SettingsModels.swift */; }; + 994AFE48757DD3D0837D5C15 /* WorkspaceStore+Settings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 589D22E9D0DC2AFDEF019676 /* WorkspaceStore+Settings.swift */; }; + 3DA8E35CB9FEAA93CC20E8CA /* ConnectionMarks.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AECEC384B56B39B473A304F /* ConnectionMarks.generated.swift */; }; + 10DB448F6FCC131739579067 /* SettingsControls.swift in Sources */ = {isa = PBXBuildFile; fileRef = E09BE25CE0E32B6C727CC177 /* SettingsControls.swift */; }; + 7920045A523FDD8220018724 /* SettingsRoutes.swift in Sources */ = {isa = PBXBuildFile; fileRef = FBE82635B60FF01AF080FBD0 /* SettingsRoutes.swift */; }; + 0FF310BEE93906295C86463A /* GeneralSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = C76E8239B30B109E870E8F14 /* GeneralSettings.swift */; }; + 53A085042FC34514F51A7B1C /* TimeZoneChoices.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C18EA6BBF624195608456BA /* TimeZoneChoices.swift */; }; + DAAA304E178E7D173FE69E82 /* TimeZoneRegions.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 873C84F0279D6D76333C3483 /* TimeZoneRegions.generated.swift */; }; + 5E7713A0C0DE5E7713A0B001 /* SettingsRules.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E7713A0C0DE5E7713A0F001 /* SettingsRules.swift */; }; + 4CF9728C331A85D4C826C7E3 /* NotificationsSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF8FC49139B599C120B7D6ED /* NotificationsSettings.swift */; }; + A05B5E91E27D8F0F69777783 /* MembersSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75E71D1EC4C8A6B094B25B4E /* MembersSettings.swift */; }; + F9D5750E1AEA32374BEEB0E9 /* DebugOpen.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD9A335A9A5442C76F023DE2 /* DebugOpen.swift */; }; + A816F549A0E0E2EB923E91EB /* PodSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD1D49FA56C7193A680C892E /* PodSettings.swift */; }; + 25867A417CB06854D531BF5F /* ConnectionsSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02D85E60705BA0DC714ADC6A /* ConnectionsSettings.swift */; }; + D187A60D7B3ADF63F44F2647 /* ConnectionPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85C0EFB5BFA9402D2CD9F940 /* ConnectionPage.swift */; }; + FA821A49A667A911307BF67B /* ColourSwatches.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7A1827C942AA90B2D3EB965 /* ColourSwatches.swift */; }; + 249623BB9727331D9C0F5D96 /* AgentSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = A931A73B966B632383E9C0BC /* AgentSettings.swift */; }; + 23AC9AFB2CDDD7D8C5222273 /* ModelsSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BB0DF69DA4A58C2812D48F0 /* ModelsSettings.swift */; }; + C62784527B08A2F0E440A4AB /* ConnectionMark.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7735721739FE7F1D2F40AF09 /* ConnectionMark.swift */; }; + 186BFF29AC5EB32CA0A0D11C /* RoutineModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = F7D3976E868E592145F3B9E3 /* RoutineModels.swift */; }; + C31F1130C0A7B9FFAA55F4A9 /* WorkspaceStore+Routines.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69AE950A36AC68EEBD4537BB /* WorkspaceStore+Routines.swift */; }; + 342D59F4540E2AC34977698C /* ScheduleWords.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC56AB658DF8B18780349F2D /* ScheduleWords.swift */; }; + 755290CA91AEB8AC6A6491E9 /* TriggerKinds.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = BDBA8C19ABAFDF160D9328A6 /* TriggerKinds.generated.swift */; }; + 4292C7B5D53DE6E788AE937C /* RoutineControls.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4E9C3CD82602C1B55E3D8A7 /* RoutineControls.swift */; }; + DB935D4AB5D7A95AA147AE5D /* TriggerEditing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16EFE48FA4C7613990277611 /* TriggerEditing.swift */; }; + 06D2F0D0FE4AB24184343174 /* RoutinesScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9934674F90D46B29F1AB008 /* RoutinesScreen.swift */; }; + 01A2DE075096379A7B469531 /* NewRoutineScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 889A46AA6F25B160A7A1F294 /* NewRoutineScreen.swift */; }; + 4F846D56D14917E85E96531F /* DebugOpenHome.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38D3677EBFFBCA8150313124 /* DebugOpenHome.swift */; }; + 55B17967038D5B785C8C668B /* ArtifactModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DF8FADC896F2CFA236BC02B /* ArtifactModels.swift */; }; + 73F58CFA1996A4F95F96E3B9 /* WorkspaceStore+Artifacts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 558E3307ED370217C59EB036 /* WorkspaceStore+Artifacts.swift */; }; + 919ADFCB6E9C069177C4531B /* ArtifactFrame.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C9564343685BD6C83549998 /* ArtifactFrame.swift */; }; + 33FAF92D880C887E17B893FE /* ArtifactPages.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61943FB0A6104BBB460ADDE0 /* ArtifactPages.generated.swift */; }; + 280C73D7B253F98D6219B5FC /* ArtifactsPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 953C3A03EF2114702F254CE1 /* ArtifactsPage.swift */; }; + 6A969BD9219C38B3950F7709 /* ArtifactCards.swift in Sources */ = {isa = PBXBuildFile; fileRef = 822F7F6BBE6BABD74B894486 /* ArtifactCards.swift */; }; + 1E4A434548D45BC8A547D21D /* RoutinePanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E50772926836D5DE04CBAA6 /* RoutinePanel.swift */; }; + 659E6B0A2058967EB1436F20 /* NewBotScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2353E7C3C8F0403A42BA441 /* NewBotScreen.swift */; }; + D859F08D1EE8EF656110BEF9 /* ModelPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD6636E6A3257EE56021C9DC /* ModelPicker.swift */; }; + 33B61878F2657F3841A48892 /* SignInScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 651277A641BE9BD51645EE45 /* SignInScreen.swift */; }; + DED39DC497BC82F7F83892F1 /* ChannelScreens.swift in Sources */ = {isa = PBXBuildFile; fileRef = 85F29193548909BC2CCC58FE /* ChannelScreens.swift */; }; + 911486C29CA7E136C3CDC3F6 /* NewThreadScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = C802B2139BEABA1C22E45865 /* NewThreadScreen.swift */; }; + FF957784004CF1F6D6753C36 /* ConfirmDeleteDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8D1CCC7B6291E582B7D80F8 /* ConfirmDeleteDialog.swift */; }; + 374C8C456779E060628FB5FF /* DesktopView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66E1BF9210883459137CEB86 /* DesktopView.swift */; }; + 6462D41314BE925FE8C066A2 /* ProviderSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88BCC70A38C5B18BC179952B /* ProviderSettings.swift */; }; + 796504B28EE71524D7D5A6BE /* ProviderTile.swift in Sources */ = {isa = PBXBuildFile; fileRef = B955C4A61A6549ED7DAA50E9 /* ProviderTile.swift */; }; + 578B4E83991EA2DEF60F2D00 /* ProviderLogos.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1272D8CD70B77F1DAF2CBB2 /* ProviderLogos.generated.swift */; }; + EEE62D7EB9FB9225B7BD1025 /* SandboxSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98C2B6CD37DEE31313BE4246 /* SandboxSettings.swift */; }; + 5BFA0075781575ECD30A79D2 /* WebSearchSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = D652F74C77C307ABF9A9757F /* WebSearchSettings.swift */; }; + 3D192FDE223975417DDB223E /* UsageSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEFB57588D18C03552AF5CB3 /* UsageSettings.swift */; }; + 2D669B091D05F5810578580E /* LookGlyphs.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF37997E25C72B10B274A29C /* LookGlyphs.swift */; }; + D7E2756032BA67BEF1D0A3BD /* Emoji.json in Resources */ = {isa = PBXBuildFile; fileRef = 6FE7E31401120A6B1C0A3330 /* Emoji.json */; }; + 03BFB3E633FA346A132FA58A /* EmojiData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 693B7E2A31C552969EFC42A4 /* EmojiData.swift */; }; + C2E1473ED24F0651857E96D4 /* EmojiPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2847293D8D514B7FEDD0A337 /* EmojiPicker.swift */; }; + D21A0A2B17C70D3228EF01C3 /* MentionEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F6D808A39606BF2F89E2E8A /* MentionEditor.swift */; }; + C7D47946DBE8B8A992B87549 /* Mentions.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3B3DAD48F347BEE048AD888 /* Mentions.swift */; }; + 34DFE18A966ADD697ABA604C /* WorkspaceSetup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1342CDDC7441F57A99CB6871 /* WorkspaceSetup.swift */; }; + ECFCEE9261AABA53F76D02F5 /* OnboardingScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE98F9B193A58ED9BA76367 /* OnboardingScreen.swift */; }; + 16CEB72DB2AA48EB7D7F71D0 /* APISupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED438D930AB133C4512934A4 /* APISupport.swift */; }; + 3C9FB1ACEBAC9ECBA0490779 /* Catalogs.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = B35DBAF340D151BF01764C36 /* Catalogs.generated.swift */; }; + 98051DF9B579ACC50C8280C6 /* Limits.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1AAFB107CEA25DC79FD9BD44 /* Limits.generated.swift */; }; + 35BA3351830AC73EE7E4C384 /* API.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = F565504977686DC2C6646F64 /* API.generated.swift */; }; + D87FE125A7ADB72DF2396E1C /* Palette.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = E306B63D1457877EF13B86BF /* Palette.generated.swift */; }; + C991C157AB8643EBD2F366D3 /* NativeConstants.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECCE520164B8191D214F5470 /* NativeConstants.generated.swift */; }; + 838707CAAE8CAE5F736C8037 /* Names.swift in Sources */ = {isa = PBXBuildFile; fileRef = F662813640A6971D34A1AB38 /* Names.swift */; }; + 625126C23B6A0824899CB2B0 /* Times.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78BFE7ED0A6563A5C93D8419 /* Times.swift */; }; + 120153D4DAC5764E203FFA59 /* BuiltInTools.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = C940E332400943C18187F142 /* BuiltInTools.generated.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + D2A57DC1D883FD21FB995169 /* Sugabots.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Sugabots.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 6F69073C48BD4C561EB05E2D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + DCE498C0536AFA6C6A77EB68 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + BAFF3753A73D409BD8C6219E /* APIClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIClient.swift; sourceTree = ""; }; + DD21706A0BFD0B507360D0A6 /* EventStream.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventStream.swift; sourceTree = ""; }; + A845C4A941EF4C62CC1B72BA /* Models.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Models.swift; sourceTree = ""; }; + 5AD65F3FB1C73D3097D5544B /* TokenStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TokenStore.swift; sourceTree = ""; }; + 061F596D31E4BA0BDA6983BF /* Route.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Route.swift; sourceTree = ""; }; + B988EB0CC10D6C4FCFC119FC /* WorkspacePreferences.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspacePreferences.swift; sourceTree = ""; }; + B15E85FCE3C8F3302D41DA2A /* Slugify.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Slugify.swift; sourceTree = ""; }; + 1B9E4E5D6776C07BE193F6BE /* Invites.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Invites.swift; sourceTree = ""; }; + 8C7F9FE44C3DA1D8C9681E29 /* Session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = ""; }; + 771379D6666B436844B2CC97 /* SugabotsApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SugabotsApp.swift; sourceTree = ""; }; + 9CCDEE968E91A607D2491E3E /* WorkspaceStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceStore.swift; sourceTree = ""; }; + FD2C3910E54E2E86F393F731 /* ApprovalsScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApprovalsScreen.swift; sourceTree = ""; }; + 1020A44A0C86DE2D9520F568 /* InboxScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InboxScreen.swift; sourceTree = ""; }; + 9126239CAE2BD0FA71AF54CD /* YouScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YouScreen.swift; sourceTree = ""; }; + 8D83A730B36A4354C35075EB /* ConversationModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationModel.swift; sourceTree = ""; }; + 8BEF89D5AF9F65699B2ABBF5 /* ConversationScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationScreen.swift; sourceTree = ""; }; + F69069503089209E71755A2E /* ChatGroups.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatGroups.swift; sourceTree = ""; }; + 3BFED9759698A4C6228B7364 /* ComputerSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerSheet.swift; sourceTree = ""; }; + 2569580027B199748BFE2298 /* ToolNames.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolNames.swift; sourceTree = ""; }; + C3CF3D0257661908A10B1289 /* BotLooks.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotLooks.generated.swift; sourceTree = ""; }; + 76F6F585620EC11CCDE525A6 /* Controls.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Controls.swift; sourceTree = ""; }; + DB9AE8FE1CDBAFCE46BF578E /* Faces.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Faces.swift; sourceTree = ""; }; + A5F6B58CD306C531CFFC774F /* Avatars.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Avatars.swift; sourceTree = ""; }; + 6B17129B8579BC8CF7E165FE /* Palette.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Palette.swift; sourceTree = ""; }; + 3A1A8E67DCFD5C397203F038 /* SVGPath.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SVGPath.swift; sourceTree = ""; }; + ABED72F46CC97B327B1A2B9E /* JetBrainsMono.woff2 */ = {isa = PBXFileReference; lastKnownFileType = file; path = JetBrainsMono.woff2; sourceTree = ""; }; + 598D2FB4341356F112931C01 /* Rubik.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = Rubik.ttf; sourceTree = ""; }; + 1AF57B4CF1C84550D1950112 /* HomeScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeScreen.swift; sourceTree = ""; }; + 408EDC11EC2CA7283C513A41 /* Lucide.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Lucide.generated.swift; sourceTree = ""; }; + 23CE8BE1CA6F1856CFA083DD /* Icon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Icon.swift; sourceTree = ""; }; + F0C410CDD148CD91675A9414 /* ConversationList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationList.swift; sourceTree = ""; }; + 05527E8985E2286166609041 /* HomeSheets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSheets.swift; sourceTree = ""; }; + DEE2BBA45144B7EB2E9BEB19 /* Mutes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutes.swift; sourceTree = ""; }; + 02742345AC712F500BBD22C1 /* Mutes.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutes.generated.swift; sourceTree = ""; }; + C8E0D97BBFE3A7030B5AC9D1 /* WebControls.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebControls.swift; sourceTree = ""; }; + 343115024B02F8B39DE8BA3A /* ToolSteps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolSteps.swift; sourceTree = ""; }; + E5BEA6FC7A051708AED71BFA /* Previews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Previews.swift; sourceTree = ""; }; + 2937D7959A0F3A95E8669D7C /* ToolLine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolLine.swift; sourceTree = ""; }; + CD21D5D43F8CA3FD7804B9A0 /* ApprovalCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApprovalCard.swift; sourceTree = ""; }; + E4B5643F53167BF6E1494838 /* MessageMarkdown.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageMarkdown.swift; sourceTree = ""; }; + 839E8934009A0D4A1516F613 /* MarkdownBlocks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownBlocks.swift; sourceTree = ""; }; + C32D3548CAD2D2050E423B07 /* MessageRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageRow.swift; sourceTree = ""; }; + 59F3E9AAB97BE3118ABCA11A /* Segments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Segments.swift; sourceTree = ""; }; + 6DFBB9352631DD57ACB1E2FE /* MessageFiles.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageFiles.swift; sourceTree = ""; }; + EA0E2FE73B74657967D20417 /* FileLook.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileLook.swift; sourceTree = ""; }; + 6A24149A3BEB7FFCC9310462 /* FileLook.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileLook.generated.swift; sourceTree = ""; }; + CB21A5D56BBEE882143AABD3 /* Composer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Composer.swift; sourceTree = ""; }; + 5EC56AFFDD7DF0B39B412DD8 /* ConversationHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationHeader.swift; sourceTree = ""; }; + 68168D1A99186730E5EB3C1B /* ConversationDetails.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationDetails.swift; sourceTree = ""; }; + 5C1EA0CB6193C5DF0F5CC27B /* SideThreadSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SideThreadSheet.swift; sourceTree = ""; }; + E2D62A2282BFDAC378FF09E2 /* RoutineRun.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoutineRun.swift; sourceTree = ""; }; + 901F9A4C4D2BAE0536F086D5 /* ActivityState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActivityState.swift; sourceTree = ""; }; + 18DF9D5AC4667D0090F56D50 /* BotDetailsSections.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotDetailsSections.swift; sourceTree = ""; }; + 0285C577E55CD98A04645EFA /* WorkspaceStore+Conversations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceStore+Conversations.swift"; sourceTree = ""; }; + 93D61877D383E2D2C771F3B0 /* DebugLaunch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugLaunch.swift; sourceTree = ""; }; + 0CB77A42DADE6C912766F2C8 /* SettingsModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsModels.swift; sourceTree = ""; }; + 589D22E9D0DC2AFDEF019676 /* WorkspaceStore+Settings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceStore+Settings.swift"; sourceTree = ""; }; + 9AECEC384B56B39B473A304F /* ConnectionMarks.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionMarks.generated.swift; sourceTree = ""; }; + E09BE25CE0E32B6C727CC177 /* SettingsControls.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsControls.swift; sourceTree = ""; }; + FBE82635B60FF01AF080FBD0 /* SettingsRoutes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsRoutes.swift; sourceTree = ""; }; + C76E8239B30B109E870E8F14 /* GeneralSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneralSettings.swift; sourceTree = ""; }; + 9C18EA6BBF624195608456BA /* TimeZoneChoices.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimeZoneChoices.swift; sourceTree = ""; }; + 873C84F0279D6D76333C3483 /* TimeZoneRegions.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimeZoneRegions.generated.swift; sourceTree = ""; }; + 5E7713A0C0DE5E7713A0F001 /* SettingsRules.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsRules.swift; sourceTree = ""; }; + CF8FC49139B599C120B7D6ED /* NotificationsSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsSettings.swift; sourceTree = ""; }; + 75E71D1EC4C8A6B094B25B4E /* MembersSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MembersSettings.swift; sourceTree = ""; }; + CD9A335A9A5442C76F023DE2 /* DebugOpen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DebugOpen.swift"; sourceTree = ""; }; + FD1D49FA56C7193A680C892E /* PodSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PodSettings.swift"; sourceTree = ""; }; + 02D85E60705BA0DC714ADC6A /* ConnectionsSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ConnectionsSettings.swift"; sourceTree = ""; }; + 85C0EFB5BFA9402D2CD9F940 /* ConnectionPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ConnectionPage.swift"; sourceTree = ""; }; + D7A1827C942AA90B2D3EB965 /* ColourSwatches.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ColourSwatches.swift"; sourceTree = ""; }; + A931A73B966B632383E9C0BC /* AgentSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AgentSettings.swift"; sourceTree = ""; }; + 3BB0DF69DA4A58C2812D48F0 /* ModelsSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ModelsSettings.swift"; sourceTree = ""; }; + 7735721739FE7F1D2F40AF09 /* ConnectionMark.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionMark.swift; sourceTree = ""; }; + F7D3976E868E592145F3B9E3 /* RoutineModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoutineModels.swift; sourceTree = ""; }; + 69AE950A36AC68EEBD4537BB /* WorkspaceStore+Routines.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceStore+Routines.swift"; sourceTree = ""; }; + DC56AB658DF8B18780349F2D /* ScheduleWords.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleWords.swift; sourceTree = ""; }; + BDBA8C19ABAFDF160D9328A6 /* TriggerKinds.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TriggerKinds.generated.swift; sourceTree = ""; }; + B4E9C3CD82602C1B55E3D8A7 /* RoutineControls.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoutineControls.swift; sourceTree = ""; }; + 16EFE48FA4C7613990277611 /* TriggerEditing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TriggerEditing.swift; sourceTree = ""; }; + E9934674F90D46B29F1AB008 /* RoutinesScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoutinesScreen.swift; sourceTree = ""; }; + 889A46AA6F25B160A7A1F294 /* NewRoutineScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewRoutineScreen.swift; sourceTree = ""; }; + 38D3677EBFFBCA8150313124 /* DebugOpenHome.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugOpenHome.swift; sourceTree = ""; }; + 7DF8FADC896F2CFA236BC02B /* ArtifactModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactModels.swift; sourceTree = ""; }; + 558E3307ED370217C59EB036 /* WorkspaceStore+Artifacts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceStore+Artifacts.swift"; sourceTree = ""; }; + 7C9564343685BD6C83549998 /* ArtifactFrame.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactFrame.swift; sourceTree = ""; }; + 61943FB0A6104BBB460ADDE0 /* ArtifactPages.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactPages.generated.swift; sourceTree = ""; }; + 953C3A03EF2114702F254CE1 /* ArtifactsPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactsPage.swift; sourceTree = ""; }; + 822F7F6BBE6BABD74B894486 /* ArtifactCards.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArtifactCards.swift; sourceTree = ""; }; + 4E50772926836D5DE04CBAA6 /* RoutinePanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoutinePanel.swift; sourceTree = ""; }; + F2353E7C3C8F0403A42BA441 /* NewBotScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewBotScreen.swift; sourceTree = ""; }; + AD6636E6A3257EE56021C9DC /* ModelPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelPicker.swift; sourceTree = ""; }; + 651277A641BE9BD51645EE45 /* SignInScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SignInScreen.swift; sourceTree = ""; }; + 85F29193548909BC2CCC58FE /* ChannelScreens.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChannelScreens.swift; sourceTree = ""; }; + C802B2139BEABA1C22E45865 /* NewThreadScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewThreadScreen.swift; sourceTree = ""; }; + B8D1CCC7B6291E582B7D80F8 /* ConfirmDeleteDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfirmDeleteDialog.swift; sourceTree = ""; }; + 66E1BF9210883459137CEB86 /* DesktopView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DesktopView.swift; sourceTree = ""; }; + 88BCC70A38C5B18BC179952B /* ProviderSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ProviderSettings.swift"; sourceTree = ""; }; + B955C4A61A6549ED7DAA50E9 /* ProviderTile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ProviderTile.swift"; sourceTree = ""; }; + B1272D8CD70B77F1DAF2CBB2 /* ProviderLogos.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ProviderLogos.generated.swift"; sourceTree = ""; }; + 98C2B6CD37DEE31313BE4246 /* SandboxSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SandboxSettings.swift"; sourceTree = ""; }; + D652F74C77C307ABF9A9757F /* WebSearchSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WebSearchSettings.swift"; sourceTree = ""; }; + CEFB57588D18C03552AF5CB3 /* UsageSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UsageSettings.swift"; sourceTree = ""; }; + EF37997E25C72B10B274A29C /* LookGlyphs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LookGlyphs.swift"; sourceTree = ""; }; + 6FE7E31401120A6B1C0A3330 /* Emoji.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = Emoji.json; sourceTree = ""; }; + 693B7E2A31C552969EFC42A4 /* EmojiData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmojiData.swift; sourceTree = ""; }; + 2847293D8D514B7FEDD0A337 /* EmojiPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmojiPicker.swift; sourceTree = ""; }; + 9F6D808A39606BF2F89E2E8A /* MentionEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MentionEditor.swift; sourceTree = ""; }; + D3B3DAD48F347BEE048AD888 /* Mentions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mentions.swift; sourceTree = ""; }; + 1342CDDC7441F57A99CB6871 /* WorkspaceSetup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceSetup.swift"; sourceTree = ""; }; + 2CE98F9B193A58ED9BA76367 /* OnboardingScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OnboardingScreen.swift"; sourceTree = ""; }; + ED438D930AB133C4512934A4 /* APISupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APISupport.swift; sourceTree = ""; }; + B35DBAF340D151BF01764C36 /* Catalogs.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Catalogs.generated.swift; sourceTree = ""; }; + 1AAFB107CEA25DC79FD9BD44 /* Limits.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Limits.generated.swift; sourceTree = ""; }; + F565504977686DC2C6646F64 /* API.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = API.generated.swift; sourceTree = ""; }; + E306B63D1457877EF13B86BF /* Palette.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Palette.generated.swift; sourceTree = ""; }; + ECCE520164B8191D214F5470 /* NativeConstants.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeConstants.generated.swift; sourceTree = ""; }; + F662813640A6971D34A1AB38 /* Names.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Names.swift; sourceTree = ""; }; + 78BFE7ED0A6563A5C93D8419 /* Times.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Times.swift; sourceTree = ""; }; + C940E332400943C18187F142 /* BuiltInTools.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BuiltInTools.generated.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 059DB2086B49B680F85B3555 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2B731CEFC6751AAE0EC69B98 = { + isa = PBXGroup; + children = ( + B945424A59364AC577FA6EFB /* Sugabots */, + 86024CAD1E83101D97359D73 /* Products */, + ); + sourceTree = ""; + }; + 86024CAD1E83101D97359D73 /* Products */ = { + isa = PBXGroup; + children = ( + D2A57DC1D883FD21FB995169 /* Sugabots.app */, + ); + name = Products; + sourceTree = ""; + }; + B945424A59364AC577FA6EFB /* Sugabots */ = { + isa = PBXGroup; + children = ( + 79F10BEF106597FE8BD205AF /* Onboarding */, + 40CFF98091139328436606A8 /* Settings */, + 48FAA6CB0EFDCDAB44EAA116 /* Emoji */, + 420F7432802D557CBA72077D /* Resources */, + 80722794BEEE82F2B47CBD8D /* SignIn */, + 7725477645CCAE7424C68340 /* NewBot */, + 17D25F90999B67D7F3A840C4 /* Artifacts */, + 2D76DAA65B9454D26E28CD3B /* Routines */, + E7C104A736AD814AC8A35A1F /* API */, + 267AEBE1BACFD8AB573455B5 /* App */, + BED7F2C1414D6C26AA25E43D /* Attention */, + 1126876B13C913BD3FDF2A0C /* Conversation */, + A9AE7DB7DE0391BBB4A4BE96 /* Design */, + 67217F514C5B00F432CEAA29 /* Fonts */, + 860397D40B2B22547F4E9666 /* Home */, + 6F69073C48BD4C561EB05E2D /* Info.plist */, + DCE498C0536AFA6C6A77EB68 /* Assets.xcassets */, + ); + path = Sugabots; + sourceTree = ""; + }; + E7C104A736AD814AC8A35A1F /* API */ = { + isa = PBXGroup; + children = ( + F565504977686DC2C6646F64 /* API.generated.swift */, + ED438D930AB133C4512934A4 /* APISupport.swift */, + B35DBAF340D151BF01764C36 /* Catalogs.generated.swift */, + 1AAFB107CEA25DC79FD9BD44 /* Limits.generated.swift */, + 0CB77A42DADE6C912766F2C8 /* SettingsModels.swift */, + 7DF8FADC896F2CFA236BC02B /* ArtifactModels.swift */, + F7D3976E868E592145F3B9E3 /* RoutineModels.swift */, + BAFF3753A73D409BD8C6219E /* APIClient.swift */, + DD21706A0BFD0B507360D0A6 /* EventStream.swift */, + A845C4A941EF4C62CC1B72BA /* Models.swift */, + 5AD65F3FB1C73D3097D5544B /* TokenStore.swift */, + ); + path = API; + sourceTree = ""; + }; + 267AEBE1BACFD8AB573455B5 /* App */ = { + isa = PBXGroup; + children = ( + 93D61877D383E2D2C771F3B0 /* DebugLaunch.swift */, + 0285C577E55CD98A04645EFA /* WorkspaceStore+Conversations.swift */, + 589D22E9D0DC2AFDEF019676 /* WorkspaceStore+Settings.swift */, + 558E3307ED370217C59EB036 /* WorkspaceStore+Artifacts.swift */, + 38D3677EBFFBCA8150313124 /* DebugOpenHome.swift */, + 69AE950A36AC68EEBD4537BB /* WorkspaceStore+Routines.swift */, + 061F596D31E4BA0BDA6983BF /* Route.swift */, + B988EB0CC10D6C4FCFC119FC /* WorkspacePreferences.swift */, + B15E85FCE3C8F3302D41DA2A /* Slugify.swift */, + 1B9E4E5D6776C07BE193F6BE /* Invites.swift */, + 8C7F9FE44C3DA1D8C9681E29 /* Session.swift */, + 771379D6666B436844B2CC97 /* SugabotsApp.swift */, + 9CCDEE968E91A607D2491E3E /* WorkspaceStore.swift */, + ); + path = App; + sourceTree = ""; + }; + BED7F2C1414D6C26AA25E43D /* Attention */ = { + isa = PBXGroup; + children = ( + FD2C3910E54E2E86F393F731 /* ApprovalsScreen.swift */, + 1020A44A0C86DE2D9520F568 /* InboxScreen.swift */, + 9126239CAE2BD0FA71AF54CD /* YouScreen.swift */, + ); + path = Attention; + sourceTree = ""; + }; + 1126876B13C913BD3FDF2A0C /* Conversation */ = { + isa = PBXGroup; + children = ( + C940E332400943C18187F142 /* BuiltInTools.generated.swift */, + 78BFE7ED0A6563A5C93D8419 /* Times.swift */, + F662813640A6971D34A1AB38 /* Names.swift */, + 9F6D808A39606BF2F89E2E8A /* MentionEditor.swift */, + D3B3DAD48F347BEE048AD888 /* Mentions.swift */, + 66E1BF9210883459137CEB86 /* DesktopView.swift */, + C802B2139BEABA1C22E45865 /* NewThreadScreen.swift */, + 18DF9D5AC4667D0090F56D50 /* BotDetailsSections.swift */, + E2D62A2282BFDAC378FF09E2 /* RoutineRun.swift */, + 901F9A4C4D2BAE0536F086D5 /* ActivityState.swift */, + 5C1EA0CB6193C5DF0F5CC27B /* SideThreadSheet.swift */, + 68168D1A99186730E5EB3C1B /* ConversationDetails.swift */, + 5EC56AFFDD7DF0B39B412DD8 /* ConversationHeader.swift */, + CB21A5D56BBEE882143AABD3 /* Composer.swift */, + 6DFBB9352631DD57ACB1E2FE /* MessageFiles.swift */, + EA0E2FE73B74657967D20417 /* FileLook.swift */, + 6A24149A3BEB7FFCC9310462 /* FileLook.generated.swift */, + C32D3548CAD2D2050E423B07 /* MessageRow.swift */, + 59F3E9AAB97BE3118ABCA11A /* Segments.swift */, + E4B5643F53167BF6E1494838 /* MessageMarkdown.swift */, + 839E8934009A0D4A1516F613 /* MarkdownBlocks.swift */, + CD21D5D43F8CA3FD7804B9A0 /* ApprovalCard.swift */, + 343115024B02F8B39DE8BA3A /* ToolSteps.swift */, + E5BEA6FC7A051708AED71BFA /* Previews.swift */, + 2937D7959A0F3A95E8669D7C /* ToolLine.swift */, + 8D83A730B36A4354C35075EB /* ConversationModel.swift */, + 8BEF89D5AF9F65699B2ABBF5 /* ConversationScreen.swift */, + F69069503089209E71755A2E /* ChatGroups.swift */, + 3BFED9759698A4C6228B7364 /* ComputerSheet.swift */, + 2569580027B199748BFE2298 /* ToolNames.swift */, + ); + path = Conversation; + sourceTree = ""; + }; + A9AE7DB7DE0391BBB4A4BE96 /* Design */ = { + isa = PBXGroup; + children = ( + E306B63D1457877EF13B86BF /* Palette.generated.swift */, + ECCE520164B8191D214F5470 /* NativeConstants.generated.swift */, + 7735721739FE7F1D2F40AF09 /* ConnectionMark.swift */, + EF37997E25C72B10B274A29C /* LookGlyphs.swift */, + B1272D8CD70B77F1DAF2CBB2 /* ProviderLogos.generated.swift */, + B955C4A61A6549ED7DAA50E9 /* ProviderTile.swift */, + D7A1827C942AA90B2D3EB965 /* ColourSwatches.swift */, + 9AECEC384B56B39B473A304F /* ConnectionMarks.generated.swift */, + B8D1CCC7B6291E582B7D80F8 /* ConfirmDeleteDialog.swift */, + C8E0D97BBFE3A7030B5AC9D1 /* WebControls.swift */, + 23CE8BE1CA6F1856CFA083DD /* Icon.swift */, + 408EDC11EC2CA7283C513A41 /* Lucide.generated.swift */, + C3CF3D0257661908A10B1289 /* BotLooks.generated.swift */, + 76F6F585620EC11CCDE525A6 /* Controls.swift */, + DB9AE8FE1CDBAFCE46BF578E /* Faces.swift */, + A5F6B58CD306C531CFFC774F /* Avatars.swift */, + 6B17129B8579BC8CF7E165FE /* Palette.swift */, + 3A1A8E67DCFD5C397203F038 /* SVGPath.swift */, + ); + path = Design; + sourceTree = ""; + }; + 67217F514C5B00F432CEAA29 /* Fonts */ = { + isa = PBXGroup; + children = ( + ABED72F46CC97B327B1A2B9E /* JetBrainsMono.woff2 */, + 598D2FB4341356F112931C01 /* Rubik.ttf */, + ); + path = Fonts; + sourceTree = ""; + }; + 860397D40B2B22547F4E9666 /* Home */ = { + isa = PBXGroup; + children = ( + 85F29193548909BC2CCC58FE /* ChannelScreens.swift */, + 05527E8985E2286166609041 /* HomeSheets.swift */, + DEE2BBA45144B7EB2E9BEB19 /* Mutes.swift */, + 02742345AC712F500BBD22C1 /* Mutes.generated.swift */, + F0C410CDD148CD91675A9414 /* ConversationList.swift */, + 1AF57B4CF1C84550D1950112 /* HomeScreen.swift */, + ); + path = Home; + sourceTree = ""; + }; + 40CFF98091139328436606A8 /* Settings */ = { + isa = PBXGroup; + children = ( + CEFB57588D18C03552AF5CB3 /* UsageSettings.swift */, + D652F74C77C307ABF9A9757F /* WebSearchSettings.swift */, + 98C2B6CD37DEE31313BE4246 /* SandboxSettings.swift */, + 88BCC70A38C5B18BC179952B /* ProviderSettings.swift */, + 3BB0DF69DA4A58C2812D48F0 /* ModelsSettings.swift */, + A931A73B966B632383E9C0BC /* AgentSettings.swift */, + 85C0EFB5BFA9402D2CD9F940 /* ConnectionPage.swift */, + 02D85E60705BA0DC714ADC6A /* ConnectionsSettings.swift */, + FD1D49FA56C7193A680C892E /* PodSettings.swift */, + CD9A335A9A5442C76F023DE2 /* DebugOpen.swift */, + 75E71D1EC4C8A6B094B25B4E /* MembersSettings.swift */, + CF8FC49139B599C120B7D6ED /* NotificationsSettings.swift */, + C76E8239B30B109E870E8F14 /* GeneralSettings.swift */, + 9C18EA6BBF624195608456BA /* TimeZoneChoices.swift */, + 873C84F0279D6D76333C3483 /* TimeZoneRegions.generated.swift */, + 5E7713A0C0DE5E7713A0F001 /* SettingsRules.swift */, + FBE82635B60FF01AF080FBD0 /* SettingsRoutes.swift */, + E09BE25CE0E32B6C727CC177 /* SettingsControls.swift */, + ); + path = Settings; + sourceTree = ""; + }; + 2D76DAA65B9454D26E28CD3B /* Routines */ = { + isa = PBXGroup; + children = ( + 4E50772926836D5DE04CBAA6 /* RoutinePanel.swift */, + 889A46AA6F25B160A7A1F294 /* NewRoutineScreen.swift */, + E9934674F90D46B29F1AB008 /* RoutinesScreen.swift */, + 16EFE48FA4C7613990277611 /* TriggerEditing.swift */, + B4E9C3CD82602C1B55E3D8A7 /* RoutineControls.swift */, + DC56AB658DF8B18780349F2D /* ScheduleWords.swift */, + BDBA8C19ABAFDF160D9328A6 /* TriggerKinds.generated.swift */, + ); + path = Routines; + sourceTree = ""; + }; + 17D25F90999B67D7F3A840C4 /* Artifacts */ = { + isa = PBXGroup; + children = ( + 822F7F6BBE6BABD74B894486 /* ArtifactCards.swift */, + 953C3A03EF2114702F254CE1 /* ArtifactsPage.swift */, + 7C9564343685BD6C83549998 /* ArtifactFrame.swift */, + 61943FB0A6104BBB460ADDE0 /* ArtifactPages.generated.swift */, + ); + path = Artifacts; + sourceTree = ""; + }; + 7725477645CCAE7424C68340 /* NewBot */ = { + isa = PBXGroup; + children = ( + AD6636E6A3257EE56021C9DC /* ModelPicker.swift */, + F2353E7C3C8F0403A42BA441 /* NewBotScreen.swift */, + ); + path = NewBot; + sourceTree = ""; + }; + 80722794BEEE82F2B47CBD8D /* SignIn */ = { + isa = PBXGroup; + children = ( + 651277A641BE9BD51645EE45 /* SignInScreen.swift */, + ); + path = SignIn; + sourceTree = ""; + }; + 420F7432802D557CBA72077D /* Resources */ = { + isa = PBXGroup; + children = ( + 6FE7E31401120A6B1C0A3330 /* Emoji.json */, + ); + path = Resources; + sourceTree = ""; + }; + 48FAA6CB0EFDCDAB44EAA116 /* Emoji */ = { + isa = PBXGroup; + children = ( + 2847293D8D514B7FEDD0A337 /* EmojiPicker.swift */, + 693B7E2A31C552969EFC42A4 /* EmojiData.swift */, + ); + path = Emoji; + sourceTree = ""; + }; + 79F10BEF106597FE8BD205AF /* Onboarding */ = { + isa = PBXGroup; + children = ( + 2CE98F9B193A58ED9BA76367 /* OnboardingScreen.swift */, + 1342CDDC7441F57A99CB6871 /* WorkspaceSetup.swift */, + ); + path = Onboarding; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 42AEFBAE01D2DFD981F7DA7D /* Sugabots */ = { + isa = PBXNativeTarget; + buildConfigurationList = 84BD75DECF42B745CB4F39AA /* Build configuration list for PBXNativeTarget "Sugabots" */; + buildPhases = ( + FCA229C23F166EBB0BA5029E /* Sources */, + 059DB2086B49B680F85B3555 /* Frameworks */, + B9C6EB6F79FC54535ACB3053 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Sugabots; + productName = Sugabots; + productReference = D2A57DC1D883FD21FB995169 /* Sugabots.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 46F86FAA6BBF9AC94A7E4595 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1540; + LastUpgradeCheck = 1540; + TargetAttributes = { + 42AEFBAE01D2DFD981F7DA7D = { + CreatedOnToolsVersion = 15.4; + }; + }; + }; + buildConfigurationList = 1E2EF4F27A9C5D42CF8A02FE /* Build configuration list for PBXProject "Sugabots" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 2B731CEFC6751AAE0EC69B98; + productRefGroup = 86024CAD1E83101D97359D73 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 42AEFBAE01D2DFD981F7DA7D /* Sugabots */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + B9C6EB6F79FC54535ACB3053 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D7E2756032BA67BEF1D0A3BD /* Emoji.json in Resources */, + B0237D3616875AAE4DBEE4A3 /* Assets.xcassets in Resources */, + B45C3394E1C301AF023CED1C /* JetBrainsMono.woff2 in Resources */, + 0553BA0E11818B87D31397D2 /* Rubik.ttf in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + FCA229C23F166EBB0BA5029E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 120153D4DAC5764E203FFA59 /* BuiltInTools.generated.swift in Sources */, + 625126C23B6A0824899CB2B0 /* Times.swift in Sources */, + 838707CAAE8CAE5F736C8037 /* Names.swift in Sources */, + D87FE125A7ADB72DF2396E1C /* Palette.generated.swift in Sources */, + C991C157AB8643EBD2F366D3 /* NativeConstants.generated.swift in Sources */, + 35BA3351830AC73EE7E4C384 /* API.generated.swift in Sources */, + 16CEB72DB2AA48EB7D7F71D0 /* APISupport.swift in Sources */, + 3C9FB1ACEBAC9ECBA0490779 /* Catalogs.generated.swift in Sources */, + 98051DF9B579ACC50C8280C6 /* Limits.generated.swift in Sources */, + D21A0A2B17C70D3228EF01C3 /* MentionEditor.swift in Sources */, + C7D47946DBE8B8A992B87549 /* Mentions.swift in Sources */, + ECFCEE9261AABA53F76D02F5 /* OnboardingScreen.swift in Sources */, + 34DFE18A966ADD697ABA604C /* WorkspaceSetup.swift in Sources */, + 374C8C456779E060628FB5FF /* DesktopView.swift in Sources */, + 911486C29CA7E136C3CDC3F6 /* NewThreadScreen.swift in Sources */, + DED39DC497BC82F7F83892F1 /* ChannelScreens.swift in Sources */, + C62784527B08A2F0E440A4AB /* ConnectionMark.swift in Sources */, + C71CE8C25A6B0CBF00997E95 /* DebugLaunch.swift in Sources */, + FB3F17851A55B876FB3AF5AC /* WorkspaceStore+Conversations.swift in Sources */, + 803F7E434FCB9FA4A7CE5289 /* BotDetailsSections.swift in Sources */, + 065664D7ACEB8C0D8538752B /* RoutineRun.swift in Sources */, + 80698FDADA5E387160D635A7 /* ActivityState.swift in Sources */, + 60DA7188734489205E79386B /* SideThreadSheet.swift in Sources */, + A080E6556BF3BCFF1A7ABEAE /* ConversationDetails.swift in Sources */, + E205780B7F664F3AA03D2408 /* ConversationHeader.swift in Sources */, + F7716B1C4577DC5139268799 /* Composer.swift in Sources */, + EB3361094F8F4A5A4C812EDA /* MessageFiles.swift in Sources */, + F270E01F9A910443F30BDD75 /* FileLook.swift in Sources */, + 37549AFC4C61033FA902F3B4 /* FileLook.generated.swift in Sources */, + 9601D5A24437AEA5B5B7240B /* MessageRow.swift in Sources */, + B5DA939D7B51FB165B391AD0 /* Segments.swift in Sources */, + ECE190D9BABE1D1FDF850C3B /* MessageMarkdown.swift in Sources */, + EC77EAD976208E1428915D17 /* MarkdownBlocks.swift in Sources */, + 87630CC3F40AD712F923A612 /* ApprovalCard.swift in Sources */, + F010B03F5C4A8D71A952421A /* ToolSteps.swift in Sources */, + 7B7FBA065E1C20632EE3192E /* Previews.swift in Sources */, + 003D4B5B8C9B131030076509 /* ToolLine.swift in Sources */, + 2D669B091D05F5810578580E /* LookGlyphs.swift in Sources */, + 3D192FDE223975417DDB223E /* UsageSettings.swift in Sources */, + 5BFA0075781575ECD30A79D2 /* WebSearchSettings.swift in Sources */, + EEE62D7EB9FB9225B7BD1025 /* SandboxSettings.swift in Sources */, + 578B4E83991EA2DEF60F2D00 /* ProviderLogos.generated.swift in Sources */, + 796504B28EE71524D7D5A6BE /* ProviderTile.swift in Sources */, + 6462D41314BE925FE8C066A2 /* ProviderSettings.swift in Sources */, + 23AC9AFB2CDDD7D8C5222273 /* ModelsSettings.swift in Sources */, + 249623BB9727331D9C0F5D96 /* AgentSettings.swift in Sources */, + FA821A49A667A911307BF67B /* ColourSwatches.swift in Sources */, + D187A60D7B3ADF63F44F2647 /* ConnectionPage.swift in Sources */, + 25867A417CB06854D531BF5F /* ConnectionsSettings.swift in Sources */, + A816F549A0E0E2EB923E91EB /* PodSettings.swift in Sources */, + F9D5750E1AEA32374BEEB0E9 /* DebugOpen.swift in Sources */, + A05B5E91E27D8F0F69777783 /* MembersSettings.swift in Sources */, + 4CF9728C331A85D4C826C7E3 /* NotificationsSettings.swift in Sources */, + 0FF310BEE93906295C86463A /* GeneralSettings.swift in Sources */, + 53A085042FC34514F51A7B1C /* TimeZoneChoices.swift in Sources */, + DAAA304E178E7D173FE69E82 /* TimeZoneRegions.generated.swift in Sources */, + 5E7713A0C0DE5E7713A0B001 /* SettingsRules.swift in Sources */, + 7920045A523FDD8220018724 /* SettingsRoutes.swift in Sources */, + 10DB448F6FCC131739579067 /* SettingsControls.swift in Sources */, + 3DA8E35CB9FEAA93CC20E8CA /* ConnectionMarks.generated.swift in Sources */, + 994AFE48757DD3D0837D5C15 /* WorkspaceStore+Settings.swift in Sources */, + 42C13543D8327A71E4EEF04C /* SettingsModels.swift in Sources */, + C2E1473ED24F0651857E96D4 /* EmojiPicker.swift in Sources */, + 03BFB3E633FA346A132FA58A /* EmojiData.swift in Sources */, + FF957784004CF1F6D6753C36 /* ConfirmDeleteDialog.swift in Sources */, + 33B61878F2657F3841A48892 /* SignInScreen.swift in Sources */, + D859F08D1EE8EF656110BEF9 /* ModelPicker.swift in Sources */, + 659E6B0A2058967EB1436F20 /* NewBotScreen.swift in Sources */, + 1E4A434548D45BC8A547D21D /* RoutinePanel.swift in Sources */, + 6A969BD9219C38B3950F7709 /* ArtifactCards.swift in Sources */, + 280C73D7B253F98D6219B5FC /* ArtifactsPage.swift in Sources */, + 919ADFCB6E9C069177C4531B /* ArtifactFrame.swift in Sources */, + 33FAF92D880C887E17B893FE /* ArtifactPages.generated.swift in Sources */, + 73F58CFA1996A4F95F96E3B9 /* WorkspaceStore+Artifacts.swift in Sources */, + 55B17967038D5B785C8C668B /* ArtifactModels.swift in Sources */, + 4F846D56D14917E85E96531F /* DebugOpenHome.swift in Sources */, + 01A2DE075096379A7B469531 /* NewRoutineScreen.swift in Sources */, + 06D2F0D0FE4AB24184343174 /* RoutinesScreen.swift in Sources */, + DB935D4AB5D7A95AA147AE5D /* TriggerEditing.swift in Sources */, + 4292C7B5D53DE6E788AE937C /* RoutineControls.swift in Sources */, + 342D59F4540E2AC34977698C /* ScheduleWords.swift in Sources */, + 755290CA91AEB8AC6A6491E9 /* TriggerKinds.generated.swift in Sources */, + C31F1130C0A7B9FFAA55F4A9 /* WorkspaceStore+Routines.swift in Sources */, + 186BFF29AC5EB32CA0A0D11C /* RoutineModels.swift in Sources */, + 128330ED532C9B24FC31C043 /* WebControls.swift in Sources */, + 156CE109B161B848CDAC638D /* HomeSheets.swift in Sources */, + B0293DC10873EFD031D2F4E3 /* Mutes.swift in Sources */, + 70D9A4ACF92FEA3F47DECEB1 /* Mutes.generated.swift in Sources */, + F49A6B37C174A83342DF222C /* ConversationList.swift in Sources */, + 3F1B39B0B0F2F193B3058325 /* Icon.swift in Sources */, + DF5C706020403B4BC8CF4043 /* Lucide.generated.swift in Sources */, + E14A4AAEEA74D2798887ABDA /* APIClient.swift in Sources */, + 88B4A6057C7C002463A28D17 /* EventStream.swift in Sources */, + 466987204D75752F3C2BA6FD /* Models.swift in Sources */, + A5DDB8E948166C443689BFD3 /* TokenStore.swift in Sources */, + D8749B7E5C9A8509CE4C62AB /* Route.swift in Sources */, + A3C5E888AA097EB072EFC794 /* WorkspacePreferences.swift in Sources */, + 09826E03DDC897C03CA8C071 /* Slugify.swift in Sources */, + 44CCFB75ABF62910FB190573 /* Invites.swift in Sources */, + 3907702C4F24DFE8E7A521C2 /* Session.swift in Sources */, + 3F6DC11E23AE431016EF4A25 /* SugabotsApp.swift in Sources */, + 32682ABBD9A64F8D119FA672 /* WorkspaceStore.swift in Sources */, + 494CCFCDCB452298E19C9BD5 /* ApprovalsScreen.swift in Sources */, + 2801792AC0CA6EC3FAA7E8BE /* InboxScreen.swift in Sources */, + 9C216A6C86C34BDD8A25634F /* YouScreen.swift in Sources */, + F2227571606E4A3AF3546F8E /* ConversationModel.swift in Sources */, + 7D4D1DC292CC3DEA99BF9194 /* ConversationScreen.swift in Sources */, + A44EF09279B3B3415595620D /* ChatGroups.swift in Sources */, + 6856F0E8D319A3609E8C4687 /* ComputerSheet.swift in Sources */, + 24D76B53130BC87F537F22D1 /* ToolNames.swift in Sources */, + 001DD58515BC4998332D5581 /* BotLooks.generated.swift in Sources */, + BBABD080951E1845220A26E8 /* Controls.swift in Sources */, + 56D6C924863DDEB7437F800F /* Faces.swift in Sources */, + CC29E82252B5FE216850DDE9 /* Avatars.swift in Sources */, + 6200298A0F341EEBB9CEC47F /* Palette.swift in Sources */, + 5519534E4D310800FBD74534 /* SVGPath.swift in Sources */, + 90FE1ACDA6033F0CDD13BFE9 /* HomeScreen.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 2D53B50AE2273FABAAF8B8FA /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + SDKROOT = iphoneos; + SWIFT_VERSION = 5.0; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_TESTABILITY = YES; + GCC_OPTIMIZATION_LEVEL = 0; + ONLY_ACTIVE_ARCH = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + D4B2141B77146EF47E948847 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + SDKROOT = iphoneos; + SWIFT_VERSION = 5.0; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + FA7C752E798F561D7D156D98 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Sugabots/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Sugabots; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = ai.sugabots.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + 22F75101C717335ACF4089A0 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Sugabots/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = Sugabots; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = ai.sugabots.app; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1E2EF4F27A9C5D42CF8A02FE /* Build configuration list for PBXProject "Sugabots" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2D53B50AE2273FABAAF8B8FA /* Debug */, + D4B2141B77146EF47E948847 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 84BD75DECF42B745CB4F39AA /* Build configuration list for PBXNativeTarget "Sugabots" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FA7C752E798F561D7D156D98 /* Debug */, + 22F75101C717335ACF4089A0 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 46F86FAA6BBF9AC94A7E4595 /* Project object */; +} diff --git a/apps/ios/Sugabots.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/apps/ios/Sugabots.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/apps/ios/Sugabots.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/apps/ios/Sugabots/API/ArtifactModels.swift b/apps/ios/Sugabots/API/ArtifactModels.swift new file mode 100644 index 000000000..0daf83f44 --- /dev/null +++ b/apps/ios/Sugabots/API/ArtifactModels.swift @@ -0,0 +1,57 @@ +import Foundation + +extension ArtifactVersionSummary: Identifiable { + var id: Int { number } +} + +/// What wrote an artifact in a reply: an `artifact_write` or `artifact_edit` call's output. +struct WrittenArtifact: Hashable, Identifiable { + let artifactId: String + let kind: ArtifactKind + let title: String + let version: Int + + var id: String { artifactId } + + /// The tools whose calls write artifacts. + static let writingTools: Set = ["artifact_write", "artifact_edit"] + + /// Each artifact a message shows, once, as the web's `writtenIn`: those a + /// routine's posted result carries, and those its reply's calls wrote, at + /// the last version written. + static func writtenIn(_ parts: [MessagePart]) -> [WrittenArtifact] { + let carried = parts.compactMap { part -> WrittenArtifact? in + guard case let .artifact(artifact) = part else { return nil } + return WrittenArtifact(artifactId: artifact.artifactId, kind: artifact.kind, title: artifact.title, version: artifact.version) + } + let calls = parts.compactMap { part -> ToolCallPart? in + if case let .toolCall(call) = part { call } else { nil } + } + var order: [String] = [] + var latest: [String: WrittenArtifact] = [:] + for artifact in carried + writtenBy(calls) { + if latest[artifact.artifactId] == nil { order.append(artifact.artifactId) } + latest[artifact.artifactId] = artifact + } + return order.compactMap { latest[$0] } + } + + /// Each artifact the calls wrote, once, at the last version they wrote. + static func writtenBy(_ calls: [ToolCallPart]) -> [WrittenArtifact] { + var order: [String] = [] + var latest: [String: WrittenArtifact] = [:] + for call in calls where call.status == .completed && writingTools.contains(call.tool) { + guard case let .object(output)? = call.output, + case .string("written")? = output["status"], + case let .string(artifactId)? = output["artifactId"], + case let .string(kindName)? = output["kind"], + case let kind = ArtifactKind(rawValue: kindName), ArtifactKind.known.contains(kind), + case let .string(title)? = output["title"], + case let .number(version)? = output["version"] + else { continue } + if latest[artifactId] == nil { order.append(artifactId) } + latest[artifactId] = WrittenArtifact(artifactId: artifactId, kind: kind, title: title, version: Int(version)) + } + return order.compactMap { latest[$0] } + } +} diff --git a/apps/ios/Sugabots/API/EventStream.swift b/apps/ios/Sugabots/API/EventStream.swift new file mode 100644 index 000000000..44c920299 --- /dev/null +++ b/apps/ios/Sugabots/API/EventStream.swift @@ -0,0 +1,105 @@ +import Foundation + +/// One live update: its `type`, and the whole event as JSON, which decodes as the stream's own union, such as `ThreadUpdateEvent`. +struct StreamEvent { + let type: String + let data: Data + + func decode(_: Payload.Type) -> Payload? { + try? APIClient.decoder.decode(Payload.self, from: data) + } +} + +/// Live updates from a workspace or a thread, as the SDK's `client.events` +/// reads them: server-sent events, reconnecting with `Last-Event-ID` so the +/// server replays what was missed. A dropped connection is normal — the +/// server hangs up every thirty minutes — so only the server ends the stream: +/// with 204 when there is nothing more to send, or by refusing it, which the +/// stream throws as an `APIFailure` with the refusal's status, such as 401 for +/// a token that has expired. +enum EventStream { + private static let firstRetry: Duration = .milliseconds(500) + private static let maxRetry: Duration = .seconds(30) + + static func workspace(_ workspaceId: String, client: APIClient) -> AsyncThrowingStream { + events(at: "workspaces/\(workspaceId)/events", client: client) + } + + static func thread(_ threadId: String, client: APIClient) -> AsyncThrowingStream { + events(at: "threads/\(threadId)/events", client: client) + } + + private static func events(at path: String, client: APIClient) -> AsyncThrowingStream { + AsyncThrowingStream { continuation in + let task = Task { + var lastEventId: String? + var retry = firstRetry + while !Task.isCancelled { + do { + var request = client.request(path) + request.setValue("text/event-stream", forHTTPHeaderField: "Accept") + // Longer than the gap between the server's pings. + request.timeoutInterval = 120 + if let lastEventId { + request.setValue(lastEventId, forHTTPHeaderField: "Last-Event-ID") + } + let (bytes, response) = try await client.session.bytes(for: request) + let status = (response as? HTTPURLResponse)?.statusCode ?? 0 + if status == 204 { break } + if isPermanent(status) { + continuation.finish(throwing: APIFailure(status: status, message: "The server refused live updates (\(status)).")) + return + } + guard (200..<300).contains(status) else { throw URLError(.badServerResponse) } + + // The server writes `id:` (durable events only), `event:`, then the + // event as JSON on one `data:` line, and `: ping` comments between. + var id: String? + for try await line in bytes.lines { + retry = firstRetry + if line.hasPrefix("id:") { + id = field(line) + } else if line.hasPrefix("data:") { + if let event = parse(field(line)) { + if let id { lastEventId = id } + continuation.yield(event) + } + id = nil + } + } + } catch { + if Task.isCancelled { break } + } + try? await Task.sleep(for: jittered(retry)) + retry = min(retry * 2, maxRetry) + } + continuation.finish() + } + continuation.onTermination = { _ in task.cancel() } + } + } + + private static func field(_ line: String) -> String { + let value = line.drop { $0 != ":" }.dropFirst() + return String(value.first == " " ? value.dropFirst() : value) + } + + private static func parse(_ text: String) -> StreamEvent? { + struct Envelope: Decodable { + let type: String + } + let data = Data(text.utf8) + guard let envelope = try? JSONDecoder().decode(Envelope.self, from: data) else { return nil } + return StreamEvent(type: envelope.type, data: data) + } + + /// A refusal reconnecting cannot fix. A timeout and a rate limit are waited out. + private static func isPermanent(_ status: Int) -> Bool { + (400..<500).contains(status) && status != 408 && status != 429 + } + + /// Spread out, so a restart does not bring every client back at once. + private static func jittered(_ delay: Duration) -> Duration { + delay * Double.random(in: 0.5...1) + } +} diff --git a/apps/ios/Sugabots/API/SettingsModels.swift b/apps/ios/Sugabots/API/SettingsModels.swift new file mode 100644 index 000000000..0ab16911f --- /dev/null +++ b/apps/ios/Sugabots/API/SettingsModels.swift @@ -0,0 +1,88 @@ +import Foundation + +// What the settings pages add to the API's types: the words the web shows for them. + +extension WorkspaceRole: Identifiable { + var id: String { rawValue } + + /// The roles somebody may be given, as `ASSIGNABLE_WORKSPACE_ROLES`. + static let assignable: [WorkspaceRole] = AssignableWorkspaceRole.known.map { WorkspaceRole(rawValue: $0.rawValue) } + + /// The role as an invitation or a change of role gives it. + var asAssignable: AssignableWorkspaceRole { AssignableWorkspaceRole(rawValue: rawValue) } + + /// As `administersWorkspace`. + var administers: Bool { self == .owner || self == .admin } + + static func label(_ role: WorkspaceRole?) -> String { role?.label ?? "No access" } +} + +extension WorkspaceInvitation { + /// The role as the workspace's roles name it. + var workspaceRole: WorkspaceRole { WorkspaceRole(rawValue: role.rawValue) } +} + +extension PodMember: Identifiable { + var id: String { userId } +} + +// MARK: Connections + +extension ConnectionAccess: Identifiable { + var id: String { rawValue } + + /// Allowed, Ask first and Off, in the order the web offers them. + static let offered: [ConnectionAccess] = [.allow, .ask, .off] +} + +extension ToolAccessCounts { + /// As `accessSummaryText`: how the tools stand, or nil with none. + var summary: String? { + let total = allow + ask + off + guard total > 0 else { return nil } + if allow == total { return "Every tool runs without asking" } + if ask == total { return "Every tool asks first" } + if off == total { return "Off for every bot" } + let parts = [(allow, "allowed"), (ask, "ask first"), (off, "off")].filter { $0.0 > 0 }.map { "\($0.0) \($0.1)" } + return "Custom: \(parts.joined(separator: ", "))" + } +} + +extension Connection { + var presetId: String? { ConnectionMark.presetId(kind: kind.rawValue, url: url) } +} + +extension ConnectionWithTools { + var presetId: String? { ConnectionMark.presetId(kind: kind.rawValue, url: url) } +} + +extension ConnectionRepositories.Repository: Identifiable { + var id: String { repository } +} + +extension PodSandboxState { + /// The pod's computer, when it has one. + var present: Present? { + if case let .present(sandbox) = self { sandbox } else { nil } + } +} + +extension PodSandboxNetwork.AddedHost: Identifiable { + var id: String { host } +} + +extension SandboxAddedHost: Identifiable { + var id: String { host } +} + +extension SandboxBlockedHost: Identifiable { + var id: String { host } +} + +extension AccountRepository: Identifiable { + var id: String { repository } +} + +extension ConnectionToolSetting: Identifiable { + var id: String { name } +} diff --git a/apps/ios/Sugabots/App/DebugLaunch.swift b/apps/ios/Sugabots/App/DebugLaunch.swift new file mode 100644 index 000000000..cdbb789fa --- /dev/null +++ b/apps/ios/Sugabots/App/DebugLaunch.swift @@ -0,0 +1,181 @@ +#if DEBUG +import Foundation + +/// What a development build opens at launch, from its launch environment, so +/// it can be screenshotted at any page without tapping. +/// +/// `SUGABOTS_OPEN` names a page as `page[/Pod name[/detail]]`; see `Target`. +/// The other variables are read through `once`. +enum DebugLaunch { + /// A page `SUGABOTS_OPEN` names. A pod is named by its name and a bot by its name within the pod. + enum Target { + // Tabs. + /// `inbox`, `approvals`, `you`. + case inbox, approvals, you + + // Signing in, before there's an account. + /// `findworkspace`, `login`, `signup`, `forgot`. + case findWorkspace, signIn, signUp, forgotPassword + + // Home, over the pod. + /// `pod/Pod`: Home on the pod. + case home(pod: String) + /// `general/Pod`. + case general(pod: String) + /// `bot/Pod/Bot`: the bot's channel. + case bot(pod: String, bot: String) + /// `newthread/Pod[/Bot]`. + case newThread(pod: String, bot: String?) + /// `conversation/`. + case conversation(id: String) + /// `settings/Pod`: the pod's settings, pushed on Home. + case podSettings(pod: String) + /// `routines/Pod`, `newRoutine/Pod`, `artifacts/Pod`, `newBot/Pod`. + case routines(pod: String), newRoutine(pod: String), artifacts(pod: String), newBot(pod: String) + /// `routinePanel/Pod[/rename|instructions|delete|trigger|webhook]`: the pod's first routine, perhaps with a dialog open. + case routinePanel(pod: String, dialog: String?) + /// `trigger/Pod[/kinds|cron|webhook|github]`: adding a trigger, at its kinds or a new one of a kind. + case trigger(pod: String, kind: String?) + /// `emoji/Pod[/full]`: the emoji picker, perhaps at its full list. + case emoji(pod: String, full: Bool) + + // Settings, pushed on You. + /// `profile`, `notifications`, `member` (the workspace's first). + case profile, notifications, member + /// A workspace section by its name: `members`, `providers`, … + case workspace(WorkspaceSection) + /// `youpod/Pod`: the pod as You lists it. + case youPod(pod: String) + /// `pod/Pod/`: one of the pod's settings pages, such as `connections`. + case podPage(pod: String, page: PodSettingsPage) + /// `agent/Pod/Bot`: the bot's settings. + case agentSettings(pod: String, bot: String) + + /// The name of the pod the page is in, if it's in one. + var podName: String? { + switch self { + case let .home(pod), let .general(pod), let .bot(pod, _), let .newThread(pod, _), let .podSettings(pod), + let .routines(pod), let .newRoutine(pod), let .artifacts(pod), let .newBot(pod), + let .routinePanel(pod, _), let .trigger(pod, _), let .emoji(pod, _), + let .youPod(pod), let .podPage(pod, _), let .agentSettings(pod, _): + pod + case .inbox, .approvals, .you, .findWorkspace, .signIn, .signUp, .forgotPassword, .conversation, + .profile, .notifications, .member, .workspace: + nil + } + } + + /// The page `value` names, or nil if it names none. + static func parse(_ value: String) -> Target? { + let parts = value.split(separator: "/").map(String.init) + guard let page = parts.first else { return nil } + let pod = parts.count > 1 ? parts[1] : nil + let detail = parts.count > 2 ? parts[2] : nil + switch (page, pod, detail) { + case ("inbox", _, _): return .inbox + case ("approvals", _, _): return .approvals + case ("you", _, _): return .you + case ("findworkspace", _, _): return .findWorkspace + case ("login", _, _): return .signIn + case ("signup", _, _): return .signUp + case ("forgot", _, _): return .forgotPassword + case ("profile", _, _): return .profile + case ("notifications", _, _): return .notifications + case ("member", _, _): return .member + case let ("conversation", id?, _): return .conversation(id: id) + case let ("pod", pod?, page?): return PodSettingsPage(rawValue: page).map { .podPage(pod: pod, page: $0) } + case let ("pod", pod?, nil): return .home(pod: pod) + case let ("general", pod?, _): return .general(pod: pod) + case let ("bot", pod?, bot?): return .bot(pod: pod, bot: bot) + case let ("newthread", pod?, bot): return .newThread(pod: pod, bot: bot) + case let ("settings", pod?, _): return .podSettings(pod: pod) + case let ("routines", pod?, _): return .routines(pod: pod) + case let ("newRoutine", pod?, _): return .newRoutine(pod: pod) + case let ("artifacts", pod?, _): return .artifacts(pod: pod) + case let ("newBot", pod?, _): return .newBot(pod: pod) + case let ("routinePanel", pod?, dialog): return .routinePanel(pod: pod, dialog: dialog) + case let ("trigger", pod?, kind): return .trigger(pod: pod, kind: kind) + case let ("emoji", pod?, list): return .emoji(pod: pod, full: list == "full") + case let ("youpod", pod?, _): return .youPod(pod: pod) + case let ("agent", pod?, bot?): return .agentSettings(pod: pod, bot: bot) + case let (section, nil, nil): return WorkspaceSection(rawValue: section).map(Target.workspace) + default: return nil + } + } + } + + private static let environment = ProcessInfo.processInfo.environment + + /// The page `SUGABOTS_OPEN` names, if any. + static let target = environment["SUGABOTS_OPEN"].flatMap(Target.parse) + + /// The variables of the launch environment `once` has answered true for. + @MainActor private static var taken: Set = [] + + /// Whether the launch environment sets `variable` to `value`, answering + /// true only the first time it is asked, so what it asks for happens once a + /// launch, not each time its page appears: `SUGABOTS_TYPING=1` gives the + /// first conversation's composer the keyboard, `SUGABOTS_DETAILS=1` opens + /// Details over it, `SUGABOTS_HOLD=1` holds a message open, and + /// `SUGABOTS_SHEET` names a sheet a settings page opens over itself: + /// `invite`, `timezone`, `addconnection` or `look`. + @MainActor static func once(_ variable: String, is value: String = "1") -> Bool { + guard environment[variable] == value, !taken.contains(variable) else { return false } + taken.insert(variable) + return true + } + + /// The pod the target is in, once the workspace has loaded it. + @MainActor + static func targetPod(in store: WorkspaceStore) -> Pod? { + guard let name = target?.podName else { return nil } + return store.pods.first { $0.name == name } + } + + /// The bot named `name` in `pod`. + @MainActor + static func bot(named name: String, in pod: Pod, store: WorkspaceStore) -> Agent? { + store.agents.first { $0.podId == pod.id && $0.name == name } + } + + /// The tab to show, and the page to push on it, for a target that is one; + /// nil for any other. A page in a pod is pushed on Home; a settings page on You. + @MainActor + static func destination(in store: WorkspaceStore) async -> (MainTabs.Tab, Route?)? { + guard let target, !store.pods.isEmpty else { return nil } + let pod = targetPod(in: store) + switch target { + case .inbox: return (.inbox, nil) + case .approvals: return (.approvals, nil) + case .you: return (.you, nil) + case let .conversation(id): return (.home, .conversation(threadId: id, title: "")) + case .home: return pod.map { _ in (.home, nil) } + case .general: return pod.map { (.home, .podChat($0)) } + case let .bot(_, name): + guard let pod, let bot = bot(named: name, in: pod, store: store) else { return nil } + return (.home, .botChannel(pod, bot)) + case let .newThread(_, name): + guard let pod else { return nil } + return (.home, .newThread(pod, agent: name.flatMap { bot(named: $0, in: pod, store: store) })) + case .podSettings: return pod.map { (.home, .podSettings($0)) } + case .routines: return pod.map { (.home, .routines($0, agent: nil)) } + case .newRoutine: return pod.map { (.home, .newRoutine($0, agent: nil)) } + case .artifacts: return pod.map { (.home, .artifacts($0)) } + case .profile: return (.you, .settings(.profile)) + case .notifications: return (.you, .settings(.notifications)) + case let .workspace(section): return (.you, .settings(.workspace(section))) + case .member: + guard let first = try? await store.workspaceMembers().first else { return nil } + return (.you, .settings(.member(id: first.id))) + case .youPod: return pod.map { (.you, .settings(.pod($0))) } + case let .podPage(_, page): return pod.map { (.you, .settings(.podPage($0, page))) } + case let .agentSettings(_, name): + guard let pod, let agent = bot(named: name, in: pod, store: store) else { return nil } + return (.you, .settings(.agent(pod, agent))) + case .findWorkspace, .signIn, .signUp, .forgotPassword, .newBot, .routinePanel, .trigger, .emoji: + // Signing in opens its own pages, and these open over Home (see `debugOpen()`). + return nil + } + } +} +#endif diff --git a/apps/ios/Sugabots/App/DebugOpenHome.swift b/apps/ios/Sugabots/App/DebugOpenHome.swift new file mode 100644 index 000000000..a2f9d82d7 --- /dev/null +++ b/apps/ios/Sugabots/App/DebugOpenHome.swift @@ -0,0 +1,97 @@ +import SwiftUI + +#if DEBUG +/// The dialog a development build opens on a page as it appears, named by +/// `SUGABOTS_OPEN`, so it can be screenshotted. +struct DebugDialogKey: EnvironmentKey { + static let defaultValue: String? = nil +} + +extension EnvironmentValues { + var debugDialog: String? { + get { self[DebugDialogKey.self] } + set { self[DebugDialogKey.self] = newValue } + } +} + +/// Opens what `SUGABOTS_OPEN` names over Home that is not a page of its own, +/// once the workspace loads: a new bot, a routine's panel, a new trigger or +/// the emoji picker (see `DebugLaunch.Target`). Pages are pushed by `DebugLaunch.destination`. +private struct DebugOpen: ViewModifier { + @Environment(WorkspaceStore.self) private var store + @State private var makingBot: Pod? + @State private var panel: (agent: Agent, pod: Pod, routine: ListedRoutine)? + @State private var triggerPod: Pod? + @State private var pickingEmoji = false + + func body(content: Content) -> some View { + content + .navigationDestination(isPresented: Binding(get: { panel != nil }, set: { if !$0 { panel = nil } })) { + if let panel { + RoutinePanel( + agent: panel.agent, + pod: panel.pod, + conversationId: panel.routine.conversation?.id ?? "", + standing: ThreadDetails.Routine( + id: panel.routine.routine.id, + agentId: panel.agent.id, + state: panel.routine.routine.state, + failed: panel.routine.routine.failed, + pausedAfterFailures: false + ) + ) + .environment(\.debugDialog, panelDialog) + } + } + .fullScreenCover(item: $makingBot) { pod in NewBotScreen(pod: pod) { _ in makingBot = nil } } + .fullScreenCover(item: $triggerPod) { pod in + TriggerSheet(pod: pod, editing: triggerKind == "kinds" ? nil : TriggerDraft.new(TriggerKind(rawValue: triggerKind ?? "") ?? .cron)) { _ in } + } + .sheet(isPresented: $pickingEmoji) { + EmojiPicker(used: fullEmojiList ? Set(EmojiDataset.shared.emojis.prefix(Limits.maxReactionEmojiPerMessage).map(\.emoji)) : ["👍"]) { _ in } + } + .task(id: store.pods.count) { + guard makingBot == nil, panel == nil, triggerPod == nil, + let target = DebugLaunch.target, let pod = DebugLaunch.targetPod(in: store) + else { return } + await store.refreshChatList(pod) + switch target { + case .newBot: makingBot = pod + case .trigger: triggerPod = pod + case .emoji: + RecentEmoji.remember("🎉") + RecentEmoji.remember("👍") + pickingEmoji = true + case .routinePanel: + if let routine = store.chatLists[pod.id]?.routines.first { + panel = (routine.agent, pod, routine) + } + default: break + } + } + } + + private var panelDialog: String? { + if case let .routinePanel(_, dialog) = DebugLaunch.target { dialog } else { nil } + } + + private var triggerKind: String? { + if case let .trigger(_, kind) = DebugLaunch.target { kind } else { nil } + } + + private var fullEmojiList: Bool { + if case .emoji(_, full: true) = DebugLaunch.target { true } else { false } + } +} +#endif + +extension View { + /// In a development build, opens the page `SUGABOTS_OPEN` names; otherwise nothing. + func debugOpen() -> some View { + #if DEBUG + modifier(DebugOpen()) + #else + self + #endif + } +} diff --git a/apps/ios/Sugabots/App/Invites.swift b/apps/ios/Sugabots/App/Invites.swift new file mode 100644 index 000000000..c92c699a7 --- /dev/null +++ b/apps/ios/Sugabots/App/Invites.swift @@ -0,0 +1,23 @@ +import Foundation + +/// An address an invitation could not go to, and why. +struct InviteFailure { + let email: String + let reason: String +} + +/// What's typed into an invite, split at spaces, commas and semicolons, once +/// each in the order given. Members sends every entry, so the server says which +/// aren't addresses, as the web's Members page does. +func inviteEntries(in text: String) -> [String] { + var seen = Set() + return text.split(whereSeparator: { $0.isWhitespace || $0 == "," || $0 == ";" }) + .map(String.init) + .filter { seen.insert($0).inserted } +} + +/// The entries that look like an address (`LOOKS_LIKE_EMAIL`), as the web's +/// setup invite step keeps them. +func emailAddresses(in text: String) -> [String] { + inviteEntries(in: text).filter { $0.range(of: "^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$", options: .regularExpression) != nil } +} diff --git a/apps/ios/Sugabots/App/Route.swift b/apps/ios/Sugabots/App/Route.swift new file mode 100644 index 000000000..fb8ca26c9 --- /dev/null +++ b/apps/ios/Sugabots/App/Route.swift @@ -0,0 +1,33 @@ +import Foundation + +/// Every page a tab's stack can push, as the web's phone routes. +enum Route: Hashable { + /// A pod's first channel, General, opened on first use. + case podChat(Pod) + /// A bot's channel in a pod, opened on first use. + case botChannel(Pod, Agent) + /// A channel, thread, routine's thread, run or collaboration, by its thread, with the title shown until it loads. + case conversation(threadId: String, title: String) + /// A conversation opened at one of its messages, from the Inbox. + case conversationAt(threadId: String, messageId: String) + /// A collaboration or a routine's run on its own page, from the Inbox. + case sideThreadPage(conversationId: String, threadId: String) + /// A request for approval on its own page, from Approvals. + case approval(callId: String) + /// Starting a thread in a pod from its first message, with `agent`, or between people. + case newThread(Pod, agent: Agent?) + /// A bot's routines, or every routine in the pod. + case routines(Pod, agent: Agent?) + /// Making a routine in a pod, for `agent` when begun from its routines. + case newRoutine(Pod, agent: Agent?) + /// A routine's own thread, where its runs post, opened first if it has none. + case routine(Pod, routineId: String) + case artifacts(Pod) + /// One artifact on its own page, at `version`, or its current version when nil. + case artifact(podId: String, artifactId: String, version: Int?) + case podSettings(Pod) + /// A settings page, as the web's `/settings` and `/you` paths name them. + case settings(SettingsPlace) + /// An open conversation's Details, over it, sharing its model so the two stay as one. + case details(ConversationModel) +} diff --git a/apps/ios/Sugabots/App/Session.swift b/apps/ios/Sugabots/App/Session.swift new file mode 100644 index 000000000..09397f805 --- /dev/null +++ b/apps/ios/Sugabots/App/Session.swift @@ -0,0 +1,223 @@ +import Foundation +import Observation + +/// Which server the app talks to, who is signed in to it, and their workspace. +@MainActor +@Observable +final class Session { + enum State { + /// Reading the token kept from last time, and asking the server who it belongs to. + case restoring + case signedOut + /// The workspace could not be opened for a reason other than the server + /// refusing the token, such as being offline. The token is kept, so + /// trying again needs no password; `client` holds it, for signing out. + case openFailed(reason: String, client: APIClient) + /// The workspace, and the bot's channel to open on Home as it loads, if any. + case signedIn(WorkspaceStore, openingChannel: ChannelToOpen?) + /// Making a workspace, or finishing one's setup, as the web's `/onboarding`. + case settingUp(WorkspaceSetup) + } + + /// A bot's channel to open on Home when a workspace opens, as setup's Start chatting opens the first bot's. + struct ChannelToOpen { + let pod: Pod + let bot: Agent + } + + private static let serverKey = "serverURL" + private static let workspaceKey = "workspaceSlug" + + /// Where a development build looks first: the API under `bun run dev`. + #if DEBUG + static let defaultServer: String? = "https://sugabots.local" + #else + static let defaultServer: String? = nil + #endif + + private(set) var state: State = .restoring + + /// How many changes of state have begun. A change records the count as it + /// begins, and is dropped if the count has moved on by the time it + /// finishes: a later change, such as signing out while a workspace opens, wins. + private var transitionsBegun = 0 + /// Opening the workspace `switchWorkspace` chose; cancelled when another change of state begins. + private var switching: Task? + + /// The server as the person last typed it, without the API's path; nil when there is none. + var server: String? { + UserDefaults.standard.string(forKey: Self.serverKey) ?? Self.defaultServer + } + + /// Opens the workspace with the token kept from last time, or shows sign-in when there is none. + func restore() async { + #if DEBUG + if await signInFromLaunchEnvironment() { return } + #endif + guard let server, let client = try? requireClient(for: server), client.tokens.token != nil else { + await transition { .signedOut } + return + } + await transition { await openingStateOrFailure(with: client) } + } + + /// Whether a Sugabots server answers at `server`, so a mistyped workspace is caught before the password is. + func checkServer(_ server: String) async throws { + let client = try requireClient(for: server) + do { + _ = try await client.health() + } catch let failure as APIFailure { + throw APIFailure(status: failure.status, message: "There's no Sugabots workspace at \(client.baseURL.host() ?? server).") + } catch { + throw APIFailure(status: 0, message: "Couldn't reach \(client.baseURL.host() ?? server). \(error.localizedDescription)") + } + } + + /// Signs in and opens the person's workspace, throwing when either fails. + func signIn(server: String, email: String, password: String) async throws { + let client = try requireClient(for: server) + try await client.signIn(email: email, password: password) + UserDefaults.standard.set(server, forKey: Self.serverKey) + try await transition { try await openingState(with: client) } + } + + /// Makes an account and opens it. Answers false when the installation waits + /// on the emailed link before signing anyone in. + func signUp(server: String, name: String, email: String, password: String) async throws -> Bool { + let client = try requireClient(for: server) + guard try await client.signUp(name: name, email: email, password: password) else { return false } + UserDefaults.standard.set(server, forKey: Self.serverKey) + try await transition { try await openingState(with: client) } + return true + } + + /// Emails `email` a link to choose a new password, if it has an account. The link opens the web app. + func requestPasswordReset(server: String, email: String) async throws { + let client = try requireClient(for: server) + try await client.requestPasswordReset(email: email, redirectTo: client.webRoot.appending(path: "reset-password").absoluteString) + } + + /// Signs out on the server, forgets the token and what this device remembers about the person's workspaces, and shows sign-in. + func signOut() async { + await transition { + switch state { + case let .signedIn(store, _): + WorkspacePreferences.forget(workspaceIds: store.workspaces.map(\.id)) + await store.client.signOut() + case let .openFailed(_, client): + await client.signOut() + case .restoring, .signedOut, .settingUp: + break + } + return .signedOut + } + } + + func switchWorkspace(to workspace: Workspace) { + guard case let .signedIn(store, _) = state else { return } + UserDefaults.standard.set(workspace.slug, forKey: Self.workspaceKey) + let begun = beginTransition() + switching = Task { + let next = await WorkspaceSetup.stateOpening(workspace, client: store.client, user: store.user, workspaces: store.workspaces) + guard !Task.isCancelled else { return } + complete(begun, with: next) + } + } + + /// Leaves setup for `workspace`: the one it set up, the one it was opened + /// from, or with nil, whatever the person has. With `channel`, Home opens + /// that bot's channel once the workspace does. + func finishWorkspaceSetup(opening workspace: Workspace?, showing channel: ChannelToOpen? = nil) async { + guard case let .settingUp(setup) = state else { return } + if let workspace { UserDefaults.standard.set(workspace.slug, forKey: Self.workspaceKey) } + await transition { await openingStateOrFailure(with: setup.client, showing: channel) } + } + + // MARK: Changing state + + /// Moves to the state `next` returns, unless another change of state begins while `next` runs. + private func transition(_ next: () async throws -> State) async rethrows { + let begun = beginTransition() + let state = try await next() + complete(begun, with: state) + } + + /// Starts a change of state, cancelling a workspace `switchWorkspace` is still opening. Returns the count `complete` checks. + private func beginTransition() -> Int { + switching?.cancel() + transitionsBegun += 1 + return transitionsBegun + } + + /// Moves to `next` if no change of state has begun since the one `begun` counts, stopping the workspace that was open. + private func complete(_ begun: Int, with next: State) { + guard begun == transitionsBegun else { return } + if case let .signedIn(open, _) = state { open.stop() } + state = next + } + + /// Asks the server who the token belongs to, and returns what opening + /// their workspace shows: the one last open, or their first. Forgets the + /// token when the server refuses it, and throws every failure. + private func openingState(with client: APIClient, showing channel: ChannelToOpen? = nil) async throws -> State { + let me: Me + do { + me = try await client.me() + } catch let failure as APIFailure where failure.isUnauthorized { + client.tokens.clear() + throw failure + } + let remembered = UserDefaults.standard.string(forKey: Self.workspaceKey) + guard let workspace = me.workspaces.first(where: { $0.slug == remembered }) ?? me.workspaces.first else { + // Somebody in no workspace makes their first. + return .settingUp(WorkspaceSetup(client: client, user: me.user, workspaces: me.workspaces)) + } + return await WorkspaceSetup.stateOpening(workspace, client: client, user: me.user, workspaces: me.workspaces, showing: channel) + } + + /// As `openingState`, for when there is no form to show a failure on: a + /// refused token shows sign-in, and any other failure `.openFailed`. + private func openingStateOrFailure(with client: APIClient, showing channel: ChannelToOpen? = nil) async -> State { + do { + return try await openingState(with: client, showing: channel) + } catch let failure as APIFailure where failure.isUnauthorized { + return .signedOut + } catch { + return .openFailed(reason: error.localizedDescription, client: client) + } + } + + #if DEBUG + /// Signs in with `SUGABOTS_SERVER`, `SUGABOTS_EMAIL` and `SUGABOTS_PASSWORD` + /// from the launch environment, when all three are set, so a development + /// account opens without typing: `SIMCTL_CHILD_SUGABOTS_SERVER=… xcrun simctl launch`. + private func signInFromLaunchEnvironment() async -> Bool { + let environment = ProcessInfo.processInfo.environment + guard let server = environment["SUGABOTS_SERVER"], + let email = environment["SUGABOTS_EMAIL"], + let password = environment["SUGABOTS_PASSWORD"] + else { return false } + do { + try await signIn(server: server, email: email, password: password) + return true + } catch { + print("Launch sign-in failed: \(error)") + return false + } + } + #endif + + /// The API under `server`, which may be typed without its scheme. Throws `InvalidServerAddress` when `server` is empty or not an address. + private func requireClient(for server: String) throws -> APIClient { + let trimmed = server.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + let withScheme = trimmed.contains("://") ? trimmed : "https://\(trimmed)" + guard !trimmed.isEmpty, let root = URL(string: withScheme), root.host() != nil else { throw InvalidServerAddress() } + let api = root.appending(path: "api") + return APIClient(baseURL: api, tokens: TokenStore(server: api)) + } +} + +/// A server address that is empty, or isn't an address. +struct InvalidServerAddress: LocalizedError { + var errorDescription: String? { "Enter the address you open Sugabots at, such as https://sugabots.example.com." } +} diff --git a/apps/ios/Sugabots/App/Slugify.swift b/apps/ios/Sugabots/App/Slugify.swift new file mode 100644 index 000000000..934aad8d3 --- /dev/null +++ b/apps/ios/Sugabots/App/Slugify.swift @@ -0,0 +1,16 @@ +import Foundation + +/// The longest slug `slugify` returns, as `slugify` in `@sugabots/contracts` caps it. +private let maxSlugCharacters = 48 + +/// slugify returns `name` as a pod or workspace slug, as `slugify` in +/// `@sugabots/contracts` does: `Suga Team` becomes `suga-team`. A name with no +/// letter or digit in it gives an empty slug. +func slugify(_ name: String) -> String { + let hyphens = CharacterSet(charactersIn: "-") + let joined = name.lowercased() + .replacingOccurrences(of: "[^a-z0-9]+", with: "-", options: .regularExpression) + .trimmingCharacters(in: hyphens) + // Trimmed again after the cap, which can fall between a word and the hyphen after it. + return String(joined.prefix(maxSlugCharacters)).trimmingCharacters(in: hyphens) +} diff --git a/apps/ios/Sugabots/App/SugabotsApp.swift b/apps/ios/Sugabots/App/SugabotsApp.swift new file mode 100644 index 000000000..ee5bf656e --- /dev/null +++ b/apps/ios/Sugabots/App/SugabotsApp.swift @@ -0,0 +1,362 @@ +import SwiftUI + +@main +@MainActor +struct SugabotsApp: App { + @State private var session = Session() + @State private var toaster = Toaster() + @AppStorage(Theme.storageKey) private var theme = Theme.dark + + init() { + Typeface.registerWebFonts() + } + + var body: some Scene { + WindowGroup { + RootView() + .environment(session) + .environment(toaster) + .font(Typeface.rubik(15)) + .foregroundStyle(Palette.foreground) + .tint(Palette.foreground) + .preferredColorScheme(theme.colorScheme) + } + } +} + +/// Signing in, or the signed-in person's workspace. A view rather than the +/// scene's body, since only a view's body redraws when `Session` changes. +private struct RootView: View { + @Environment(Session.self) private var session + @Environment(Toaster.self) private var toaster + + var body: some View { + ZStack(alignment: .bottom) { + switch session.state { + case .restoring: + Palette.background.ignoresSafeArea() + .task { await session.restore() } + case .signedOut: + SignInScreen() + case let .openFailed(reason, _): + OpenFailedScreen(reason: reason) + case let .settingUp(setup): + OnboardingScreen(setup: setup) + case let .signedIn(store, openingChannel): + MainTabs(openingChannel: openingChannel) + .environment(store) + .id(store.workspace.id) + .task { await run(store) } + } + ToastOverlay() + } + .animation(.easeOut(duration: 0.2), value: toaster.message) + .background(Palette.background.ignoresSafeArea()) + } + + /// Runs `store` until its view goes, signing out when the server refuses + /// the token, and saying so when it refuses live updates for another reason. + private func run(_ store: WorkspaceStore) async { + do { + try await store.run() + } catch let failure as APIFailure where failure.isUnauthorized { + await session.signOut() + } catch { + guard !Task.isCancelled else { return } + toaster.show(error.localizedDescription) + } + } +} + +/// What shows when the workspace could not be opened, such as while offline: +/// why, with Try again, and Sign out for somebody who would rather. +private struct OpenFailedScreen: View { + let reason: String + @Environment(Session.self) private var session + @State private var retrying = false + + var body: some View { + VStack(spacing: 16) { + EmptyState(title: "Could not open your workspace", text: reason) + Button(retrying ? "Trying…" : "Try again") { + retrying = true + Task { + await session.restore() + retrying = false + } + } + .buttonStyle(WebButtonStyle(size: .large)) + .disabled(retrying) + Button("Sign out") { Task { await session.signOut() } }.buttonStyle(QuietLinkStyle()) + } + .padding(.horizontal, 16) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Palette.background.ignoresSafeArea()) + } +} + +/// The four tabs, each its own stack, under the design's floating glass bar. +struct MainTabs: View { + enum Tab { + case home, inbox, approvals, you + } + + /// The bot's channel Home opens on, if any. + let openingChannel: Session.ChannelToOpen? + @Environment(WorkspaceStore.self) private var store + @Environment(\.scenePhase) private var scenePhase + @State private var tab = Tab.home + @State private var keyboardUp = false + /// Each tab's pages over its root. + @State private var paths: [Tab: [Route]] + + init(openingChannel: Session.ChannelToOpen?) { + self.openingChannel = openingChannel + _paths = State(initialValue: openingChannel.map { [.home: [.botChannel($0.pod, $0.bot)]] } ?? [:]) + } + + var body: some View { + ZStack { + TabStack(path: path(.home)) { HomeScreen().debugOpen() }.opacity(tab == .home ? 1 : 0).allowsHitTesting(tab == .home) + TabStack(path: path(.inbox)) { InboxScreen() }.opacity(tab == .inbox ? 1 : 0).allowsHitTesting(tab == .inbox) + TabStack(path: path(.approvals)) { ApprovalsScreen() }.opacity(tab == .approvals ? 1 : 0).allowsHitTesting(tab == .approvals) + TabStack(path: path(.you)) { YouScreen() }.opacity(tab == .you ? 1 : 0).allowsHitTesting(tab == .you) + } + .task { + // Home behind the opening channel is on the channel's pod. + if let openingChannel { store.preferences.homePodId = openingChannel.pod.id } + } + #if DEBUG + .task(id: store.pods.isEmpty) { + if let pod = DebugLaunch.targetPod(in: store) { store.preferences.homePodId = pod.id } + guard let (openTab, route) = await DebugLaunch.destination(in: store) else { return } + tab = openTab + if let route { paths[openTab] = [route] } + } + #endif + // The tabs float over every page, which scrolls on under them; while something is typed, the keyboard has the room. + .overlay(alignment: .bottom) { + if !keyboardUp { + // Tapping the open tab again goes back to its first page, as iOS's own tab bars do. + TabBar(tab: $tab) { reopened in paths[reopened] = [] }.offset(y: WindowInsets.tabBarSink) + } + } + .environment(\.tabBarRoom, keyboardUp ? 0 : TabBar.room) + // Every page opens on the open tab's own stack, so Back returns to where it was opened from. + .environment(\.openPage, OpenPage { route in paths[tab, default: []].append(route) }) + .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in keyboardUp = true } + .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in keyboardUp = false } + .onChange(of: scenePhase) { _, phase in + // The stream may have been dropped while the app was away; what it missed is fetched again. + if phase == .active { Task { await store.refreshAll() } } + } + } + + private func path(_ tab: Tab) -> Binding<[Route]> { + Binding(get: { paths[tab] ?? [] }, set: { paths[tab] = $0 }) + } +} + +/// One tab's stack, rooted at `root`, pushing every `Route` without a navigation bar: each page draws its own header. +private struct TabStack: View { + @Binding var path: [Route] + @ViewBuilder let root: Root + + var body: some View { + NavigationStack(path: $path) { + root + .tabBarClearance() + .toolbar(.hidden, for: .navigationBar) + .swipeBackWithoutNavigationBar() + .background(Palette.background.ignoresSafeArea()) + .navigationDestination(for: Route.self) { route in + RouteDestination(route: route) + } + } + } +} + +/// A stack of its own for a sheet or cover, rooted at `root`: pages opened +/// inside it push here, not onto the tab's stack hidden behind the sheet. +struct PageStack: View { + @ViewBuilder let root: Root + @State private var path: [Route] = [] + + var body: some View { + NavigationStack(path: $path) { + root + .swipeBackWithoutNavigationBar() + .navigationDestination(for: Route.self) { route in + RouteDestination(route: route) + } + } + .environment(\.openPage, OpenPage { route in path.append(route) }) + } +} + +/// The page a `Route` opens, without a navigation bar: each page draws its own header. +struct RouteDestination: View { + let route: Route + + var body: some View { + page + .tabBarClearance() + .toolbar(.hidden, for: .navigationBar) + .background(Palette.background.ignoresSafeArea()) + } + + @ViewBuilder private var page: some View { + switch route { + case let .podChat(pod): OpeningConversationScreen.podChat(pod) + case let .botChannel(pod, agent): OpeningConversationScreen.botChannel(agent, in: pod) + case let .newThread(pod, agent): NewThreadScreen(pod: pod, agent: agent) + case let .podSettings(pod): PodSettingsScreen(pod: pod) + case let .conversation(threadId, title): ConversationScreen(threadId: threadId, title: title) + case let .approval(callId): ApprovalPage(callId: callId) + case let .conversationAt(threadId, messageId): ConversationScreen(threadId: threadId, title: "", focusMessageId: messageId) + case let .sideThreadPage(conversationId, threadId): SideThreadSheet(threadId: threadId, conversationId: conversationId, entry: nil, chatAgentId: nil, asPage: true) { _ in } + case let .routines(pod, agent): RoutinesScreen(pod: pod, agent: agent) + case let .newRoutine(pod, agent): NewRoutineScreen(pod: pod, agent: agent) + case let .routine(pod, routineId): OpeningConversationScreen.routineFeed(routineId, in: pod) + case let .artifacts(pod): ArtifactsScreen(pod: pod) + case let .artifact(podId, artifactId, version): ArtifactScreen(podId: podId, artifactId: artifactId, version: version) + case let .settings(place): SettingsDestination(place: place) + case let .details(model): ConversationDetails(model: model) + } + } +} + +/// Home, Inbox, Approvals and You, floating along the foot of the screen, +/// as the web's `MobileTabBar`: the open tab marked by a highlight that +/// slides from tab to tab, Inbox counting what is unread and Approvals what +/// waits on you. +private struct TabBar: View { + @Binding var tab: MainTabs.Tab + /// The open tab, tapped again. + let reopen: (MainTabs.Tab) -> Void + @Environment(WorkspaceStore.self) private var store + + private static let tabs: [MainTabs.Tab] = [.home, .inbox, .approvals, .you] + /// What the bar takes at the foot of a page, over the safe area: itself, 60 + /// tall, and 8 over it, less how far it sinks into the safe area below. + @MainActor static var room: CGFloat { 68 - WindowInsets.tabBarSink } + private static let gap: CGFloat = 2 + /// Where a count sits on its icon's corner, as the web's `-top-1.5 left-3.5`. + private static let badgeFromLeading: CGFloat = 14 + private static let badgeAboveTop: CGFloat = 6 + + var body: some View { + let index = CGFloat(Self.tabs.firstIndex(of: tab) ?? 0) + HStack(spacing: Self.gap) { + item(.home, "Home") { Icon(.house, size: 24, strokeWidth: 1.75) } + item(.inbox, "Inbox", count: store.unreadInInbox, label: "\(store.unreadInInbox) unread") { + Icon(.inbox, size: 24, strokeWidth: 1.75) + } + item(.approvals, "Approvals", count: store.waitingApprovals, label: "\(store.waitingApprovals) waiting on you") { + Icon(.shieldCheck, size: 24, strokeWidth: 1.75) + } + item(.you, "You") { + PersonAvatar(name: store.user.name, email: store.user.email, image: store.user.image, size: 24) + .overlay(Circle().strokeBorder(Palette.foreground, lineWidth: tab == .you ? 1.5 : 0)) + } + } + .background(alignment: .leading) { + GeometryReader { geometry in + let width = (geometry.size.width - Self.gap * 3) / 4 + RoundedRectangle(cornerRadius: 26, style: .continuous) + .fill(Palette.hover) + .frame(width: width) + .offset(x: index * (width + Self.gap)) + .animation(.easeOut(duration: 0.3), value: tab) + } + } + .padding(5) + .glass(in: RoundedRectangle(cornerRadius: 32, style: .continuous)) + // The web's glass, which keeps the highlight under the open tab visible. + .environment(\.glassStyle, .web) + .padding(.horizontal, barSideInset) + .padding(.top, 8) + } + + /// One tab: its icon and name, bright while open, with a count over the icon's corner. + private func item( + _ target: MainTabs.Tab, + _ name: String, + count: Int = 0, + label: String = "", + @ViewBuilder icon: () -> some View + ) -> some View { + let open = tab == target + return Button { if open { reopen(target) } else { tab = target } } label: { + VStack(spacing: 3) { + icon() + .frame(width: 24, height: 24) + .overlay(alignment: .topLeading) { + if count > 0 { + CountBadge(count: count).offset(x: Self.badgeFromLeading, y: -Self.badgeAboveTop) + } + } + Text(name).font(Typeface.rubik(10, .medium)) + } + .foregroundStyle(open ? Palette.foreground : Palette.mutedForeground) + .frame(maxWidth: .infinity, minHeight: 50) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(count > 0 ? "\(name), \(label)" : name) + .accessibilityAddTraits(open ? .isSelected : []) + } +} + +private struct TabBarRoomKey: EnvironmentKey { + static let defaultValue: CGFloat = 0 +} + +extension EnvironmentValues { + /// How much of a page's foot the floating tabs cover, while they show. + var tabBarRoom: CGFloat { + get { self[TabBarRoomKey.self] } + set { self[TabBarRoomKey.self] = newValue } + } +} + +private struct TabBarClearance: ViewModifier { + @Environment(\.tabBarRoom) private var room + + func body(content: Content) -> some View { + content.safeAreaPadding(.bottom, room) + } +} + +extension View { + /// Leaves the floating tabs their room at the page's foot, so what scrolls comes clear of them. + func tabBarClearance() -> some View { + modifier(TabBarClearance()) + } +} + +/// Pushes a page onto the stack it is called in: the open tab's, or a +/// sheet's `PageStack`. Pages open this way, not with a +/// `navigationDestination` of their own: a page pushed beside the stack's path +/// can't push onto that path itself, so its links would do nothing. +/// +/// A `NavigationLink(value:)` with a `Route` does the same as calling this: +/// both append to the path of the stack it is in. A row that only opens a page +/// is a `NavigationLink`; code that opens one after doing something else calls this. +struct OpenPage { + let open: (Route) -> Void + + func callAsFunction(_ route: Route) { open(route) } +} + +private struct OpenPageKey: EnvironmentKey { + /// Outside a `TabStack` or `PageStack` there is no stack to push on, so opening a page there is a mistake. + static let defaultValue = OpenPage { route in assertionFailure("Opened \(route) outside a stack that pushes pages") } +} + +extension EnvironmentValues { + var openPage: OpenPage { + get { self[OpenPageKey.self] } + set { self[OpenPageKey.self] = newValue } + } +} diff --git a/apps/ios/Sugabots/App/WorkspacePreferences.swift b/apps/ios/Sugabots/App/WorkspacePreferences.swift new file mode 100644 index 000000000..fddbd2c1c --- /dev/null +++ b/apps/ios/Sugabots/App/WorkspacePreferences.swift @@ -0,0 +1,59 @@ +import Foundation +import Observation + +/// What this device remembers about one workspace between launches: the pod +/// Home shows, and which of a pod's sections are folded. Kept in +/// `UserDefaults` under keys that include the workspace's id, so one +/// workspace's choices don't carry into another; `forget` removes them. +@MainActor +@Observable +final class WorkspacePreferences { + private enum Key: String, CaseIterable { + case homePodId + case foldedSections + } + + let workspaceId: String + + /// The pod Home shows; nil until one is chosen, when Home shows the first. + var homePodId: String? { + didSet { Self.defaults.set(homePodId, forKey: Self.key(.homePodId, workspaceId: workspaceId)) } + } + + /// The folded sections, each as `
:`. + private var foldedSections: Set { + didSet { Self.defaults.set(foldedSections.sorted(), forKey: Self.key(.foldedSections, workspaceId: workspaceId)) } + } + + private static var defaults: UserDefaults { .standard } + + init(workspaceId: String) { + self.workspaceId = workspaceId + homePodId = Self.defaults.string(forKey: Self.key(.homePodId, workspaceId: workspaceId)) + foldedSections = Set(Self.defaults.stringArray(forKey: Self.key(.foldedSections, workspaceId: workspaceId)) ?? []) + } + + /// isFolded reports whether `section` of the pod `podId` is folded shut. + func isFolded(_ section: String, in podId: String) -> Bool { + foldedSections.contains("\(section):\(podId)") + } + + /// Folds `section` of the pod `podId` shut, or opens it if it is folded. + func toggleFolded(_ section: String, in podId: String) { + let entry = "\(section):\(podId)" + if foldedSections.contains(entry) { foldedSections.remove(entry) } else { foldedSections.insert(entry) } + } + + /// Removes what this device remembers about each of `workspaceIds`. + static func forget(workspaceIds: [String]) { + for workspaceId in workspaceIds { + for key in Key.allCases { + defaults.removeObject(forKey: Self.key(key, workspaceId: workspaceId)) + } + } + } + + private static func key(_ key: Key, workspaceId: String) -> String { + "workspace.\(workspaceId).\(key.rawValue)" + } +} diff --git a/apps/ios/Sugabots/App/WorkspaceStore+Artifacts.swift b/apps/ios/Sugabots/App/WorkspaceStore+Artifacts.swift new file mode 100644 index 000000000..7302ca9f8 --- /dev/null +++ b/apps/ios/Sugabots/App/WorkspaceStore+Artifacts.swift @@ -0,0 +1,36 @@ +import Foundation + +/// The documents and pages a pod's bots have made. +extension WorkspaceStore { + /// The pod's artifacts, newest first. + func artifacts(in podId: String) async throws -> [ArtifactSummary] { + try await client.artifacts.list(podId: podId) + } + + /// An artifact at `version`, or its current version when nil. + func artifact(_ artifactId: String, in podId: String, version: Int? = nil) async throws -> Artifact { + guard let version else { return try await client.artifacts.get(podId: podId, artifactId: artifactId) } + return try await client.artifacts.getVersion(podId: podId, artifactId: artifactId, version: String(version)) + } + + /// Every version of an artifact, newest first. + func artifactVersions(_ artifactId: String, in podId: String) async throws -> [ArtifactVersionSummary] { + try await client.artifacts.versions(podId: podId, artifactId: artifactId) + } + + /// Deletes an artifact, every version of it. + func deleteArtifact(_ artifactId: String, in podId: String) async throws { + try await client.artifacts.remove(podId: podId, artifactId: artifactId) + } + + /// Where a page's version is served from the installation's content origin, or nil when it has none. + func pageAddress(_ artifactId: String, in podId: String, version: Int) async throws -> URL? { + let address = try await client.artifacts.pageAddress(podId: podId, artifactId: artifactId, version: String(version)) + return address.url.flatMap(URL.init(string:)) + } + + /// The web app's address for an artifact, for Copy link. + func webLink(toArtifact artifactId: String, in pod: Pod) -> URL { + webURL("pods/\(pod.slug)/artifacts/\(artifactId)") + } +} diff --git a/apps/ios/Sugabots/App/WorkspaceStore+Conversations.swift b/apps/ios/Sugabots/App/WorkspaceStore+Conversations.swift new file mode 100644 index 000000000..53b223fd8 --- /dev/null +++ b/apps/ios/Sugabots/App/WorkspaceStore+Conversations.swift @@ -0,0 +1,70 @@ +import Foundation + +extension WorkspaceStore { + /// The name a bot's model goes by, as `useModelName`: its display name, else its id; nil with none chosen. + func modelName(_ model: String?) -> String? { + guard let model else { return nil } + return enabledModels?.models.first { $0.modelId == model }?.displayName ?? model + } + + /// What kind of conversation `model` is: as its thread says once loaded, + /// else as a pod's chat list already says, so the header shows the bot's + /// face and model from the start rather than changing as it loads; else a + /// thread between people. + func kind(of model: ConversationModel) -> ConversationKind { + guard let thread = model.thread else { return listedKind(of: model.threadId) ?? .peopleThread } + if thread.type == .podChat { + // The pod's list has a rename as soon as it's made; the thread's own title waits for its details to reload. + return .podChat(name: podChat(model.conversationId, in: thread.podId)?.title ?? thread.title) + } + if thread.type == .botChannel, let agent = thread.hostAgentId.flatMap(agent(id:)) { + return .botChannel(agent) + } + return threadKind(hostAgentId: thread.hostAgentId) + } + + /// Whether a loaded chat list in some pod shows `conversationId`. + func isListed(_ conversationId: String) -> Bool { + listedKind(of: conversationId) != nil + } + + /// What kind of conversation `conversationId` is, as a pod's chat list + /// already says, before its own details load; nil when no loaded list has it. + private func listedKind(of conversationId: String) -> ConversationKind? { + for list in chatLists.values { + if let chat = list.chats.first(where: { $0.conversation.id == conversationId }) { + return .podChat(name: chat.conversation.title) + } + if let channel = list.channels.first(where: { $0.conversation.id == conversationId }) { + return .botChannel(channel.agent) + } + if let thread = list.threads.first(where: { $0.conversation.id == conversationId }) { + return threadKind(hostAgentId: thread.conversation.hostAgentId) + } + } + return nil + } + + /// A thread a bot hosts is that bot's; any other is between people. + private func threadKind(hostAgentId: String?) -> ConversationKind { + hostAgentId.flatMap(agent(id:)).map(ConversationKind.botThread) ?? .peopleThread + } + + /// One of a pod's channels as the pod's list has it, renames included; nil + /// until the list has loaded, or once the channel is archived. + func podChat(_ conversationId: String, in podId: String) -> PodChat? { + chatLists[podId]?.chats.first { $0.id == conversationId }?.conversation + } + + /// Renames one of a pod's channels. + func renameChat(_ conversationId: String, to name: String, in pod: Pod) async throws { + try await client.chats.renameChat(conversationId: conversationId, name: name) + await refreshChatList(pod) + } + + /// Archives one of a pod's channels, which leaves its list for everyone. + func archiveChat(_ conversationId: String, in pod: Pod) async throws { + try await client.chats.archiveChat(conversationId: conversationId) + await refreshChatList(pod) + } +} diff --git a/apps/ios/Sugabots/App/WorkspaceStore+Routines.swift b/apps/ios/Sugabots/App/WorkspaceStore+Routines.swift new file mode 100644 index 000000000..3074c9dfa --- /dev/null +++ b/apps/ios/Sugabots/App/WorkspaceStore+Routines.swift @@ -0,0 +1,145 @@ +import Foundation + +/// Routines in full: listing, making, and changing their triggers. +extension WorkspaceStore { + /// Every routine the person reaches in the workspace, in full. + func workspaceRoutines() async throws -> [WorkspaceRoutine] { + try await client.routines.listInWorkspace(workspace: workspace.id).items + } + + /// A bot's routines, in full. + func routines(of agentId: String) async throws -> [Routine] { + try await client.routines.list(agentId: agentId) + } + + /// When a routine of the bot `agentId` runs next, in words, as its thread's last divider says it. + func nextRunWords(routineId: String, agentId: String) async -> String? { + guard let routine = try? await routines(of: agentId).first(where: { $0.id == routineId }) else { return nil } + return ScheduleWords.nextRunWords(routine) + } + + /// Changes some of a routine's fields; those left nil or omitted stay as they are. + func updateRoutine( + _ routineId: String, + agentId: String, + name: String? = nil, + instructions: String? = nil, + state: RoutineState? = nil, + results: RoutineResults? = nil, + chatId: Omittable = .omitted + ) async throws -> Routine { + let result = try await client.routines.update( + agentId: agentId, routineId: routineId, name: name, instructions: instructions, state: state, results: results, chatId: chatId + ) + await refreshAfterRoutineChange(agentId: agentId) + return result.routine + } + + /// Runs a routine now; its result posts in its thread. + func runRoutine(_ routineId: String, agentId: String) async throws { + _ = try await client.routines.run(agentId: agentId, routineId: routineId, requestId: UUID().uuidString.lowercased()) + await refreshAfterRoutineChange(agentId: agentId) + } + + /// Deletes a routine. Runs already in its bot's chat stay there. + func deleteRoutine(_ routineId: String, agentId: String) async throws { + try await client.routines.remove(agentId: agentId, routineId: routineId) + await refreshAfterRoutineChange(agentId: agentId) + } + + /// Makes a routine, then refreshes what it may show in: the pod's list and the attention counts. + func createRoutine(agentId: String, routine: NewRoutine) async throws -> RoutineWriteResult { + let result = try await client.routines.create( + agentId: agentId, + name: routine.name, + instructions: routine.instructions, + state: routine.state, + results: routine.results, + chatId: routine.chatId, + triggers: routine.triggers + ) + await refreshAfterRoutineChange(agentId: agentId) + return result + } + + /// The pod's list and the attention counts, which a routine's change may move. + private func refreshAfterRoutineChange(agentId: String) async { + guard let podId = agent(id: agentId)?.podId, let pod = pod(id: podId) else { return } + await refreshChatList(pod) + await refreshAttention() + } + + /// The address that runs a webhook trigger. + func webhookAddress(of triggerId: String) -> String { + client.baseURL.appending(path: "hooks/triggers/\(triggerId)").absoluteString + } + + /// A routine in full, by its bot and id. + func routine(_ routineId: String, agentId: String) async throws -> Routine { + try await client.routines.get(agentId: agentId, routineId: routineId) + } + + /// The routine's latest run, if it has run. + func latestRun(of routineId: String, agentId: String) async throws -> RoutineExecution? { + try await client.routines.executions(agentId: agentId, routineId: routineId, limit: 1).items.first + } + + /// Adds a trigger to a routine. + func addTrigger(_ trigger: TriggerInput, to routineId: String, agentId: String) async throws -> RoutineWriteResult { + let result = try await client.routines.addTrigger(agentId: agentId, routineId: routineId, body: trigger.apiValue) + await refreshAfterRoutineChange(agentId: agentId) + return result + } + + /// Replaces one of a routine's triggers. + func updateTrigger(_ triggerId: String, with trigger: TriggerInput, routineId: String, agentId: String) async throws -> RoutineWriteResult { + let result = try await client.routines.updateTrigger(agentId: agentId, routineId: routineId, triggerId: triggerId, body: trigger.apiValue) + await refreshAfterRoutineChange(agentId: agentId) + return result + } + + /// Removes one of a routine's triggers. + func removeTrigger(_ triggerId: String, routineId: String, agentId: String) async throws -> Routine { + let routine = try await client.routines.removeTrigger(agentId: agentId, routineId: routineId, triggerId: triggerId) + await refreshAfterRoutineChange(agentId: agentId) + return routine + } + + /// A webhook trigger's secret, for somebody who manages the routine. + func webhookSecret(of triggerId: String, routineId: String, agentId: String) async throws -> RoutineCurrentSecret { + try await client.routines.getSecret(agentId: agentId, routineId: routineId, triggerId: triggerId) + } + + /// What a webhook trigger's secret is replaced with. + enum SecretReplacement { + /// A new secret the server makes. + case generated + case given(String) + /// No secret, so the address alone runs the routine. + case removed + } + + /// Replaces a webhook trigger's secret, and returns the secret it has now, if any. + func replaceWebhookSecret(of triggerId: String, routineId: String, agentId: String, with replacement: SecretReplacement) async throws -> String? { + let secret: Omittable = + switch replacement { + case .generated: .omitted + case let .given(secret): .present(secret) + case .removed: .present(nil) + } + return try await client.routines.rotateSecret(agentId: agentId, routineId: routineId, triggerId: triggerId, secret: secret).secret + } + + /// The repositories a pod's GitHub connection reaches. + func repositories(in podId: String, connectionId: String) async throws -> ConnectionRepositories { + try await client.gitHubConnections.repositories(podId: podId, connectionId: connectionId) + } + + /// A routine's thread, by the routine's id, opened the first time somebody looks at it. + func routineFeed(routineId: String, in pod: Pod) async throws -> RoutineFeed { + if let listed = chatLists[pod.id]?.routines.first(where: { $0.routine.id == routineId }) { + return try await routineFeed(for: listed) + } + return try await client.chats.openRoutineFeed(workspace: workspace.id, routineId: routineId) + } +} diff --git a/apps/ios/Sugabots/App/WorkspaceStore+Settings.swift b/apps/ios/Sugabots/App/WorkspaceStore+Settings.swift new file mode 100644 index 000000000..f83e6e1ab --- /dev/null +++ b/apps/ios/Sugabots/App/WorkspaceStore+Settings.swift @@ -0,0 +1,212 @@ +import Foundation + +// What the settings pages read and change, as the web's `lib/workspace.ts`, +// `lib/pods.ts`, `lib/connections.ts` and `lib/notifications.ts` do. +extension WorkspaceStore { + // MARK: Workspace + + /// This workspace with its clock, which `me` leaves out. + func workspaceRecord() async throws -> Workspace { + guard let found = try await client.workspaces.list().first(where: { $0.id == workspace.id }) else { + throw APIFailure(status: 404, message: "This workspace could not be found.") + } + return found + } + + func workspaceTimeZone() async throws -> WorkspaceTimeZone { + try await client.workspaces.timeZone(workspace: workspace.id) + } + + func changeTimeZone(to timeZone: String) async throws { + try await client.workspaces.changeTimeZone(workspace: workspace.id, timeZone: timeZone) + } + + func deleteWorkspace() async throws { + try await client.workspaces.delete(workspace: workspace.id) + } + + // MARK: People + + func workspaceMembers() async throws -> [WorkspaceMember] { + try await client.workspaces.members(workspace: workspace.id) + } + + func setRole(_ role: AssignableWorkspaceRole, of member: WorkspaceMember) async throws { + try await client.workspaces.updateMember(workspace: workspace.id, memberId: member.id, role: role) + } + + func removeMember(_ member: WorkspaceMember) async throws { + try await client.workspaces.removeMember(workspace: workspace.id, memberId: member.id) + } + + func leaveWorkspace() async throws { + try await client.workspaces.leave(workspace: workspace.id) + } + + func transferOwnership(to member: WorkspaceMember) async throws { + try await client.workspaces.transferOwnership(workspace: workspace.id, memberId: member.id) + } + + func invitations() async throws -> [WorkspaceInvitation] { + try await client.workspaces.invitations(workspace: workspace.id) + } + + func invite(_ email: String, as role: AssignableWorkspaceRole, resend: Bool = false) async throws { + _ = try await client.workspaces.invite(workspace: workspace.id, email: email, role: role, resend: resend) + } + + /// Invites each address in turn, carrying on past failures, and returns those that failed. + func invite(_ emails: [String], as role: AssignableWorkspaceRole) async -> [InviteFailure] { + var failures: [InviteFailure] = [] + for email in emails { + do { try await invite(email, as: role) } catch { failures.append(InviteFailure(email: email, reason: error.localizedDescription)) } + } + return failures + } + + func cancelInvitation(_ invitation: WorkspaceInvitation) async throws { + try await client.workspaces.cancelInvitation(invitationId: invitation.id) + } + + // MARK: Pods + + /// Every pod, freshly, with all it lets the person do. + func podRecords() async throws -> [Pod] { + try await client.pods.list(workspace: workspace.id) + } + + func podRecord(_ podId: String) async throws -> Pod { + guard let found = try await podRecords().first(where: { $0.id == podId }) else { + throw APIFailure(status: 404, message: "No such pod here") + } + return found + } + + func updatePod(_ podId: String, name: String? = nil, color: PodColor? = nil) async throws { + _ = try await client.pods.update(podId: podId, name: name, color: color.map { .present($0) } ?? .omitted) + await refreshAll() + } + + func deletePod(_ podId: String) async throws { + try await client.pods.remove(podId: podId) + await refreshAll() + } + + func podMembers(_ podId: String) async throws -> [PodMember] { + try await client.pods.listMembers(podId: podId) + } + + func addToPod(_ podId: String, userId: String) async throws { + try await client.pods.addMember(podId: podId, userId: userId) + } + + func removeFromPod(_ podId: String, userId: String) async throws { + try await client.pods.removeMember(podId: podId, userId: userId) + } + + func leavePod(_ podId: String) async throws { + try await client.pods.leave(podId: podId) + await refreshAll() + } + + // MARK: You + + func referralLink() async throws -> String? { + try await client.referrals.link().url + } + + func resetReferralLink() async throws -> String? { + try await client.referrals.resetLink().url + } + + /// Saves what the person is notified about, as Notifications' controls change it. + func updateNotificationPreferences( + level: NotificationLevel, + pausedUntil: Date?, + quietHours: QuietHours?, + turnFailures: Bool, + routineRuns: RoutineRunNotifications + ) async throws -> NotificationSettings { + try await client.notifications.updatePreferences( + level: level, pausedUntil: pausedUntil, quietHours: quietHours, turnFailures: turnFailures, routineRuns: routineRuns + ) + } + + // MARK: Connections + + func connections(in podId: String) async throws -> [Connection] { + try await client.connections.list(podId: podId) + } + + /// The pod's connections by handle, with the name and mark each is shown with, as `useConnectionLooks`. + /// Whether the system agent that writes summaries has a model; nil when it can't be told. + func summariesHaveModel() async -> Bool? { + let agents = try? await client.systemAgents.list(workspace: workspace.id) + return agents?.first { $0.key == .summarise }.map { $0.model != nil } + } + + func connectionLooks(podId: String) async -> [String: ConnectionLook] { + let found = (try? await connections(in: podId)) ?? [] + return Dictionary(found.map { ($0.handle, ConnectionLook(name: $0.name, presetId: $0.presetId)) }, uniquingKeysWith: { first, _ in first }) + } + + func connectionTools(_ connection: Connection) async throws -> [ConnectionToolSetting] { + try await client.connections.get(podId: connection.podId, connectionId: connection.id).tools + } + + func setToolAccess(_ toolAccess: [String: ConnectionAccess], of connection: Connection) async throws { + _ = try await client.connections.update(podId: connection.podId, connectionId: connection.id, toolAccess: toolAccess) + } + + /// Saves a new secret, or for a server with none yet, an access token sent as a bearer. + func saveSecret(_ secret: String, of connection: Connection) async throws { + if connection.secretHeader == nil { + _ = try await client.connections.update( + podId: connection.podId, connectionId: connection.id, secretHeader: .present("Authorization"), secret: .present(Self.bearerAuthorization(secret)) + ) + } else { + _ = try await client.connections.update(podId: connection.podId, connectionId: connection.id, secret: .present(secret)) + } + } + + func removeConnection(_ connection: Connection) async throws { + try await client.connections.remove(podId: connection.podId, connectionId: connection.id) + } + + func testConnection(_ connection: Connection) async throws -> ConnectionTestResult { + try await client.connections.test(podId: connection.podId, connectionId: connection.id) + } + + func testUnsavedConnection(in podId: String, url: String, secretHeader: String?, secret: String?) async throws -> ConnectionTestResult { + try await client.connections.testUnsaved(podId: podId, url: url, secretHeader: secretHeader, secret: secret) + } + + func createConnection(in podId: String, connection: NewConnection) async throws { + _ = try await client.connections.create(podId: podId, body: connection) + } + + /// Starts connecting a catalog app or a server that signs in, and gives the address to sign in at. + func connectSigningIn(in podId: String, name: String, url: String) async throws -> URL? { + let started = try await client.connections.connectFromCatalog(podId: podId, name: name, url: url) + return URL(string: started.authorizationUrl) + } + + /// Signs a connection in again, giving the address to sign in at, or nil when it needs none. + func startSignIn(_ connection: Connection) async throws -> URL? { + let started = try await client.connections.startOAuth(podId: connection.podId, connectionId: connection.id) + return started.authorizationUrl.flatMap(URL.init(string:)) + } + + /// As `bearerAuthorization`: a token as an Authorization header's value. + static func bearerAuthorization(_ token: String) -> String { + let trimmed = token.trimmingCharacters(in: .whitespacesAndNewlines) + return "Bearer " + trimmed.replacingOccurrences(of: "^bearer\\s+", with: "", options: [.regularExpression, .caseInsensitive]) + } + + // MARK: The web + + /// The web app's address for a path in this workspace, for what the app sends there: `settings/pods/support/connections`. + func webURL(_ path: String) -> URL { + client.webRoot.appending(path: workspace.slug).appending(path: path) + } +} diff --git a/apps/ios/Sugabots/App/WorkspaceStore.swift b/apps/ios/Sugabots/App/WorkspaceStore.swift new file mode 100644 index 000000000..cef800e12 --- /dev/null +++ b/apps/ios/Sugabots/App/WorkspaceStore.swift @@ -0,0 +1,423 @@ +import Foundation +import Observation + +/// One workspace as the signed-in person sees it: its pods and bots, each +/// pod's channels, threads and routines, Inbox and Approvals. Kept fresh by +/// the workspace's event stream, which says what changed but not how, so +/// each event refreshes what it may have touched. +@MainActor +@Observable +final class WorkspaceStore { + let client: APIClient + private(set) var user: SessionUser + private(set) var workspaces: [Workspace] + private(set) var workspace: Workspace + /// What this device remembers about the workspace, such as the pod Home shows. + let preferences: WorkspacePreferences + + private(set) var pods: [Pod] = [] + private(set) var agents: [Agent] = [] + private(set) var markers: [String: PodChatMarkers.Pod] = [:] + private(set) var chatLists: [String: ChatList] = [:] + private(set) var activity: [ActivityItem] = [] + /// Whether the Inbox has loaded once, and whether its latest load failed. + private(set) var activityLoaded = false + private(set) var activityFailed = false + private(set) var approvalsLoaded = false + private(set) var approvalsFailed = false + private(set) var approvals = ApprovalInbox(waiting: [], answered: []) + private(set) var notificationSettings: NotificationSettings? + /// What you may do in the workspace, and your role there. + private(set) var permissions: WorkspacePermissions? + private(set) var role: WorkspaceRole? + /// Conversations as they were when last left, so one opened again shows at once while it refreshes. + /// Not observed: nothing redraws when one is kept. + @ObservationIgnored var leftConversations: [String: ConversationModel.Snapshot] = [:] + /// The models the workspace's bots may run on, for naming a bot's. + private(set) var enabledModels: WorkspaceModelsResponse? + private(set) var loadError: String? + + private var pendingRefresh: Task? + /// How many loads of each kind have begun, so `loadLatest` can tell a load overtaken by a later one. + @ObservationIgnored private var loadsBegun: [LoadKind: Int] = [:] + + /// How long events gather before one refresh answers them all: a reply streaming in sends many. + private static let refreshDelay: Duration = .milliseconds(400) + + init(client: APIClient, user: SessionUser, workspaces: [Workspace], workspace: Workspace) { + self.client = client + self.user = user + self.workspaces = workspaces + self.workspace = workspace + preferences = WorkspacePreferences(workspaceId: workspace.id) + } + + /// Renames the signed-in person, everywhere the app shows their name. + func rename(to name: String) async throws { + try await client.updateName(name) + user.name = name + } + + /// Renames the workspace, keeping its slug, which every link to it holds. + func renameWorkspace(to name: String) async throws { + let renamed = try await client.workspaces.update(workspace: workspace.id, name: name, slug: workspace.slug) + workspace.name = renamed.name + workspaces = workspaces.map { $0.id == renamed.id ? renamed : $0 } + } + + var unreadInInbox: Int { activity.filter(\.unread).count } + var waitingApprovals: Int { approvals.waiting.count } + + /// Shared pods first, then the person's own, as the web's rail orders them. + var podsInRailOrder: [Pod] { + pods.filter { $0.kind == .shared } + pods.filter { $0.kind == .personal } + } + + func pod(id: String) -> Pod? { pods.first { $0.id == id } } + + func agent(id: String) -> Agent? { agents.first { $0.id == id } } + + /// The pod's own bots, by name, leaving out the system bots every pod has. + func bots(in pod: Pod) -> [Agent] { + agents.filter { $0.podId == pod.id && $0.systemAgentKey == nil }.sorted { $0.name.localizedCompare($1.name) == .orderedAscending } + } + + /// The pod's open threads, or those with `agent`: unread first, each part newest first. + func openThreads(in pod: Pod, with agent: Agent? = nil) -> [ChatListItem] { + let open = (chatLists[pod.id]?.threads ?? []).filter { item in + item.conversation.doneAt == nil && (agent == nil || item.agent?.id == agent?.id) + } + return open.filter(\.isNew) + open.filter { !$0.isNew } + } + + /// Whether anything with the bot is new: its channel, or one of its threads. + func hasNews(with agent: Agent, in pod: Pod) -> Bool { + let list = chatLists[pod.id] + let channelIsNew = list?.channels.first { $0.agent.id == agent.id }?.isNew ?? false + return channelIsNew || openThreads(in: pod, with: agent).contains(where: \.isNew) + } + + /// Where a thread was started: a pod's channel, a bot's channel, or with the bot directly. + func origin(of thread: ConversationThread) -> ThreadOrigin { + if let chatId = thread.startedInChatId, let channel = channel(chatId, in: thread.podId) { + return channel + } + if let agent = thread.hostAgentId.flatMap(agent(id:)) { + return .bot(agent) + } + return .people + } + + /// The pod's channel or bot's channel `conversationId`, as a thread's origin names it, once the pod's list has it. + func channel(_ conversationId: String, in podId: String) -> ThreadOrigin? { + if let chat = podChat(conversationId, in: podId) { + return .channel(chat.title) + } + if let channel = chatLists[podId]?.channels.first(where: { $0.id == conversationId }) { + return .bot(channel.agent) + } + return nil + } + + /// Whether the person has yet to read something in the thread. + func isNew(threadId: String, in podId: String) -> Bool { + chatLists[podId]?.threads.first { $0.id == threadId }?.isNew ?? false + } + + /// The routine whose runs post in the thread `threadId`. + func routine(postingIn threadId: String, podId: String) -> ListedRoutine? { + chatLists[podId]?.routines.first { $0.conversation?.id == threadId } + } + + func hasNews(in pod: Pod) -> Bool { + guard let marker = markers[pod.id] else { return false } + return marker.unreadMessages > 0 || marker.needsApproval || marker.failedRoutines > 0 + } + + // MARK: Loading + + /// Loads the workspace, then keeps it fresh from its event stream until the + /// task running this is cancelled. Throws the server's refusal of the + /// stream, such as a 401 `APIFailure` for a token that has expired. + func run() async throws { + await refreshAll() + for try await _ in EventStream.workspace(workspace.id, client: client) { + scheduleRefresh() + } + } + + func stop() { + pendingRefresh?.cancel() + } + + /// Reloads everything the workspace's pages show. A failure to load the pods + /// and bots shows in `loadError`. The rest keeps what was last loaded when + /// its request fails: Inbox and Approvals say so themselves, and each page + /// that needs the settings, your access or the models reloads them as it + /// opens and shows its own failure. + func refreshAll() async { + await loadLatest(.podsAndAgents) { [client, workspace] in + async let pods = client.pods.list(workspace: workspace.id) + async let agents = client.agents.list(workspace: workspace.id) + return try await (pods, agents) + } apply: { result in + switch result { + case let .success((pods, agents)): + (self.pods, self.agents) = (pods, agents) + loadError = nil + case let .failure(error): + loadError = error.localizedDescription + } + } + async let settingsRefreshed: Void = refreshNotificationSettings() + async let accessRefreshed: Void = refreshAccess() + _ = await (settingsRefreshed, accessRefreshed) + _ = try? await refreshModels() + await refreshAttention() + await refreshLoadedChatLists() + } + + /// Reloads what the person is notified about, keeping what was known if the request fails. + private func refreshNotificationSettings() async { + await loadLatest(.notificationSettings) { [client] in + try await client.notifications.settings() + } apply: { result in + if case let .success(settings) = result { notificationSettings = settings } + } + } + + /// Reloads what you may do and your role, keeping what was known if the + /// request fails. The settings pages call it as they open, so a role + /// changed since the last full refresh shows there. + func refreshAccess() async { + await loadLatest(.access) { [client, workspace] in + try await client.workspaceAccess(workspace: workspace.id) + } apply: { result in + guard case let .success(access) = result else { return } + permissions = access.permissions + role = access.role + } + } + + /// Reloads the models the workspace's bots may run on into `enabledModels`, and returns them. + @discardableResult + func refreshModels() async throws -> WorkspaceModelsResponse { + try await loadLatest(.models) { [client, workspace] in + try await client.modelProviders.listEnabledModels(workspace: workspace.id) + } apply: { result in + if case let .success(models) = result { enabledModels = models } + } + .get() + } + + /// The rail's markers, Inbox and Approvals: what the tab bar counts. + func refreshAttention() async { + await loadLatest(.attention) { [client, workspace] in + async let markers = try? client.chats.podMarkers(workspace: workspace.id) + async let activity = try? client.chats.activity(workspace: workspace.id) + async let approvals = try? client.chats.approvals(workspace: workspace.id) + return await (markers, activity, approvals) + } apply: { result in + guard case let .success((markers, activity, approvals)) = result else { return } + // The rail keeps its last markers when they fail to load; Inbox and Approvals say theirs failed. + if let markers { self.markers = markers.pods } + if let activity { + self.activity = activity.items + activityLoaded = true + activityFailed = false + } else { + activityFailed = true + } + if let approvals { + self.approvals = approvals + approvalsLoaded = true + approvalsFailed = false + } else { + approvalsFailed = true + } + } + } + + /// Reloads the pod's list, keeping the one last loaded if the request fails. + func refreshChatList(_ pod: Pod) async { + await loadLatest(.chatList(podId: pod.id)) { [client, workspace] in + try await client.chats.list(workspace: workspace.id, pod: pod.id) + } apply: { result in + if case let .success(list) = result { chatLists[pod.id] = list } + } + } + + /// What a load fetches, for telling whether a later load of the same overtook it. + private enum LoadKind: Hashable { + case podsAndAgents + case notificationSettings + case access + case models + case attention + case chatList(podId: String) + } + + /// Runs `load` and hands its result to `apply`, unless another load of + /// `kind` began while `load` ran. That later load's result is at least as + /// fresh, so the overtaken one is not applied, to keep it from overwriting + /// the later one. Returns `load`'s result either way. + @discardableResult + private func loadLatest( + _ kind: LoadKind, + _ load: () async throws -> Value, + apply: (Result) -> Void + ) async -> Result { + let begun = (loadsBegun[kind] ?? 0) + 1 + loadsBegun[kind] = begun + let result: Result + do { result = .success(try await load()) } catch { result = .failure(error) } + if loadsBegun[kind] == begun { apply(result) } + return result + } + + /// Every pod's list that has been loaded, so what's on screen catches up. + private func refreshLoadedChatLists() async { + for podId in chatLists.keys { + if let pod = pod(id: podId) { await refreshChatList(pod) } + } + } + + private func scheduleRefresh() { + pendingRefresh?.cancel() + pendingRefresh = Task { + try? await Task.sleep(for: Self.refreshDelay) + guard !Task.isCancelled else { return } + await refreshAttention() + await refreshLoadedChatLists() + } + } + + // MARK: Doing things + + /// The pod's first channel, General, opened first if nobody has. + func openPodChat(in pod: Pod) async throws -> PodChat { + if let main = chatLists[pod.id]?.chats.first(where: \.conversation.main) { return main.conversation } + let chat = try await client.chats.openPodChat(workspace: workspace.id, podId: pod.id) + await refreshChatList(pod) + return chat + } + + /// A new shared pod, named `name`, in `color`. + func createPod(named name: String, color: PodColor) async throws -> Pod { + let pod = try await client.pods.create(workspace: workspace.id, name: name, color: color) + pods.append(pod) + return pod + } + + /// A new channel in a shared pod, named `name`. + func startChat(in pod: Pod, named name: String) async throws -> PodChat { + let chat = try await client.chats.startChat(podId: pod.id, name: name) + await refreshChatList(pod) + return chat + } + + /// Chooses `level` for `place`, or with nil, follows the level above it, which also ends a mute. + /// Sets `place`'s level, or with nil, has it follow the level above it, and returns the settings as they now stand. + @discardableResult + func setNotificationLevel(_ level: NotificationLevel?, for place: NotificationPlace) async throws -> NotificationSettings { + try await client.notifications.setLevel(kind: place.kind, id: place.id, level: level) + let settings = try await client.notifications.settings() + notificationSettings = settings + return settings + } + + /// Mutes `place` until `until`, or with nil, unmutes it. + func mute(_ place: NotificationPlace, until: Date?) async throws { + try await client.notifications.mute(kind: place.kind, id: place.id, until: until) + notificationSettings = try await client.notifications.settings() + } + + /// Records that the person has read the conversation to its newest message. + func markRead(conversationId: String) async { + try? await client.chats.markRead(conversationId: conversationId) + await refreshAttention() + } + + func markAllRead() async { + let conversations = Set(activity.filter(\.unread).compactMap(\.conversationId)) + await withTaskGroup(of: Void.self) { group in + for conversationId in conversations { + group.addTask { [client] in + try? await client.chats.markRead(conversationId: conversationId) + } + } + } + await refreshAttention() + } + + typealias Decision = ToolApprovalDecision.Decision + + func decide(_ decision: Decision, toolCallId: String, podId: String) async throws { + try await client.toolApprovals.decide(podId: podId, toolCallId: toolCallId, decision: decision) + await refreshAttention() + } + + /// The bot's channel in the pod: the one listed, or opened now on first use. + func botChannel(in pod: Pod, with agent: Agent) async throws -> BotChannel { + if let listed = chatLists[pod.id]?.channels.first(where: { $0.agent.id == agent.id }) { + return listed.conversation + } + let channel = try await client.chats.openBotChannel(workspace: workspace.id, podId: pod.id, hostAgentId: agent.id) + await refreshChatList(pod) + return channel + } + + /// The thread started from a message in a channel, started now if it has none: + /// with the bot in a bot's channel, between people in a pod's. + func thread(from message: Message, podId: String) async throws -> ConversationThread { + let thread = try await client.chats.threadFrom(messageId: message.id) + if let pod = pod(id: podId) { await refreshChatList(pod) } + return thread + } + + /// Makes a bot in `pod` and adds it to the pod's bots. + func createBot(in pod: Pod, name: String, look: BotLook, model: String) async throws -> Agent { + let agent = try await client.agents.create( + podId: pod.id, + name: name, + color: look.color, + face: look.face, + shape: look.shape, + model: model + ) + agents.append(agent) + return agent + } + + /// Whether the workspace has computers set up for its bots. + func computersEnabled() async throws -> Bool { + try await client.sandboxProviders.access(workspace: workspace.id).enabled + } + + /// Gives the bot a computer in its pod's sandbox. + func giveComputer(to agent: Agent) async throws { + let updated = try await client.agents.update(agentId: agent.id, usesSandbox: .present(true)) + if let index = agents.firstIndex(where: { $0.id == updated.id }) { agents[index] = updated } + } + + /// A routine's thread, opened the first time somebody looks at it. + func routineFeed(for routine: ListedRoutine) async throws -> RoutineFeed { + if let feed = routine.conversation { return feed } + return try await client.chats.openRoutineFeed(workspace: workspace.id, routineId: routine.routine.id) + } +} + +/// Where a thread was started, as its rows and header name it. +enum ThreadOrigin { + case channel(String) + case bot(Agent) + case people + + var name: String { + switch self { + case let .channel(name): "#\(name)" + case let .bot(agent): agent.name + case .people: "People" + } + } +} diff --git a/apps/ios/Sugabots/Artifacts/ArtifactCards.swift b/apps/ios/Sugabots/Artifacts/ArtifactCards.swift new file mode 100644 index 000000000..7ae3a5e13 --- /dev/null +++ b/apps/ios/Sugabots/Artifacts/ArtifactCards.swift @@ -0,0 +1,206 @@ +import SwiftUI + +/// The artifacts a message shows, each a card at the version written, as the +/// web's `ArtifactCards`: those its reply's calls wrote, under its tool line, +/// or, on a routine's posted result, those its run wrote. `onOpen` is given +/// the artifact as the message wrote it, to open at that version. +struct ArtifactCards: View { + let parts: [MessagePart] + let podId: String + /// The bot that wrote the reply, whom each card names as its maker. + let botName: String + let onOpen: (WrittenArtifact) -> Void + + var body: some View { + let written = WrittenArtifact.writtenIn(parts) + if !written.isEmpty { + VStack(alignment: .leading, spacing: 8) { + ForEach(written) { artifact in + ArtifactCard(podId: podId, artifact: artifact, botName: botName) { onOpen(artifact) } + } + } + .padding(.bottom, 6) + } + } +} + +/// An artifact among the messages: a header saying which bot made it, so a +/// page is never taken for the app's own screens, which expands to show it +/// in place, and opens it large. +@MainActor +private struct ArtifactCard: View { + let podId: String + let artifact: WrittenArtifact + let botName: String + let onOpen: () -> Void + @Environment(WorkspaceStore.self) private var store + @State private var content: Content = .loading + @State private var expanded = false + @State private var pageHeight = PageFrame.fitHeight.min + @State private var pageExpanded = false + + private enum Content: Equatable { + case loading + case loaded(String) + case failed + case deleted + } + + /// How much of a document a collapsed preview shows. + private static let documentPreviewHeight: CGFloat = 168 + + var body: some View { + let kind = artifact.kind + Group { + if content == .deleted { + HStack(spacing: 10) { + Icon(kind.icon, size: 16) + .foregroundStyle(Palette.subtleForeground) + .frame(width: 32, height: 32) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + VStack(alignment: .leading, spacing: 1) { + Text(artifact.title).font(Typeface.rubik(12.5, .medium)).foregroundStyle(Palette.mutedForeground).strikethrough().lineLimit(1) + Text("\(kind.label) by \(botName), deleted").font(Typeface.rubik(12.5)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border, style: StrokeStyle(lineWidth: 1, dash: [4, 3]))) + } else { + VStack(spacing: 0) { + header(kind) + if expanded, content != .failed { + Rectangle().fill(Palette.border).frame(height: 1) + inline + } + } + .background(Palette.panel) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border)) + } + } + .frame(maxWidth: expanded && artifact.kind == .html ? .infinity : 560, alignment: .leading) + .accessibilityElement(children: .contain) + .accessibilityLabel(artifact.title) + .task(id: artifact.version) { await load() } + } + + private func header(_ kind: ArtifactKind) -> some View { + HStack(spacing: 10) { + Icon(kind.icon, size: 15, strokeWidth: 2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 28, height: 28) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + VStack(alignment: .leading, spacing: 1) { + Text(artifact.title).font(Typeface.rubik(12.5, .medium)).foregroundStyle(Palette.foreground).lineLimit(1) + Text("\(kind.label) by \(botName)").font(Typeface.rubik(12.5)).foregroundStyle(Palette.mutedForeground).lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + if content != .failed { + Button { expanded.toggle() } label: { + HStack(spacing: 6) { + Icon(expanded ? .chevronUp : .chevronDown, size: 14) + Text(expanded ? "Hide" : "Preview") + } + } + .buttonStyle(CardButtonStyle(outlined: true)) + .accessibilityLabel("\(expanded ? "Hide" : "Preview") \(artifact.title)") + .accessibilityValue(expanded ? "Expanded" : "Collapsed") + } + Button(action: onOpen) { + HStack(spacing: 6) { + Icon(.maximize2, size: 14) + Text("Open") + } + } + .buttonStyle(CardButtonStyle(outlined: false)) + .accessibilityLabel("Open \(artifact.title)") + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + } + + @ViewBuilder private var inline: some View { + switch content { + case let .loaded(text): + if artifact.kind == .html { + let tall = pageHeight > PageFrame.fitHeight.max + ArtifactFrame(html: text, title: artifact.title, podId: podId, artifactId: artifact.artifactId, version: artifact.version) { pageHeight = max(PageFrame.fitHeight.min, $0.rounded(.up)) } + .frame(height: pageExpanded ? pageHeight : min(pageHeight, PageFrame.fitHeight.max)) + .overlay(alignment: .bottom) { + if tall, !pageExpanded { + LinearGradient(colors: [Palette.panel.opacity(0), Palette.panel], startPoint: .top, endPoint: .bottom) + .frame(height: 80) + .allowsHitTesting(false) + } + } + .overlay(alignment: .bottom) { + if tall { + Button { pageExpanded.toggle() } label: { + HStack(spacing: 6) { + Icon(pageExpanded ? .chevronUp : .chevronDown, size: 15) + Text(pageExpanded ? "Show less" : "Show all") + } + .font(Typeface.rubik(13, .semibold)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 14) + .frame(height: 32) + .background(Palette.panel, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong)) + } + .buttonStyle(.plain) + .padding(.bottom, 12) + } + } + } else { + Button(action: onOpen) { + MessageMarkdown(text: text) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 8) + .frame(maxHeight: Self.documentPreviewHeight, alignment: .top) + .clipped() + .mask(LinearGradient(stops: [.init(color: .black, location: 0.6), .init(color: .clear, location: 1)], startPoint: .top, endPoint: .bottom)) + } + .buttonStyle(.plain) + .accessibilityLabel("Open \(artifact.title)") + } + default: + Text("Loading…") + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, minHeight: 120) + } + } + + private func load() async { + do { + content = .loaded(try await store.artifact(artifact.artifactId, in: podId, version: artifact.version).content) + } catch let failure as APIFailure where failure.status == 404 { + content = .deleted + } catch { + content = .failed + } + } +} + +/// The card's small buttons: Preview outlined on nothing, Open on a chip. +private struct CardButtonStyle: ButtonStyle { + let outlined: Bool + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(Typeface.rubik(13, outlined ? .medium : .semibold)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 14) + .frame(height: 29) + .background( + configuration.isPressed ? Palette.hover : (outlined ? .clear : Palette.chip), + in: RoundedRectangle(cornerRadius: 8, style: .continuous) + ) + .overlay { + if outlined { RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong) } + } + } +} diff --git a/apps/ios/Sugabots/Artifacts/ArtifactFrame.swift b/apps/ios/Sugabots/Artifacts/ArtifactFrame.swift new file mode 100644 index 000000000..7ae88c15d --- /dev/null +++ b/apps/ios/Sugabots/Artifacts/ArtifactFrame.swift @@ -0,0 +1,175 @@ +import SwiftUI +import WebKit + +extension ArtifactKind { + /// Its mark, as the web's `ARTIFACT_KINDS` draws it; a kind this app doesn't know is drawn as a document. + var icon: Lucide { + switch self { + case .html: .panelsTopLeft + case .document, .unknown: .fileText + } + } +} + +/// A bot-made page in a web view, as the web's `HtmlFrame`: served from the +/// installation's content origin when it has one, else written in with the +/// page's content policy before anything else. The view keeps nothing between +/// pages and loads nothing but the page: what the page fetches is limited by +/// the content policy, and any navigation it starts is cancelled. The app's +/// colours reach the page as the web's tokens. With `onPageHeight`, it reports +/// how tall the page is, and leaves scrolling to whatever holds it. +struct ArtifactFrame: View { + let html: String + let title: String + let podId: String + let artifactId: String + let version: Int + var onPageHeight: ((CGFloat) -> Void)? + @Environment(WorkspaceStore.self) private var store + @Environment(\.colorScheme) private var colorScheme + @State private var source: PageWebView.Source? + @State private var failed = false + + var body: some View { + Group { + if let source { + PageWebView(source: source, onPageHeight: onPageHeight) + } else if failed { + VStack(spacing: 12) { + FormAlert(text: "This page couldn't be loaded.").fixedSize() + Button("Try again") { Task { await load() } }.buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + } + .frame(maxWidth: .infinity, minHeight: PageFrame.fitHeight.min) + } else { + Color.clear.frame(minHeight: PageFrame.fitHeight.min) + } + } + .task(id: colorScheme) { await load() } + .accessibilityLabel(title) + } + + private func load() async { + failed = false + let theme = PageTheme(dark: colorScheme == .dark) + do { + if let url = try await store.pageAddress(artifactId, in: podId, version: version) { + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + components?.fragment = theme.json + source = components?.url.map(PageWebView.Source.url) + } else { + source = .html(theme.written(into: html)) + } + } catch { + failed = true + } + } +} + +/// The app's colour scheme and tokens, as the web hands them to a page (`pageThemeCss`). +struct PageTheme { + let dark: Bool + + var colorScheme: String { dark ? "dark" : "light" } + + var tokenDeclarations: String { + PageFrame.tokens.map { "\($0.name): \(dark ? $0.dark : $0.light);" }.joined(separator: " ") + } + + var css: String { PageFrame.themeCss(colorScheme: colorScheme, tokens: tokenDeclarations) } + + /// The theme as the page served from the content origin reads it from its fragment. + var json: String { + let object = ["colorScheme": colorScheme, "tokens": tokenDeclarations] + let data = (try? JSONSerialization.data(withJSONObject: object)) ?? Data() + return String(decoding: data, as: UTF8.self) + } + + /// `html` with the content policy and the theme before anything else in it, after any doctype. + func written(into html: String) -> String { + let tags = "" + let trimmed = html.drop { $0.isWhitespace } + guard trimmed.lowercased().hasPrefix("") else { return tags + html } + return String(trimmed[...end]) + tags + String(trimmed[trimmed.index(after: end)...]) + } +} + +/// A web view that keeps nothing between pages, loads nothing but `source`, +/// and, with `onPageHeight`, says how tall its page is instead of scrolling it. +struct PageWebView: UIViewRepresentable { + enum Source: Equatable { + case url(URL) + case html(String) + + /// The address the web view's main frame loads it at: its own, or a blank page's for written-in HTML. + var address: URL { + switch self { + case let .url(url): url + case .html: Self.blankPage + } + } + + private static let blankPage = URL(string: "about:blank")! + } + + let source: Source + var onPageHeight: ((CGFloat) -> Void)? + + func makeCoordinator() -> Coordinator { Coordinator() } + + func makeUIView(context: Context) -> WKWebView { + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = .nonPersistent() + configuration.userContentController.add(context.coordinator, name: PageFrame.heightMessageHandler) + configuration.userContentController.addUserScript( + WKUserScript(source: PageFrame.heightReport, injectionTime: .atDocumentEnd, forMainFrameOnly: true) + ) + let view = WKWebView(frame: .zero, configuration: configuration) + view.isOpaque = false + view.backgroundColor = .clear + view.scrollView.backgroundColor = .clear + view.navigationDelegate = context.coordinator + return view + } + + func updateUIView(_ view: WKWebView, context: Context) { + context.coordinator.onPageHeight = onPageHeight + view.scrollView.isScrollEnabled = onPageHeight == nil + if context.coordinator.loaded != source { load(source, into: view, context: context) } + } + + private func load(_ source: Source, into view: WKWebView, context: Context) { + context.coordinator.loaded = source + switch source { + case let .url(url): view.load(URLRequest(url: url)) + case let .html(html): view.loadHTMLString(html, baseURL: nil) + } + } + + final class Coordinator: NSObject, WKScriptMessageHandler, WKNavigationDelegate { + var onPageHeight: ((CGFloat) -> Void)? + var loaded: Source? + + func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) { + guard let height = message.body as? Double else { return } + onPageHeight?(CGFloat(height)) + } + + /// Only `loaded` loads, in the main frame, at its own address; a jump to + /// a fragment of it stays in the page. A link the page follows, a script + /// or `` sending it elsewhere, or a frame in it + /// opens nothing, so the page can't carry what it holds away in an address. + func webView(_: WKWebView, decidePolicyFor action: WKNavigationAction) async -> WKNavigationActionPolicy { + guard let loaded, action.targetFrame?.isMainFrame == true, let requested = action.request.url, + Self.withoutFragment(requested) == Self.withoutFragment(loaded.address) + else { return .cancel } + return .allow + } + + /// `url` without its fragment, which carries the page's theme and never leaves the web view. + private static func withoutFragment(_ url: URL) -> URL? { + var components = URLComponents(url: url, resolvingAgainstBaseURL: false) + components?.fragment = nil + return components?.url + } + } +} diff --git a/apps/ios/Sugabots/Artifacts/ArtifactsPage.swift b/apps/ios/Sugabots/Artifacts/ArtifactsPage.swift new file mode 100644 index 000000000..bcc17effd --- /dev/null +++ b/apps/ios/Sugabots/Artifacts/ArtifactsPage.swift @@ -0,0 +1,309 @@ +import SwiftUI + +/// What an artifact names as its maker once that bot is deleted. +private let removedBotName = "A removed bot" + +/// The documents and pages a pod's bots have made, newest first, under when +/// each was last changed, as the web's `ArtifactListView` on a phone. Each +/// opens on a page of its own. +@MainActor +struct ArtifactsScreen: View { + let pod: Pod + @Environment(WorkspaceStore.self) private var store + @State private var artifacts: [ArtifactSummary]? + @State private var failed = false + + var body: some View { + VStack(spacing: 0) { + PodPageHeader(title: "Artifacts") + if failed { + EmptyState(title: "Could not load the artifacts", text: "The API did not answer. Reload, or check that it is running.") + } else if let artifacts, artifacts.isEmpty { + EmptyState( + title: "No artifacts in \(pod.name) yet", + icon: .fileText, + text: "When a bot writes you a doc, report or page, it's saved here so the whole pod can find it later." + ) + .padding(.bottom, 60) + } else if let artifacts { + ScrollView { + LazyVStack(alignment: .leading, spacing: 20) { + ForEach(Self.byWhen(artifacts, now: .now), id: \.label) { group in + VStack(alignment: .leading, spacing: 2) { + Text(group.label) + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 8) + .padding(.bottom, 6) + .accessibilityAddTraits(.isHeader) + ForEach(group.artifacts) { artifact in + ArtifactRow(pod: pod, artifact: artifact) + } + } + } + } + .padding(.horizontal, 16) + .padding(.top, 16) + .padding(.bottom, 48) + } + .refreshable { await load() } + } else { + Spacer() + } + } + .background(Palette.background.ignoresSafeArea()) + .task { await load() } + } + + private func load() async { + do { + artifacts = try await store.artifacts(in: pod.id) + failed = false + } catch { + failed = artifacts == nil + } + } + + /// Artifacts last changed in the same span of time. + struct TimeGroup { + /// "Today", "Earlier this week", then the month, with its year when not this one. + let label: String + var artifacts: [ArtifactSummary] + } + + /// The artifacts, newest first, under when each was last updated. + static func byWhen(_ artifacts: [ArtifactSummary], now: Date) -> [TimeGroup] { + var groups: [TimeGroup] = [] + let week: TimeInterval = 7 * 24 * 60 * 60 + for artifact in artifacts { + let updated = artifact.updatedAt + let sameYear = Calendar.current.isDate(updated, equalTo: now, toGranularity: .year) + let label = + Calendar.current.isDate(updated, inSameDayAs: now) ? "Today" + : now.timeIntervalSince(updated) < week ? "Earlier this week" + : sameYear ? updated.formatted(.dateTime.month(.wide)) + : updated.formatted(.dateTime.month(.wide).year()) + if groups.last?.label == label { + groups[groups.count - 1].artifacts.append(artifact) + } else { + groups.append(TimeGroup(label: label, artifacts: [artifact])) + } + } + return groups + } +} + +/// An artifact in the list: its kind, title, which version, who made it, and when it last changed. +private struct ArtifactRow: View { + let pod: Pod + let artifact: ArtifactSummary + + var body: some View { + let kind = artifact.kind + NavigationLink(value: Route.artifact(podId: pod.id, artifactId: artifact.id, version: nil)) { + HStack(spacing: 12) { + Icon(kind.icon, size: 16, strokeWidth: 1.75) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 32, height: 32) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + VStack(alignment: .leading, spacing: 1) { + Text(artifact.title).font(Typeface.rubik(13, .medium)).foregroundStyle(Palette.foreground).lineLimit(1) + Text([kind.label, "v\(artifact.version)", artifact.createdBy?.name ?? removedBotName].joined(separator: ", ")) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Text(Times.list(artifact.updatedAt)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + .padding(8) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(pressed: Palette.messageHover, cornerRadius: 10)) + } +} + +/// An artifact opened on its own page, as the web's `ArtifactStage` on a +/// phone: Back, its title and who wrote this version when, the version +/// shown with the others to switch to, and ⋯ with Download, Copy link and, +/// for those who may, Delete. +@MainActor +struct ArtifactScreen: View { + let podId: String + let artifactId: String + /// An earlier version to show; the current one when nil. + @State var version: Int? + @Environment(WorkspaceStore.self) private var store + @Environment(Toaster.self) private var toaster + @Environment(\.dismiss) private var dismiss + @State private var artifact: Artifact? + @State private var versions: [ArtifactVersionSummary] = [] + @State private var failed = false + @State private var confirmingDelete = false + @State private var download: SavedFile? + + var body: some View { + let pod = store.pod(id: podId) + VStack(spacing: 0) { + HStack(spacing: 8) { + PhoneBackButton() + VStack(alignment: .leading, spacing: 1) { + Text(artifact?.title ?? "") + .font(Typeface.rubik(17, .semibold)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + if let artifact { + Text("\(artifact.shownVersion.author?.name ?? removedBotName) \(Self.writtenWhen(artifact.shownVersion.createdAt))") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .lineLimit(1) + } + } + .padding(.leading, 4) + .frame(maxWidth: .infinity, alignment: .leading) + if let artifact { + versionPicker(artifact) + moreMenu(artifact, pod: pod) + } + } + .pageHeaderInsets() + Group { + if let artifact { + content(artifact) + } else if failed { + EmptyState(title: "No such artifact here", text: "It may have been removed, or the API did not answer.") + } else { + Spacer() + } + } + .padding(.horizontal, 12) + .padding(.top, 16) + .padding(.bottom, 12) + } + .background(Palette.background.ignoresSafeArea()) + .task(id: version) { await load() } + .confirmDelete( + isPresented: $confirmingDelete, + title: "Delete \(artifact?.title ?? "")?", + description: "Every version goes with it, for everyone in the pod. Replies that showed it keep only its name. This can't be undone." + ) { + try await store.deleteArtifact(artifactId, in: podId) + dismiss() + } + .sheet(item: $download) { file in + ShareSheet(items: [file.url]) + } + } + + @ViewBuilder private func content(_ artifact: Artifact) -> some View { + let border = RoundedRectangle(cornerRadius: 12, style: .continuous) + if artifact.kind == .html { + ArtifactFrame(html: artifact.content, title: artifact.title, podId: artifact.podId, artifactId: artifact.id, version: artifact.shownVersion.number) + .clipShape(border) + .overlay(border.strokeBorder(Palette.border)) + } else { + ScrollView { + MessageMarkdown(text: artifact.content) + .frame(maxWidth: 760, alignment: .leading) + .padding(.horizontal, 16) + .padding(.vertical, 24) + .frame(maxWidth: .infinity, alignment: .leading) + } + .background(Palette.list, in: border) + .overlay(border.strokeBorder(Palette.border)) + } + } + + /// Which version is shown, round on glass, and the others to switch to. + private func versionPicker(_ artifact: Artifact) -> some View { + let shown = artifact.shownVersion.number + let isCurrent = shown == artifact.version + return Menu { + ForEach(versions) { candidate in + Button { + version = candidate.number == artifact.version ? nil : candidate.number + } label: { + let byline = "by \(candidate.author?.name ?? removedBotName.lowercased())" + let label = "Version \(candidate.number) \(byline) · \(Times.list(candidate.createdAt))" + if candidate.number == shown { Label(label, systemImage: "checkmark") } else { Text(label) } + } + } + } label: { + HStack(spacing: 6) { + Text("v\(shown)\(isCurrent ? "" : " of \(artifact.version)")") + .font(Typeface.rubik(12.5)) + .foregroundStyle(isCurrent ? Palette.softForeground : Palette.foreground) + Icon(.chevronDown, size: 12).foregroundStyle(Palette.subtleForeground) + } + .padding(.leading, 14) + .padding(.trailing, 12) + .frame(height: 44) + .glass(in: Capsule()) + } + .accessibilityLabel("Version \(shown) of \(artifact.version)") + } + + private func moreMenu(_ artifact: Artifact, pod: Pod?) -> some View { + Menu { + Button { saveForDownload(artifact) } label: { Label("Download", systemImage: "arrow.down.to.line") } + if let pod { + Button { + UIPasteboard.general.url = store.webLink(toArtifact: artifact.id, in: pod) + toaster.show("Copied") + } label: { Label("Copy link", systemImage: "link") } + if pod.permissions.deleteArtifacts { + Button(role: .destructive) { confirmingDelete = true } label: { Label("Delete", systemImage: "trash") } + } + } + } label: { + GlassRoundIcon(icon: .ellipsis) + } + .accessibilityLabel("More") + } + + private func load() async { + do { + async let shown = store.artifact(artifactId, in: podId, version: version) + async let all = store.artifactVersions(artifactId, in: podId) + artifact = try await shown + versions = (try? await all) ?? versions + } catch { + // Leaving the page cancels its request, which isn't a failure. + if Task.isCancelled { return } + guard let artifact else { + failed = true + return + } + // Switching versions failed: say so, and point the picker back at the version still shown. + toaster.show(error.localizedDescription) + let shown = artifact.shownVersion.number + version = shown == artifact.version ? nil : shown + } + } + + /// Saves the artifact as shown as a file named after its title, for the share sheet. + private func saveForDownload(_ artifact: Artifact) { + let kind = artifact.kind + var name = artifact.title.replacingOccurrences(of: "[\\\\/:*?\"<>|]+", with: "-", options: .regularExpression) + .trimmingCharacters(in: .whitespaces) + if !name.lowercased().hasSuffix(".\(kind.fileExtension)") { name += ".\(kind.fileExtension)" } + let content = artifact.kind == .html ? PageTheme(dark: false).written(into: artifact.content) : artifact.content + let file = FileManager.default.temporaryDirectory.appending(path: name) + do { + try content.write(to: file, atomically: true, encoding: .utf8) + download = SavedFile(url: file) + } catch { + toaster.show(error.localizedDescription) + } + } + + /// When a version was written, to follow its author: "at 2:46", "yesterday", "on Mon", "on 14 Sep". + static func writtenWhen(_ date: Date) -> String { + let shown = Times.listInSentence(date) + switch Times.daysAgo(date) { + case ...0: return "at \(shown)" + case 1: return shown + default: return "on \(shown)" + } + } +} diff --git a/apps/ios/Sugabots/Assets.xcassets/AccentColor.colorset/Contents.json b/apps/ios/Sugabots/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 000000000..d38b74c66 --- /dev/null +++ b/apps/ios/Sugabots/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,23 @@ +{ + "colors": [ + { + "color": { + "color-space": "srgb", + "components": { "alpha": "1.000", "blue": "0x13", "green": "0x11", "red": "0x11" } + }, + "idiom": "universal" + }, + { + "appearances": [{ "appearance": "luminosity", "value": "dark" }], + "color": { + "color-space": "srgb", + "components": { "alpha": "1.000", "blue": "0xED", "green": "0xED", "red": "0xED" } + }, + "idiom": "universal" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/AppIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..faa97a6a4ab6c082942e434346b12a0adba3cfba GIT binary patch literal 39953 zcmeEu^7x(V6q##{_fJ#b>lpw4HB1ouoEg&Hvof69$ptOP#Qi=-FigfHsDjm`d z0@5rU1~7wKodut%U`Y5082M2X@KS+u{rRj0 z7lx7j^*f*wcJD8uM{Tsh>*$XYypF#A{Z5tv|ED$hEd%kt)<{?e*}tEUx)n@U#DX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esNq%m+tEEH;ep>q#jXiwxe~aJn2ZB4E99B`d=7#nd*R z#M`+VxCC4Ep6M(8OryiAuCMrw{T^(3sb?&FsD6epK@BVOJm7vWPYG-Fi0n*Y7yJX^ zv<6!eJ#5ZyAL)x4nXO2*qXb3xYTPaHgy3^ZJpbRD;lG3LzjOb;u;<@M>c6P(pO97Xzo7TOnE(Ilm1hrH)bi*q U$^L9d0sdXpGP+W7$?3uW0nBHw`Tzg` literal 0 HcmV?d00001 diff --git a/apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..317fcc7fc --- /dev/null +++ b/apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images": [ + { + "filename": "AppIcon.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" + } + ], + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/apps/ios/Sugabots/Assets.xcassets/Contents.json b/apps/ios/Sugabots/Assets.xcassets/Contents.json new file mode 100644 index 000000000..d458f1c59 --- /dev/null +++ b/apps/ios/Sugabots/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info": { + "author": "xcode", + "version": 1 + } +} diff --git a/apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Contents.json b/apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Contents.json new file mode 100644 index 000000000..3e30c0d29 --- /dev/null +++ b/apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "filename" : "Mark.png", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Mark.png b/apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Mark.png new file mode 100644 index 0000000000000000000000000000000000000000..103da27f933c773059ca78975cdc3f65fc0d8716 GIT binary pat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Iv^Lld4j6d2ZHgU1_t_i!@x`X=#4>!j(>! zWdD=;BRa(^&4+mty52|OLI+&D{6>xa#i&2u7;}Q%+elf9ZV4AF+zWuIU0nHrFy+rJ z0!L43E7OM{DMbs?vPN*!6`IBOgU@~oYX6LU(5H>!Z2rugozrdtOd shown.count { + Button("Show older") { showAll = true } + .font(Typeface.rubik(15, .medium)) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + } + } + } + } + .padding(.horizontal, 16) + .padding(.top, 6) + .padding(.bottom, 48) + } + .refreshable { await store.refreshAttention() } + } + .background(Palette.background.ignoresSafeArea()) + } +} + +private struct SectionLabel: View { + let text: String + + var body: some View { + Text(text) + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 2) + .padding(.bottom, -2) + .accessibilityAddTraits(.isHeader) + } +} + +/// Approvals with nothing waiting: a card saying so, and what Approvals is for. +private struct NothingWaiting: View { + var body: some View { + HStack(spacing: 14) { + Icon(.shieldCheck, size: 20, strokeWidth: 1.75) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 40, height: 40) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + VStack(alignment: .leading, spacing: 2) { + Text("Nothing waiting on you").font(Typeface.rubik(15, .medium)).foregroundStyle(Palette.foreground) + Text("Bots ask here before they do anything you need to allow.").font(Typeface.rubik(14)).lineSpacing(4).foregroundStyle(Palette.mutedForeground) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 16) + .frame(minHeight: 98) + .background(Palette.card, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.border)) + } +} + +/// Where and when a request was asked: `in Acme at 6:12`. +private func askedWhereAndWhen(_ request: ApprovalEntry, in pod: Pod?) -> String { + [pod.map { "in \($0.name)" }, "at \(Times.list(request.call.startedAt))"].compactMap { $0 }.joined(separator: " ") +} + +private extension AnsweredApproval.Answer { + /// `Allowed` or `Denied`. + var verdict: String { status == .allowed ? "Allowed" : "Denied" } +} + +/// A request waiting on the person: who asked for what, where and when, which opens it; the request folded; Deny and Allow. +@MainActor +private struct WaitingCard: View { + let request: ApprovalEntry + @Environment(WorkspaceStore.self) private var store + + var body: some View { + let action = ToolNames.step(request.call.tool) + let asked = askedWhereAndWhen(request, in: store.pod(id: request.podId)) + VStack(alignment: .leading, spacing: 12) { + NavigationLink(value: Route.approval(callId: request.call.id)) { + HStack(spacing: 12) { + BotFace(look: request.agent.look, size: 24) + VStack(alignment: .leading, spacing: 2) { + Text(action).font(Typeface.rubik(17, .medium)).foregroundStyle(Palette.foreground).multilineTextAlignment(.leading) + Text("\(request.agent.name) asked \(asked)").font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + Icon(.chevronRight, size: 16, strokeWidth: 2).foregroundStyle(Palette.disabledForeground) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + FoldedRequest(input: request.call.input) + Answer(call: request.call, podId: request.podId, agentName: request.agent.name, actionLabel: action) + } + .padding(14) + .background(Palette.card, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.border)) + .accessibilityElement(children: .contain) + .accessibilityLabel("\(request.agent.name): \(action)") + } +} + +/// A resolved request on two lines, what it would have done over which bot, with how it was answered and when. +private struct ResolvedRow: View { + let request: ApprovalEntry + + var body: some View { + let action = ToolNames.step(request.call.tool) + NavigationLink(value: Route.approval(callId: request.call.id)) { + HStack(spacing: 12) { + BotFace(look: request.agent.look, size: 20) + VStack(alignment: .leading, spacing: 2) { + Text(action).font(Typeface.rubik(15)).foregroundStyle(Palette.foreground).lineLimit(1) + Text(request.agent.name).font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Text(request.answer?.verdict ?? "") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + Text(request.answer.map { Times.age($0.decidedAt) } ?? "") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .frame(width: 64, alignment: .trailing) + } + .padding(.horizontal, 4) + .frame(minHeight: 56) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(cornerRadius: 8)) + } +} + +/// One request on its own page, as the web's `ApprovalPage` on a phone: the +/// app's mark and the action over who asked, where and when, every field, +/// then Deny and Allow, or how it was answered, and Open conversation. +@MainActor +struct ApprovalPage: View { + let callId: String + @Environment(WorkspaceStore.self) private var store + @State private var looks: [String: ConnectionLook] = [:] + + var body: some View { + let waiting = store.approvals.waiting.first { $0.call.id == callId }.map(ApprovalEntry.init) + let request = waiting ?? store.approvals.answered.first { $0.call.id == callId }.map(ApprovalEntry.init) + ScrollView { + VStack(alignment: .leading, spacing: 20) { + HStack { PhoneBackButton(label: "Back to Approvals"); Spacer() } + if let request { + detail(request, waiting: waiting != nil) + } else if store.approvalsLoaded { + VStack(spacing: 6) { + Text("This request is no longer here").font(Typeface.rubik(15, .medium)).foregroundStyle(Palette.foreground) + Text("It may have been answered a while ago, or its chat removed.").font(Typeface.rubik(14)).foregroundStyle(Palette.mutedForeground) + } + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .padding(.top, 80) + } + } + .padding(.horizontal, 16) + .pageTopPadding() + .padding(.bottom, 32) + } + .background(Palette.background.ignoresSafeArea()) + .task(id: request?.podId) { + if let podId = request?.podId { looks = await store.connectionLooks(podId: podId) } + } + } + + @ViewBuilder private func detail(_ request: ApprovalEntry, waiting: Bool) -> some View { + let step = ApprovalStep(call: request.call, agentName: request.agent.name, looks: looks) + let pod = store.pod(id: request.podId) + let asked = askedWhereAndWhen(request, in: pod) + HStack(spacing: 12) { + ConnectionMark(presetId: step.look?.presetId, name: step.appName, size: .sm) + VStack(alignment: .leading, spacing: 4) { + Text(step.action).font(Typeface.rubik(22, .semibold)).tracking(-0.22).foregroundStyle(Palette.foreground) + Text("\(request.agent.name) wants to use \(step.appName) · \(asked)").font(Typeface.rubik(14)).foregroundStyle(Palette.mutedForeground) + } + } + let fields = request.call.input.fields.sorted { $0.key < $1.key } + if !fields.isEmpty { + VStack(spacing: 0) { + DividedRows(data: fields, id: \.key) { field in + VStack(alignment: .leading, spacing: 4) { + Text(ToolNames.words(fromKey: field.key)).font(Typeface.rubik(14)).foregroundStyle(Palette.subtleForeground) + RequestValue(value: field.value, depth: 1) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 12) + } + } + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border)) + } + VStack(spacing: 16) { + if let answer = request.answer, !waiting { + HStack(spacing: 6) { + Icon(answer.status == .allowed ? .check : .x, size: 13, strokeWidth: 2.8) + Text("\(answer.verdict)\(answer.decidedByName.map { " by \($0)" } ?? "") at \(Times.list(answer.decidedAt))") + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, alignment: .leading) + } else { + Answer(call: request.call, podId: request.podId, agentName: request.agent.name, actionLabel: step.action) + } + if pod != nil, let conversationId = request.conversationId { + NavigationLink("Open conversation", value: Route.conversation(threadId: conversationId, title: "")) + .font(Typeface.rubik(15, .medium)) + .foregroundStyle(Palette.foreground) + .padding(.vertical, 8) + } + } + .padding(.top, 4) + } +} diff --git a/apps/ios/Sugabots/Attention/InboxScreen.swift b/apps/ios/Sugabots/Attention/InboxScreen.swift new file mode 100644 index 000000000..ae13a6563 --- /dev/null +++ b/apps/ios/Sugabots/Attention/InboxScreen.swift @@ -0,0 +1,299 @@ +import SwiftUI + +/// Inbox, as the web's `Inbox` on a phone: its large title with Unread only, +/// a filter by kind and Mark all as read at the right, then what happened in +/// the person's conversations, newest first, each opening where it happened. +@MainActor +struct InboxScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var unreadOnly = true + @State private var kinds: Set = [] + @State private var marking = false + + var body: some View { + let inView = store.activity.filter { !unreadOnly || $0.unread } + let items = inView.filter { kinds.isEmpty || kinds.contains(InboxKind($0)) } + let unreadConversations = Set(store.activity.filter(\.unread).compactMap(\.conversationId)) + VStack(spacing: 0) { + TabPageHeader(title: "Inbox") { + HeaderIconToggle(on: unreadOnly, label: "Unread only") { unreadOnly.toggle() } icon: { + UnreadOnlyIcon() + } + Menu { + ForEach(InboxKind.allCases) { kind in + let count = inView.filter { InboxKind($0) == kind }.count + Button { + if kinds.contains(kind) { kinds.remove(kind) } else { kinds.insert(kind) } + } label: { + if kinds.contains(kind) { + Label(count > 0 ? "\(kind.label) \(count)" : kind.label, systemImage: "checkmark") + } else { + Text(count > 0 ? "\(kind.label) \(count)" : kind.label) + } + } + } + } label: { + Icon(.listFilter, size: 20, strokeWidth: 1.75) + .foregroundStyle(kinds.isEmpty ? Palette.mutedForeground : Palette.foreground) + .frame(width: 40, height: 40) + .background(kinds.isEmpty ? .clear : Palette.chip, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + .accessibilityLabel("Filter") + if !unreadConversations.isEmpty { + HeaderIconToggle(on: false, label: "Mark all as read") { + marking = true + Task { + await store.markAllRead() + marking = false + } + } icon: { + Icon(.checkCheck, size: 20, strokeWidth: 1.75) + } + .disabled(marking) + } + } + ScrollView { + LazyVStack(spacing: 2) { + if store.activityFailed { + Text("Inbox could not be loaded.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(12) + } + ForEach(items) { item in + InboxRow(item: item, pod: item.podId.flatMap(store.pod(id:))) + } + } + .padding(8) + } + .overlay { + if store.activityLoaded && items.isEmpty { + VStack(spacing: 8) { + Icon(.inbox, size: 40, strokeWidth: 1.25) + .foregroundStyle(Palette.subtleForeground) + .padding(.bottom, 8) + Text(unreadOnly ? "Nothing unread" : "Nothing here yet") + .font(Typeface.rubik(15)) + .foregroundStyle(Palette.mutedForeground) + if unreadOnly { + Button("Show everything") { unreadOnly = false } + .font(Typeface.rubik(15, .medium)) + .foregroundStyle(Palette.foreground) + } + } + .multilineTextAlignment(.center) + .padding(.horizontal, 24) + } + } + .refreshable { await store.refreshAttention() } + } + .background(Palette.background.ignoresSafeArea()) + } +} + +/// What kind of thing an Inbox item is, as its filter names it. +enum InboxKind: String, CaseIterable, Identifiable { + case mention, message, routine, collaboration + + var id: String { rawValue } + + init(_ item: ActivityItem) { + switch item { + case let .mentionOrMessage(message): self = message.kind == .mention ? .mention : .message + case .routine: self = .routine + case .collaboration, .unknown: self = .collaboration + } + } + + var label: String { + switch self { + case .mention: "Mentions" + case .message: "Messages" + case .routine: "Routines" + case .collaboration: "Collaborations" + } + } +} + +/// A tab's page header on a phone, as the web's `PageHeader` for a tab: its +/// large title at the left, and its controls at the right. +struct TabPageHeader: View { + let title: String + @ViewBuilder var actions: Actions + + var body: some View { + HStack(spacing: 2) { + Text(title) + .font(Typeface.rubik(28, .semibold)) + .tracking(-0.56) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityAddTraits(.isHeader) + actions + } + .pageHeaderInsets(trailing: 8) + } +} + +/// A header's quiet icon button, as the web's `bar` icon buttons roomy on a phone: filled while it's on. +struct HeaderIconToggle: View { + let on: Bool + let label: String + let action: () -> Void + @ViewBuilder var icon: Icon + + var body: some View { + Button(action: action) { + icon + .foregroundStyle(on ? Palette.foreground : Palette.softForeground) + .frame(width: 40, height: 40) + .background(on ? Palette.chip : .clear, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + .accessibilityAddTraits(on ? .isSelected : []) + } +} + +/// The web's Unread only mark: an inbox tray with a dot at its corner. +private struct UnreadOnlyIcon: View { + var body: some View { + ZStack(alignment: .topTrailing) { + UnreadTray() + .stroke(style: StrokeStyle(lineWidth: 1.75 * 20 / 24, lineCap: .round, lineJoin: .round)) + Circle().frame(width: 5 * 20 / 24, height: 5 * 20 / 24).offset(x: -2 * 20 / 24, y: 2 * 20 / 24) + } + .frame(width: 20, height: 20) + } + + private struct UnreadTray: Shape { + func path(in rect: CGRect) -> Path { + var path = SVGPath.path("M22 12h-6l-2 3h-4l-2-3H2") + path.addPath(SVGPath.path("M14 4H7.24a2 2 0 0 0-1.79 1.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-1.4-2.8")) + return path.applying(CGAffineTransform(scaleX: rect.width / 24, y: rect.height / 24)) + } + } +} + +/// One thing in the Inbox: a dot while unread, its face, what happened with its pod's mark, and what was said and when. +@MainActor +private struct InboxRow: View { + let item: ActivityItem + let pod: Pod? + + var body: some View { + let (title, detail) = words + let content = HStack(alignment: .top, spacing: 12) { + Circle() + .fill(item.unread ? Palette.foreground : .clear) + .frame(width: 6, height: 6) + .padding(.top, 7) + .accessibilityLabel(item.unread ? "Unread" : "") + face + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 8) { + Text(title) + .font(Typeface.rubik(13, item.unread ? .semibold : .regular)) + .foregroundStyle(item.unread ? Palette.foreground : Palette.mutedForeground) + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + if let pod { + PodInitial(kind: pod.kind, name: pod.name, color: pod.color?.rawValue, size: .small).accessibilityElement().accessibilityLabel("in \(pod.name)") + } + } + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(detail) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + Text(Times.age(item.at)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + } + } + .padding(10) + .contentShape(Rectangle()) + if let route { + NavigationLink(value: route) { content } + .buttonStyle(PressableRowStyle(cornerRadius: 8)) + } else { + content + } + } + + /// Where it opens: the conversation at its message, or a run's or collaboration's own page. + private var route: Route? { + guard pod != nil else { return nil } + switch item { + case let .mentionOrMessage(message): + return .conversationAt(threadId: message.conversationId, messageId: message.messageId) + case let .routine(run): + return .sideThreadPage(conversationId: run.conversationId, threadId: run.threadId) + case let .collaboration(collaboration): + return .sideThreadPage(conversationId: collaboration.conversationId, threadId: collaboration.threadId) + case .unknown: + return nil + } + } + + private var words: (String, String) { + switch item { + case let .mentionOrMessage(message): + let author = message.author + if message.kind == .mention { return ("\(author.name) mentioned you", message.preview) } + return (author.agent != nil ? "\(author.name) replied" : "\(author.name) wrote", message.preview) + case let .routine(run): + let activity = ActivityState(routineRun: run.state) + return (activity.routineText(run.routineName), run.preview ?? run.agent.name) + case let .collaboration(collaboration): + let activity = ActivityState(collaboration: collaboration.status) + return (activity.collaborationText(host: collaboration.initiator.name, other: collaboration.recipient.name), collaboration.brief) + case .unknown: + return ("", "") + } + } + + @ViewBuilder private var face: some View { + switch item { + case let .routine(run): + BotFace(look: run.agent.look, size: 24) + .overlay(alignment: .bottomTrailing) { + Icon(TriggerIcons.of(run.triggerKind), size: 11, strokeWidth: 2.4) + .foregroundStyle(Palette.foreground) + .frame(width: 16, height: 16) + .background(Palette.chipStrong, in: Circle()) + .padding(2) + .background(Palette.background, in: Circle()) + .offset(x: 8, y: 8) + } + case let .collaboration(collaboration): + ZStack(alignment: .leading) { + BotFace(look: collaboration.initiator.look, size: 24) + BotFace(look: collaboration.recipient.look, size: 24) + .padding(2) + .background(Palette.background, in: Circle()) + .offset(x: 10) + } + .frame(width: 36, height: 24, alignment: .leading) + case let .mentionOrMessage(message): + ParticipantFace(participant: message.author, size: 24) + case .unknown: + Color.clear.frame(width: 24, height: 24) + } + } +} + +/// A routine trigger's mark: a clock, a webhook, a branch, or a run by hand. +enum TriggerIcons { + static func of(_ kind: RoutineExecutionTriggerKind) -> Lucide { + switch kind { + case .cron: .clock + case .webhook: .webhook + case .github: .gitBranch + case .manual, .unknown: .refreshCw + } + } +} diff --git a/apps/ios/Sugabots/Attention/YouScreen.swift b/apps/ios/Sugabots/Attention/YouScreen.swift new file mode 100644 index 000000000..1d95c5112 --- /dev/null +++ b/apps/ios/Sugabots/Attention/YouScreen.swift @@ -0,0 +1,245 @@ +import SwiftUI + +/// You, the last tab, as the web's `You`: Settings, with your card leading to +/// your profile, the workspace's sections, its pods, other workspaces, Help +/// and docs, and Sign out. +@MainActor +struct YouScreen: View { + @Environment(Session.self) private var session + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @State private var members: Int? + + /// `projectLinks.documentation` in `packages/contracts`. + static let documentation = URL(string: "https://sugabots.ai/docs")! + + var body: some View { + let others = store.workspaces.filter { $0.id != store.workspace.id } + ScrollView { + VStack(alignment: .leading, spacing: 24) { + SettingsListGroups(permissions: store.permissions, members: members) + // No New workspace: a workspace is its own server now, found when signing in. + if !others.isEmpty { + SettingsGroup(label: "Other workspaces") { + DividedRows(data: others) { other in + Button { session.switchWorkspace(to: other) } label: { + SettingsRow(label: other.name, chevron: true, leading: { LetterTile(name: other.name) }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + SettingsGroup { + Button { openURL(Self.documentation) } label: { + SettingsRow(label: "Help and docs", trailing: { + Icon(.arrowUpRight, size: 16, strokeWidth: 2).foregroundStyle(Palette.subtleForeground) + }) + } + .buttonStyle(SettingsRowPressStyle()) + SettingsDivider() + Button { Task { await session.signOut() } } label: { + HStack { + Text("Sign out").font(Typeface.rubik(16)).foregroundStyle(Palette.destructiveText) + Spacer() + } + .padding(.horizontal, 16) + .frame(minHeight: 56) + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + .padding(.horizontal, 16) + .padding(.top, 6) + .padding(.bottom, 24) + } + .safeAreaInset(edge: .top, spacing: 0) { + Text("Settings") + .font(Typeface.rubik(28, .semibold)) + .tracking(-0.56) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity, alignment: .leading) + .pageHeaderInsets(trailing: 8) + .background(Palette.background) + .accessibilityAddTraits(.isHeader) + } + .background(Palette.background.ignoresSafeArea()) + .task { + await store.refreshAccess() + // Hide the member count when you're the only member. + let count = (try? await store.workspaceMembers())?.count + members = count == 1 ? nil : count + } + } +} + +/// The list You leads with, as the web's `SettingsListGroups`: your card, the +/// workspace's sections, then its pods and Personal pods. +@MainActor +private struct SettingsListGroups: View { + let permissions: WorkspacePermissions? + let members: Int? + @Environment(WorkspaceStore.self) private var store + + var body: some View { + let user = store.user + NavigationLink(value: Route.settings(.profile)) { + HStack(spacing: 16) { + PersonAvatar(name: user.name, email: user.email, image: user.image, size: 64) + VStack(alignment: .leading, spacing: 2) { + Text(user.name).font(Typeface.rubik(20, .semibold)).foregroundStyle(Palette.foreground).lineLimit(1) + Text("Profile and notifications").font(Typeface.rubik(14)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Icon(.chevronRight, size: 18).foregroundStyle(Palette.subtleForeground) + } + .padding(16) + .settingsCard() + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + + let sections = WorkspaceSection.allCases.filter { section in + permissions.map(section.allowed(by:)) ?? (section == .general || section == .members) + } + SettingsGroup(label: "Workspace") { + DividedRows(data: sections, id: \.self) { section in + NavigationLink(value: Route.settings(.workspace(section))) { + SettingsRow(label: section.label, chevron: true, trailing: { + if section == .members, let members { SettingsValue(text: "\(members)") } + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + ForEach([("Pods", Pod.Kind.shared), ("Personal pods", .personal)], id: \.0) { label, kind in + let pods = store.pods.filter { $0.kind == kind } + if !pods.isEmpty { + SettingsGroup(label: label) { + DividedRows(data: pods) { pod in + NavigationLink(value: Route.settings(.pod(pod))) { + SettingsRow(label: pod.name, chevron: true, leading: { PodInitial(kind: pod.kind, name: pod.name, color: pod.color?.rawValue, size: .small) }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + } + } +} + +/// A pod's settings as You opens them, as the web's `YouPod`: its initial and +/// name, then a row for each of its pages, with how many of each it holds. +@MainActor +struct YouPodScreen: View { + let pod: Pod + @Environment(WorkspaceStore.self) private var store + @State private var computers = false + @State private var counts: [PodSettingsPage: Int] = [:] + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 24) { + HStack(spacing: 12) { + PodInitial(kind: pod.kind, name: pod.name, color: pod.color?.rawValue, size: .medium) + Text(pod.name) + .font(Typeface.rubik(28, .semibold)) + .tracking(-0.56) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + } + .padding(.horizontal, 4) + SettingsGroup { + let pages = PodSettingsPage.pages(for: pod.kind, computersEnabled: computers) + DividedRows(data: pages, id: \.self) { page in + NavigationLink(value: Route.settings(.podPage(pod, page))) { + SettingsRow(label: page.label, chevron: true, trailing: { + if let count = counts[page] { SettingsValue(text: "\(count)") } + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + .padding(.horizontal, 16) + .padding(.top, 6) + .padding(.bottom, 24) + } + .safeAreaInset(edge: .top, spacing: 0) { + HStack { PhoneBackButton(label: "Back to Settings"); Spacer() } + .pageHeaderInsets() + } + .background(Palette.background.ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + .task { + computers = (try? await store.computersEnabled()) ?? false + counts = await store.podCounts(pod) + } + } +} + +extension WorkspaceStore { + /// How many connections, people and bots a pod holds, as `usePodCounts`; none for an empty one. + func podCounts(_ pod: Pod) async -> [PodSettingsPage: Int] { + var counts: [PodSettingsPage: Int] = [:] + let bots = bots(in: pod).count + if bots > 0 { counts[.bots] = bots } + if let connections = try? await connections(in: pod.id), !connections.isEmpty { counts[.connections] = connections.count } + // Only you are ever in a personal pod, so there is nobody to count. + if pod.kind == .shared, let people = try? await podMembers(pod.id), !people.isEmpty { counts[.people] = people.count } + return counts + } +} + +/// A pod's initial on its colour, as the web's `PodInitial`: small on its tint, +/// larger on its swatch in dark type, or a person for a Personal pod. +struct PodInitial: View { + enum Size { + case small, medium, row, large + } + + let kind: Pod.Kind + let name: String + let color: String? + var size = Size.medium + + var body: some View { + let palette = color.flatMap { BotLooks.pods[$0] } + let (box, radius, font, icon): (CGFloat, CGFloat, CGFloat, CGFloat) = + switch size { + case .small: (16, 4, 10, 10) + case .medium: (20, 5, 11, 11) + // A settings row's mark, as the web's `size-7 rounded-[7px] text-xs`. + case .row: (28, 7, 12, 14) + case .large: (44, 11, 15, 20) + } + Group { + if kind == .personal { + Icon(.user, size: icon, strokeWidth: 2.25) + } else { + Text(Initials.first(of: name)).font(Typeface.rubik(font, .semibold)) + } + } + .foregroundStyle(palette == nil ? Palette.foreground : size == .small ? palette!.swatch : Color.black.opacity(0.8)) + .frame(width: box, height: box) + .background( + palette == nil ? Palette.tile : size == .small ? palette!.tile.resolved : palette!.swatch, + in: RoundedRectangle(cornerRadius: radius, style: .continuous) + ) + .accessibilityHidden(true) + } +} + +/// Another workspace's initial, white on black, as You lists them. +private struct LetterTile: View { + let name: String + + var body: some View { + Text(Initials.first(of: name)) + .font(Typeface.rubik(12, .semibold)) + .foregroundStyle(Palette.background) + .frame(width: 24, height: 24) + .background(Palette.foreground, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + .accessibilityHidden(true) + } +} diff --git a/apps/ios/Sugabots/Conversation/ActivityState.swift b/apps/ios/Sugabots/Conversation/ActivityState.swift new file mode 100644 index 000000000..6fbf0cbec --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ActivityState.swift @@ -0,0 +1,54 @@ +import Foundation + +/// How a side thread stands, a routine's run or a collaboration, as the web's `ActivityState`. +enum ActivityState { + case running, waitingOnYou, done, failed + + /// How a side thread stands as its entry in a conversation's history says, + /// as the web's `activityStateOf`: running until it ends, and while no entry + /// has loaded. + init(historyEntry entry: ChatHistoryEntry?) { + switch entry?.status { + case .failed, .cancelled: self = .failed + case .completed: self = .done + default: self = .running + } + } + + /// How a routine's run stands, by the state of its execution. + init(routineRun state: RoutineExecutionState) { + switch state { + case .completed: self = .done + case .failed, .cancelled: self = .failed + case .queued, .running, .unknown: self = .running + } + } + + /// How a collaboration stands, by its status: waiting on the person while it needs their approval. + init(collaboration status: CollaborationStatus) { + switch status { + case .waiting: self = .running + case .pending: self = .waitingOnYou + case .answered: self = .done + case .failed, .unknown: self = .failed + } + } + + func routineText(_ name: String) -> String { + switch self { + case .running: "\(name) is running" + case .waitingOnYou: "\(name) is waiting on your approval" + case .done: "\(name) ran" + case .failed: "\(name) failed" + } + } + + func collaborationText(host: String, other: String) -> String { + switch self { + case .running: "\(host) is talking to \(other)" + case .waitingOnYou: "\(host) is waiting on your approval" + case .done: "\(host) collaborated with \(other)" + case .failed: "Collaboration with \(other) failed" + } + } +} diff --git a/apps/ios/Sugabots/Conversation/ApprovalCard.swift b/apps/ios/Sugabots/Conversation/ApprovalCard.swift new file mode 100644 index 000000000..626c6a4cd --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ApprovalCard.swift @@ -0,0 +1,462 @@ +import SwiftUI + +/// A bot's request to use a tool, in its message, as the web's +/// `ToolApprovalCard` shows it on a phone: who wants what, the request folded +/// to a few lines, and Review, which opens it whole over the screen with +/// Deny and Allow. +@MainActor +struct ApprovalCard: View { + let call: ToolCallPart + let agent: AgentParticipant + let podId: String + /// What the person may decide in the call's thread. + let capabilities: ThreadDetails.Capabilities? + /// The pod's connections, by handle. + let looks: [String: ConnectionLook] + @State private var reviewing = false + /// Whether the person answered here, before the answer arrives back on `call`. + @State private var answered = false + + var body: some View { + let step = ApprovalStep(call: call, agentName: agent.name, looks: looks) + let answerable = call.awaitsApproval && mayAnswer && !answered + VStack(alignment: .leading, spacing: 10) { + StepHeading(step: step) + FoldedRequest(input: call.input) + VStack(alignment: .leading, spacing: 8) { + status + Button(answerable ? "Review" : "See request") { reviewing = true } + .buttonStyle(WebButtonStyle(variant: answerable ? .primary : .secondary, size: .phone)) + } + } + .padding(.top, 10) + .padding(.trailing, 12) + .padding(.bottom, 12) + .padding(.leading, 10) + .frame(maxWidth: 460, alignment: .leading) + .background(Palette.card, in: UnevenRoundedRectangle(topLeadingRadius: 6, bottomLeadingRadius: 20, bottomTrailingRadius: 20, topTrailingRadius: 20, style: .continuous)) + .accessibilityElement(children: .contain) + .accessibilityLabel("Approval request: \(step.title)") + .fullScreenCover(isPresented: $reviewing) { + ReviewSheet(step: step, input: call.input, agent: agent) { + if answerable { + Answer(call: call, podId: podId, agentName: agent.name, actionLabel: step.action) { + answered = true + reviewing = false + } + } else { + status + } + } + } + } + + /// Whether the person may answer the call, as the web's `mayAnswer` + /// decides: a request to change the pod's sandbox is for those who manage + /// it, any other for those who may approve the pod's tool calls. + private var mayAnswer: Bool { + answersSandbox + ? capabilities?.approveSandboxRequests ?? false + : capabilities?.approveToolCalls ?? false + } + + private var answersSandbox: Bool { call.approval?.deciders == .sandboxManagers } + + @ViewBuilder private var status: some View { + if call.awaitsApproval && !mayAnswer { + Text(answersSandbox + ? "Waiting for an admin of this pod to answer this." + : "Waiting for someone with permission to answer this.") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + } else if call.approval?.status == .allowed { + Outcome(icon: .check, text: "Allowed\(call.approval?.decidedByName.map { " by \($0)" } ?? "")") + } else if call.approval?.status == .denied { + Outcome(icon: .x, text: "Denied\(call.approval?.decidedByName.map { " by \($0)" } ?? ""). \(agent.name) won't go ahead.") + } + } +} + +/// What a request is, in the words its card, its sheet and Approvals use, as +/// the web's `useApprovalApp` names them. +struct ApprovalStep { + let action: String + let who: String + /// The connection the tool belongs to, by its label; empty for a tool of no connection. + let whereName: String + let look: ConnectionLook? + let networkRequest: Bool + + /// `looks` is the pod's connections, by handle. + init(call: ToolCallPart, agentName: String, looks: [String: ConnectionLook]) { + let handle = ToolNames.handle(call.tool) + let look = looks[handle] + whereName = handle.isEmpty ? "" : ToolNames.connectionLabel(handle, name: look?.name) + action = ToolNames.step(call.tool) + networkRequest = call.tool == ToolNames.networkRequestTool + who = networkRequest + ? "\(agentName) wants its sandbox to reach a new host" + : "\(agentName) wants to use \(whereName.isEmpty ? "a tool" : whereName)" + self.look = look + } + + var title: String { whereName.isEmpty ? action : "\(action) in \(whereName)" } + + /// What the request's mark is named for: its connection, else the action. + var appName: String { whereName.isEmpty ? action : whereName } +} + +/// A request's app: its connection's mark, or a globe for reaching a host. +struct StepMark: View { + enum Size { + /// 24 points, beside the request on its card. + case card + /// 32 points, on the bot's face over a request shown in full. + case badge + } + + let step: ApprovalStep + let size: Size + + var body: some View { + if step.networkRequest { + let badge = size == .badge + Icon(.globe, size: badge ? 16 : 14, strokeWidth: 2) + .foregroundStyle(Palette.foreground) + .frame(width: badge ? 32 : 24, height: badge ? 32 : 24) + .background(Palette.borderStrong, in: RoundedRectangle(cornerRadius: badge ? 8 : 7, style: .continuous)) + } else { + ConnectionMark(presetId: step.look?.presetId, name: step.appName, size: size == .badge ? .sm : .md) + } + } +} + +private struct StepHeading: View { + let step: ApprovalStep + + var body: some View { + HStack(alignment: .top, spacing: 10) { + StepMark(step: step, size: .card).padding(.top, 1) + VStack(alignment: .leading, spacing: 2) { + Text(step.who).font(Typeface.rubik(12)).foregroundStyle(Palette.mutedForeground) + Text(step.action).font(Typeface.rubik(14, .medium)).foregroundStyle(Palette.foreground) + } + } + } +} + +private struct Outcome: View { + let icon: Lucide + let text: String + + var body: some View { + HStack(alignment: .top, spacing: 6) { + Icon(icon, size: 12, strokeWidth: 2.8).padding(.top, 3) + Text(text) + } + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + } +} + +/// A request folded to its first few lines, fading out, as a phone shows it on the card. +struct FoldedRequest: View { + let input: JSONValue + @State private var height: CGFloat = 0 + + /// How tall a folded request stands. + private static let foldedHeight: CGFloat = 66 + + var body: some View { + let foldable = height > Self.foldedHeight + RequestValue(value: input, depth: 0) + .fixedSize(horizontal: false, vertical: true) + .background(GeometryReader { Color.clear.preference(key: HeightKey.self, value: $0.size.height) }) + .onPreferenceChange(HeightKey.self) { height = $0 } + .frame(maxHeight: foldable ? Self.foldedHeight : nil, alignment: .top) + .clipped() + .mask { + if foldable { + LinearGradient(stops: [.init(color: .black, location: 0.55), .init(color: .clear, location: 1)], startPoint: .top, endPoint: .bottom) + } else { + Color.black + } + } + .padding(.leading, 10) + .overlay(alignment: .leading) { Rectangle().fill(Palette.borderDashed).frame(width: 2) } + } + + private struct HeightKey: PreferenceKey { + static let defaultValue: CGFloat = 0 + static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } + } +} + +/// A request over the whole screen: the bot's face with the app's mark, +/// what it wants, every field, and the answer pinned at the foot. +private struct ReviewSheet: View { + let step: ApprovalStep + let input: JSONValue + let agent: AgentParticipant + @ViewBuilder var footer: Footer + @Environment(\.dismiss) private var dismiss + + var body: some View { + VStack(spacing: 0) { + HStack { + GlassRoundButton(icon: .x, label: "Close", iconSize: 20) { dismiss() } + Spacer() + } + .padding(.horizontal, 16) + .pageTopPadding(14) + ScrollView { + VStack(alignment: .leading, spacing: 16) { + VStack(spacing: 4) { + BotFace(look: agent.look, size: 64) + .overlay(alignment: .bottomTrailing) { + StepMark(step: step, size: .badge) + .padding(3) + .background(Palette.panel, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .offset(x: 8, y: 4) + } + .padding(.bottom, 10) + Text(step.action) + .font(Typeface.rubik(20, .bold)) + .foregroundStyle(Palette.foreground) + .multilineTextAlignment(.center) + .accessibilityAddTraits(.isHeader) + Text(step.who) + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + .multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity) + .padding(.bottom, 8) + RequestValue(value: input, depth: 0) + } + .padding(16) + } + VStack(spacing: 0) { + Rectangle().fill(Palette.borderSubtle).frame(height: 1) + footer + .padding(.horizontal, 16) + .padding(.top, 12) + .padding(.bottom, 16) + } + } + .background(Palette.panel.ignoresSafeArea()) + } +} + +/// Deny and Allow, side by side, which answer `call`, with what went wrong +/// under them; or, once its bot stopped waiting, that it no longer waits. +/// Once an answer is sent they stay disabled until `call` stops waiting. +@MainActor +struct Answer: View { + let call: ToolCallPart + let podId: String + let agentName: String + let actionLabel: String + /// Runs once an answer is sent. + var onDecided: () -> Void = {} + @Environment(WorkspaceStore.self) private var store + @State private var sending = false + @State private var failure: String? + + var body: some View { + if call.awaitsApproval { + VStack(alignment: .leading, spacing: 6) { + HStack(spacing: 8) { + Button("Deny") { decide(.deny) } + .buttonStyle(WebButtonStyle(variant: .muted, size: .phone)) + .accessibilityLabel("Deny: \(actionLabel)") + Button("Allow") { decide(.allowOnce) } + .buttonStyle(WebButtonStyle(size: .phone)) + .accessibilityLabel("Allow: \(actionLabel)") + } + .disabled(sending) + if let failure { + Text(failure).font(Typeface.rubik(12)).foregroundStyle(Palette.destructiveText) + } + } + } else { + Text("No longer waiting: \(agentName) stopped before it was answered.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + } + } + + private func decide(_ decision: WorkspaceStore.Decision) { + sending = true + failure = nil + Task { + do { + try await store.decide(decision, toolCallId: call.id, podId: podId) + onDecided() + } catch { + failure = error.localizedDescription + sending = false + } + } + } +} + +/// What a tool was asked to do, laid out for a person to read: fields as +/// labelled values, lists of like records as tables, the rest as code. +struct RequestValue: View { + let value: JSONValue + let depth: Int + + /// How deep structure is laid out before it shows as code. + private static let maxDepth = 3 + + var body: some View { + switch value { + case let .object(fields) where !fields.isEmpty && depth < Self.maxDepth: + FieldList(fields: fields.sorted { $0.key < $1.key }, depth: depth) + case let .array(entries) where Self.isRecordList(entries) && depth < Self.maxDepth: + EntryList(entries: entries, depth: depth) + case .array where Self.isPlainList(value): + PlainValue(value: value) + case .object, .array: + Text(value.prettyPrinted) + .font(Typeface.mono(11)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 10) + .padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + default: + PlainValue(value: value) + } + } + + static func isPlainList(_ value: JSONValue) -> Bool { + guard case let .array(items) = value else { return false } + return items.allSatisfy { if case .object = $0 { false } else if case .array = $0 { false } else { true } } + } + + static func isRecordList(_ entries: [JSONValue]) -> Bool { + !entries.isEmpty && !isPlainList(.array(entries)) + } + + static func hasStructure(_ value: JSONValue) -> Bool { + if case let .array(items) = value { return isRecordList(items) } + if case let .object(fields) = value { return !fields.isEmpty } + return false + } +} + +private struct FieldList: View { + let fields: [(key: String, value: JSONValue)] + let depth: Int + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + ForEach(fields, id: \.key) { field in + VStack(alignment: .leading, spacing: 2) { + Text(ToolNames.words(fromKey: field.key)) + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + if RequestValue.hasStructure(field.value) { + RequestValue(value: field.value, depth: depth + 1) + .padding(.leading, 12) + .overlay(alignment: .leading) { Rectangle().fill(Palette.borderSubtle).frame(width: 1) } + .padding(.leading, 4) + .padding(.top, 4) + } else { + PlainValue(value: field.value) + } + } + } + } + } +} + +private struct EntryList: View { + let entries: [JSONValue] + let depth: Int + @State private var showAll = false + + /// How many entries show before Show all. + private static let shown = 10 + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + ForEach(Array((showAll ? entries : Array(entries.prefix(Self.shown))).enumerated()), id: \.offset) { index, entry in + HStack(alignment: .firstTextBaseline, spacing: 10) { + Text("\(index + 1)") + .font(Typeface.mono(11)) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 20, alignment: .trailing) + if Self.isSmallRecord(entry) { + SmallRecord(fields: entry.fields.sorted { $0.key < $1.key }) + } else { + RequestValue(value: entry, depth: depth + 1) + } + } + } + if entries.count > Self.shown { + Button(showAll ? "Show fewer" : "Show all \(entries.count)") { showAll.toggle() } + .font(Typeface.rubik(12, .semibold)) + .foregroundStyle(Palette.foreground) + .padding(.leading, 28) + } + } + } + + /// A record of a few plain fields, written on one line. + static func isSmallRecord(_ value: JSONValue) -> Bool { + guard case let .object(fields) = value, !fields.isEmpty, fields.count <= 4 else { return false } + return fields.values.allSatisfy { !RequestValue.hasStructure($0) } + } +} + +private struct SmallRecord: View { + let fields: [(key: String, value: JSONValue)] + + var body: some View { + fields.enumerated().reduce(Text("")) { text, element in + let (index, field) = element + let label = Text((index > 0 ? ", " : "") + ToolNames.words(fromKey: field.key) + " ").foregroundStyle(Palette.mutedForeground) + return text + label + Text(PlainValue.words(field.value)).foregroundStyle(Palette.foreground) + } + .font(Typeface.rubik(14)) + } +} + +/// A plain value: text as written, a number, Yes or No, or Empty. +struct PlainValue: View { + let value: JSONValue + + var body: some View { + let quiet = PlainValue.isQuiet(value) + Text(Self.words(value)) + .font(Typeface.rubik(14)) + .foregroundStyle(quiet ? Palette.mutedForeground : Palette.foreground) + .monospacedDigit() + .textSelection(.enabled) + } + + static func isQuiet(_ value: JSONValue) -> Bool { + switch value { + case .null, .bool: true + case let .string(text): text.isEmpty + case let .array(items): items.isEmpty + case .object: true + case .number: false + } + } + + static func words(_ value: JSONValue) -> String { + switch value { + case let .array(items) where RequestValue.isPlainList(value): + return items.isEmpty ? "None" : items.map { words($0) }.joined(separator: ", ") + case .null: return "Empty" + case let .string(text): return text.isEmpty ? "Empty" : text + case let .bool(flag): return flag ? "Yes" : "No" + case .number: return value.prettyPrinted + default: return "None" + } + } +} diff --git a/apps/ios/Sugabots/Conversation/BotDetailsSections.swift b/apps/ios/Sugabots/Conversation/BotDetailsSections.swift new file mode 100644 index 000000000..2d5b08e79 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/BotDetailsSections.swift @@ -0,0 +1,110 @@ +import SwiftUI + +/// A bot's routines on its Details page, as the web's `Routines` section: the +/// first two, then Show more, each opening its thread, with what starts it and +/// a switch to pause it for those who may. +@MainActor +struct BotRoutinesSection: View { + let pod: Pod + let agent: Agent + @Environment(WorkspaceStore.self) private var store + @Environment(Toaster.self) private var toaster + @State private var routines: [Routine] = [] + @State private var open = false + @State private var changing: String? + + /// How many routines show before Show more. + private static let shown = 2 + + var body: some View { + Group { + if !routines.isEmpty { + DetailsSection(title: "Routines") { + VStack(alignment: .leading, spacing: 0) { + ForEach(open ? routines : Array(routines.prefix(Self.shown))) { routine in + HStack(spacing: 12) { + NavigationLink(value: Route.routine(pod, routineId: routine.id)) { + VStack(alignment: .leading, spacing: 1) { + Text(routine.name).font(Typeface.rubik(15)).foregroundStyle(Palette.foreground).lineLimit(1) + if let label = ScheduleWords.scheduleLabel(routine) { + Text(label).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + WebToggle(label: "\(routine.name) on", isOn: routine.state == .enabled) { on in toggle(routine, on: on) } + .disabled(!pod.permissions.manageRoutines || changing == routine.id) + } + .frame(minHeight: 44) + } + if routines.count > Self.shown { + ShowMoreButton(open: $open).padding(.vertical, 4) + } + } + } + } + } + .task(id: agent.id) { routines = (try? await store.routines(of: agent.id)) ?? [] } + } + + private func toggle(_ routine: Routine, on: Bool) { + changing = routine.id + Task { + do { + let changed = try await store.updateRoutine(routine.id, agentId: agent.id, state: on ? .enabled : .paused) + if let index = routines.firstIndex(where: { $0.id == changed.id }) { routines[index] = changed } + } catch { + toaster.show(error.localizedDescription) + } + changing = nil + } + } +} + +/// The pod's connections a bot can use, on its Details page, as the web's +/// `Tools` section: each one's mark, name and how many tools, opening the +/// bot's settings. +@MainActor +struct BotToolsSection: View { + let pod: Pod + let agent: Agent + @Environment(WorkspaceStore.self) private var store + @Environment(\.openPage) private var openPage + @State private var connections: [Connection] = [] + + var body: some View { + Group { + if !connections.isEmpty { + DetailsSection(title: "Tools") { + VStack(alignment: .leading, spacing: 0) { + ForEach(connections) { connection in + Button { openPage(.settings(.agent(pod, agent))) } label: { + HStack(spacing: 12) { + ConnectionMark(presetId: connection.presetId, name: connection.name, size: .md) + Text(connection.name).font(Typeface.rubik(15)).foregroundStyle(Palette.foreground).lineLimit(1) + Spacer(minLength: 0) + Text(Names.count(Self.usable(connection), "tool", "tools")) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + } + .frame(height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(cornerRadius: 6)) + } + } + } + } + } + .task(id: pod.id) { + connections = ((try? await store.connections(in: pod.id)) ?? []).filter { Self.usable($0) > 0 } + } + } + + /// As `usableToolCount`: the tools a bot may use, with or without asking. + static func usable(_ connection: Connection) -> Int { + connection.toolCounts.allow + connection.toolCounts.ask + } +} diff --git a/apps/ios/Sugabots/Conversation/Composer.swift b/apps/ios/Sugabots/Conversation/Composer.swift new file mode 100644 index 000000000..29a23e5ec --- /dev/null +++ b/apps/ios/Sugabots/Conversation/Composer.swift @@ -0,0 +1,491 @@ +import PhotosUI +import SwiftUI +import UniformTypeIdentifiers + +/// A file being attached to a draft: uploading, ready, or failed. +@MainActor +@Observable +final class ComposerAttachment: Identifiable { + enum Upload { + case uploading + case ready(FilePart) + case failed(String, retryable: Bool) + } + + let id = UUID() + let name: String + let contentType: String + let data: Data + var upload = Upload.uploading + + init(name: String, contentType: String, data: Data) { + self.name = name + self.contentType = contentType + self.data = data + } + + var file: FilePart? { + if case let .ready(file) = upload { file } else { nil } + } +} + +/// The files attached to a draft, each uploaded as soon as it is added, as the web's `useComposerAttachments`. +@MainActor +@Observable +final class ComposerAttachments { + static let maximum = Limits.maxAttachmentsPerMessage + /// Why a file over `MAX_ATTACHMENT_BYTES` is never uploaded, as the web says it. + static let tooLargeReason = "Too large. \(Limits.maxAttachmentMegabytes) MB at most." + + private(set) var items: [ComposerAttachment] = [] + /// How many files were left out for going past the most a message holds. + private(set) var leftOut = 0 + private let conversationId: String + private let client: APIClient + + init(conversationId: String, client: APIClient) { + self.conversationId = conversationId + self.client = client + } + + var isFull: Bool { items.count >= Self.maximum } + var uploading: Int { items.filter { if case .uploading = $0.upload { true } else { false } }.count } + var failed: Int { items.filter { if case .failed = $0.upload { true } else { false } }.count } + var ready: Bool { uploading == 0 && failed == 0 } + + func attach(_ files: [(name: String, contentType: String, data: Data)]) { + let room = Self.maximum - items.count + leftOut = max(files.count - room, 0) + for file in files.prefix(max(room, 0)) { + let attachment = ComposerAttachment(name: file.name, contentType: file.contentType, data: file.data) + items.append(attachment) + if file.data.count > Limits.maxAttachmentBytes { + attachment.upload = .failed(Self.tooLargeReason, retryable: false) + } else { + upload(attachment) + } + } + } + + func remove(_ attachment: ComposerAttachment) { + items.removeAll { $0.id == attachment.id } + leftOut = 0 + if let file = attachment.file { + Task { try? await client.chats.removeFile(conversationId: conversationId, fileId: file.id) } + } + } + + func retry(_ attachment: ComposerAttachment) { + attachment.upload = .uploading + upload(attachment) + } + + /// Takes the uploaded files out of the draft and returns what `deliver` + /// returns for them. When `deliver` throws, they go back into the draft, + /// ahead of any added meanwhile, and the error is rethrown. + func send(through deliver: ([FilePart]) async throws -> Delivered) async throws -> Delivered { + let taken = items + items = [] + leftOut = 0 + do { + return try await deliver(taken.compactMap(\.file)) + } catch { + items = taken + items + throw error + } + } + + private func upload(_ attachment: ComposerAttachment) { + Task { + do { + let uploaded = try await client.chats.uploadFile( + conversationId: conversationId, name: attachment.name, type: attachment.contentType, data: attachment.data + ) + attachment.upload = .ready(FilePart(id: uploaded.id, name: uploaded.name, contentType: uploaded.contentType, size: uploaded.size)) + } catch let failure as APIFailure { + attachment.upload = .failed(failure.status == 413 ? "Too big to attach" : failure.message, retryable: failure.status >= 500) + } catch { + attachment.upload = .failed("Couldn't upload", retryable: true) + } + } + } +} + +/// The message box at a conversation's foot, as the web's `ChatComposer` on +/// a phone: a pill holding + to attach, the draft, and a round Send; over +/// them what it replies to and the files attached; over the pill, people and +/// bots to mention while an `@` is typed. +@MainActor +struct Composer: View { + let label: String + /// What the empty draft says, when it isn't the label. + var placeholder: String? + @Binding var text: String + /// Whom an `@` can name: people and bots, and where it would notify somebody, everyone. + let mentionable: [MentionTarget] + var replyingTo: MessageReplyTo? + var cancelReply: () -> Void = {} + let attachments: ComposerAttachments? + var sending = false + var error: String? + var needsText = false + let submit: () -> Void + /// Told of each edit the person makes in the field, but not of the text being set from outside it. + var edited: () -> Void = {} + /// Whether the field has the keyboard. Plain state, not `FocusState`: the + /// field is UIKit's, so no SwiftUI view is focused on it, and SwiftUI puts a + /// `FocusState` nothing is focused on back to false, taking the keyboard away + /// as soon as it comes up. + @Binding var focused: Bool + @State private var picking = false + @State private var importing = false + @State private var photos: [PhotosPickerItem] = [] + + var body: some View { + let shortcode = shortcodeBeingTyped + let mention = shortcode == nil ? mentionBeingTyped : nil + VStack(alignment: .leading, spacing: 0) { + ZStack(alignment: .bottomLeading) { + pill + if let shortcode, focused { + EmojiSuggestionList(matches: shortcode.matches) { emoji in + text = String(text[.. 0 { + Text("\(Names.count(attachments.leftOut, "file was", "files were")) left out. \(ComposerAttachments.maximum) is the most for one message.") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .frame(maxWidth: .infinity, alignment: .leading) + } + HStack(alignment: .bottom, spacing: 4) { + Menu { + Button { picking = true } label: { Label("Photo Library", systemImage: "photo.on.rectangle") } + Button { importing = true } label: { Label("Choose Files", systemImage: "folder") } + } label: { + Icon(.plus, size: 20, strokeWidth: 2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 36, height: 36) + .contentShape(Circle()) + } + .disabled(attachments == nil || attachments?.isFull == true) + .opacity(attachments == nil || attachments?.isFull == true ? 0.4 : 1) + .accessibilityLabel("Attach files") + MentionEditor(text: $text, isFocused: $focused, mentionable: mentionable, edited: edited) + .overlay(alignment: .topLeading) { + if text.isEmpty { + Text(placeholder ?? label) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.subtleForeground) + .lineLimit(1) + .padding(.leading, 4) + .padding(.top, 8) + .allowsHitTesting(false) + } + } + .frame(maxWidth: .infinity) + .accessibilityLabel(label) + .onChange(of: text) { _, typed in completeShortcode(typed) } + Button(action: submit) { + Icon(.arrowUp, size: 18, strokeWidth: 2.25) + .foregroundStyle(canSend ? Palette.primaryForeground : Palette.disabledForeground) + .frame(width: 36, height: 36) + .background(canSend ? Palette.primary : Palette.chipStrong, in: Circle()) + } + .buttonStyle(.plain) + .disabled(!canSend) + .accessibilityLabel("Send message") + } + } + .padding(4) + .background(Palette.panel, in: RoundedRectangle(cornerRadius: 23, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 23, style: .continuous).strokeBorder(Palette.borderStrong)) + .background(GeometryReader { geometry in + Color.clear.onAppear { pillHeight = geometry.size.height } + .onChange(of: geometry.size.height) { _, height in pillHeight = height } + }) + } + + private var canSend: Bool { + let hasText = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + let hasFiles = !(attachments?.items.isEmpty ?? true) + guard !sending, attachments?.ready ?? true else { return false } + return needsText ? hasText : hasText || hasFiles + } + + /// The `@` being typed at the draft's end, and who it could mention. + private var mentionBeingTyped: MentionBeingTyped? { + guard let at = text.lastIndex(of: "@"), Mentions.canStart(at: at, in: text) else { return nil } + let query = String(text[text.index(after: at)...]) + guard !query.contains("\n"), !query.hasPrefix(" "), !query.contains("@") else { return nil } + let lowered = query.lowercased() + let matches = mentionable.filter { $0.handle.contains(lowered) || $0.participant?.name.lowercased().contains(lowered) == true } + return MentionBeingTyped(start: at, matches: matches) + } + + /// The `:shortcode` being typed at the draft's end, two characters or more, and the emoji it could be. + private var shortcodeBeingTyped: (start: String.Index, matches: [Emoji])? { + guard let typed = text.firstMatch(of: /(?:^|[\s(]):([a-z0-9_+\-]{2,})$/.ignoresCase()) else { return nil } + let matches = EmojiShortcodes.matching(String(typed.1)) + guard !matches.isEmpty else { return nil } + return (text.index(typed.1.startIndex, offsetBy: -1), matches) + } + + /// Turns a whole `:shortcode:` just typed into its emoji, as the web's composer does. + private func completeShortcode(_ typed: String) { + guard let closed = typed.firstMatch(of: /(?:^|[\s(]):([a-z0-9_+\-]+):$/.ignoresCase()), + let emoji = EmojiShortcodes.named(String(closed.1)) + else { return } + text = String(typed[.. (name: String, contentType: String, data: Data)? { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + guard let data = try? Data(contentsOf: url) else { return nil } + let type = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream" + return (url.lastPathComponent, type, data) + } +} + +/// An `@` being typed at the draft's end: where it starts, and who it could mention. +private struct MentionBeingTyped { + let start: String.Index + let matches: [MentionTarget] +} + +/// What the draft replies to, over the draft, with a × to stop replying. +private struct ReplyingToStrip: View { + let replyTo: MessageReplyTo + let cancel: () -> Void + + var body: some View { + HStack(spacing: 8) { + (Text("Replying to ") + Text(replyTo.author.name).fontWeight(.semibold).foregroundStyle(Palette.softForeground) + Text(" " + replyTo.preview)) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + SmallIconButton(icon: .x, label: "Cancel reply", action: cancel).frame(width: 24, height: 24) + } + .padding(.vertical, 6) + .padding(.leading, 12) + .padding(.trailing, 6) + .overlay(alignment: .bottom) { Rectangle().fill(Palette.border).frame(height: 1) } + } +} + +/// The files attached to the draft, each with how its upload is going and ×. +@MainActor +private struct AttachmentTray: View { + let attachments: ComposerAttachments + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(attachments.items) { attachment in + HStack(spacing: 8) { + switch attachment.upload { + case .uploading: + ProgressView().controlSize(.mini) + case .ready: + Icon(.fileIcon, size: 14).foregroundStyle(Palette.softForeground) + case let .failed(_, retryable): + if retryable { + Button { attachments.retry(attachment) } label: { Icon(.rotateCcw, size: 14) } + .buttonStyle(.plain) + .foregroundStyle(Palette.destructiveText) + .accessibilityLabel("Retry \(attachment.name)") + } else { + Icon(.x, size: 14).foregroundStyle(Palette.destructiveText) + } + } + VStack(alignment: .leading, spacing: 0) { + Text(attachment.name).font(Typeface.rubik(12.5, .medium)).lineLimit(1).truncationMode(.middle) + Text(note(attachment)).font(Typeface.rubik(11)).foregroundStyle(failed(attachment) ? Palette.destructiveText : Palette.subtleForeground) + } + .frame(maxWidth: 140, alignment: .leading) + SmallIconButton(icon: .x, label: "Remove \(attachment.name)") { attachments.remove(attachment) } + } + .padding(.leading, 10) + .padding(.trailing, 4) + .padding(.vertical, 6) + .background(Palette.card, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.border)) + } + } + .padding(8) + } + } + + private func failed(_ attachment: ComposerAttachment) -> Bool { + if case .failed = attachment.upload { true } else { false } + } + + private func note(_ attachment: ComposerAttachment) -> String { + switch attachment.upload { + case .uploading: "Uploading…" + case let .ready(file): FileLook.sizeLabel(file.size) + case let .failed(why, _): why + } + } +} + +/// People and bots matching the `@` being typed, over the composer. +private struct SuggestionList: View { + let matches: [MentionTarget] + let choose: (MentionTarget) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Text("Mention") + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 12) + .padding(.top, 10) + .padding(.bottom, 4) + ScrollView { + VStack(spacing: 0) { + ForEach(matches, id: \.key) { target in + Button { choose(target) } label: { + HStack(spacing: 10) { + if let member = target.participant { + ParticipantFace(participant: member, size: 26) + } else { + Icon(.atSign, size: 14, strokeWidth: 2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 26, height: 26) + .background(Palette.chip, in: Circle()) + } + VStack(alignment: .leading, spacing: 1) { + Text(target.participant?.name ?? "@\(target.handle)").font(Typeface.rubik(14, .medium)).foregroundStyle(Palette.foreground).lineLimit(1) + Text(subtitle(target)).font(Typeface.rubik(12)).foregroundStyle(Palette.mutedForeground).lineLimit(1) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(pressed: Palette.chip, cornerRadius: 6)) + } + } + .padding(.horizontal, 4) + .padding(.bottom, 4) + } + .frame(maxHeight: 240) + .fixedSize(horizontal: false, vertical: true) + } + .frame(width: 280) + .background(Palette.panel, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong)) + .shadow(color: .black.opacity(0.3), radius: 16, y: 6) + .accessibilityElement(children: .contain) + .accessibilityLabel("People and bots to mention") + } + + /// Under a suggestion's name: Bot, a person's handle, or what mentioning everyone does. + private func subtitle(_ target: MentionTarget) -> String { + switch target { + case .group: "Notify everyone who can see this" + case .participant(.agent): "Bot" + case let .participant(participant): "@\(participant.handle)" + } + } +} + +/// Emoji matching the `:shortcode` being typed, over the composer. +private struct EmojiSuggestionList: View { + let matches: [Emoji] + let choose: (Emoji) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Text("Emoji") + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 12) + .padding(.top, 10) + .padding(.bottom, 4) + VStack(spacing: 0) { + ForEach(matches, id: \.emoji) { emoji in + Button { choose(emoji) } label: { + HStack(spacing: 10) { + Text(emoji.emoji).font(.system(size: 20)).frame(width: 26, height: 26) + Text(":\(emoji.shortcodes.first ?? ""):").font(Typeface.rubik(14)).foregroundStyle(Palette.foreground).lineLimit(1) + Spacer(minLength: 0) + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(pressed: Palette.chip, cornerRadius: 6)) + } + } + .padding(.horizontal, 4) + .padding(.bottom, 4) + } + .frame(width: 280) + .background(Palette.panel, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong)) + .shadow(color: .black.opacity(0.3), radius: 16, y: 6) + .accessibilityElement(children: .contain) + .accessibilityLabel("Emoji matching what was typed") + } +} diff --git a/apps/ios/Sugabots/Conversation/ComputerSheet.swift b/apps/ios/Sugabots/Conversation/ComputerSheet.swift new file mode 100644 index 000000000..f52258cb0 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ComputerSheet.swift @@ -0,0 +1,130 @@ +import SwiftUI + +/// A bot's computer, as the web's `ComputerSheet` on a phone: a sheet with a +/// grabber over its desktop and Open full screen, or why there is none and, +/// for those who may, how to give it one. +@MainActor +struct ComputerSheet: View { + let agent: Agent + /// The conversation whose desktop it shows. + var conversationId: String? + @Environment(WorkspaceStore.self) private var store + @State private var access = Access.checking + @State private var turningOn = false + @State private var failure: String? + @State private var fullScreen = false + @State private var settingUp = false + + var body: some View { + // The store's copy, which turning a computer on updates. + let agent = store.agent(id: agent.id) ?? agent + let pod = store.pod(id: agent.podId) + VStack(spacing: 16) { + SheetGrabber().frame(height: 24, alignment: .top) + switch access { + case .checking: + ProgressView().frame(maxWidth: .infinity, minHeight: 120) + case .unknown: + NoComputer(text: "Could not check for a computer", detail: "Close this and open it again to try again.") {} + case .known(false): + NoComputer( + text: "Computers aren't set up yet", + detail: store.permissions?.manageProviders == true ? "They're set up once, for the whole workspace." : "Ask a workspace admin to set them up." + ) { + if store.permissions?.manageProviders == true { + Button("Set up computers") { settingUp = true }.buttonStyle(WebButtonStyle(size: .phone)) + } + } + case .known(true) where !agent.usesSandbox: + let may = pod?.permissions.updateAgents ?? false + NoComputer( + text: "\(agent.name) doesn't have a computer", + detail: may ? "Give it one to run commands, browse and make files." : "Ask somebody who can edit it to give it one." + ) { + if may { + Button("Turn on computer", action: turnOn) + .buttonStyle(WebButtonStyle(size: .phone)) + .disabled(turningOn) + if let failure { FormAlert(text: failure) } + } + } + case .known(true): + VStack(spacing: 12) { + Button { fullScreen = true } label: { + ZStack { + Color.black + VStack(spacing: 8) { + Icon(.monitor, size: 28, strokeWidth: 1.5) + Text("\(agent.name)'s desktop").font(Typeface.rubik(13)) + } + .foregroundStyle(Color.white.opacity(0.6)) + } + .aspectRatio(4 / 3, contentMode: .fit) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.borderStrong)) + } + .buttonStyle(.plain) + .accessibilityLabel("Open \(agent.name)'s computer full screen") + Button("Open full screen") { fullScreen = true } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .phone)) + } + } + } + .padding(.horizontal, 16) + .padding(.bottom, 16) + .phoneSheet(detents: [.medium]) + .task { + do { + access = .known(try await store.computersEnabled()) + } catch { + access = .unknown + } + } + .fullScreenCover(isPresented: $fullScreen) { + if let pod, let conversationId { DesktopView(pod: pod, conversationId: conversationId) } + } + .fullScreenCover(isPresented: $settingUp) { + PageStack { SettingsDestination(place: .workspace(.sandboxes)) } + } + } + + /// Whether the workspace has computers set up. + private enum Access { + case checking + case known(Bool) + /// The check failed. + case unknown + } + + private func turnOn() { + turningOn = true + failure = nil + Task { + do { + try await store.giveComputer(to: agent) + } catch { + failure = error.localizedDescription + } + turningOn = false + } + } +} + +/// Why there's no computer: a monitor, the reason, a line under it, and what to do. +private struct NoComputer: View { + let text: String + let detail: String + @ViewBuilder var actions: Actions + + var body: some View { + VStack(spacing: 8) { + Icon(.monitor, size: 28, strokeWidth: 1.5).foregroundStyle(Palette.subtleForeground) + Text(text).font(Typeface.rubik(15, .medium)).foregroundStyle(Palette.foreground) + Text(detail).font(Typeface.rubik(14)).lineSpacing(4).foregroundStyle(Palette.mutedForeground) + VStack(spacing: 8) { actions }.padding(.top, 12) + } + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .padding(.top, 8) + } +} diff --git a/apps/ios/Sugabots/Conversation/ConversationDetails.swift b/apps/ios/Sugabots/Conversation/ConversationDetails.swift new file mode 100644 index 000000000..7cc2c0ee3 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationDetails.swift @@ -0,0 +1,357 @@ +import SwiftUI + +/// A conversation's Details on a phone, the whole screen with a glass Back, +/// as the web's `DetailsSidebar`, `ChannelDetails`, `PeopleDetails` and, +/// for a routine's thread, `RoutinePanel`. +@MainActor +struct ConversationDetails: View { + let model: ConversationModel + @Environment(WorkspaceStore.self) private var store + + var body: some View { + // Live while it shows, as the conversation under it is. + ZStack { content }.task { await model.listen() } + } + + @ViewBuilder private var content: some View { + let kind = store.kind(of: model) + if let details = model.details, let pod = store.pod(id: details.thread.podId) { + if let routine = details.routine, let agent = kind.agent { + RoutinePanel(agent: agent, pod: pod, conversationId: model.conversationId, standing: routine) + } else { + DetailsPage { + switch kind { + case let .botChannel(agent), let .botThread(agent): + BotDetails(agent: agent, pod: pod, threadId: details.thread.id) + case let .podChat(name): + ChannelHeading(model: model, pod: pod, details: details, name: name) + case .peopleThread: + EmptyView() + } + InThisThread(participants: details.participants) + SharedFiles(files: sharedFiles, conversationId: model.conversationId) + } + } + } + } + + /// The files posted here, newest first. + private var sharedFiles: [FilePart] { + model.items.reversed().flatMap { $0.message?.files ?? [] } + } +} + +/// A Details page: Back floating at the top left, then its sections. +private struct DetailsPage: View { + @ViewBuilder var content: Content + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 0) { content } + .padding(.bottom, 24) + } + .safeAreaInset(edge: .top, spacing: 0) { + HStack { PhoneBackButton(); Spacer() } + .pageHeaderInsets() + } + .background(Palette.aside.ignoresSafeArea()) + } +} + +/// The top of a Details page: a large face or mark, the name under it, a line under that, and round actions. +private struct DetailsHeading: View { + let name: String + let line: String + @ViewBuilder var mark: Mark + @ViewBuilder var actions: Actions + + var body: some View { + VStack(spacing: 10) { + mark + VStack(spacing: 2) { + Text(name).font(Typeface.rubik(22, .semibold)).foregroundStyle(Palette.foreground).lineLimit(1) + Text(line).font(Typeface.rubik(14)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + HStack(spacing: 28) { actions }.padding(.top, 8) + } + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .padding(.horizontal, 16) + .padding(.top, 4) + .padding(.bottom, 16) + } +} + +/// The look of a round action under a Details heading, for a button or link +/// to wear: an icon on a chip, its name under it. +private struct RoundActionLabel: View { + let icon: Lucide + let label: String + + var body: some View { + VStack(spacing: 6) { + Icon(icon, size: 20, strokeWidth: 1.75) + .foregroundStyle(Palette.foreground) + .frame(width: 48, height: 48) + .background(Palette.chip, in: Circle()) + Text(label).font(Typeface.rubik(13)).foregroundStyle(Palette.softForeground) + } + .frame(width: 64) + } +} + +/// A section of Details on a phone: its title in small grey type over a card. +struct DetailsSection: View { + let title: String + @ViewBuilder var end: End + @ViewBuilder var content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 8) { + Text(title).font(Typeface.rubik(13, .medium)).foregroundStyle(Palette.subtleForeground).frame(maxWidth: .infinity, alignment: .leading) + end + } + .padding(.horizontal, 4) + VStack(alignment: .leading, spacing: 10) { content } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Palette.card, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border)) + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } +} + +extension DetailsSection where End == EmptyView { + init(title: String, @ViewBuilder content: () -> Content) { + self.init(title: title, end: { EmptyView() }, content: content) + } +} + +/// A bot's Details: its face large, its model, Settings and Routines, then its summary, memory and routines. +@MainActor +private struct BotDetails: View { + let agent: Agent + let pod: Pod + let threadId: String + @Environment(WorkspaceStore.self) private var store + @Environment(\.openPage) private var openPage + @State private var activity: ThreadActivity? + @State private var summaryOpen = false + /// Whether the system agent that writes summaries has a model; nil until known. + @State private var scribeHasModel: Bool? + + /// How long a summary runs before it folds. + private static let summaryFoldedOver = 240 + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + sections + } + .task { + activity = try? await store.client.threads.activity(threadId: threadId) + scribeHasModel = await store.summariesHaveModel() + } + } + + @ViewBuilder private var sections: some View { + DetailsHeading(name: agent.name, line: store.modelName(agent.model) ?? "No model chosen") { + BotFace(look: agent.look, size: 88) + } actions: { + Button { openPage(.settings(.agent(pod, agent))) } label: { + RoundActionLabel(icon: .settings, label: "Settings") + } + .buttonStyle(.plain) + NavigationLink(value: Route.routines(pod, agent: agent)) { + RoundActionLabel(icon: .refreshCcw, label: "Routines") + } + .buttonStyle(.plain) + } + DetailsSection(title: "Summary") { + if scribeHasModel == false { + SystemAgentsNotSetUp() + } else { + summary + } + } + if let context = activity?.context { + DetailsSection(title: "Memory") { + Text("\(Self.usedPercent(context))%").font(Typeface.mono(12)).foregroundStyle(Palette.mutedForeground) + } content: { + MemoryMeter(context: context).padding(.vertical, 6) + } + } + BotRoutinesSection(pod: pod, agent: agent) + BotToolsSection(pod: pod, agent: agent) + } + + @ViewBuilder private var summary: some View { + let text = activity?.summary?.content + let folds = (text?.count ?? 0) > Self.summaryFoldedOver + Text(text ?? "A summary will appear after the first reply.") + .font(Typeface.rubik(13)) + .lineSpacing(4) + .foregroundStyle(text == nil ? Palette.mutedForeground : Palette.softForeground) + .lineLimit(folds && !summaryOpen ? 3 : nil) + if folds { + ShowMoreButton(open: $summaryOpen) + } + } + + static func usedPercent(_ context: ThreadContext) -> Int { + Int((min(Double(context.usedTokens) / Double(max(context.windowTokens, 1)), 1) * 100).rounded()) + } +} + +/// How much of the bot's short-term memory the thread fills, with a tick where it starts compacting. +private struct MemoryMeter: View { + let context: ThreadContext + + var body: some View { + let used = Double(BotDetails.usedPercent(context)) / 100 + let line = Double(context.compactionLineTokens) / Double(max(context.windowTokens, 1)) + let compactedSince = context.compactedAt.map { $0 > context.measuredAt } ?? false + GeometryReader { geometry in + ZStack(alignment: .leading) { + Capsule().fill(Palette.chipStrong) + Capsule().fill(Palette.primary).frame(width: geometry.size.width * used) + Rectangle().fill(Palette.mutedForeground).frame(width: 1, height: 9).offset(x: geometry.size.width * line) + } + } + .frame(height: 3) + .opacity(compactedSince ? 0.4 : 1) + .accessibilityElement() + .accessibilityLabel("Short-term memory used") + .accessibilityValue("\(Int(used * 100)) percent") + } +} + +/// A pod channel's Details: its mark, how many people and bots, and Rename and Archive. +@MainActor +private struct ChannelHeading: View { + let model: ConversationModel + let pod: Pod + let details: ThreadDetails + let name: String + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var change: ChannelChange? + + var body: some View { + let listed = store.podChat(model.conversationId, in: pod.id) + let (people, bots) = details.headCount + DetailsHeading(name: name, line: "\(people), \(bots)") { + ChannelFace(size: 88) + } actions: { + if let listed { + if ChannelChange.mayRename(in: pod) { + Button { change = .rename(listed) } label: { + RoundActionLabel(icon: .pencil, label: "Rename") + } + .buttonStyle(.plain) + } + if ChannelChange.mayArchive(listed, in: pod) { + Button { change = .archive(listed) } label: { + RoundActionLabel(icon: .archive, label: "Archive") + } + .buttonStyle(.plain) + } + } + } + .channelChange($change, in: pod) { dismiss() } + } +} + +/// Who is in the thread: each face, name, and whether a bot, you, or a member. +@MainActor +private struct InThisThread: View { + let participants: [ThreadParticipant] + @Environment(WorkspaceStore.self) private var store + + var body: some View { + if !participants.isEmpty { + DetailsSection(title: "In this thread") { + VStack(spacing: 0) { + ForEach(participants, id: \.id) { participant in + HStack(spacing: 12) { + ParticipantFace(participant: participant, size: 22) + Text(participant.name).font(Typeface.rubik(15)).foregroundStyle(Palette.foreground).lineLimit(1) + Spacer(minLength: 0) + Text(participant.agent != nil ? "Bot" : participant.id == store.user.id ? "You" : "Member") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + } + .frame(height: 44) + } + } + } + } + } +} + +/// The files posted in the thread, the first few with Show more. +@MainActor +private struct SharedFiles: View { + let files: [FilePart] + let conversationId: String + @State private var open = false + + /// How many files show before Show more. + private static let shown = 3 + + var body: some View { + if !files.isEmpty { + DetailsSection(title: "Files") { + VStack(alignment: .leading, spacing: 0) { + ForEach(open ? files : Array(files.prefix(Self.shown))) { file in + ShareFileButton(file: file, conversationId: conversationId) { + HStack(spacing: 12) { + Icon(.fileText, size: 12, strokeWidth: 2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 22, height: 22) + .overlay(RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(Palette.borderStrong)) + Text(file.name).font(Typeface.rubik(15)).foregroundStyle(Palette.foreground).lineLimit(1) + Spacer(minLength: 0) + } + .frame(height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(cornerRadius: 6)) + } + if files.count > Self.shown { + ShowMoreButton(open: $open).padding(.vertical, 4) + } + } + } + } + } +} + +/// Why there's no summary yet: the system agents that write them have no model, and who chooses it. +@MainActor +private struct SystemAgentsNotSetUp: View { + @Environment(WorkspaceStore.self) private var store + @Environment(\.openPage) private var openPage + + var body: some View { + let may = store.permissions?.configureBuiltInAgents ?? false + Group { + if may { + Button { openPage(.settings(.systemModel)) } label: { + (Text("The system agents write these, and they have no model yet. ") + Text("Choose their model").foregroundStyle(Palette.foreground).fontWeight(.medium) + Text(".")) + .multilineTextAlignment(.leading) + } + .buttonStyle(.plain) + } else { + Text("The system agents write these, and they have no model yet. A workspace administrator chooses their model.") + } + } + .font(Typeface.rubik(15)) + .lineSpacing(5) + .foregroundStyle(Palette.mutedForeground) + .padding(.top, 12) + } +} diff --git a/apps/ios/Sugabots/Conversation/ConversationHeader.swift b/apps/ios/Sugabots/Conversation/ConversationHeader.swift new file mode 100644 index 000000000..e205109e1 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationHeader.swift @@ -0,0 +1,371 @@ +import SwiftUI + +/// The top of a conversation on a phone: Back in glass with Inbox's unread +/// count; then what the conversation is, as one glass row (its face, its name, +/// and a quieter line under it), which opens Details; and at the right one +/// control: a bot's channel's ⋯ (Computer, Routines), a thread's ⋯ (Computer, +/// Mark done), or Mark done for a thread between people. +/// +/// The row, its place up against the Dynamic Island, and the channel's ⋯ are +/// the app's own, after Slack's: the web has a face over its name in the +/// middle, Computer at the right, and Routines under the bot on Home. +@MainActor +struct ConversationHeader: View { + let model: ConversationModel + let kind: ConversationKind + let pod: Pod? + let fallbackTitle: String + let openDetails: () -> Void + let openComputer: () -> Void + let openRoutines: () -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(Toaster.self) private var toaster + @Environment(\.dismiss) private var dismiss + + /// A face in the title pill: 6 points inside its rounded end, and 6 over and under in its 44. + private static let faceSize = NativeConstants.headerFaceSize + + var body: some View { + HStack(spacing: 8) { + HeaderBack() + badge.frame(maxWidth: .infinity, alignment: .leading) + controls + } + .padding(.horizontal, 16) + // Placed from the top of the screen: up into the safe area as far as it gives, + // and 12 points down where it has none, as a page's header. + .padding(.top, max(12, WindowInsets.current.top - WindowInsets.headerRise)) + .padding(.bottom, 8) + .ignoresSafeArea(edges: .top) + } + + private var title: String { model.thread?.title ?? fallbackTitle } + + @ViewBuilder private var badge: some View { + switch kind { + case let .botChannel(agent): + TitleRow(name: agent.name, line: store.modelName(agent.model) ?? "No model chosen", open: openDetails) { + BotFace(look: agent.look, size: Self.faceSize) + } + case let .botThread(agent): + if model.details?.routine != nil { + TitleRow(name: title, line: "Runs as \(agent.name)", open: openDetails) { + bareFace(.refreshCcw) + } + } else { + TitleRow(name: title, line: "With \(agent.name)", open: openDetails) { + BotFace(look: agent.look, size: Self.faceSize) + } + } + case let .podChat(name): + TitleRow(name: name, line: podChatCounts ?? pod?.name, open: openDetails) { + bareFace(.hash) + } + case .peopleThread: + TitleRow(name: title, line: (startedIn.map { "#\($0)" } ?? pod?.name).map { "In \($0)" }, open: openDetails) + } + } + + /// A bare mark in a face's place: a tile's square corners would sit oddly in the round pill. + private func bareFace(_ icon: Lucide) -> some View { + Icon(icon, size: 24, strokeWidth: 2.25) + .foregroundStyle(Palette.foreground) + .frame(width: Self.faceSize, height: Self.faceSize) + } + + @ViewBuilder private var controls: some View { + switch kind { + case let .botChannel(agent): + let failed = routinesFailed(agent) + GlassMenuButton( + label: failed ? "More for \(agent.name), a routine's latest run failed" : "More for \(agent.name)", + items: [ + .init(title: "Computer", systemImage: "desktopcomputer", action: openComputer), + .init(title: "Routines", systemImage: "arrow.triangle.2.circlepath", action: openRoutines), + ] + ) + .overlay(alignment: .topTrailing) { + if failed { FailedRoutineDot().offset(x: -6, y: 6).allowsHitTesting(false) } + } + case .botThread: + if model.details?.routine == nil { + GlassMenuButton( + label: "More for this thread", + items: [ + .init(title: "Computer", systemImage: "desktopcomputer", action: openComputer), + .init( + title: isDone ? "Reopen" : "Mark done", + systemImage: isDone ? "arrow.counterclockwise" : "checkmark.circle", + action: toggleDone + ), + ] + ) + } + case .peopleThread: + GlassRoundButton(icon: isDone ? .rotateCcw : .circleCheck, label: isDone ? "Reopen" : "Mark done", iconSize: 20, strokeWidth: 1.75, action: toggleDone) + case .podChat: + EmptyView() + } + } + + private var isDone: Bool { model.thread?.doneAt != nil } + + /// Whether the latest run of one of the bot's routines failed. + private func routinesFailed(_ agent: Agent) -> Bool { + guard let pod else { return false } + return (store.chatLists[pod.id]?.routines ?? []).contains { $0.agent.id == agent.id && $0.routine.failed } + } + + /// Who is in a pod's channel: `1 person · 1 bot`. + private var podChatCounts: String? { + guard let (people, bots) = model.details?.headCount else { return nil } + return "\(people) · \(bots)" + } + + /// The channel a thread between people was started from, by its name. + private var startedIn: String? { + guard let parent = model.thread?.parentThreadId, let pod else { return nil } + return store.podChat(parent, in: pod.id)?.title + } + + private func toggleDone() { + let marking = !isDone + Task { + do { + try await model.setDone(marking) + // Done with, it is left, as Back leaves it. + if marking { dismiss() } + } catch { + toaster.show("This thread was not marked done or reopened. Try again.") + } + } + } +} + +/// Back on a phone's conversation: the glass chevron, with Inbox's unread count beside it. +struct HeaderBack: View { + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + + var body: some View { + let unread = store.unreadInInbox + Button { dismiss() } label: { + HStack(spacing: 6) { + Icon(.chevronLeft, size: 22, strokeWidth: 2.25) + if unread > 0 { + CountBadge(count: unread, size: .large) + } + } + .foregroundStyle(Palette.foreground) + .padding(.horizontal, unread > 0 ? 8 : 0) + .frame(minWidth: 44, minHeight: 44) + .contentShape(Capsule()) + } + .buttonStyle(CapsuleGlassPressStyle()) + .accessibilityLabel(unread > 0 ? "Back, \(unread) unread in Inbox" : "Back") + } +} + +/// What a conversation is, in a glass row 44 points tall: its face, its name, +/// and a quieter line under it, after Slack's. Opens Details. +private struct TitleRow: View { + let name: String + let line: String? + let open: () -> Void + /// How far the row starts inside the pill's round end: close beside a face, + /// and for text alone, as far as the row ends from the other end. + private let leadingInset: CGFloat + private let face: Face + + /// The inset at either end of the pill, for text. + private static var textInset: CGFloat { 16 } + /// The inset beside a face, which sits close to the pill's round end. + private static var faceInset: CGFloat { 6 } + + init(name: String, line: String?, open: @escaping () -> Void, @ViewBuilder face: () -> Face) { + self.init(name: name, line: line, open: open, leadingInset: Self.faceInset, face: face()) + } + + private init(name: String, line: String?, open: @escaping () -> Void, leadingInset: CGFloat, face: Face) { + self.name = name + self.line = line + self.open = open + self.leadingInset = leadingInset + self.face = face + } + + var body: some View { + Button(action: open) { + HStack(spacing: 10) { + face + VStack(alignment: .leading, spacing: 0) { + Text(name).font(Typeface.rubik(16, .semibold)).foregroundStyle(Palette.foreground) + if let line { + Text(line).font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + } + } + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.leading, leadingInset) + .padding(.trailing, Self.textInset) + .frame(height: NativeConstants.headerPillHeight) + .contentShape(Capsule()) + } + // Glass that fills a step darker while pressed, as Back does; the plain style would fade + // the whole pill, glass and all, and fade it back only after Details has opened. + .buttonStyle(CapsuleGlassPressStyle()) + .accessibilityLabel([name, line].compactMap { $0 }.joined(separator: ", ") + ", details") + } +} + +extension TitleRow where Face == EmptyView { + /// A title with nothing beside it, for a thread among people, which has no face of its own. + init(name: String, line: String?, open: @escaping () -> Void) { + self.init(name: name, line: line, open: open, leadingInset: Self.textInset, face: EmptyView()) + } +} + +/// The start of a conversation, over its first message, as the web's intros: +/// a thread's title with who started it and from what; a channel's tile and +/// what it is for; a routine's title; a bot's face and what it does. +struct Intro: View { + let details: ThreadDetails + let kind: ConversationKind + let pod: Pod + + var body: some View { + let thread = details.thread + Group { + if thread.parentThreadId != nil { + threadIntro + } else { + switch kind { + case let .podChat(name): podChatIntro(name) + case let .botChannel(agent): botChannelIntro(agent) + case let .botThread(agent): + if thread.type == .routineFeed { + titled(thread.title, "Runs as \(agent.name). Each run posts here.") + } else { + botThreadIntro(agent, title: thread.title) + } + case .peopleThread: threadIntro + } + } + } + .padding(.horizontal, 20) + } + + private var threadIntro: some View { + let thread = details.thread + let starter = details.members.first { $0.id == thread.initiatorUserId } + return VStack(alignment: .leading, spacing: 6) { + Text(thread.title).font(Typeface.rubik(22, .bold)).foregroundStyle(Palette.foreground) + Text("\(starter.map { "Started by \($0.name) in \(pod.name)" } ?? "Started in \(pod.name)"), \(Times.list(thread.createdAt))") + .font(Typeface.rubik(13.5)) + .foregroundStyle(Palette.mutedForeground) + if let startedFrom = details.startedFrom { + StartedFrom(message: startedFrom, mentionable: details.participants) + } + } + .padding(.top, 24) + .padding(.bottom, 16) + } + + private func titled(_ title: String, _ line: String) -> some View { + VStack(alignment: .leading, spacing: 6) { + Text(title).font(Typeface.rubik(22, .bold)).foregroundStyle(Palette.foreground) + Text(line).font(Typeface.rubik(13.5)).foregroundStyle(Palette.mutedForeground) + } + .padding(.top, 24) + .padding(.bottom, 16) + } + + private func podChatIntro(_ name: String) -> some View { + let (people, bots) = details.headCount + return VStack(alignment: .leading, spacing: 8) { + PodChatTile(color: pod.color?.rawValue, size: 64) + Text(name).font(Typeface.rubik(24, .bold)).tracking(-0.24).foregroundStyle(Palette.foreground).padding(.top, 4) + Text("This is the start of \(name), with \(people) and \(bots). Talk here, or mention a bot to start a thread with it.") + .font(Typeface.rubik(14.5)) + .lineSpacing(4) + .foregroundStyle(Palette.mutedForeground) + } + .padding(.top, 8) + .padding(.bottom, 14) + } + + /// A bot's thread: its title, and the bot it's with. + private func botThreadIntro(_ agent: Agent, title: String) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(title).font(Typeface.rubik(20, .bold)).tracking(-0.2).foregroundStyle(Palette.foreground) + HStack(spacing: 8) { + BotFace(look: agent.look, size: 20) + Text("With \(agent.name)") + } + .font(Typeface.rubik(14.5)) + .foregroundStyle(Palette.mutedForeground) + } + .padding(.top, 8) + .padding(.bottom, 14) + } + + /// A bot's channel: its face large, its name, and whose it is. + private func botChannelIntro(_ agent: Agent) -> some View { + let line = pod.kind == .personal + ? "Your own bot. It works for you only and nobody else in the workspace can see this conversation." + : "This is the start of \(agent.name)'s channel." + return VStack(alignment: .leading, spacing: 8) { + BotFace(look: agent.look, size: 64) + Text(agent.name).font(Typeface.rubik(24, .bold)).tracking(-0.24).foregroundStyle(Palette.foreground).padding(.top, 4) + Text(line) + .font(Typeface.rubik(14.5)) + .lineSpacing(4) + .foregroundStyle(Palette.mutedForeground) + } + .padding(.top, 8) + .padding(.bottom, 14) + } +} + +/// The message a thread was started from, under its title: who said it and what, behind a rule. +private struct StartedFrom: View { + let message: Message + let mentionable: [ThreadParticipant] + + var body: some View { + let files = message.files.map(\.name) + VStack(alignment: .leading, spacing: 4) { + Text(message.author.name).font(Typeface.rubik(14, .semibold)).foregroundStyle(Palette.foreground) + if !message.content.isEmpty { + Text(MarkdownInline.plainWithMentions(message.content, by: message.author, mentionable: mentionable)) + .font(Typeface.rubik(15)) + .lineSpacing(4) + .foregroundStyle(Palette.softForeground) + } + if !files.isEmpty { + Text(files.joined(separator: ", ")).font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground).lineLimit(1) + } + } + .padding(.leading, 12) + .overlay(alignment: .leading) { Rectangle().fill(Palette.borderStrong).frame(width: 2) } + .padding(.top, 4) + } +} + +/// A pod's channel as a tile: a # in the foreground on the pod's tint, as the web's `PodChatTile`. +struct PodChatTile: View { + let color: String? + let size: CGFloat + + var body: some View { + let palette = color.flatMap { BotLooks.pods[$0] } + // The web's sizes: 26, 28 and 64, each with its own corner and icon. + let (radius, icon): (CGFloat, CGFloat) = size >= 64 ? (18, 30) : size >= 28 ? (8, 15) : (7, 14) + Icon(.hash, size: icon, strokeWidth: 2) + .foregroundStyle(Palette.foreground) + .frame(width: size, height: size) + .background(palette?.tile.resolved ?? Palette.tile, in: RoundedRectangle(cornerRadius: radius, style: .continuous)) + .accessibilityHidden(true) + } +} diff --git a/apps/ios/Sugabots/Conversation/ConversationModel.swift b/apps/ios/Sugabots/Conversation/ConversationModel.swift new file mode 100644 index 000000000..bb798d216 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationModel.swift @@ -0,0 +1,648 @@ +import Foundation +import Observation +import os + +/// One open conversation, as the web's `ConversationChat` keeps it: the +/// thread's details, the pages of its items (messages, runs, threads started +/// here), its side threads, and what the person is sending. The thread's +/// event stream keeps it live while a screen calls `listen()`. +@MainActor +@Observable +final class ConversationModel { + /// Where a model's items come from. + enum ItemSource { + /// The conversation's pages of items and its side threads. What is shown is + /// kept in the store when the last screen stops listening, and shown at once + /// the next time a model of the conversation is made. + case conversationPages + /// The thread's newest messages alone, as its details carry them: a side + /// thread, which isn't a conversation of its own, or a channel opened only to + /// start a thread from. + case threadMessages + } + + /// How sending a draft ended. + enum SubmitOutcome { + case sent + /// Not sent, with why in words for the person. + case failed(String) + } + + /// The conversation's own thread, whose id is the conversation's. + let threadId: String + private let store: WorkspaceStore + private let source: ItemSource + + private(set) var details: ThreadDetails? + /// The items of the pages loaded, newest page last. + private(set) var pageItems: [ChatMessageItem] = [] { didSet { rebuildItems() } } + /// Where older items start, while there are any. + private(set) var olderCursor: String? + private(set) var pagesLoaded = 0 + /// Whether a load has finished since the model was made, so its items are + /// current rather than as the conversation was left. + private(set) var isLoaded = false + /// The newest messages, as the thread's details and its stream keep them. + private(set) var liveMessages: [Message] = [] { didSet { rebuildItems() } } + /// Messages the person sent that the server hasn't confirmed yet. + private(set) var sendingMessages: [Message] = [] { didSet { rebuildItems() } } + /// Every item to show, oldest first: the pages, what is being sent, and the live messages over both. + private(set) var items: [ChatMessageItem] = [] + /// The ids of messages still being sent. + private(set) var sendingIds: Set = [] + /// The conversation's side threads: collaborations and routine runs. + private(set) var entries: [ChatHistoryEntry] = [] + private(set) var loadError: String? + /// Why a reply somebody asked for is not coming. The server keeps these in no history. + private(set) var notices: [String] = [] + /// The turn in progress. + private(set) var runningTurnId: String? + + private var newestPageFailed = false + private var olderPageFailed = false + private var historyFailed = false + /// People typing now, by id, each until their last signal runs out. + private var typing: [String: TypingPerson] = [:] + private var lastTypingSignal = Date.distantPast + + /// The stream of the thread's events, while any screen listens. + private var streaming: Task? + /// How many screens are listening now: a conversation and its Details may overlap while one is pushed over the other. + private var listeners = 0 + private var reloading: Task? + private var refetching: Task? + private var loadingOlderPage: Task? + + /// How many items a page holds. + private static let pageSize = 50 + /// How long a person is shown typing after they last said so: twice the gap between their signals. + private static let typingShownFor: Duration = .seconds(6) + /// How often a person still typing says so again, as the web's composer does. + private static let typingSignalInterval: TimeInterval = 3 + /// How long events must stop arriving before what they couldn't say exactly is fetched again. + private static let refetchDelay: Duration = .milliseconds(250) + /// The status of a message the server refused as written, whose reason is worth showing. + private static let badRequestStatus = 400 + private static let log = Logger(subsystem: Bundle.main.bundleIdentifier ?? "Sugabots", category: "Conversation") + + init(threadId: String, store: WorkspaceStore, source: ItemSource = .conversationPages) { + self.threadId = threadId + self.store = store + self.source = source + // Shown at once as it was left, while `listen` brings it up to date. + if source == .conversationPages, let left = store.leftConversations[threadId] { restore(left) } + rebuildItems() + } + + /// What a conversation showed when it was left. + struct Snapshot { + let details: ThreadDetails + let pageItems: [ChatMessageItem] + let olderCursor: String? + let pagesLoaded: Int + let entries: [ChatHistoryEntry] + } + + private func restore(_ left: Snapshot) { + show(left.details) + pageItems = left.pageItems + olderCursor = left.olderCursor + pagesLoaded = left.pagesLoaded + entries = left.entries + } + + /// Keeps what's shown for the next time the conversation opens. + private func keep() { + guard source == .conversationPages, let details, loadError == nil, !messagesFailed else { return } + store.leftConversations[threadId] = Snapshot(details: details, pageItems: pageItems, olderCursor: olderCursor, pagesLoaded: pagesLoaded, entries: entries) + } + + var thread: Thread? { details?.thread } + var conversationId: String { thread?.conversationId ?? threadId } + var isPodChat: Bool { thread?.type == .podChat } + var isBotChannel: Bool { thread?.type == .botChannel } + var isRoutineFeed: Bool { thread?.type == .routineFeed } + var isRunning: Bool { runningTurnId != nil || thread?.status == .running } + /// Whether the newest page, an older page, or the side threads failed to load. + var messagesFailed: Bool { newestPageFailed || olderPageFailed || historyFailed } + var loadingOlder: Bool { loadingOlderPage != nil } + + private func rebuildItems() { + // Each id's latest version, kept at the place it first arrived, so items + // written at the same moment stay in the same order from one rebuild to the next. + var byId: [String: ChatMessageItem] = [:] + var arrival: [String] = [] + func put(_ id: String, _ item: ChatMessageItem) { + if byId.updateValue(item, forKey: id) == nil { arrival.append(id) } + } + for item in pageItems { put(item.id, item) } + for message in sendingMessages { put("message:\(message.id)", .message(.init(message: message))) } + for message in liveMessages { put("message:\(message.id)", .message(.init(message: message))) } + // A stable sort, so arrival order breaks ties. + items = arrival.compactMap { byId[$0] }.sorted { $0.createdAt < $1.createdAt } + let saved = Set(pageItems.compactMap(\.message?.id) + liveMessages.map(\.id)) + sendingIds = Set(sendingMessages.map(\.id).filter { !saved.contains($0) }) + } + + /// Everybody who can be mentioned here: those in the thread, then the pod's bots and people. + var mentionable: [ThreadParticipant] { + guard let details else { return [] } + var joined = Set(details.participants.map(\.id)) + var all = details.participants + for member in details.crew where !joined.contains(member.id) { + all.append(member) + joined.insert(member.id) + } + for person in details.members where !joined.contains(person.id) { + all.append(.person(person)) + joined.insert(person.id) + } + return all + } + + /// People typing now, but not the person themselves, by name. + var peopleTyping: [PersonParticipant] { + typing.values.map(\.person).sorted { $0.name < $1.name } + } + + /// The person's messages waiting behind a reply in progress, by id. + var queuedBehindReply: Set { + guard let since = details?.queuedSince else { return [] } + return Set(items.compactMap { item -> String? in + guard let message = item.message, message.author.personId != nil, message.createdAt >= since else { return nil } + return message.id + }) + } + + /// What each message row needs from this conversation, once its details + /// have loaded. `looks` are the pod's connections by handle; files are + /// fetched from `filesConversationId`. + func messageContext(looks: [String: ConnectionLook], filesConversationId: String) -> MessageContext? { + guard let details else { return nil } + let messages = items.compactMap(\.message) + return MessageContext( + podId: details.thread.podId, + mentionable: mentionable, + capabilities: details.capabilities, + looks: looks, + fileNames: Dictionary(messages.flatMap(\.files).map { ($0.id, $0.name) }, uniquingKeysWith: { first, _ in first }), + threadActivityAt: Dictionary(entries.map { ($0.threadId, $0.latestActivityAt) }, uniquingKeysWith: { first, _ in first }), + queued: queuedBehindReply, + sending: sendingIds, + inRoutineThread: isRoutineFeed, + userId: store.user.id, + conversationId: filesConversationId + ) + } + + /// The bot a pod channel's `draft` mentions first, whom sending it starts a thread with; nil anywhere else. + func threadBot(for draft: String) -> AgentParticipant? { + guard isPodChat, let crew = details?.crew else { return nil } + return Mentions.firstBot(in: draft, among: crew) + } + + // MARK: Loading and listening + + /// Loads the conversation and keeps it live from its thread's events until + /// the calling task is cancelled. Screens showing the model each call it + /// from their own task; the stream runs while any of them listens, and when + /// the last stops, what is shown is kept for the next time it opens. + func listen() async { + listeners += 1 + if streaming == nil { + streaming = Task { await streamEvents() } + } + await Self.waitUntilCancelled() + listeners -= 1 + guard listeners == 0 else { return } + streaming?.cancel() + streaming = nil + refetching?.cancel() + keep() + } + + private func streamEvents() async { + await reload() + // A refused thread stream just stops: the workspace's own stream reports a refusal such as an expired token. + do { + for try await event in EventStream.thread(threadId, client: store.client) { + apply(event) + } + } catch {} + } + + /// Returns once the calling task is cancelled. + private static func waitUntilCancelled() async { + while !Task.isCancelled { + // Throws, ending the wait, as soon as the task is cancelled. + try? await Task.sleep(for: .seconds(60 * 60)) + } + } + + /// Loads the thread's details and its newest items again. A reload still + /// under way is abandoned, so an older response never replaces a newer one. + func reload() async { + reloading?.cancel() + let task = Task { await load() } + reloading = task + await task.value + } + + private func load() async { + if source == .conversationPages, store.isListed(threadId) { + // A conversation the pods' lists show is its own thread, so its pages can load + // alongside its details instead of a round trip after them. + async let details: Void = loadDetails() + async let pages: Void = loadPages() + _ = await (details, pages) + } else { + await loadDetails() + if loadError == nil, source == .conversationPages, thread?.conversationId != nil { + await loadPages() + } + } + if !Task.isCancelled { isLoaded = true } + } + + private func loadDetails() async { + do { + let loaded = try await store.client.threads.get(threadId: threadId, limit: Self.pageSize) + guard !Task.isCancelled else { return } + show(loaded) + } catch { + guard !error.isCancellation, !Task.isCancelled else { return } + Self.log.error("Thread details failed: \(String(describing: error))") + // A conversation already showing from when it was left stays shown; the next refresh tries again. + if details == nil { loadError = error.localizedDescription } + } + } + + private func show(_ details: ThreadDetails) { + self.details = details + liveMessages = details.messages.sorted { $0.createdAt < $1.createdAt } + if details.thread.status != .running { runningTurnId = nil } + loadError = nil + } + + /// Loads the conversation's newest page of items and its side threads, together. + private func loadPages() async { + async let page: Void = loadNewestPage() + async let history: Void = loadHistory() + _ = await (page, history) + } + + private func loadNewestPage() async { + do { + let page = try await store.client.chats.messages(conversationId: conversationId, limit: Self.pageSize) + guard !Task.isCancelled else { return } + // Older pages loaded before stay; the newest is replaced. + let newest = Set(page.items.map(\.id)) + let older = pageItems.filter { !newest.contains($0.id) && pagesLoaded > 1 } + pageItems = older + page.items + if pagesLoaded <= 1 { olderCursor = page.nextCursor } + pagesLoaded = max(pagesLoaded, 1) + newestPageFailed = false + } catch { + guard !error.isCancellation, !Task.isCancelled else { return } + Self.log.error("Messages failed: \(String(describing: error))") + newestPageFailed = true + } + } + + private func loadHistory() async { + do { + let page = try await store.client.chats.history(conversationId: conversationId) + guard !Task.isCancelled else { return } + entries = page.items + historyFailed = false + } catch { + guard !error.isCancellation, !Task.isCancelled else { return } + Self.log.error("Side threads failed: \(String(describing: error))") + historyFailed = true + } + } + + /// Loads the page of items before those shown, and reports whether it did. + /// Called while a page is loading, it waits for that page instead. + @discardableResult + func loadOlder() async -> Bool { + if let loadingOlderPage { return await loadingOlderPage.value } + guard let cursor = olderCursor else { return false } + let task = Task { await loadOlderPage(from: cursor) } + loadingOlderPage = task + let loaded = await task.value + loadingOlderPage = nil + return loaded + } + + private func loadOlderPage(from cursor: String) async -> Bool { + do { + let page = try await store.client.chats.messages(conversationId: conversationId, cursor: cursor, limit: Self.pageSize) + pageItems = page.items + pageItems + olderCursor = page.nextCursor + pagesLoaded += 1 + olderPageFailed = false + return true + } catch { + if !error.isCancellation { + Self.log.error("Older messages failed: \(String(describing: error))") + olderPageFailed = true + } + return false + } + } + + /// Loads older pages until the message with `messageId` is among `items`, + /// with at most `maxPages` pages loaded in all, and reports whether it is. + func loadUntilShown(messageId: String, maxPages: Int) async -> Bool { + while !items.contains(where: { $0.message?.id == messageId }) { + guard olderCursor != nil, pagesLoaded < maxPages, await loadOlder() else { return false } + } + return true + } + + /// Refetches once events stop arriving for a moment: what an event could not say exactly. + private func refetchSoon() { + refetching?.cancel() + refetching = Task { + try? await Task.sleep(for: Self.refetchDelay) + guard !Task.isCancelled else { return } + await reload() + } + } + + // MARK: Events + + private func apply(_ streamed: StreamEvent) { + guard let event = streamed.decode(ThreadUpdateEvent.self) else { return refetchSoon() } + switch event { + case let .messageCreated(created): + upsert(created.message) + notices = [] + if let personId = created.message.author.personId { typing[personId] = nil } + if created.message.threadId != threadId { refetchSoon() } + case let .messageDelta(delta): + appendDelta(delta) + case let .messageCompleted(completed): + // The stored parts place tool calls in the final text exactly, which deltas cannot. + update(completed.messageId) { $0.status = completed.status } + refetchSoon() + case let .messageFailed(failed): + guard !failed.willRetry else { return } + update(failed.messageId) { + $0.status = .failed + $0.error = failed.error + } + case let .toolCallStarted(changed): + upsertToolCall(changed.toolCall, in: changed.messageId) + case let .toolCallCompleted(changed): + upsertToolCall(changed.toolCall, in: changed.messageId) + case let .toolCallUpdated(changed): + upsertToolCall(changed.toolCall, in: changed.messageId) + case let .messageReactionsChanged(changed): + update(changed.messageId) { $0.reactions = changed.reactions } + case let .turnStarted(started): + runningTurnId = started.turnId + case .turnCompleted: + runningTurnId = nil + refetchSoon() + case let .threadNotice(notice): + notices.append(notice.notice) + case let .personTyping(typing): + guard typing.person.id != store.user.id else { return } + showTyping(typing.person) + default: + refetchSoon() + } + } + + /// Shows `person` typing for `typingShownFor`, unless they say so again meanwhile. + private func showTyping(_ person: PersonParticipant) { + let signal = UUID() + typing[person.id] = TypingPerson(person: person, signal: signal) + Task { [weak self] in + try? await Task.sleep(for: Self.typingShownFor) + guard let self, self.typing[person.id]?.signal == signal else { return } + self.typing[person.id] = nil + } + } + + private func upsert(_ message: Message) { + sendingMessages.removeAll { $0.id == message.id } + if let index = liveMessages.firstIndex(where: { $0.id == message.id }) { + liveMessages[index] = message + } else { + liveMessages = (liveMessages + [message]).sorted { $0.createdAt < $1.createdAt } + } + } + + private func update(_ messageId: String, _ change: (inout Message) -> Void) { + if let index = liveMessages.firstIndex(where: { $0.id == messageId }) { + change(&liveMessages[index]) + return + } + if let index = pageItems.firstIndex(where: { $0.id == "message:\(messageId)" }), case var .message(item) = pageItems[index] { + change(&item.message) + pageItems[index] = .message(item) + return + } + refetchSoon() + } + + /// Appends streamed text where it belongs. `offset` says how much came before + /// it, so a repeat is skipped and a gap is filled by refetching. Offsets + /// count UTF-16 code units, as JavaScript strings do. + private func appendDelta(_ delta: ThreadUpdateEvent.MessageDelta) { + guard let index = liveMessages.firstIndex(where: { $0.id == delta.messageId }) else { return refetchSoon() } + var message = liveMessages[index] + let written = message.content.utf16.count + guard delta.offset <= written else { return refetchSoon() } + let fresh = String(decoding: Array(delta.text.utf16.dropFirst(written - delta.offset)), as: UTF16.self) + guard !fresh.isEmpty else { return } + message.content += fresh + if case let .text(part)? = message.parts.last { + message.parts[message.parts.count - 1] = .text(TextPart(text: part.text + fresh)) + } else { + message.parts.append(.text(TextPart(text: fresh))) + } + liveMessages[index] = message + } + + private func upsertToolCall(_ call: ToolCallPart, in messageId: String) { + guard let index = liveMessages.firstIndex(where: { $0.id == messageId }) else { return refetchSoon() } + let existing = liveMessages[index].parts.firstIndex { + if case let .toolCall(part) = $0 { part.id == call.id } else { false } + } + if let existing { + liveMessages[index].parts[existing] = .toolCall(call) + } else { + liveMessages[index].parts.append(.toolCall(call)) + } + } + + // MARK: Doing things + + /// Sends `draft` with the files attached to it, answering `replyTo`: in a + /// pod's channel as a new thread with the bot `draft` names first, else as a + /// message here. When sending fails the files go back into `attachments`. + func submit(_ draft: String, replyTo: MessageReplyTo?, attachments: ComposerAttachments?) async -> SubmitOutcome { + let text = draft.trimmingCharacters(in: .whitespacesAndNewlines) + let bot = threadBot(for: draft) + let deliver: ([FilePart]) async throws -> Void = { files in + if let bot { + try await self.startThread(text, with: bot, replyTo: replyTo, files: files) + } else { + try await self.send(text, replyTo: replyTo, files: files) + } + } + do { + if let attachments { + try await attachments.send(through: deliver) + } else { + try await deliver([]) + } + return .sent + } catch { + if bot != nil { return .failed("The thread was not started. Your message is still here.") } + if let failure = error as? APIFailure, failure.status == Self.badRequestStatus { + return .failed("Message not sent. \(failure.message).") + } + return .failed("Message not sent. Your draft is still here.") + } + } + + /// Sends `text` with `files`, answering `replyTo`, shown at once and confirmed when the server has it. + private func send(_ text: String, replyTo: MessageReplyTo?, files: [FilePart]) async throws { + let id = UUID().uuidString.lowercased() + let sending = Message( + id: id, + threadId: threadId, + author: .person(PersonParticipant(id: store.user.id, name: store.user.name, email: store.user.email, handle: "", image: store.user.image)), + status: .complete, + parts: (text.isEmpty ? [] : [.text(TextPart(text: text))]) + files.map { .file($0) }, + content: text, + replyTo: replyTo, + createdAt: .now + ) + sendingMessages.append(sending) + do { + let sent = try await store.client.chats.send( + conversationId: conversationId, + id: id, + message: text, + attachments: files.isEmpty ? nil : files.map(\.id), + replyTo: replyTo?.id + ) + upsert(sent) + } catch { + sendingMessages.removeAll { $0.id == id } + throw error + } + } + + /// Starts a thread from this channel with `bot` from `text`, as mentioning a bot does, or between people with none. + @discardableResult + func startThread(_ text: String, with bot: AgentParticipant?, replyTo: MessageReplyTo?, files: [FilePart]) async throws -> StartedThread { + let started = try await store.client.chats.startThread( + conversationId: conversationId, + id: UUID().uuidString.lowercased(), + message: text, + attachments: files.isEmpty ? nil : files.map(\.id), + hostAgentId: bot?.id, + replyTo: replyTo?.id + ) + await showStartedThread() + return started + } + + /// The thread started from `message` in this channel, started now if it has none. + func thread(from message: Message) async throws -> ConversationThread { + let started = try await store.client.chats.threadFrom(messageId: message.id) + await showStartedThread() + return started + } + + /// Brings in a thread just started here: its line in the conversation's items and its place in the pod's list. + private func showStartedThread() async { + if source == .conversationPages { await reload() } + await refreshPodChatList() + } + + /// Marks the thread done, or with false, reopens it. + func setDone(_ done: Bool) async throws { + if done { + try await store.client.chats.markDone(conversationId: conversationId) + } else { + try await store.client.chats.reopen(conversationId: conversationId) + } + await reload() + await refreshPodChatList() + } + + /// Refreshes the chat list of the pod the conversation is in, which lists its threads and whether each is done. + private func refreshPodChatList() async { + guard let podId = thread?.podId, let pod = store.pod(id: podId) else { return } + await store.refreshChatList(pod) + } + + /// Adds the person's `emoji` to `message`, or takes it away. + func toggleReaction(_ emoji: String, on message: Message) async { + let mine = message.reactions?.first { $0.emoji == emoji }?.people.contains { $0.id == store.user.id } ?? false + update(message.id) { changed in + var reactions = changed.reactions ?? [] + if let index = reactions.firstIndex(where: { $0.emoji == emoji }) { + if mine { + reactions[index].people.removeAll { $0.id == self.store.user.id } + if reactions[index].people.isEmpty { reactions.remove(at: index) } + } else { + reactions[index].people.append(.init(id: self.store.user.id, name: self.store.user.name, at: .now)) + } + } else if !mine { + reactions.append(MessageReaction(emoji: emoji, people: [.init(id: self.store.user.id, name: self.store.user.name, at: .now)])) + } + changed.reactions = reactions + } + do { + if mine { + _ = try await store.client.threads.unreact(messageId: message.id, emoji: emoji) + } else { + _ = try await store.client.threads.react(messageId: message.id, emoji: emoji) + } + } catch { + refetchSoon() + } + } + + /// Records that the person has read the conversation to its newest message. + func markRead() async { + await store.markRead(conversationId: conversationId) + } + + /// Tells others watching that the person is writing, at most once every + /// `typingSignalInterval`. Others show it for a few seconds; a lost signal + /// only shortens that, so a failure is not reported. + func noteTyping() { + guard Date.now.timeIntervalSince(lastTypingSignal) > Self.typingSignalInterval else { return } + lastTypingSignal = .now + Task { try? await store.client.events.typing(threadId: threadId) } + } +} + +/// Somebody shown typing, and which of their signals put them there. +private struct TypingPerson { + let person: PersonParticipant + let signal: UUID +} + +private extension Error { + /// Whether the error is a request given up because its task was cancelled, as leaving a page does: nothing to report. + var isCancellation: Bool { + self is CancellationError || (self as? URLError)?.code == .cancelled + } +} + +/// A conversation's model is one open conversation, the same however often a route names it. +extension ConversationModel: Hashable { + nonisolated static func == (lhs: ConversationModel, rhs: ConversationModel) -> Bool { lhs === rhs } + nonisolated func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } +} diff --git a/apps/ios/Sugabots/Conversation/ConversationScreen.swift b/apps/ios/Sugabots/Conversation/ConversationScreen.swift new file mode 100644 index 000000000..913f88947 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationScreen.swift @@ -0,0 +1,666 @@ +import SwiftUI + +/// A conversation as the web's `ConversationChat` shows it on a phone: a +/// pod's channel, a bot's channel, a thread, or a routine's thread. Its +/// header floats over the messages, which start with an introduction and +/// follow the newest as they arrive, and the composer sits at the foot over +/// the tabs. +struct ConversationScreen: View { + let threadId: String + let title: String + /// A message to open at, pointed out for a moment, as from the Inbox. + var focusMessageId: String? + @Environment(WorkspaceStore.self) private var store + @State private var model: ConversationModel? + + var body: some View { + ZStack { + Palette.background.ignoresSafeArea() + if let model { + ConversationContent(model: model, fallbackTitle: title, focusMessageId: focusMessageId) + } else { + ProgressView() + } + } + .task(id: threadId) { + // The model outlives a page pushed over the conversation, such as its + // Details, which listens to the same model while it shows. + if model?.threadId != threadId { model = ConversationModel(threadId: threadId, store: store) } + await model?.listen() + } + } +} + +/// What a conversation is, for its header, introduction and composer. +enum ConversationKind { + /// A pod's channel, by its name. + case podChat(name: String) + case botChannel(Agent) + case botThread(Agent) + /// A thread between people. + case peopleThread + + var agent: Agent? { + switch self { + case let .botChannel(agent), let .botThread(agent): agent + default: nil + } + } +} + +@MainActor +private struct ConversationContent: View { + let model: ConversationModel + let fallbackTitle: String + let focusMessageId: String? + /// Whether the page has jumped to `focusMessageId`, or given up looking for it. + @State private var jumpedToFocus = false + @State private var focusNotFound = false + @Environment(WorkspaceStore.self) private var store + @State private var draft = "" + @State private var replyingTo: MessageReplyTo? + @State private var attachments: ComposerAttachments? + @State private var sending = false + @State private var sendError: String? + @Environment(\.openPage) private var openPage + @State private var sideThread: SideThread? + @State private var showingComputer = false + @State private var highlighted: String? + /// The message whose actions are up without a touch, as a screenshot at launch asks. + @State private var heldMessageId: String? + @State private var latestInView = true + /// The pod's connections, by handle, for naming and marking a bot's steps. + @State private var looks: [String: ConnectionLook] = [:] + /// Whether the composer has the keyboard, as `Composer.focused` says. + @State private var composing = false + + private static let foot = "foot" + + /// The space between the composer and the keyboard, over the hint row's own. + private static let keyboardGap = NativeConstants.keyboardGap + /// How long a message jumped to stays highlighted. + private static let pointedOutFor: Duration = .seconds(2) + /// The space over the first message, under the floating header. + private static let headerRoom: CGFloat = 64 + /// How many pages are loaded, at most, looking for the message the page opened at. + private static let focusSearchPages = 10 + /// How long a jump waits for the pages just loaded to be laid out before scrolling to its message. + private static let jumpAfterLayout: Duration = .milliseconds(100) + + private func openDetails() { + openPage(.details(model)) + } + + var body: some View { + let kind = kind + let pod = model.thread.flatMap { store.pod(id: $0.podId) } + ZStack(alignment: .top) { + GeometryReader { viewport in + ScrollViewReader { scroller in + ScrollView { + // Anchored to the foot, so a short conversation sits just over the composer. + LazyVStack(alignment: .leading, spacing: 0) { + log(kind: kind, pod: pod, scroller: scroller) + Color.clear.frame(height: 16).id(Self.foot) + .onAppear { + latestInView = true + markRead() + } + .onDisappear { latestInView = false } + } + .padding(.top, Self.headerRoom) + .modifier(FootOfShortConversation(height: viewport.size.height)) + } + .defaultScrollAnchor(.bottom) + .scrollDismissesKeyboard(.interactively) + .task(id: model.isLoaded) { await jumpToFocus(scroller) } + .onChange(of: model.items.last?.id) { _, _ in + guard latestInView else { return } + withAnimation { scroller.scrollTo(Self.foot, anchor: .bottom) } + markRead() + } + } + } + ConversationHeader( + model: model, + kind: kind, + pod: pod, + fallbackTitle: fallbackTitle, + openDetails: openDetails, + openComputer: { showingComputer = true }, + openRoutines: { + if let pod, let agent = kind.agent { openPage(.routines(pod, agent: agent)) } + } + ) + } + .safeAreaInset(edge: .bottom, spacing: 0) { foot(kind: kind, pod: pod) } + .toolbar(.hidden, for: .navigationBar) + .sheet(item: $sideThread) { side in + SideThreadSheet(threadId: side.id, conversationId: model.conversationId, entry: model.entries.first { $0.threadId == side.id }, chatAgentId: kind.agent?.id) { + openSideThread($0) + } + } + .sheet(isPresented: $showingComputer) { + if let agent = kind.agent { ComputerSheet(agent: agent, conversationId: model.conversationId) } + } + .onAppear { + if attachments == nil { attachments = ComposerAttachments(conversationId: model.conversationId, client: store.client) } + } + #if DEBUG + .task { await poseForScreenshot() } + #endif + .onChange(of: draft) { _, text in drafts?.save(text: text) } + .onChange(of: replyingTo) { _, reply in drafts?.save(reply: reply) } + .task(id: model.thread?.podId) { + // What was being written here last, kept on the device as the web keeps it in the browser. + guard let drafts, draft.isEmpty else { return } + draft = drafts.text() + replyingTo = drafts.reply() + } + .task(id: model.thread?.podId) { + guard let podId = model.thread?.podId else { return } + looks = await store.connectionLooks(podId: podId) + } + } + + private var kind: ConversationKind { store.kind(of: model) } + + /// Where this conversation's drafts are kept, once its thread has loaded. + private var drafts: Drafts? { + guard let podId = model.thread?.podId else { return nil } + return Drafts(userId: store.user.id, podId: podId, conversationId: model.conversationId) + } + + private var host: AgentParticipant? { + guard let agent = kind.agent else { return nil } + return model.details?.participants.compactMap(\.agent).first { $0.id == agent.id } ?? AgentParticipant(agent) + } + + // MARK: The log + + @ViewBuilder private func log(kind: ConversationKind, pod: Pod?, scroller: ScrollViewProxy) -> some View { + if let details = model.details, let pod, let context = model.messageContext(looks: looks, filesConversationId: model.conversationId) { + let items = model.items + let routineFeed = model.isRoutineFeed + let byMessage = Self.threadsByMessage(items) + let groups = ChatGroups.of(items, byRun: routineFeed, under: Set(byMessage.values.flatMap { $0 }.map(\.id))) + let actions = messageActions(kind: kind, pod: pod, scroller: scroller) + if model.messagesFailed { + FormAlert(text: "Messages could not be loaded. Reload this page to try again.").padding(.horizontal, 20) + } + if model.olderCursor != nil { + Button(model.loadingOlder ? "Loading…" : "Load older messages") { Task { await model.loadOlder() } } + .font(Typeface.rubik(14, .medium)) + .foregroundStyle(Palette.foreground) + .disabled(model.loadingOlder) + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + } else if model.pagesLoaded > 0 { + Intro(details: details, kind: kind, pod: pod) + } + ForEach(groups) { group in + if group.separated { + LabelledDivider(text: routineFeed ? Self.runWords(group.at) : Times.day(group.at), strong: !routineFeed) + } + switch group.content { + case let .messages(messages): + ForEach(Array(messages.enumerated()), id: \.element.id) { index, message in + let previous = index > 0 ? messages[index - 1] : nil + if case .routineTrigger = message.author { + RoutineTriggerCard(message: message) + } else { + MessageRow( + message: message, + startsGroup: ChatGroups.startsGroup(previous, message), + context: context, + actions: actions, + highlighted: highlighted == message.id, + heldOpen: heldMessageId == message.id, + startedThreads: byMessage[message.id] ?? [] + ) + .id(message.id) + } + } + case let .thread(thread): + ThreadLine(item: thread, startedBy: nil) { openThread(thread) } + .padding(.leading, MessageRow.wordsInset) + .padding(.trailing, 20) + .padding(.vertical, 2) + case let .paused(at): + PausedLine(at: at) + case let .run(run): + if let routine = details.routine, let host { + RunMessage( + item: run, + agent: host, + pod: pod, + routine: routine, + latest: routine.failed && run.id == Self.latestRunId(items), + mentionable: model.mentionable + ) + } else { + ActivityRow(run: run, entry: model.entries.first { $0.threadId == run.threadId }) { openSideThread(run.threadId) } + } + } + } + if let routine = details.routine { + NextRunDivider(routine: routine) + } + if focusNotFound { + Text("Could not find the message you opened in this chat.") + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity) + .padding(.vertical, 8) + } + ForEach(Array(model.notices.enumerated()), id: \.offset) { index, notice in + Text(notice) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.destructiveText) + .frame(maxWidth: .infinity) + .padding(.top, index == 0 ? 12 : 4) + } + } else if let error = model.loadError { + EmptyState(title: "Could not load this conversation", text: error).frame(minHeight: 320) + } + } + + private func messageActions(kind: ConversationKind, pod: Pod, scroller: ScrollViewProxy) -> MessageActions { + let channel: Bool = switch kind { + case .podChat, .botChannel: true + default: false + } + return MessageActions( + reply: { message in + replyingTo = MessageReplyTo(id: message.id, author: message.author, preview: Previews.quoted(message)) + composing = true + }, + startThread: channel ? { message in startThread(from: message) } : nil, + react: { message, emoji in Task { await model.toggleReaction(emoji, on: message) } }, + openThread: { openSideThread($0) }, + openStartedThread: { openThread($0) }, + openArtifact: { artifact in openPage(.artifact(podId: pod.id, artifactId: artifact.artifactId, version: artifact.version)) }, + openDesktop: { showingComputer = true }, + jumpTo: { messageId in + withAnimation { scroller.scrollTo(messageId, anchor: .center) } + Task { await pointOut(messageId) } + } + ) + } + + // MARK: The foot + + @ViewBuilder private func foot(kind: ConversationKind, pod: Pod?) -> some View { + if let details = model.details, let pod { + VStack(alignment: .leading, spacing: 0) { + if let agent = kind.agent, agent.model == nil { + AgentNotSetUp(agent: agent, pod: pod) + } else { + Composer( + label: composerLabel(kind: kind, pod: pod, details: details), + text: $draft, + mentionable: composerMentionable(kind: kind), + replyingTo: replyingTo, + cancelReply: { replyingTo = nil }, + attachments: attachments, + sending: sending, + error: sendError, + submit: submit, + edited: { + if !draft.isEmpty { model.noteTyping() } + }, + focused: $composing + ) + } + let typers = typingNames() + Group { + if !typers.isEmpty { + TypingIndicator(names: typers).padding(.horizontal, 4) + } else if let hint = hint(kind: kind) { + Text(hint) + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 4) + .padding(.vertical, 4) + } + } + .frame(minHeight: 8, alignment: .leading) + } + .padding(.horizontal, barSideInset) + .padding(.top, 4) + // Clear of the keyboard while typing, as the tab bar keeps it clear of the foot otherwise, + // on frost that runs into the keyboard's glass rather than a band of the page's colour over it. + .padding(.bottom, composing ? Self.keyboardGap : 0) + .background { + if composing { + Rectangle().fill(.regularMaterial).ignoresSafeArea(edges: .bottom) + } else { + Palette.background + } + } + } + } + + private func composerLabel(kind: ConversationKind, pod: Pod, details: ThreadDetails) -> String { + let mentioned = Mentions.mentioned(in: draft, among: model.mentionable) + if botStaysOut(mentioned: mentioned), !mentioned.isEmpty { + return "Message \(Names.list(mentioned.map(\.name)))" + } + if details.routine != nil, let agent = kind.agent { return "Message \(agent.name) about this routine" } + if let agent = kind.agent { return "Message \(agent.name)" } + if case let .podChat(name) = kind { return "Message \(name)" } + return "Message \(pod.name)" + } + + /// The people here and this chat's own bot, not yourself, then `@here` and `@channel` where they notify somebody; + /// the pod's other bots are offered only in the pod's chat, where naming one starts a thread with it. + private func composerMentionable(kind: ConversationKind) -> [MentionTarget] { + let isPodChat: Bool = if case .podChat = kind { true } else { false } + let offered = model.mentionable.filter { member in + member.id != store.user.id && (member.agent == nil || isPodChat || member.id == host?.id) + } + let groups = Mentions.groupMentions( + writtenBy: store.user.id, + members: model.details?.members ?? [], + threadType: model.details?.thread.type + ) + return offered.map(MentionTarget.participant) + groups.map(\.target) + } + + /// Whether a bot's thread's draft leaves the bot out: it mentions somebody, and only people. + private func botStaysOut(mentioned: [ThreadParticipant]) -> Bool { + host != nil && !Mentions.handles(in: draft).isEmpty && !mentioned.contains { $0.agent != nil } + } + + private func hint(kind: ConversationKind) -> String? { + if case .podChat = kind { + return model.threadBot(for: draft).map { "Sending starts a thread with \($0.name)." } ?? "Mention a bot to start a thread." + } + if let host, botStaysOut(mentioned: Mentions.mentioned(in: draft, among: model.mentionable)) { + return "\(host.name) won't reply." + } + return nil + } + + /// Who is typing, by name: a bot whose newest message is still coming, then people. + private func typingNames() -> [String] { + let people = model.peopleTyping.map(\.name) + guard let last = model.items.last?.message, last.author.agentParticipant != nil, ChatGroups.isTyping(last) else { return people } + return [last.author.name] + people + } + + // MARK: Doing things + + private func submit() { + guard !sending else { return } + sendError = nil + let submitted = draft + let answering = replyingTo + draft = "" + replyingTo = nil + sending = true + Task { + if case let .failed(reason) = await model.submit(submitted, replyTo: answering, attachments: attachments) { + // What was sent goes back, unless the person has started writing something else meanwhile. + if draft.isEmpty { draft = submitted } + if replyingTo == nil { replyingTo = answering } + sendError = reason + } + sending = false + } + } + + private func startThread(from message: Message) { + if let run = message.routineResultOf { + openSideThread(run.threadId) + return + } + Task { + do { + let thread = try await model.thread(from: message) + openPage(.conversation(threadId: thread.id, title: thread.title)) + } catch { + sendError = "The thread was not started. Try again." + } + } + } + + /// Jumps to the message the page opened at, once the conversation has + /// loaded, loading older pages to find it, up to `focusSearchPages`. + private func jumpToFocus(_ scroller: ScrollViewProxy) async { + guard let focusMessageId, !jumpedToFocus, model.isLoaded else { return } + jumpedToFocus = true + guard await model.loadUntilShown(messageId: focusMessageId, maxPages: Self.focusSearchPages) else { + focusNotFound = true + return + } + try? await Task.sleep(for: Self.jumpAfterLayout) + scroller.scrollTo(focusMessageId, anchor: .center) + await pointOut(focusMessageId) + } + + /// Highlights a message jumped to for a moment, unless another is jumped to meanwhile. + private func pointOut(_ messageId: String) async { + highlighted = messageId + try? await Task.sleep(for: Self.pointedOutFor) + if highlighted == messageId { highlighted = nil } + } + + private func openThread(_ thread: ChatMessageItem.Thread) { + openPage(.conversation(threadId: thread.threadId, title: thread.title)) + } + + /// A collaboration or a run, which opens in a sheet over the conversation. + private func openSideThread(_ threadId: String) { + sideThread = SideThread(id: threadId) + } + + private func markRead() { + Task { await model.markRead() } + } + + #if DEBUG + /// Poses the conversation for a screenshot, once it has settled, as the + /// launch environment asks (see `DebugLaunch.once`): the composer with the + /// keyboard, Details open over it, or its newest finished message held. + private func poseForScreenshot() async { + let typing = DebugLaunch.once("SUGABOTS_TYPING") + let openingDetails = DebugLaunch.once("SUGABOTS_DETAILS") + let holding = DebugLaunch.once("SUGABOTS_HOLD") + guard typing || openingDetails || holding else { return } + try? await Task.sleep(for: .seconds(1.5)) + if typing { composing = true } + if openingDetails { openDetails() } + if holding { heldMessageId = model.items.last { $0.message?.status == .complete }?.message?.id } + } + #endif + + // MARK: Helpers + + /// The threads started from each message, by the message's id. + static func threadsByMessage(_ items: [ChatMessageItem]) -> [String: [ChatMessageItem.Thread]] { + let messageIds = Set(items.compactMap(\.message?.id)) + var byMessage: [String: [ChatMessageItem.Thread]] = [:] + for case let .thread(thread) in items { + guard let origin = thread.originMessageId, messageIds.contains(origin) else { continue } + byMessage[origin, default: []].append(thread) + } + return byMessage + } + + static func latestRunId(_ items: [ChatMessageItem]) -> String? { + for item in items.reversed() { + if case let .routine(run) = item { return run.id } + } + return nil + } + + /// `Run today`, `Run yesterday`, `Run on Mar 3`. + static func runWords(_ at: Date) -> String { + switch Times.daysAgo(at) { + case 0: return "Run today" + case 1: return "Run yesterday" + default: return "Run on \(Times.day(at))" + } + } +} + +/// A side thread open over a conversation, by its thread's id. +private struct SideThread: Identifiable { + let id: String +} + +/// A routine pausing itself, in its thread. +private struct PausedLine: View { + let at: Date + + var body: some View { + HStack(spacing: 8) { + Icon(.pause, size: 14, strokeWidth: 2) + Text("Paused after two failed runs in a row.").font(Typeface.rubik(13.5, .medium)) + Text(Times.list(at)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + .foregroundStyle(Palette.mutedForeground) + .padding(.leading, MessageRow.wordsInset) + .padding(.trailing, 20) + .padding(.vertical, 8) + } +} + +/// A routine's run in the channel it posts to: its trigger's mark, what it did, and the time, or dots while it runs. +private struct ActivityRow: View { + let run: ChatMessageItem.Routine + let entry: ChatHistoryEntry? + let open: () -> Void + + var body: some View { + let state = ActivityState(historyEntry: entry) + Button(action: open) { + HStack(spacing: 14) { + Group { + if state == .failed { + Text("!") + .font(Typeface.rubik(10, .bold)) + .foregroundStyle(.white) + .frame(width: 15, height: 15) + .background(Palette.destructive, in: Circle()) + } else { + Icon(TriggerIcons.of(run.triggerKind), size: 15, strokeWidth: 2.2) + } + } + .foregroundStyle(Palette.mutedForeground) + .frame(width: 36) + Text(state.routineText(run.routineName)) + .font(Typeface.rubik(13.5, .medium)) + .foregroundStyle(Palette.mutedForeground) + .lineLimit(1) + if state == .running { + TypingDots(small: true).foregroundStyle(Palette.mutedForeground) + } else { + Text(Times.clock(run.createdAt)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 20) + .padding(.vertical, 6) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Open Routine run: \(state.routineText(run.routineName))") + } +} + +/// A bot with no model yet, in place of the composer: it can't answer, and who can fix it. +private struct AgentNotSetUp: View { + let agent: Agent + let pod: Pod + @Environment(\.openPage) private var openPage + + var body: some View { + Group { + if pod.permissions.updateAgents { + Button { openPage(.settings(.agent(pod, agent))) } label: { + (Text("\(agent.name) has no model yet, so it cannot answer. ") + + Text("Choose a model").foregroundStyle(Palette.foreground).fontWeight(.medium) + + Text(" to start chatting.")) + .multilineTextAlignment(.leading) + } + .buttonStyle(.plain) + } else { + Text("\(agent.name) has no model yet, so it cannot answer. Somebody who can edit this agent chooses its model.") + } + } + .font(Typeface.rubik(15)) + .lineSpacing(4) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 16) + .padding(.vertical, 14) + .frame(maxWidth: .infinity, alignment: .leading) + .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Palette.borderStrong)) + } +} + +/// What the person was writing in one conversation, kept on the device as +/// the web's `useChatDraft` keeps it in the browser: the text, and the message +/// it replies to. +struct Drafts { + let userId: String + let podId: String + let conversationId: String + + /// What is kept, each under a key of its own, as the web names them. + private enum Slot: String { + case text = "draft" + case reply = "draft-reply" + } + + private func key(_ slot: Slot) -> String { + "sugabots-\(slot.rawValue):\(userId):\(podId):\(conversationId)" + } + + func text() -> String { + UserDefaults.standard.string(forKey: key(.text)) ?? "" + } + + /// Keeps `text`, or forgets it when it's blank. + func save(text: String) { + let blank = text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + store(blank ? nil : text, in: .text) + } + + func reply() -> MessageReplyTo? { + guard let json = UserDefaults.standard.string(forKey: key(.reply)), let data = json.data(using: .utf8) else { return nil } + return try? JSONDecoder().decode(MessageReplyTo.self, from: data) + } + + /// Keeps `reply`, or forgets it when there's none. + func save(reply: MessageReplyTo?) { + let json = reply.flatMap { try? JSONEncoder().encode($0) }.flatMap { String(data: $0, encoding: .utf8) } + store(json, in: .reply) + } + + private func store(_ value: String?, in slot: Slot) { + if let value { + UserDefaults.standard.set(value, forKey: key(slot)) + } else { + UserDefaults.standard.removeObject(forKey: key(slot)) + } + } +} + +/// Keeps a short conversation at the foot of its scroll view, just over the +/// composer. iOS 18 does this itself with the scroll view's bottom anchor. Before +/// it, the list is given at least the scroll view's height, aligned to its foot. +/// Not from iOS 18 on: there that frame leaves a long conversation blank when it +/// arrives all at once, until something lays the list out again. +private struct FootOfShortConversation: ViewModifier { + let height: CGFloat + + func body(content: Content) -> some View { + if #available(iOS 18, *) { + content + } else { + content.frame(minHeight: height, alignment: .bottom) + } + } +} diff --git a/apps/ios/Sugabots/Conversation/DesktopView.swift b/apps/ios/Sugabots/Conversation/DesktopView.swift new file mode 100644 index 000000000..df46efe8f --- /dev/null +++ b/apps/ios/Sugabots/Conversation/DesktopView.swift @@ -0,0 +1,78 @@ +import SwiftUI +import WebKit + +/// A bot's desktop over the whole screen: the web app's own phone desktop +/// (noVNC over the API's WebSocket, with Close and Take over) in a web view +/// signed in with the person's session, which closes when the page does. +@MainActor +struct DesktopView: View { + let pod: Pod + let conversationId: String + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + + var body: some View { + DesktopWebView(url: store.webURL("pods/\(pod.slug)/threads/\(conversationId)").appending(queryItems: [URLQueryItem(name: "desktop", value: "true")]), cookieDomain: store.client.baseURL.host()) { + dismiss() + } + .ignoresSafeArea() + .background(Color.black.ignoresSafeArea()) + } +} + +private struct DesktopWebView: UIViewRepresentable { + let url: URL + let cookieDomain: String? + let closed: () -> Void + + /// Reports when the page no longer shows the desktop, as its Close leaves it. + private static let watchClose = """ + (() => { + const report = () => { + if (!new URLSearchParams(location.search).has("desktop")) window.webkit.messageHandlers.desktop.postMessage("closed"); + }; + for (const name of ["pushState", "replaceState"]) { + const original = history[name]; + history[name] = function (...args) { const result = original.apply(this, args); report(); return result; }; + } + addEventListener("popstate", report); + })(); + """ + + func makeCoordinator() -> Coordinator { Coordinator(closed: closed) } + + func makeUIView(context: Context) -> WKWebView { + let configuration = WKWebViewConfiguration() + configuration.userContentController.add(context.coordinator, name: "desktop") + configuration.userContentController.addUserScript(WKUserScript(source: Self.watchClose, injectionTime: .atDocumentStart, forMainFrameOnly: true)) + let view = WKWebView(frame: .zero, configuration: configuration) + view.isOpaque = false + view.backgroundColor = .black + view.scrollView.contentInsetAdjustmentBehavior = .never + // The session the app signed in with, as a cookie, so the page and its desktop socket are the person's. + let cookies = (HTTPCookieStorage.shared.cookies ?? []).filter { cookie in + guard let cookieDomain else { return false } + return cookieDomain.hasSuffix(cookie.domain.trimmingCharacters(in: CharacterSet(charactersIn: "."))) + } + let store = configuration.websiteDataStore.httpCookieStore + Task { @MainActor in + for cookie in cookies { await store.setCookie(cookie) } + view.load(URLRequest(url: url)) + } + return view + } + + func updateUIView(_: WKWebView, context _: Context) {} + + final class Coordinator: NSObject, WKScriptMessageHandler { + let closed: () -> Void + + init(closed: @escaping () -> Void) { + self.closed = closed + } + + func userContentController(_: WKUserContentController, didReceive _: WKScriptMessage) { + closed() + } + } +} diff --git a/apps/ios/Sugabots/Conversation/MentionEditor.swift b/apps/ios/Sugabots/Conversation/MentionEditor.swift new file mode 100644 index 000000000..c3606b301 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/MentionEditor.swift @@ -0,0 +1,231 @@ +import SwiftUI +import UIKit + +/// The composer's text, as the web's `MentionEditor`: plain text with +/// `@handle` for a mention, but each finished mention of somebody it knows +/// drawn as a chip, their face and name, kept whole and removed with one +/// Backspace. A mention is finished once whitespace follows it, so one still +/// being typed stays text for the mention menu to complete. +struct MentionEditor: UIViewRepresentable { + @Binding var text: String + @Binding var isFocused: Bool + let mentionable: [MentionTarget] + /// The longest a draft may run: the longest message the API takes. + var maxLength = Limits.messageMaxLength + /// How many lines it grows to before it scrolls. + var maxLines = 8 + /// Told of each edit the person makes, never of the text being set from outside. + var edited: () -> Void = {} + + private static let font = UIFont(name: "Rubik", size: 16) ?? .systemFont(ofSize: 16) + + func makeCoordinator() -> Coordinator { Coordinator(self) } + + func makeUIView(context: Context) -> UITextView { + let view = UITextView() + view.delegate = context.coordinator + view.font = Self.font + view.textColor = UIColor(Palette.foreground) + view.backgroundColor = .clear + view.textContainerInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0) + view.textContainer.lineFragmentPadding = 4 + view.isScrollEnabled = false + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + view.autocorrectionType = .default + view.typingAttributes = Coordinator.plainAttributes + context.coordinator.render(text, in: view, caret: text.utf16.count) + // The chips are images drawn in one appearance, so they're drawn again when it changes. + view.registerForTraitChanges([UITraitUserInterfaceStyle.self]) { [coordinator = context.coordinator] (view: UITextView, _) in + let plain = Coordinator.plainText(of: view.attributedText) + coordinator.render(plain, in: view, caret: Coordinator.plainOffset(of: view.attributedText, at: view.selectedRange.location)) + } + return view + } + + func updateUIView(_ view: UITextView, context: Context) { + context.coordinator.parent = self + if Coordinator.plainText(of: view.attributedText) != text { + context.coordinator.render(text, in: view, caret: text.utf16.count) + } + if isFocused, !view.isFirstResponder { + DispatchQueue.main.async { view.becomeFirstResponder() } + } else if !isFocused, view.isFirstResponder { + DispatchQueue.main.async { view.resignFirstResponder() } + } + } + + func sizeThatFits(_ proposal: ProposedViewSize, uiView view: UITextView, context _: Context) -> CGSize? { + let width = proposal.width ?? 280 + let fitting = view.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)) + let lineHeight = Self.font.lineHeight + let most = lineHeight * CGFloat(maxLines) + view.textContainerInset.top + view.textContainerInset.bottom + view.isScrollEnabled = fitting.height > most + return CGSize(width: width, height: min(fitting.height, most)) + } + + @MainActor + final class Coordinator: NSObject, UITextViewDelegate { + var parent: MentionEditor + + static let plainAttributes: [NSAttributedString.Key: Any] = [ + .font: MentionEditor.font, + .foregroundColor: UIColor(Palette.foreground), + ] + + init(_ parent: MentionEditor) { + self.parent = parent + } + + func textViewDidBeginEditing(_: UITextView) { + if !parent.isFocused { parent.isFocused = true } + } + + func textViewDidEndEditing(_: UITextView) { + if parent.isFocused { parent.isFocused = false } + } + + func textView(_ view: UITextView, shouldChangeTextIn range: NSRange, replacementText replacement: String) -> Bool { + let current = Self.plainText(of: view.attributedText).utf16.count + let removed = Self.plainLength(of: view.attributedText, in: range) + return current - removed + replacement.utf16.count <= parent.maxLength + } + + func textViewDidChange(_ view: UITextView) { + let plain = Self.plainText(of: view.attributedText) + let caret = Self.plainOffset(of: view.attributedText, at: view.selectedRange.location) + parent.text = plain + parent.edited() + // Draw any mention finished by this edit as a chip. + if Self.segments(of: plain, mentionable: parent.mentionable).contains(where: \.isMention) { + render(plain, in: view, caret: caret) + } + } + + /// Draws `plain` with its finished mentions as chips, and puts the caret back where it was in the text. + func render(_ plain: String, in view: UITextView, caret: Int) { + let rendered = NSMutableAttributedString() + var location = 0 + var caretLocation = 0 + var placed = false + for segment in Self.segments(of: plain, mentionable: parent.mentionable) { + let length = segment.text.utf16.count + if !placed, caret <= location + length { + caretLocation = rendered.length + (segment.isMention ? (caret == location ? 0 : 1) : caret - location) + placed = true + } + if let target = segment.target { + rendered.append(Self.chip(for: target, handle: segment.text, traits: view.traitCollection)) + } else { + rendered.append(NSAttributedString(string: segment.text, attributes: Self.plainAttributes)) + } + location += length + } + if !placed { caretLocation = rendered.length } + view.attributedText = rendered + view.typingAttributes = Self.plainAttributes + view.selectedRange = NSRange(location: min(caretLocation, rendered.length), length: 0) + view.invalidateIntrinsicContentSize() + } + + // MARK: Text and chips + + struct Segment { + let text: String + var target: MentionTarget? + var isMention: Bool { target != nil } + } + + /// `plain` split around its finished mentions of somebody in `mentionable`. + static func segments(of plain: String, mentionable: [MentionTarget]) -> [Segment] { + var segments: [Segment] = [] + var rest = plain[...] + while let match = rest.firstMatch(of: Mentions.finished) { + let before = rest[.. String { + var plain = "" + attributed.enumerateAttributes(in: NSRange(location: 0, length: attributed.length)) { attributes, range, _ in + if let handle = attributes[.mentionHandle] as? String { + plain += handle + } else { + plain += (attributed.string as NSString).substring(with: range) + } + } + return plain + } + + /// Where `location` in the drawn text falls in the plain text. + static func plainOffset(of attributed: NSAttributedString, at location: Int) -> Int { + plainLength(of: attributed, in: NSRange(location: 0, length: min(location, attributed.length))) + } + + static func plainLength(of attributed: NSAttributedString, in range: NSRange) -> Int { + var length = 0 + attributed.enumerateAttributes(in: range) { attributes, part, _ in + length += (attributes[.mentionHandle] as? String)?.utf16.count ?? part.length + } + return length + } + + /// A mention as a chip: a bot's face and name, or a person's or everyone's `@handle`, on + /// the chip colour, drawn in the appearance of the text it sits in. That is + /// the theme chosen on You, which needn't be the device's, so `traits` are + /// the text view's rather than whatever traits are current. + static func chip(for target: MentionTarget, handle: String, traits: UITraitCollection) -> NSAttributedString { + let scheme: ColorScheme = traits.userInterfaceStyle == .dark ? .dark : .light + let renderer = ImageRenderer(content: MentionChipImage(target: target).environment(\.colorScheme, scheme)) + renderer.scale = traits.displayScale + let attachment = NSTextAttachment() + var drawn: UIImage? + traits.performAsCurrent { drawn = renderer.uiImage } + if let image = drawn { + attachment.image = image + // Sat on the text's baseline, as the web's `align-[-0.15em]`. + attachment.bounds = CGRect(x: 0, y: font.descender + 1, width: image.size.width, height: image.size.height) + } + let chip = NSMutableAttributedString(attachment: attachment) + chip.addAttributes([.mentionHandle: handle, .font: font], range: NSRange(location: 0, length: chip.length)) + return chip + } + } +} + +extension NSAttributedString.Key { + /// The `@handle` a mention chip stands for in the draft's text. + static let mentionHandle = NSAttributedString.Key("sugabotsMentionHandle") +} + +/// A mention chip as the web's `MentionChip` draws it in the composer. +private struct MentionChipImage: View { + let target: MentionTarget + + var body: some View { + HStack(spacing: 4) { + if case let .participant(.agent(agent)) = target { + BotFace(look: agent.look, size: 14) + Text(agent.name) + } else { + Text("@\(target.handle)") + } + } + .font(Typeface.rubik(16, .semibold)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 4) + .padding(.vertical, 1) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 5, style: .continuous)) + .padding(.horizontal, 1) + } +} diff --git a/apps/ios/Sugabots/Conversation/MessageFiles.swift b/apps/ios/Sugabots/Conversation/MessageFiles.swift new file mode 100644 index 000000000..bf77999a8 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/MessageFiles.swift @@ -0,0 +1,258 @@ +import SwiftUI +import UIKit + +/// The files on a message, as the web's `MessageFiles`: pictures as tiles, +/// which open over the screen, and other files as chips with their kind, +/// size and Download. +@MainActor +struct MessageFiles: View { + let files: [FilePart] + let conversationId: String + /// Whether the server has them yet; a message being sent has none to show. + let sent: Bool + + var body: some View { + let images = files.filter { FileLook.of($0) == .image } + let others = files.filter { FileLook.of($0) != .image } + VStack(alignment: .leading, spacing: 6) { + if images.count == 1, let only = images.first { + ImageTile(file: only, conversationId: conversationId, sent: sent, fit: .fit) + .aspectRatio(4 / 3, contentMode: .fit) + .frame(maxWidth: 360) + } else if !images.isEmpty { + let columns = images.count == 2 ? 2 : 3 + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: columns), spacing: 4) { + ForEach(images) { file in + ImageTile(file: file, conversationId: conversationId, sent: sent, fit: .fill) + .aspectRatio(4 / 3, contentMode: .fit) + } + } + .frame(maxWidth: images.count == 2 ? 320 : 482) + } + ForEach(others) { file in + FileChip(file: file, conversationId: conversationId, sent: sent) + } + } + .padding(.top, 6) + } +} + +extension FileLook { + var icon: Lucide { + switch self { + case .pdf: .fileText + case .sheet: .fileSpreadsheet + default: .fileIcon + } + } +} + +/// A file's bytes, fetched with the person's token, kept on disk under its name so it can be shared or opened. +@MainActor +enum ChatFiles { + /// The files fetched lately, by id, oldest first, at most `cacheLimit` of them. + private static var cache: [(fileId: String, url: URL)] = [] + /// How many fetched files stay on disk; fetching another deletes the oldest. + private static let cacheLimit = 50 + + /// `file` on disk, in a folder of its own under the temporary directory, fetched unless it was lately. + static func local(_ file: FilePart, in conversationId: String, client: APIClient) async throws -> URL { + if let cached = cache.first(where: { $0.fileId == file.id })?.url, FileManager.default.fileExists(atPath: cached.path()) { + return cached + } + let data = try await client.chats.file(conversationId: conversationId, fileId: file.id) + let folder = FileManager.default.temporaryDirectory.appending(path: "chat-files").appending(path: pathComponent(file.id, else: "file")) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let url = folder.appending(path: pathComponent(file.name, else: file.id)) + try data.write(to: url) + remember(url, for: file.id) + return url + } + + /// `name` as one name in a folder, so it can't reach outside it: its last + /// part after any `/`, or `fallback` when that is empty, `.` or `..`. + private static func pathComponent(_ name: String, else fallback: String) -> String { + let last = name.split(separator: "/").last.map(String.init) ?? "" + return last.isEmpty || last == "." || last == ".." ? fallback : last + } + + private static func remember(_ url: URL, for fileId: String) { + cache.removeAll { $0.fileId == fileId } + cache.append((fileId, url)) + while cache.count > cacheLimit { + let oldest = cache.removeFirst() + try? FileManager.default.removeItem(at: oldest.url.deletingLastPathComponent()) + } + } +} + +/// A button that fetches `file`, then offers it to save or share, as a phone +/// downloads; a failure shows as a toast. +@MainActor +struct ShareFileButton: View { + let file: FilePart + let conversationId: String + @ViewBuilder let label: Label + @Environment(WorkspaceStore.self) private var store + @Environment(Toaster.self) private var toaster + @State private var saved: SavedFile? + + var body: some View { + Button(action: fetch) { label } + .sheet(item: $saved) { saved in ShareSheet(items: [saved.url]) } + } + + private func fetch() { + Task { + do { + saved = SavedFile(url: try await ChatFiles.local(file, in: conversationId, client: store.client)) + } catch { + toaster.show(error.localizedDescription) + } + } + } +} + +@MainActor +private struct ImageTile: View { + let file: FilePart + let conversationId: String + let sent: Bool + let fit: ContentMode + @Environment(WorkspaceStore.self) private var store + @State private var image: UIImage? + @State private var undrawable = false + @State private var viewing = false + + var body: some View { + Button { viewing = true } label: { + ZStack { + Palette.tile + if let image { + Image(uiImage: image).resizable().aspectRatio(contentMode: fit) + } else if undrawable || !sent { + VStack(spacing: 4) { + Icon(.fileIcon, size: 18) + Text(file.name).font(Typeface.rubik(11)).lineLimit(1).truncationMode(.middle) + } + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 8) + } + } + .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.border)) + } + .buttonStyle(.plain) + .disabled(!sent) + .accessibilityLabel("Open \(file.name)") + .task(id: sent) { + guard sent, image == nil else { return } + guard let url = try? await ChatFiles.local(file, in: conversationId, client: store.client) else { + undrawable = true + return + } + image = UIImage(contentsOfFile: url.path()) + undrawable = image == nil + } + .fullScreenCover(isPresented: $viewing) { + ImageViewer(file: file, image: image, conversationId: conversationId) + } + } +} + +/// A picture over the whole screen on black: Close at the left, its name, and Download at the right. +private struct ImageViewer: View { + let file: FilePart + let image: UIImage? + let conversationId: String + @Environment(\.dismiss) private var dismiss + + var body: some View { + VStack(spacing: 12) { + HStack(spacing: 12) { + GlassRoundButton(icon: .x, label: "Close", iconSize: 20) { dismiss() } + Text(file.name) + .font(Typeface.rubik(15)) + .foregroundStyle(.white) + .lineLimit(1) + .truncationMode(.middle) + .frame(maxWidth: .infinity) + DownloadButton(file: file, conversationId: conversationId, round: true) + } + .padding(.horizontal, 16) + .pageTopPadding() + Group { + if let image { + Image(uiImage: image).resizable().scaledToFit() + } else { + Text("This picture can't be shown here. Download it to open it.") + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + .multilineTextAlignment(.center) + .padding(.horizontal, 16) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + .padding(.bottom, 16) + .background(Color.black.ignoresSafeArea()) + .environment(\.colorScheme, .dark) + } +} + +/// A file that isn't a picture: its kind's mark, its name, its kind and size, and Download. +private struct FileChip: View { + let file: FilePart + let conversationId: String + let sent: Bool + + var body: some View { + let ext = FileLook.extensionOf(file.name).uppercased() + HStack(spacing: 10) { + Icon(FileLook.of(file).icon, size: 16) + .foregroundStyle(Palette.softForeground) + .frame(width: 32, height: 32) + .background(Palette.tile, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + VStack(alignment: .leading, spacing: 1) { + Text(file.name).font(Typeface.rubik(14, .medium)).foregroundStyle(Palette.foreground).lineLimit(1).truncationMode(.middle) + Text((ext.isEmpty ? "" : "\(ext) · ") + FileLook.sizeLabel(file.size)) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, minHeight: 30, alignment: .leading) + if sent { DownloadButton(file: file, conversationId: conversationId, round: false) } + } + .padding(.vertical, 8) + .padding(.leading, 10) + .padding(.trailing, 8) + .background(Palette.card, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.border)) + } +} + +/// Download: fetches the file, then offers it to save or share, as a phone downloads. +private struct DownloadButton: View { + let file: FilePart + let conversationId: String + let round: Bool + + var body: some View { + ShareFileButton(file: file, conversationId: conversationId) { + Icon(.download, size: round ? 20 : 16, strokeWidth: 2) + .foregroundStyle(round ? Palette.foreground : Palette.mutedForeground) + .frame(width: round ? 44 : 30, height: round ? 44 : 30) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .modifier(GlassIf(on: round)) + .accessibilityLabel("Download \(file.name)") + } +} + +private struct GlassIf: ViewModifier { + let on: Bool + + func body(content: Content) -> some View { + if on { content.glass(in: Circle()) } else { content } + } +} diff --git a/apps/ios/Sugabots/Conversation/MessageMarkdown.swift b/apps/ios/Sugabots/Conversation/MessageMarkdown.swift new file mode 100644 index 000000000..ebd8f4a8b --- /dev/null +++ b/apps/ios/Sugabots/Conversation/MessageMarkdown.swift @@ -0,0 +1,238 @@ +import SwiftUI +import UIKit + +/// What a bot says, as the web's `MessageMarkdown` renders it: paragraphs, +/// headings sized for a message, lists, quotes, tables that scroll, code +/// blocks with Copy, and inline code and links in the bot's own colour. +/// Mentions show as chips. +struct MessageMarkdown: View { + let text: String + var mentionable: [ThreadParticipant] = [] + /// The bot's palette, for its links and inline code; nil in a person's words. + var palette: BotPalette? + /// The body's type size. + var size: CGFloat = 15 + + var body: some View { + let blocks = MarkdownBlocks.parse(text) + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(blocks.enumerated()), id: \.offset) { index, block in + view(for: block) + .padding(.top, index == 0 ? 0 : topGap(block)) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + + private func topGap(_ block: MarkdownBlocks.Block) -> CGFloat { + switch block { + case .heading: 16 + case .table: 16 + default: 12 + } + } + + @ViewBuilder private func view(for block: MarkdownBlocks.Block) -> some View { + switch block { + case let .paragraph(text): + inline(text) + case let .heading(level, text): + inline(text, size: headingSize(level: level), weight: .semibold) + .padding(.bottom, 4) + .accessibilityAddTraits(.isHeader) + case let .list(items, ordered, start): + VStack(alignment: .leading, spacing: 4) { + ForEach(Array(items.enumerated()), id: \.offset) { index, item in + HStack(alignment: .firstTextBaseline, spacing: 8) { + Group { + if let checked = item.checked { + Image(systemName: checked ? "checkmark.square.fill" : "square") + .font(.system(size: size * 0.9)) + .accessibilityLabel(checked ? "Done" : "Not done") + } else { + Text(ordered ? "\(start + index)." : "•").font(Typeface.rubik(size)) + } + } + .foregroundStyle(Palette.mutedForeground) + .frame(minWidth: 14, alignment: .trailing) + VStack(alignment: .leading, spacing: 4) { + inline(item.text) + if !item.children.isEmpty { + MessageMarkdown(text: item.children, mentionable: mentionable, palette: palette, size: size) + } + } + } + } + } + .padding(.leading, 4) + case let .quote(text): + MessageMarkdown(text: text, mentionable: mentionable, palette: palette, size: size) + .foregroundStyle(Palette.mutedForeground) + .padding(.leading, 12) + .overlay(alignment: .leading) { Rectangle().fill(Palette.borderStrong).frame(width: 3) } + case let .code(language, code): + CodeBlock(language: language, code: code) + case let .table(header, rows): + MarkdownTable(header: header, rows: rows) { inline($0, size: 14) } + case .rule: + Rectangle().fill(Palette.border).frame(height: 1).padding(.vertical, 8) + } + } + + /// The type size of a heading at `level`: three sizes for a message, then the body's. + private func headingSize(level: Int) -> CGFloat { + switch level { + case 1: HeadingSize.first + case 2: HeadingSize.second + case 3: HeadingSize.third + default: size + } + } + + private enum HeadingSize { + static let first: CGFloat = 24 + static let second: CGFloat = 20 + static let third: CGFloat = 18 + } + + /// One line of `text` with its inline marks, at `size`, the body's size when nil. + private func inline(_ text: String, size: CGFloat? = nil, weight: Font.Weight = .regular) -> some View { + let size = size ?? self.size + return Text(MarkdownInline.attributed(text, size: size, weight: weight, mentionable: mentionable, palette: palette)) + .lineSpacing(size * 0.5 - 4) + .foregroundStyle(Palette.bodyForeground) + .tint(palette?.mono.resolved ?? Palette.foreground) + // Not selectable: holding a message brings up its actions, Copy among them, as Slack's do. + .fixedSize(horizontal: false, vertical: true) + } +} + +/// A fenced code block: its language, Copy, and the code scrolling sideways. +private struct CodeBlock: View { + let language: String? + let code: String + @Environment(Toaster.self) private var toaster + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Text(language ?? "") + .font(Typeface.mono(12)) + .foregroundStyle(Palette.subtleForeground) + Spacer() + Button { + UIPasteboard.general.string = code + toaster.show("Copied") + } label: { + Icon(.copy, size: 14, strokeWidth: 2).frame(width: 28, height: 28) + } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("Copy code") + } + .padding(.leading, 12) + .padding(.trailing, 4) + .padding(.top, 4) + ScrollView(.horizontal, showsIndicators: false) { + Text(code) + .font(Typeface.mono(13)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 12) + .padding(.bottom, 12) + .padding(.top, 2) + } + } + .background(Palette.card, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.border)) + } +} + +/// A table that scrolls sideways when it is wider than the message. +private struct MarkdownTable: View { + let header: [String] + let rows: [[String]] + @ViewBuilder let cell: (String) -> Cell + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) { + GridRow { + ForEach(Array(header.enumerated()), id: \.offset) { _, title in + cell(title).fontWeight(.semibold).padding(.horizontal, 12).padding(.vertical, 8) + } + } + .background(Palette.card) + ForEach(Array(rows.enumerated()), id: \.offset) { _, row in + Divider().overlay(Palette.border) + GridRow { + ForEach(Array(row.enumerated()), id: \.offset) { _, value in + cell(value).padding(.horizontal, 12).padding(.vertical, 8) + } + } + } + } + .background(Palette.background) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(Palette.border)) + } + .padding(8) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.border)) + } +} + +/// One line of markdown's inline marks as styled text: emphasis, code in the +/// bot's tint, links in its colour, and mentions as bold chips. +enum MarkdownInline { + static func attributed(_ text: String, size: CGFloat, weight: Font.Weight, mentionable: [ThreadParticipant], palette: BotPalette?) -> AttributedString { + var attributed = MarkdownBlocks.inline(text) + attributed.font = Typeface.rubik(size, weight) + for run in attributed.runs { + let intent = run.inlinePresentationIntent ?? [] + if intent.contains(.code) { + attributed[run.range].font = Typeface.mono(13, .medium) + attributed[run.range].backgroundColor = palette?.tint.resolved ?? Palette.chip + attributed[run.range].foregroundColor = palette?.mono.resolved ?? Palette.foreground + } else if intent.contains(.stronglyEmphasized) && intent.contains(.emphasized) { + attributed[run.range].font = Typeface.rubik(size, .bold).italic() + } else if intent.contains(.stronglyEmphasized) { + attributed[run.range].font = Typeface.rubik(size, .bold) + } else if intent.contains(.emphasized) { + attributed[run.range].font = Typeface.rubik(size, weight).italic() + } + if intent.contains(.strikethrough) { + attributed[run.range].strikethroughStyle = .single + } + if run.link != nil { + attributed[run.range].foregroundColor = palette?.mono.resolved ?? Palette.foreground + attributed[run.range].underlineStyle = .single + } + } + Mentions.chip(in: &attributed, size: size, mentionable: mentionable.map(MentionTarget.participant)) + return attributed + } +} + +extension Mentions { + /// Marks each mention of somebody in `mentionable` as a chip: a bot by + /// its name, a person or everyone by `@handle`, in bold on the chip colour. + static func chip(in attributed: inout AttributedString, size: CGFloat, mentionable: [MentionTarget]) { + var chipped = AttributedString() + var offset = 0 + for piece in pieces(of: String(attributed.characters)) { + let written = piece.written + let start = attributed.index(attributed.startIndex, offsetByUnicodeScalars: offset) + let end = attributed.index(start, offsetByUnicodeScalars: written.unicodeScalars.count) + offset += written.unicodeScalars.count + guard case let .mention(handle) = piece, let target = target(withHandle: handle, among: mentionable) else { + chipped.append(attributed[start.. + /// Messages the server hasn't confirmed yet, by id. + let sending: Set + /// Whether the conversation is a routine's own thread, where a run's report needn't say which routine it's from. + let inRoutineThread: Bool + /// The person reading, whose reactions are theirs. + let userId: String + let conversationId: String +} + +/// What a message row can do, each absent where the conversation doesn't offer it. +struct MessageActions { + var reply: ((Message) -> Void)? + var startThread: ((Message) -> Void)? + var react: ((Message, String) -> Void)? + /// Opens a side thread, a collaboration or a run, by its thread's id. + var openThread: (String) -> Void + /// Opens a thread started from a message, on its own page. + var openStartedThread: ((ChatMessageItem.Thread) -> Void)? + var openArtifact: ((WrittenArtifact) -> Void)? + var openDesktop: (() -> Void)? + var jumpTo: ((String) -> Void)? +} + +/// One message, as the web's `MessageRow` draws it on a phone: its author's +/// face and name with Bot and the time when it starts a group, else its time +/// on a tap; then what it quotes, its steps, its words, approvals, files, +/// artifacts, the threads started from it, its reactions, and how it ended. +/// Held, it offers React, Reply, Start a thread and Copy text. +@MainActor +struct MessageRow: View { + let message: Message + let startsGroup: Bool + let context: MessageContext + let actions: MessageActions + var highlighted = false + /// Whether its actions are up without a touch, as a screenshot at launch asks. + var heldOpen = false + /// The threads started from it, each a line under its words. + var startedThreads: [ChatMessageItem.Thread] = [] + /// Smaller, as a side thread's sheet shows its messages. + var compact = false + @State private var timeTapped = false + @State private var pickingReaction = false + /// Whether the message is held, with what can be done with it slid up from the foot. + @State private var holding = false + /// Whether the emoji picker opens once the held message's sheet has gone. + @State private var pickAfterHolding = false + @Environment(Toaster.self) private var toaster + + /// How far a full-size row's words sit from its leading edge, past its face, + /// where lines between messages start so they line up with the words. + static let wordsInset = FaceColumn.full.wordsInset + + private var column: FaceColumn { compact ? .compact : .full } + + var body: some View { + let agent: AgentParticipant? = if case let .agent(agent) = message.author { agent } else { nil } + let segments = Segments.of(message) + let files = message.files + let held = heldActions(words: segments.compactMap(\.text).joined(separator: "\n\n")) + if !Segments.showsNothingYet(message) { + HStack(alignment: .top, spacing: column.gap) { + face + VStack(alignment: .leading, spacing: 0) { + if let replyTo = message.replyTo { + ReplyQuote(replyTo: replyTo, jump: actions.jumpTo) + } + if startsGroup { + AuthorLine(name: message.author.name, isBot: agent != nil, at: message.createdAt) + .padding(.bottom, 1) + } + if agent != nil { + ToolLine(parts: message.parts, looks: context.looks, fileNames: context.fileNames) + } + ForEach(segments) { segment in + segmentView(segment, agent: agent) + } + if !files.isEmpty { + MessageFiles(files: files, conversationId: context.conversationId, sent: !context.sending.contains(message.id)) + } + if let agent, let openArtifact = actions.openArtifact { + ArtifactCards(parts: message.parts, podId: context.podId, botName: agent.name, onOpen: openArtifact) + .padding(.top, 8) + } + ForEach(startedThreads) { thread in + ThreadLine(item: thread, startedBy: message.author) { actions.openStartedThread?(thread) } + } + MessageReactionsView( + message: message, + userId: context.userId, + addable: finished && actions.react != nil, + toggle: actions.react.map { react in { emoji in react(message, emoji) } } + ) { + pickingReaction = true + } + notes + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, column.sidePadding) + .padding(.top, startsGroup ? 14 : 2) + .padding(.bottom, 2) + .background(highlighted ? Palette.chip : .clear) + .animation(.easeOut(duration: 0.7), value: highlighted) + .contentShape(Rectangle()) + .onTapGesture { + guard !startsGroup else { return } + timeTapped.toggle() + } + .onLongPressGesture(minimumDuration: 0.35) { + guard held != nil else { return } + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + holding = true + } + .onChange(of: heldOpen, initial: true) { _, open in + if open { holding = true } + } + .sheet(isPresented: $holding, onDismiss: { + // One sheet at a time: the picker waits for the actions to slide away. + if pickAfterHolding { + pickAfterHolding = false + pickingReaction = true + } + }) { + if let held { held } + } + .sheet(isPresented: $pickingReaction) { + EmojiPicker(used: reactionEmoji) { emoji in + pickingReaction = false + addReaction(emoji) + } + } + .accessibilityElement(children: .contain) + .accessibilityLabel("\(message.author.name), \(statusWords)") + } + } + + private var finished: Bool { message.status == .complete && !context.sending.contains(message.id) } + + private var statusWords: String { + if context.queued.contains(message.id) { return "queued" } + if message.status == .failed { return "failed" } + if message.status == .cancelled { return "stopped" } + return Times.clock(message.createdAt) + } + + @ViewBuilder private var face: some View { + Group { + if startsGroup { + ParticipantFace(participant: message.author.participant, size: column.faceSize) + .padding(.top, 2) + } else { + Text(Times.clock(message.createdAt)) + .font(Typeface.rubik(11)) + .monospacedDigit() + .foregroundStyle(Palette.subtleForeground) + .frame(height: 22) + .opacity(timeTapped ? 1 : 0) + } + } + .frame(width: column.faceSize) + // A reply's face lines up with its author's name, under the quote. + .padding(.top, message.replyTo != nil ? 21 : 0) + .accessibilityHidden(true) + } + + @ViewBuilder private func segmentView(_ segment: Segments.Segment, agent: AgentParticipant?) -> some View { + switch segment.kind { + case let .collaboration(collaboration): + if let agent, let recipient = context.mentionable.compactMap(\.agent).first(where: { $0.id == collaboration.agentId }) { + SideThreadLine( + faces: [.agent(agent), .agent(recipient)], + label: "Asked \(recipient.name)", + description: "Open Collaboration: \(agent.name) and \(recipient.name)", + lastActivityAt: context.threadActivityAt[collaboration.threadId], + status: SideThreadStatus.of(collaboration: collaboration.status) + ) { actions.openThread(collaboration.threadId) } + } + case let .toolCall(call): + if let agent { + ApprovalCard(call: call, agent: agent, podId: context.podId, capabilities: context.capabilities, looks: context.looks) + .padding(.top, 6) + .padding(.bottom, 4) + } + case let .text(text): + if !text.isEmpty { + if let agent { + MessageMarkdown(text: text, mentionable: context.mentionable, palette: BotLooks.palette(for: agent.color), size: compact ? 14.5 : 15) + } else { + Text(MarkdownInline.plainWithMentions(text, by: message.author, mentionable: context.mentionable, size: compact ? 14.5 : 15)) + .lineSpacing(3.5) + .foregroundStyle(Palette.bodyForeground) + // Not selectable: holding a message brings up its actions, Copy among them. + .fixedSize(horizontal: false, vertical: true) + } + } + } + } + + @ViewBuilder private var notes: some View { + if let run = message.routineResultOf, !context.inRoutineThread { + Button { actions.openThread(run.threadId) } label: { + HStack(spacing: 2) { + Text("From \(run.routineName)") + Icon(.chevronRight, size: 12, strokeWidth: 2.4) + } + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.subtleForeground) + } + .buttonStyle(.plain) + .padding(.top, 4) + } + if message.status == .failed { + (Text("Reply failed.").fontWeight(.semibold) + Text(message.error.map { " \($0)" } ?? "")) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.destructiveText) + .padding(.top, 4) + } + if message.status == .cancelled { + Text("Reply stopped").font(Typeface.rubik(12, .semibold)).foregroundStyle(Palette.subtleForeground).padding(.top, 4) + } + if context.queued.contains(message.id) { + Text("Queued").font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground).padding(.top, 4) + } + } + + /// The different emoji the message has been reacted with. + private var reactionEmoji: Set { Set((message.reactions ?? []).map(\.emoji)) } + + /// Adds the person's `emoji` to the message as the picker chooses one: a + /// message with the most different emoji takes only one of those, and + /// `emoji` becomes the one chosen last on this device. + private func addReaction(_ emoji: String) { + guard EmojiPicker.admits(emoji, besides: reactionEmoji) else { return } + RecentEmoji.remember(emoji) + actions.react?(message, emoji) + } + + /// What holding the message offers, given its `words`; nil when it offers nothing. + private func heldActions(words: String) -> MessageActionsSheet? { + let sheet = MessageActionsSheet( + react: finished && actions.react != nil ? { emoji in + holding = false + addReaction(emoji) + } : nil, + pickReaction: { + pickAfterHolding = true + holding = false + }, + reply: finished && message.author.isReplyable ? actions.reply.map { reply in { holding = false; reply(message) } } : nil, + startThread: finished ? actions.startThread.map { start in { holding = false; start(message) } } : nil, + copy: words.isEmpty ? nil : { + holding = false + UIPasteboard.general.string = words + toaster.show("Copied") + } + ) + return sheet.isEmpty ? nil : sheet + } +} + +/// What can be done with a held message, slid up from the foot as Slack's is: +/// a row of quick reactions, then its actions as tiles. +private struct MessageActionsSheet: View { + /// Reacts with an emoji; nil when the message can't take reactions. + let react: ((String) -> Void)? + let pickReaction: () -> Void + let reply: (() -> Void)? + let startThread: (() -> Void)? + let copy: (() -> Void)? + @State private var height: CGFloat = 240 + + var isEmpty: Bool { react == nil && reply == nil && startThread == nil && copy == nil } + + /// How many emoji the quick row offers before the picker's button. + private static let quickCount = NativeConstants.quickReactionCount + /// What fills the quick row after the emoji chosen lately on this device. + private static let usualReactions = NativeConstants.usualReactions + + private var quick: [String] { + var seen = Set() + return (RecentEmoji.all + Self.usualReactions).filter { seen.insert($0).inserted }.prefix(Self.quickCount).map { $0 } + } + + var body: some View { + VStack(spacing: 18) { + SheetGrabber() + if let react { + HStack(spacing: 10) { + ForEach(quick, id: \.self) { emoji in + Button { react(emoji) } label: { + Text(emoji).font(.system(size: 26)).frame(maxWidth: .infinity).frame(height: 52) + .background(Palette.chip, in: Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel("React with \(emoji)") + } + Button(action: pickReaction) { + Image(systemName: "face.smiling").font(.system(size: 22, weight: .medium)) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity).frame(height: 52) + .background(Palette.chip, in: Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Add reaction") + } + } + HStack(spacing: 10) { + if let reply { tile("Reply", systemImage: "arrowshape.turn.up.left", action: reply) } + if let startThread { tile("Thread", systemImage: "text.bubble", action: startThread) } + if let copy { tile("Copy", systemImage: "doc.on.doc", action: copy) } + } + } + .padding(.horizontal, 16) + .padding(.bottom, 12) + .fixedSize(horizontal: false, vertical: true) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height = $0 } + .phoneSheet(detents: [.height(height)]) + } + + private func tile(_ title: String, systemImage: String, action: @escaping () -> Void) -> some View { + Button(action: action) { + VStack(spacing: 8) { + Image(systemName: systemImage).font(.system(size: 21, weight: .medium)) + Text(title).font(Typeface.rubik(14, .medium)) + } + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity) + .frame(height: 84) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } + .buttonStyle(.plain) + } +} + +/// The column a message row's face sits in: the row's side padding, the face, and the gap after it. +private struct FaceColumn { + let sidePadding: CGFloat + let faceSize: CGFloat + let gap: CGFloat + + static let full = FaceColumn(sidePadding: 20, faceSize: 36, gap: 14) + /// Smaller, as a side thread's sheet shows its messages. + static let compact = FaceColumn(sidePadding: 18, faceSize: 32, gap: 12) + + var wordsInset: CGFloat { sidePadding + faceSize + gap } +} + +/// Who wrote a group of messages: their name, Bot for a bot, and the time. +private struct AuthorLine: View { + let name: String + let isBot: Bool + let at: Date + + var body: some View { + HStack(spacing: 8) { + Text(name).font(Typeface.rubik(15, .semibold)).foregroundStyle(Palette.foreground).lineLimit(1) + if isBot { BotTag() } + Text(Times.clock(at)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + } +} + +/// The message a reply answers, in a line over it, which jumps to it. +private struct ReplyQuote: View { + let replyTo: MessageReplyTo + let jump: ((String) -> Void)? + + var body: some View { + Button { jump?(replyTo.id) } label: { + HStack(spacing: 4) { + Icon(.cornerUpLeft, size: 13, strokeWidth: 2.2) + Text("Replying to").fixedSize() + Text(replyTo.author.name).fontWeight(.semibold).foregroundStyle(Palette.softForeground).fixedSize() + Text(replyTo.preview).lineLimit(1).padding(.leading, 2) + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .frame(height: 21) + .padding(.horizontal, 4) + .padding(.leading, -4) + } + .buttonStyle(.plain) + .disabled(jump == nil) + .accessibilityLabel("Replying to \(replyTo.author.name): \(replyTo.preview)") + } +} + +/// A routine's trigger, as a card over the run it started. +struct RoutineTriggerCard: View { + let message: Message + + var body: some View { + if case let .routineTrigger(trigger) = message.author { + let source = switch trigger.triggerKind { + case .cron: "Scheduled trigger" + case .webhook: "Webhook trigger" + case .github: "Repository trigger" + case .manual, .unknown: "Manual run" + } + VStack(alignment: .leading, spacing: 4) { + (Text(trigger.routineName).fontWeight(.semibold) + Text(" \(source)")) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + Text(message.content) + .font(Typeface.rubik(13)) + .lineSpacing(4) + .foregroundStyle(Palette.bodyForeground) + .textSelection(.enabled) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border)) + .padding(.horizontal, 20) + .padding(.top, 14) + .accessibilityElement(children: .combine) + } + } +} + +/// How a side thread stands, at the end of its line. +enum SideThreadStatus: Equatable { + /// Moving, shown as typing dots. + case working + /// Waiting on the person, its words on the primary colour. + case urgent(String) + /// Finished, its words after a check. + case done(String) + /// Ended any other way, its words alone. + case ended(String) + + static func of(collaboration status: CollaborationStatus) -> SideThreadStatus { + switch status { + case .pending: .urgent("Needs approval") + case .answered: .done("Done") + case .failed: .ended("Stopped") + case .waiting, .unknown: .working + } + } +} + +/// A thread hanging off a message, as the web's `SideThreadLine` on a phone: +/// a hooked rule, the faces in it, its label with what it is and when it last +/// moved, and a chevron. +struct SideThreadLine: View { + let faces: [ThreadParticipant] + let label: String + var detail: String? + let description: String + var lastActivityAt: Date? + var status: SideThreadStatus? + let open: () -> Void + + var body: some View { + Button(action: open) { + HStack(spacing: 10) { + UnevenRoundedRectangle(bottomLeadingRadius: 7) + .stroke(Palette.borderDashed, lineWidth: 1) + .mask(alignment: .bottomLeading) { Rectangle().padding(.top, -1).padding(.trailing, 1) } + .frame(width: 10, height: 20) + .padding(.top, -4) + .frame(maxHeight: .infinity, alignment: .top) + HStack(spacing: -6) { + ForEach(Array(faces.enumerated()), id: \.offset) { _, face in + ParticipantFace(participant: face, size: 22) + .padding(1.5) + .background(Palette.background, in: Circle()) + } + } + .padding(.vertical, 4) + VStack(alignment: .leading, spacing: 2) { + Text(label) + .font(Typeface.rubik(14, .semibold)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + HStack(spacing: 6) { + if let detail { + Text(detail).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + statusView + if let lastActivityAt { + Text(Times.clock(lastActivityAt)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + Icon(.chevronRight, size: 16, strokeWidth: 2).foregroundStyle(Palette.disabledForeground) + } + .padding(.trailing, 6) + .frame(minHeight: 44) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(cornerRadius: 10)) + .padding(.top, 4) + .padding(.leading, 8) + .accessibilityLabel([description, statusText, lastActivityAt.map { "Last reply \(Times.clock($0))" }].compactMap { $0 }.joined(separator: ", ")) + } + + private var statusText: String? { + switch status { + case .working: "Working" + case let .urgent(text), let .done(text), let .ended(text): text + case nil: nil + } + } + + @ViewBuilder private var statusView: some View { + switch status { + case .working: + TypingDots(small: true).foregroundStyle(Palette.mutedForeground) + case let .urgent(text): + Text(text) + .font(Typeface.rubik(11.5, .semibold)) + .foregroundStyle(Palette.primaryForeground) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(Palette.primary, in: RoundedRectangle(cornerRadius: 5, style: .continuous)) + case let .done(text): + HStack(spacing: 4) { + Icon(.check, size: 12, strokeWidth: 2.25) + Text(text) + } + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + case let .ended(text): + Text(text) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + case nil: + EmptyView() + } + } +} + +/// A thread started from a message, under it: the faces in it, how many replies, its title and whether its bot is working. +struct ThreadLine: View { + let item: ChatMessageItem.Thread + let startedBy: MessageAuthor? + let open: () -> Void + + var body: some View { + var faces: [ThreadParticipant] = [] + if let starter = startedBy?.participant, starter.id != item.agent?.id { faces.append(starter) } + if let agent = item.agent { faces.append(.agent(agent)) } + let replied = item.replies > 0 + return SideThreadLine( + faces: faces, + label: replied ? Names.count(item.replies, "reply", "replies") : item.title, + detail: replied ? item.title : nil, + description: "Open thread: \(item.title)", + lastActivityAt: item.lastReplyAt, + status: item.working ? .working : nil, + open: open + ) + } +} + +/// Who is typing, with the dots, as the web's `TypingIndicator`. +struct TypingIndicator: View { + let names: [String] + + var body: some View { + let label = "\(Names.list(names)) \(names.count == 1 ? "is" : "are") typing" + HStack(spacing: 8) { + TypingDots(small: true) + Text(label) + } + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(Palette.mutedForeground) + .frame(height: 26) + .accessibilityElement(children: .ignore) + .accessibilityLabel(label) + } +} + +/// The emoji people reacted with, each with how many, which the person taps +/// to add theirs or take it back, then a button to add another. +struct MessageReactionsView: View { + let message: Message + let userId: String + let addable: Bool + /// Adds the person's reaction with an emoji, or takes it back; nil where + /// reactions can't be changed, and the chips only show them. + let toggle: ((String) -> Void)? + let add: () -> Void + + /// A chip's height: a fingertip's, as Slack's on a phone, larger than the web's. + private static let chipHeight = NativeConstants.reactionChipHeight + + var body: some View { + let reactions = message.reactions ?? [] + if !reactions.isEmpty { + FlowLayout(spacing: 6) { + ForEach(reactions, id: \.emoji) { reaction in + let mine = reaction.people.contains { $0.id == userId } + Group { + if let toggle { + Button { toggle(reaction.emoji) } label: { chip(reaction, mine: mine) } + .buttonStyle(.plain) + } else { + chip(reaction, mine: mine).accessibilityElement(children: .ignore) + } + } + .accessibilityLabel("\(reaction.emoji) \(reaction.people.count): \(Names.list(reaction.people.map { $0.id == userId ? "You" : $0.name }))") + .accessibilityAddTraits(mine ? .isSelected : []) + } + if addable { + Button(action: add) { + Icon(.smilePlus, size: 18, strokeWidth: 2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 52, height: Self.chipHeight) + .overlay(Capsule().strokeBorder(Palette.chipStrong)) + } + .buttonStyle(.plain) + .accessibilityLabel("Add reaction") + } + } + .padding(.top, 6) + } + } + + /// An emoji and how many reacted with it, marked when the person is among them. + private func chip(_ reaction: MessageReaction, mine: Bool) -> some View { + HStack(spacing: 5) { + Text(reaction.emoji).font(.system(size: 18)) + Text("\(reaction.people.count)").font(Typeface.rubik(14, .semibold)).monospacedDigit() + } + .foregroundStyle(mine ? Palette.foreground : Palette.softForeground) + .padding(.horizontal, 11) + .frame(height: Self.chipHeight) + .background(mine ? Palette.reactionMine : Palette.card, in: Capsule()) + .overlay(Capsule().strokeBorder(mine ? Palette.primary : Palette.chipStrong)) + } +} + +extension MarkdownInline { + /// Words as written, with mentions as chips. Only a person's can mention + /// everyone, with `@here` or `@channel`: a bot's or a routine's notify nobody. + static func plainWithMentions(_ text: String, by author: MessageAuthor, mentionable: [ThreadParticipant], size: CGFloat = 15) -> AttributedString { + var attributed = AttributedString(text) + attributed.font = Typeface.rubik(size) + var targets = mentionable.map(MentionTarget.participant) + if case .person = author { targets += Mentions.groupHandles.map { .group(handle: $0) } } + Mentions.chip(in: &attributed, size: size, mentionable: targets) + return attributed + } +} diff --git a/apps/ios/Sugabots/Conversation/NewThreadScreen.swift b/apps/ios/Sugabots/Conversation/NewThreadScreen.swift new file mode 100644 index 000000000..6bd2a24c2 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/NewThreadScreen.swift @@ -0,0 +1,218 @@ +import SwiftUI + +/// Starting a thread, as the web's `NewThread` on a phone. With a bot +/// chosen, its face asks what it should work on, over the composer. Without +/// one, the pod's bots are offered as chips to name, and sending starts a +/// thread with the first named, or with the people here. A shared pod's +/// threads start from its General; a Personal pod's from the bot's channel. +@MainActor +struct NewThreadScreen: View { + let pod: Pod + let agent: Agent? + @Environment(WorkspaceStore.self) private var store + @State private var opening = Opening.loading + @State private var draft = "" + @State private var starting = false + @State private var startFailed = false + @Environment(\.openPage) private var openPage + /// Whether the composer has the keyboard, as `Composer.focused` says. + @State private var composing = false + + var body: some View { + let title = agent == nil ? "New thread in \(pod.name)" : "New thread" + VStack(spacing: 0) { + HStack(alignment: .top, spacing: 8) { + HStack { HeaderBack() }.frame(maxWidth: .infinity, alignment: .leading) + TitleBadge(title: title) + Color.clear.frame(maxWidth: .infinity, maxHeight: 1) + } + .pageHeaderInsets() + if case .failed = opening { + EmptyState(title: "Could not start a thread here", text: "The API did not answer. Reload this page to try again.") + } else if let agent { + chosen(agent) + } else { + anyone(title: title) + } + } + .background(Palette.background.ignoresSafeArea()) + .task(id: pod.id) { await open() } + } + + private func chosen(_ agent: Agent) -> some View { + VStack(spacing: 24) { + VStack(spacing: 8) { + BotFace(look: agent.look, size: 64).padding(.bottom, 12) + Text("What should \(agent.name) work on?").font(Typeface.rubik(18, .semibold)).foregroundStyle(Palette.foreground) + if let description = agent.description, !description.isEmpty { + Text(description).font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + } + } + .multilineTextAlignment(.center) + composer(placeholder: "Describe the task, paste a link or drop a file") + } + .padding(.horizontal, 20) + .frame(maxHeight: .infinity) + .padding(.bottom, 80) + } + + private func anyone(title: String) -> some View { + let bots = startsFrom?.details?.crew.compactMap(\.agent) ?? [] + return VStack(alignment: .leading, spacing: 0) { + Spacer(minLength: 0) + VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 6) { + Text(title).font(Typeface.rubik(22, .bold)).foregroundStyle(Palette.foreground) + Text("Name a bot to start the thread with it, or write to the people here.") + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + } + if !bots.isEmpty { + FlowLayout(spacing: 8) { + ForEach(bots, id: \.id) { bot in + Button { + draft = "@\(bot.handle) " + draft.drop { $0.isWhitespace } + composing = true + } label: { + HStack(spacing: 8) { + BotFace(look: bot.look, size: 20) + Text(bot.name).font(Typeface.rubik(13.5, .medium)).foregroundStyle(Palette.foreground) + } + .padding(.leading, 6) + .padding(.trailing, 12) + .frame(height: 32) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong)) + } + .buttonStyle(.plain) + } + } + } + } + .padding(.horizontal, 20) + .padding(.top, 24) + .padding(.bottom, 16) + VStack(alignment: .leading, spacing: 0) { + composer(placeholder: nil) + Text(threadWith.map { "Sending starts a thread with \($0.name)." } ?? "Sending starts a thread with the people here.") + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 4) + .frame(height: 26) + } + .padding(.horizontal, 16) + } + } + + /// Whom the draft can mention: everyone here but you, then `@here` and + /// `@channel`, offered as in a conversation, since sending starts one. + private var mentionable: [MentionTarget] { + let others = (startsFrom?.mentionable ?? []).filter { $0.id != store.user.id } + let groups = Mentions.groupMentions( + writtenBy: store.user.id, + members: startsFrom?.details?.members ?? [], + threadType: .conversation + ) + return others.map(MentionTarget.participant) + groups.map(\.target) + } + + private func composer(placeholder: String?) -> some View { + Composer( + label: threadWith.map { "Message \($0.name)" } ?? "Message \(pod.name)", + placeholder: placeholder, + text: $draft, + // What is sent here starts a conversation, so `@here` and `@channel` are offered as in one. + mentionable: mentionable, + attachments: attachments, + sending: starting, + error: startFailed ? "The thread was not started. Try again." : nil, + needsText: true, + submit: submit, + focused: $composing + ) + } + + /// The bot the thread is with: the one chosen, or the first the draft names. + private var threadWith: AgentParticipant? { + if let agent { return AgentParticipant(agent) } + return Mentions.firstBot(in: draft, among: startsFrom?.details?.crew ?? []) + } + + /// The conversation threads start from, once it has opened. + private var startsFrom: ConversationModel? { + if case let .opened(model, _) = opening { model } else { nil } + } + + /// The files attached to the draft, once the conversation they go to has opened. + private var attachments: ComposerAttachments? { + if case let .opened(_, attachments) = opening { attachments } else { nil } + } + + private func open() async { + do { + let conversationId: String + if pod.kind == .personal, let agent { + conversationId = try await store.botChannel(in: pod, with: agent).id + } else { + conversationId = try await store.openPodChat(in: pod).id + } + // Only its details are read here, for whom a draft can mention. + let model = ConversationModel(threadId: conversationId, store: store, source: .threadMessages) + opening = .opened(model, ComposerAttachments(conversationId: conversationId, client: store.client)) + await model.reload() + } catch { + opening = .failed + } + } + + private func submit() { + guard let startsFrom, !starting else { return } + startFailed = false + starting = true + let text = draft.trimmingCharacters(in: .whitespacesAndNewlines) + let bot = threadWith + Task { + do { + let start = { (files: [FilePart]) in + try await startsFrom.startThread(text, with: bot, replyTo: nil, files: files) + } + let started = if let attachments { try await attachments.send(through: start) } else { try await start([]) } + draft = "" + openPage(.conversation(threadId: started.conversation.id, title: started.conversation.title)) + } catch { + startFailed = true + } + starting = false + } + } + + /// How opening the conversation threads start from went. + private enum Opening { + case loading + /// Open, with the files attached to the draft, which upload to it. + case opened(ConversationModel, ComposerAttachments) + case failed + } +} + +/// A channel's face over the page's title in a glass pill, heading the page. +private struct TitleBadge: View { + let title: String + + var body: some View { + VStack(spacing: 0) { + ChannelFace(size: 60) + Text(title) + .font(Typeface.rubik(15, .semibold)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .padding(.horizontal, 14) + .frame(height: 32) + .glass(in: Capsule()) + .frame(maxWidth: 220) + .padding(.top, -8) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(title) + .accessibilityAddTraits(.isHeader) + } +} diff --git a/apps/ios/Sugabots/Conversation/RoutineRun.swift b/apps/ios/Sugabots/Conversation/RoutineRun.swift new file mode 100644 index 000000000..4c3ca5860 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/RoutineRun.swift @@ -0,0 +1,91 @@ +import SwiftUI + +/// A routine's run in its own thread, as the web's `RunMessage`: the bot's +/// face, name and when it ran, then its report, or how it ended; the latest +/// failed run offers Retry and Fix connection. +@MainActor +struct RunMessage: View { + let item: ChatMessageItem.Routine + let agent: AgentParticipant + let pod: Pod + let routine: ThreadDetails.Routine + let latest: Bool + let mentionable: [ThreadParticipant] + @Environment(WorkspaceStore.self) private var store + @Environment(\.openPage) private var openPage + @Environment(Toaster.self) private var toaster + @State private var retrying = false + + var body: some View { + let outcome = RunStatusLabel.Outcome(state: item.state) + let report = outcome == .passed ? item.report : nil + HStack(alignment: .top, spacing: 14) { + BotFace(look: agent.look, size: 36).padding(.top, 2).frame(width: 36) + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Text(agent.name).font(Typeface.rubik(15, .semibold)).foregroundStyle(Palette.foreground) + BotTag() + Text(Times.clock(item.createdAt)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + if report == nil { RunStatusLabel(outcome: outcome) } + } + .padding(.bottom, 1) + if let report { + MessageMarkdown(text: report, mentionable: mentionable, palette: BotLooks.palette(for: agent.color)) + } else if outcome == .running { + TypingDots(small: true).foregroundStyle(Palette.mutedForeground).padding(.top, 8) + } else { + Text(item.error ?? (outcome == .cancelled ? "The run was stopped." : "It posted nothing.")) + .font(Typeface.rubik(15)) + .lineSpacing(3.5) + .foregroundStyle(Palette.bodyForeground) + } + if latest, outcome == .failed { + HStack(spacing: 8) { + Button("Retry", action: retry).buttonStyle(WebButtonStyle(size: .small)).disabled(retrying) + Button("Fix connection") { openPage(.podSettings(pod)) }.buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + } + .padding(.top, 8) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, 20) + .padding(.top, 14) + .padding(.bottom, 2) + .accessibilityElement(children: .contain) + .accessibilityLabel("\(item.routineName): \(outcome.label)") + } + + private func retry() { + retrying = true + Task { + do { + try await store.runRoutine(routine.id, agentId: routine.agentId) + } catch { + toaster.show(error.localizedDescription) + } + retrying = false + } + } +} + +/// The line after a routine's thread's last run: when it runs next, or Paused. +@MainActor +struct NextRunDivider: View { + let routine: ThreadDetails.Routine + @Environment(WorkspaceStore.self) private var store + @State private var next: String? + + var body: some View { + Group { + if routine.state == .paused { + LabelledDivider(text: "Paused", strong: false) + } else if let next { + LabelledDivider(text: next, strong: false) + } + } + .task(id: routine.id) { + next = await store.nextRunWords(routineId: routine.id, agentId: routine.agentId) + } + } +} diff --git a/apps/ios/Sugabots/Conversation/SideThreadSheet.swift b/apps/ios/Sugabots/Conversation/SideThreadSheet.swift new file mode 100644 index 000000000..d9c38f7b6 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/SideThreadSheet.swift @@ -0,0 +1,115 @@ +import SwiftUI + +/// A collaboration or a routine's run, over the conversation it came from, +/// as the web's `ChatThreadPanel` in a phone's sheet: what it is in the +/// sheet's head, then its messages, smaller. +@MainActor +struct SideThreadSheet: View { + let threadId: String + let conversationId: String + let entry: ChatHistoryEntry? + /// The bot whose channel this opened from, which is "mine" in a collaboration. + let chatAgentId: String? + /// On its own page, as the Inbox opens it, rather than in a sheet over its conversation. + var asPage = false + let openThread: (String) -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var model: ConversationModel? + @State private var looks: [String: ConnectionLook] = [:] + + var body: some View { + VStack(spacing: 0) { + if !asPage { + SheetGrabber().padding(.bottom, 14) + } + header + Rectangle().fill(Palette.border).frame(height: 1) + content + } + .background((asPage ? Palette.background : Palette.list).ignoresSafeArea()) + .phoneSheet(detents: [.fraction(0.82), .large]) + .task(id: threadId) { + // Kept while a page is pushed over this one, as it is when it opens as a page. + if model?.threadId != threadId { model = ConversationModel(threadId: threadId, store: store, source: .threadMessages) } + await model?.listen() + } + .task(id: model?.thread?.podId) { + guard let podId = model?.thread?.podId else { return } + looks = await store.connectionLooks(podId: podId) + } + } + + /// Whether it's a collaboration or a routine's run, as its history entry or its thread says. + private var type: ThreadType? { entry.map { ThreadType(rawValue: $0.type.rawValue) } ?? model?.thread?.type } + + private var host: AgentParticipant? { + model?.details?.participants.compactMap(\.agent).first { $0.id == model?.thread?.hostAgentId } + } + + private var mine: AgentParticipant? { + model?.details?.participants.compactMap(\.agent).first { $0.id == chatAgentId } ?? host + } + + private var other: AgentParticipant? { + model?.details?.participants.compactMap(\.agent).first { $0.id != mine?.id } + } + + private var header: some View { + let title = model?.thread?.title ?? entry?.title ?? "Thread" + let heading = type == .collaboration ? "Collaboration" : title + let subheading = type == .collaboration ? other.map { "\(mine?.name ?? "") and \($0.name)" } : nil + return HStack(alignment: .center, spacing: 12) { + if asPage { HeaderBack() } + Text(heading).font(Typeface.rubik(15, .semibold)).foregroundStyle(Palette.foreground).lineLimit(1) + .accessibilityAddTraits(.isHeader) + if let subheading { + Text(subheading).font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + Spacer(minLength: 0) + if !asPage { + SmallIconButton(icon: .x, label: "Close") { dismiss() }.frame(width: 30, height: 30) + } + } + .padding(.leading, asPage ? 16 : 18) + .padding(.trailing, 12) + .frame(minHeight: 52) + .padding(.top, asPage ? 12 : 0) + .padding(.bottom, asPage ? 8 : 0) + } + + @ViewBuilder private var content: some View { + if let model, let details = model.details, let host, let context = model.messageContext(looks: looks, filesConversationId: conversationId) { + let messages: [Message] = model.items.compactMap { item in + guard let message = item.message else { return nil } + if type == .routine, case .routineTrigger = message.author { return nil } + return message + } + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(Array(messages.enumerated()), id: \.element.id) { index, message in + MessageRow( + message: message, + startsGroup: ChatGroups.startsGroup(index > 0 ? messages[index - 1] : nil, message), + context: context, + actions: MessageActions(openThread: openThread), + compact: true + ) + } + if details.thread.status == .running, model.notices.isEmpty, messages.last?.author.personId != nil { + TypingIndicator(names: [host.name]).padding(.horizontal, 18) + } + ForEach(Array(model.notices.enumerated()), id: \.offset) { _, notice in + Text(notice).font(Typeface.rubik(12)).foregroundStyle(Palette.destructiveText).frame(maxWidth: .infinity).padding(.top, 8) + } + } + .padding(.vertical, 8) + } + .defaultScrollAnchor(.bottom) + } else if model?.loadError != nil { + EmptyState(title: "Could not load this thread", text: "Go back and open it again.") + } else { + Text("Loading thread…").font(Typeface.rubik(14)).foregroundStyle(Palette.mutedForeground).frame(maxHeight: .infinity) + } + } +} diff --git a/apps/ios/Sugabots/Conversation/ToolLine.swift b/apps/ios/Sugabots/Conversation/ToolLine.swift new file mode 100644 index 000000000..110c24e05 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ToolLine.swift @@ -0,0 +1,169 @@ +import SwiftUI + +/// A bot's tool calls in a message, as the web's `ToolLine`: one line saying +/// what it used and for how long, which unfolds into each step, and each +/// step into what it was given and gave back. +struct ToolLine: View { + let parts: [MessagePart] + var looks: [String: ConnectionLook] = [:] + let fileNames: [String: String] + @State private var open = false + + var body: some View { + let runs = ToolSteps.runs(of: parts) + let calls = runs.flatMap(\.calls) + if !calls.isEmpty { + VStack(alignment: .leading, spacing: 0) { + Button { open.toggle() } label: { + HStack(spacing: 6) { + Text(ToolSteps.lineText(calls, looks: looks)).lineLimit(1) + Icon(.chevronRight, size: 10, strokeWidth: 3) + .foregroundStyle(Palette.subtleForeground) + .rotationEffect(.degrees(open ? 90 : 0)) + } + .font(Typeface.rubik(14, .medium)) + .foregroundStyle(Palette.mutedForeground) + .padding(.bottom, 6) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityValue(open ? "Expanded" : "Collapsed") + if open { + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(runs.enumerated()), id: \.offset) { index, run in + if let narration = run.narration { + Text(narration) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .padding(.top, index > 0 ? 8 : 0) + .padding(.bottom, 2) + } + ForEach(run.calls) { call in + ToolCallRow(call: call, look: looks[ToolNames.handle(call.tool)], fileNames: fileNames) + } + } + } + .padding(.vertical, 2) + .padding(.leading, 14) + .overlay(alignment: .leading) { Rectangle().fill(Palette.hover).frame(width: 1.5) } + .padding(.bottom, 8) + } + } + } + } +} + +private struct ToolCallRow: View { + let call: ToolCallPart + let look: ConnectionLook? + let fileNames: [String: String] + @State private var open = false + + var body: some View { + let step = ToolSteps.describe(call, fileNames: fileNames) + let note = ToolSteps.note(of: call) + VStack(alignment: .leading, spacing: 0) { + Button { open.toggle() } label: { + HStack(spacing: 8) { + if ToolNames.handle(call.tool).isEmpty { + Icon(.wrench, size: 10, strokeWidth: 2.4) + .foregroundStyle(Palette.softForeground) + .frame(width: 16, height: 16) + .background(Palette.borderStrong, in: RoundedRectangle(cornerRadius: 2)) + } else { + ConnectionMark(presetId: look?.presetId, name: ToolSteps.appOf(call, look: look), size: .xs) + } + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text(step.action).font(Typeface.rubik(13, .medium)).foregroundStyle(Palette.softForeground).fixedSize() + if let subject = step.subject { + Text(subject.text) + .font(subject.asCode ? Typeface.mono(12.5) : Typeface.rubik(13)) + .foregroundStyle(subject.asCode ? Palette.subtleForeground : Palette.mutedForeground) + .lineLimit(1) + } + } + if let note { + Text(note.text) + .font(Typeface.rubik(12)) + .foregroundStyle(note.failed ? Palette.destructiveText : Palette.subtleForeground) + .lineLimit(1) + .layoutPriority(-1) + } + Spacer(minLength: 8) + if call.finishedAt != nil { + Text(ToolSteps.formatDuration(ToolSteps.duration(of: call))) + .font(Typeface.mono(11.5)) + .foregroundStyle(Palette.subtleForeground) + } + Icon(.chevronRight, size: 10, strokeWidth: 3) + .foregroundStyle(Palette.subtleForeground) + .rotationEffect(.degrees(open ? 90 : 0)) + } + .padding(.vertical, 3) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + if open { CallDetails(call: call, details: ToolSteps.details(of: call)) } + } + } +} + +private struct CallDetails: View { + let call: ToolCallPart + let details: ToolSteps.Details + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text("Tool").font(Typeface.rubik(11.5, .medium)).foregroundStyle(Palette.subtleForeground) + Text(call.tool).font(Typeface.mono(11.5)).foregroundStyle(Palette.softForeground) + } + if let input = details.input { + block("Input", input, other: details.otherArguments) + } + if let error = call.error { + block("Error", .string(error), failed: true) + } else if let output = details.output { + block("Output", output, footnote: details.outputCut) + } + if details.input == nil, details.output == nil, call.error == nil { + Text(call.status == .running ? "Still running" : "Nothing to show") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + } + } + .padding(.top, 4) + .padding(.bottom, 8) + .padding(.leading, 24) + } + + private func block(_ label: String, _ value: JSONValue, other: JSONValue? = nil, failed: Bool = false, footnote: String? = nil) -> some View { + VStack(alignment: .leading, spacing: 4) { + Text(label).font(Typeface.rubik(11.5, .medium)).foregroundStyle(Palette.subtleForeground) + ToolCallValue(value: value, failed: failed) + if let other { ToolCallValue(value: other, failed: false) } + if let footnote { + Text(footnote).font(Typeface.rubik(11.5)).foregroundStyle(Palette.subtleForeground) + } + } + } +} + +/// A value a tool was given or gave back, as code on a panel. +struct ToolCallValue: View { + let value: JSONValue + let failed: Bool + + var body: some View { + ScrollView(.horizontal, showsIndicators: false) { + Text(value.prettyPrinted) + .font(Typeface.mono(11.5)) + .foregroundStyle(failed ? Palette.destructiveText : Palette.softForeground) + .textSelection(.enabled) + .padding(.horizontal, 10) + .padding(.vertical, 8) + } + .frame(maxWidth: .infinity, maxHeight: 240, alignment: .leading) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } +} diff --git a/apps/ios/Sugabots/Design/ColourSwatches.swift b/apps/ios/Sugabots/Design/ColourSwatches.swift new file mode 100644 index 000000000..c187d9ade --- /dev/null +++ b/apps/ios/Sugabots/Design/ColourSwatches.swift @@ -0,0 +1,54 @@ +import SwiftUI + +/// Round swatches, the chosen one ringed, as the web's `Swatches` in +/// `LookPicker`. Without `columns`, as many 28-point swatches as fit across the +/// row, spread to its ends, the rest wrapping into the same columns; with it, +/// that many to a row, each up to 32 points, shrinking to fit a narrow row. +struct ColourSwatches: View { + let colors: [String] + let swatch: (String) -> Color + let value: String + var columns: Int? + let choose: (String) -> Void + + /// A swatch's width, and the least gap between two, when they wrap. + private static let size: CGFloat = 28 + private static let gap: CGFloat = 6 + /// The widest a swatch grows, and the gap down as across, in set columns. + private static let columnSize: CGFloat = 32 + private static let columnGap: CGFloat = 10 + + var body: some View { + Group { + if let columns { + LazyVGrid( + columns: Array(repeating: GridItem(.flexible(maximum: Self.columnSize), spacing: Self.columnGap), count: columns), + alignment: .leading, + spacing: Self.columnGap + ) { + ForEach(colors, id: \.self) { color in swatchButton(color).aspectRatio(1, contentMode: .fit) } + } + } else { + LazyVGrid(columns: [GridItem(.adaptive(minimum: Self.size, maximum: Self.size + 20), spacing: Self.gap)], alignment: .leading, spacing: Self.gap) { + ForEach(colors, id: \.self) { color in + swatchButton(color).frame(width: Self.size, height: Self.size).frame(maxWidth: .infinity) + } + } + } + } + .padding(.vertical, 5) + .frame(maxWidth: .infinity) + } + + private func swatchButton(_ color: String) -> some View { + Button { choose(color) } label: { + Circle() + .fill(swatch(color)) + // The web's ring: a gap in the panel's colour, then the swatch's. + .overlay { if value == color { Circle().strokeBorder(swatch(color), lineWidth: 2).padding(-5) } } + } + .buttonStyle(.plain) + .accessibilityLabel(color) + .accessibilityAddTraits(value == color ? .isSelected : []) + } +} diff --git a/apps/ios/Sugabots/Design/ConfirmDeleteDialog.swift b/apps/ios/Sugabots/Design/ConfirmDeleteDialog.swift new file mode 100644 index 000000000..aa9d448bc --- /dev/null +++ b/apps/ios/Sugabots/Design/ConfirmDeleteDialog.swift @@ -0,0 +1,104 @@ +import SwiftUI + +extension View { + /// The web's `DeleteDialog`: a small card over a scrim that covers the + /// whole screen, tabs and all, saying what goes, with Cancel and the red + /// action side by side. It fades and zooms in, as the web's dialogs do, + /// rather than sliding up. + /// + /// The dialog runs `action` itself: its buttons wait while it runs, a + /// failure is shown in the card, and the dialog closes only once it + /// succeeds. `action` holds only the request and what follows it, such as + /// leaving the page or reloading. + func confirmDelete( + isPresented: Binding, + title: String, + description: String, + confirmLabel: String = "Delete", + action: @escaping () async throws -> Void + ) -> some View { + fullScreenCover(isPresented: isPresented) { + DeleteDialog( + title: title, + description: description, + confirmLabel: confirmLabel, + close: { isPresented.wrappedValue = false }, + action: action + ) + .presentationBackground(.clear) + } + .transaction(value: isPresented.wrappedValue) { $0.disablesAnimations = true } + } +} + +private struct DeleteDialog: View { + let title: String + let description: String + let confirmLabel: String + let close: () -> Void + let action: () async throws -> Void + @State private var shown = false + @State private var pending = false + @State private var failure: String? + + var body: some View { + let card = RoundedRectangle(cornerRadius: 20, style: .continuous) + ZStack { + Palette.scrim + .ignoresSafeArea() + .onTapGesture { if !pending { close() } } + VStack(spacing: 0) { + VStack(spacing: 8) { + Text(title).font(Typeface.rubik(14, .semibold)).foregroundStyle(Palette.foreground) + // The web's 1.55 leading over Rubik's own line height of about 1.19. + Text(description).font(Typeface.rubik(13.5)).lineSpacing(5).foregroundStyle(Palette.mutedForeground) + if let failure { FormAlert(text: failure).padding(.top, 8) } + } + .multilineTextAlignment(.center) + .padding(.horizontal, 22) + .padding(.top, 24) + .padding(.bottom, 18) + Rectangle().fill(Palette.borderStrong).frame(height: 1) + HStack(spacing: 0) { + Button(action: close) { + Text("Cancel").font(Typeface.rubik(15, .medium)).foregroundStyle(Palette.softForeground) + .frame(maxWidth: .infinity, minHeight: 48).contentShape(Rectangle()) + } + Rectangle().fill(Palette.borderStrong).frame(width: 1) + Button(action: confirm) { + Text(confirmLabel).font(Typeface.rubik(15, .semibold)).foregroundStyle(Palette.destructiveText) + .frame(maxWidth: .infinity, minHeight: 48).contentShape(Rectangle()) + } + } + .buttonStyle(.plain) + .fixedSize(horizontal: false, vertical: true) + .disabled(pending) + .opacity(pending ? 0.5 : 1) + } + .frame(maxWidth: 360) + .background(Palette.panel, in: card) + // The web's `--dialog-shadow`: a deep shadow and a hairline ring, black in light and white in dark. + .overlay(card.strokeBorder(Color.primary.opacity(0.06))) + .shadow(color: .black.opacity(0.6), radius: 40, y: 30) + .padding(.horizontal, 10) + .scaleEffect(shown ? 1 : 0.95) + } + .opacity(shown ? 1 : 0) + .onAppear { withAnimation(.easeOut(duration: 0.1)) { shown = true } } + .accessibilityAddTraits(.isModal) + } + + private func confirm() { + pending = true + failure = nil + Task { + do { + try await action() + close() + } catch { + failure = error.localizedDescription + } + pending = false + } + } +} diff --git a/apps/ios/Sugabots/Design/ConnectionMark.swift b/apps/ios/Sugabots/Design/ConnectionMark.swift new file mode 100644 index 000000000..881fc797d --- /dev/null +++ b/apps/ios/Sugabots/Design/ConnectionMark.swift @@ -0,0 +1,177 @@ +import SwiftUI + +/// A connection's mark, as the web's `ui/connection-mark.tsx` draws it: a +/// catalog app's glyph on a tint of its brand, a mark in its own colours, or +/// for anything else, two letters of its name on grey. +struct ConnectionMark: View { + enum Size { + case xs, md, sm, tile, regular, lg + + var box: CGFloat { + switch self { + case .xs: 16 + case .md: 24 + case .sm: 32 + case .tile: 34 + case .regular: 40 + case .lg: 44 + } + } + + var cornerRadius: CGFloat { + switch self { + case .xs: 5 + case .md: 7 + case .sm, .tile: 10 + case .regular: 12 + case .lg: 13 + } + } + + var glyph: CGFloat { + switch self { + case .xs: 10 + case .md: 14 + case .sm: 16 + case .tile: 18 + case .regular: 20 + case .lg: 22 + } + } + + var letters: CGFloat { + switch self { + case .xs: 8 + case .md: 11 + case .sm: 12 + case .tile: 13 + case .regular: 12.5 + case .lg: 15 + } + } + } + + /// A one-colour glyph on a 24-point square. + struct Glyph { + let color: Color + let tint: ThemedColor + let path: String + } + + /// A mark in its own colours on a square of `size`. + struct ColourGlyph { + enum Paint { + case hex(String) + case token(Token) + + var color: Color { + switch self { + case let .hex(hex): Color(hex: hex) + case .token(.foreground): Palette.foreground + case .token(.panel): Palette.panel + } + } + } + + /// The theme colours a mark may paint with. + enum Token { + case foreground, panel + } + + struct Part { + let path: String + let fill: Paint? + let stroke: Paint? + let strokeWidth: CGFloat + let roundCap: Bool + } + + let size: CGFloat + /// Its brand's tint behind it, or nil to sit on the panel inside a hairline. + let tint: ThemedColor? + let parts: [Part] + } + + /// The catalog app or GitHub it is drawn as, from `connectionMarkFor`; nil for its letters. + let presetId: String? + let name: String + var size = Size.regular + + var body: some View { + let shape = RoundedRectangle(cornerRadius: size.cornerRadius, style: .continuous) + Group { + if let presetId, let colour = Self.colourGlyphs[presetId] { + colourGlyph(colour) + .frame(width: size.box, height: size.box) + .background(colour.tint?.resolved ?? Palette.panel, in: shape) + .overlay { if colour.tint == nil { shape.strokeBorder(Palette.borderSubtle) } } + } else if let presetId, let glyph = Self.glyphs[presetId] { + SVGShape(data: glyph.path, box: 24) + .fill(Self.darkBrands.contains(presetId) ? Palette.foreground : glyph.color) + .frame(width: size.glyph, height: size.glyph) + .frame(width: size.box, height: size.box) + .background(glyph.tint.resolved, in: shape) + } else { + Text(Self.letters(of: name)) + .font(Typeface.rubik(size.letters, .semibold)) + .foregroundStyle(Palette.foreground) + .frame(width: size.box, height: size.box) + .background(Palette.borderStrong, in: shape) + } + } + .accessibilityHidden(true) + } + + private func colourGlyph(_ colour: ColourGlyph) -> some View { + ZStack { + ForEach(Array(colour.parts.enumerated()), id: \.offset) { _, part in + if let fill = part.fill { + SVGShape(data: part.path, box: colour.size).fill(fill.color) + } + if let stroke = part.stroke { + SVGShape(data: part.path, box: colour.size) + .stroke(stroke.color, style: StrokeStyle(lineWidth: part.strokeWidth * size.glyph / colour.size, lineCap: part.roundCap ? .round : .butt)) + } + } + } + .frame(width: size.glyph, height: size.glyph) + } + + /// As `connectionLetters`: the first letters of its first two words, or a single word's first two. + static func letters(of name: String) -> String { + let words = name.split(whereSeparator: \.isWhitespace) + guard let first = words.first else { return "?" } + if words.count >= 2 { return (String(first.prefix(1)) + String(words[1].prefix(1))).uppercased() } + return String(first.prefix(2)).uppercased() + } + + /// As `connectionMarkFor`: GitHub's mark for a GitHub connection, a catalog app's for its server, else none. + static func presetId(kind: String, url: String) -> String? { + kind == "github" ? "github" : ConnectionPreset.matching(url: url)?.id + } +} + +extension ConnectionPreset { + /// The catalog entry a connection was made from, by its address's host, as `connectionPresetFor`. + static func matching(url: String) -> ConnectionPreset? { + guard let host = host(of: url) else { return nil } + return catalog.first { self.host(of: $0.url) == host } + } + + private static func host(of url: String) -> String? { + guard let match = url.range(of: "^https?://[^/?#]+", options: [.regularExpression, .caseInsensitive]) else { return nil } + return url[match].split(separator: "/").last.map { $0.lowercased() } + } +} + +/// SVG path data on a square of `box` units, scaled to the frame it's given. +private struct SVGShape: Shape { + let data: String + let box: CGFloat + + func path(in rect: CGRect) -> Path { + SVGPath.cachedPath(data).applying( + CGAffineTransform(translationX: rect.minX, y: rect.minY).scaledBy(x: rect.width / box, y: rect.height / box) + ) + } +} diff --git a/apps/ios/Sugabots/Design/Controls.swift b/apps/ios/Sugabots/Design/Controls.swift new file mode 100644 index 000000000..980c60be8 --- /dev/null +++ b/apps/ios/Sugabots/Design/Controls.swift @@ -0,0 +1,338 @@ +import SwiftUI +import UIKit + +/// A row that darkens while pressed, as the design's rows do. +struct PressableRowStyle: ButtonStyle { + var pressed: Color = Palette.rowSelected + var cornerRadius: CGFloat = 0 + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .contentShape(Rectangle()) + .background(configuration.isPressed ? pressed : .clear, in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)) + } +} + +extension ButtonStyle where Self == PressableRowStyle { + /// A row of Home's sidebar: Artifacts, a channel, a bot. + static var sidebarRow: PressableRowStyle { PressableRowStyle(cornerRadius: 10) } +} + +/// Nothing here, or nothing could be loaded, and what to do about it, as the +/// web's `ui/empty-state.tsx`: perhaps a mark on a tile, a title, and a line +/// under it. It fills the space it's given, centred; in a scrolling page, which +/// gives none, the caller sets a height. +struct EmptyState: View { + let title: String + var icon: Lucide? + var text: String? + + var body: some View { + VStack(spacing: 10) { + if let icon { + Icon(icon, size: 20, strokeWidth: 1.75) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 56, height: 56) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.border)) + .padding(.bottom, 14) + } + Text(title).font(Typeface.rubik(15.5, .semibold)).foregroundStyle(Palette.foreground) + if let text { + Text(text).font(Typeface.rubik(13)).lineSpacing(5).foregroundStyle(Palette.mutedForeground) + } + } + .multilineTextAlignment(.center) + .frame(maxWidth: 400) + .padding(24) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +/// A count in a pill, as the web's `CountBadge`: bright, or quiet for what merely waits. +struct CountBadge: View { + enum Size { + /// In a tab, as the web's `sm`. + case small + /// Beside Back in a conversation's header. + case large + } + + let count: Int + var quiet = false + var size = Size.small + + /// Past this, the badge says `99+`. + private static let maxCounted = 99 + + var body: some View { + let large = size == .large + Text(count > Self.maxCounted ? "\(Self.maxCounted)+" : "\(count)") + .font(Typeface.rubik(large ? 12 : 10.5, .semibold)) + .monospacedDigit() + .foregroundStyle(quiet ? Palette.foreground : Palette.primaryForeground) + .padding(.horizontal, large ? 6 : 5) + .frame(minWidth: large ? 20 : 18, minHeight: large ? 20 : 16) + .background(quiet ? Palette.chipStrong : Palette.primary, in: Capsule()) + .accessibilityHidden(true) + } +} + +/// Show more, or Show less once open, under something folded. +struct ShowMoreButton: View { + @Binding var open: Bool + + var body: some View { + Button(open ? "Show less" : "Show more") { open.toggle() } + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + .accessibilityValue(open ? "Expanded" : "Collapsed") + } +} + +/// The web's small icon button: a 20-point circle with a 14-point icon, muted until pressed. +struct SmallIconButton: View { + let icon: Lucide + let label: String + let action: () -> Void + + var body: some View { + Button(action: action) { + Icon(icon, size: 14, strokeWidth: 2.2) + .frame(width: 20, height: 20) + .contentShape(Circle()) + } + .buttonStyle(IconPressStyle()) + .accessibilityLabel(label) + } +} + +/// Muted, and filled with the hover colour while pressed, as the web's quiet icon buttons are. +struct IconPressStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .foregroundStyle(configuration.isPressed ? Palette.foreground : Palette.mutedForeground) + .background(configuration.isPressed ? Palette.hover : .clear, in: Circle()) + } +} + +/// Glass in a capsule, filled stronger while pressed. +struct CapsuleGlassPressStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .background(configuration.isPressed ? Palette.hoverStrong : .clear, in: Capsule()) + .glass(in: Capsule()) + } +} + +/// The small Bot tag after a bot's name. +struct BotTag: View { + var body: some View { + Text("Bot") + .font(Typeface.rubik(10.5, .semibold)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 4, style: .continuous)) + } +} + +/// A line between days, or between a routine's runs: words between two rules. +struct LabelledDivider: View { + let text: String + var strong = true + + var body: some View { + HStack(spacing: 12) { + Rectangle().fill(Palette.border).frame(height: 1) + Text(text) + .font(Typeface.rubik(12, strong ? .semibold : .regular)) + .foregroundStyle(strong ? Palette.mutedForeground : Palette.subtleForeground) + .fixedSize() + Rectangle().fill(Palette.border).frame(height: 1) + } + .padding(.horizontal, 20) + .padding(.top, strong ? 10 : 16) + .padding(.bottom, 6) + } +} + +/// The web's typing dots: three dots rising in turn. +struct TypingDots: View { + var small = false + @State private var start = Date.now + + var body: some View { + let size: CGFloat = small ? 3.5 : 7 + TimelineView(.animation) { timeline in + let elapsed = timeline.date.timeIntervalSince(start) + HStack(spacing: small ? 3 : 5) { + ForEach(0..<3) { index in + let phase = (elapsed - Double(index) * 0.15).truncatingRemainder(dividingBy: 1.2) / 1.2 + // Up and bright in the first 30% of each 1.2s cycle's 60%, resting after. + let lift = phase < 0.3 ? phase / 0.3 : phase < 0.6 ? (0.6 - phase) / 0.3 : 0 + Circle() + .frame(width: size, height: size) + .opacity(0.35 + 0.65 * max(lift, 0)) + .offset(y: -size * 0.5 * max(lift, 0)) + } + } + } + .accessibilityHidden(true) + } +} + +/// Lays its children in rows, wrapping to the next when one is full. +struct FlowLayout: Layout { + var spacing: CGFloat = 8 + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize { + let rows = arrange(subviews, width: proposal.width ?? .infinity) + return CGSize(width: proposal.width ?? rows.width, height: rows.height) + } + + func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) { + for (index, origin) in arrange(subviews, width: bounds.width).origins.enumerated() { + subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: .unspecified) + } + } + + private func arrange(_ subviews: Subviews, width: CGFloat) -> (origins: [CGPoint], width: CGFloat, height: CGFloat) { + var origins: [CGPoint] = [] + var x: CGFloat = 0 + var y: CGFloat = 0 + var rowHeight: CGFloat = 0 + var widest: CGFloat = 0 + for subview in subviews { + let size = subview.sizeThatFits(.unspecified) + if x > 0, x + size.width > width { + x = 0 + y += rowHeight + spacing + rowHeight = 0 + } + origins.append(CGPoint(x: x, y: y)) + x += size.width + spacing + rowHeight = max(rowHeight, size.height) + widest = max(widest, x - spacing) + } + return (origins, widest, y + rowHeight) + } +} + +// MARK: Toast + +/// A short note at the foot of the screen, such as "All caught up". Any screen can raise one. +@MainActor +@Observable +final class Toaster { + private(set) var message: String? + private var hiding: Task? + + func show(_ message: String) { + self.message = message + hiding?.cancel() + hiding = Task { + try? await Task.sleep(for: .seconds(2.2)) + guard !Task.isCancelled else { return } + self.message = nil + } + } +} + +struct ToastOverlay: View { + @Environment(Toaster.self) private var toaster + + var body: some View { + if let message = toaster.message { + Text(message) + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(Palette.background) + .multilineTextAlignment(.center) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background(Palette.foreground, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .shadow(color: .black.opacity(0.4), radius: 12, y: 8) + .frame(maxWidth: 340) + .padding(.bottom, 110) + .transition(.opacity) + .accessibilityAddTraits(.updatesFrequently) + } + } +} + +// MARK: Sheets + +/// A sheet's grabber, drawn at the top of its content: the system's floats +/// over the content, where it would cover what a sheet puts at its top. +/// The system's size and colour. +struct SheetGrabber: View { + var body: some View { + Capsule().fill(Palette.borderStrong).frame(width: 36, height: 5).padding(.top, 8) + } +} + +extension View { + /// Presents a sheet as the app's are: at `detents`, on the panel colour, rounded, + /// with no system grabber, for the content to draw a `SheetGrabber`. + func phoneSheet(detents: Set) -> some View { + presentationDetents(detents) + .presentationDragIndicator(.hidden) + .presentationBackground(Palette.panel) + .presentationCornerRadius(22) + } +} + +/// The system's share sheet, which saves a file to Files or sends it elsewhere. +struct ShareSheet: UIViewControllerRepresentable { + let items: [Any] + + func makeUIViewController(context _: Context) -> UIActivityViewController { + UIActivityViewController(activityItems: items, applicationActivities: nil) + } + + func updateUIViewController(_: UIActivityViewController, context _: Context) {} +} + +/// A file saved for the share sheet. +struct SavedFile: Identifiable { + let url: URL + var id: String { url.absoluteString } +} + +// MARK: Navigation + +extension View { + /// Keeps swiping back from the left edge working in the navigation stack + /// this view is the root of, whose pages hide the navigation bar and draw + /// their own Back; UIKit turns the gesture off along with the bar. + func swipeBackWithoutNavigationBar() -> some View { + background(SwipeBackInstaller().frame(width: 0, height: 0)) + } +} + +/// A view controller with nothing to show, which gives the swipe back gesture +/// of the navigation controller it is shown in to `SwipeBack`. +private struct SwipeBackInstaller: UIViewControllerRepresentable { + func makeUIViewController(context _: Context) -> Installer { Installer() } + + func updateUIViewController(_: Installer, context _: Context) {} + + final class Installer: UIViewController { + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + navigationController?.interactivePopGestureRecognizer?.delegate = SwipeBack.delegate + } + } +} + +/// The swipe back gesture's delegate, which lets it begin whenever there's a page to go back to. +private final class SwipeBack: NSObject, UIGestureRecognizerDelegate { + /// Kept here because a gesture holds its delegate weakly. + static let delegate = SwipeBack() + + /// The gesture is on the navigation controller's view, whose next responder is the controller. + func gestureRecognizerShouldBegin(_ gesture: UIGestureRecognizer) -> Bool { + guard let navigation = gesture.view?.next as? UINavigationController else { return false } + return navigation.viewControllers.count > 1 + } +} diff --git a/apps/ios/Sugabots/Design/Faces.swift b/apps/ios/Sugabots/Design/Faces.swift new file mode 100644 index 000000000..aa23bddc1 --- /dev/null +++ b/apps/ios/Sugabots/Design/Faces.swift @@ -0,0 +1,211 @@ +import SwiftUI + +/// How a bot's colour is drawn: its face and eyes, and the tint behind what it says with the text on it. +struct BotPalette { + let face: Color + let eyes: Color + let tint: ThemedColor + let text: ThemedColor + /// Links and inline code in what the bot says. + let mono: ThemedColor +} + +/// A pod colour's tile tint, and the swatch its initial is written in. +struct PodPalette { + let tile: ThemedColor + let swatch: Color +} + +/// One filled piece of a head, in the 40-unit square a face is drawn in. +enum HeadPart { + case path(String) + case circle(cx: Double, cy: Double, r: Double) + + /// The piece's outline in the 40-unit square. A head's pieces are filled one + /// by one rather than as one path, so where they overlap stays filled. + var path: Path { + switch self { + case let .path(data): SVGPath.cachedPath(data) + case let .circle(cx, cy, r): Path(ellipseIn: CGRect(x: cx - r, y: cy - r, width: 2 * r, height: 2 * r)) + } + } +} + +/// Where a head's eyes sit, and how large, against a full-size face. +struct EyePlacement { + let x: Double + let y: Double + let scale: Double +} + +struct HeadShape { + let parts: [HeadPart] + let eyes: EyePlacement +} + +/// One mark on a face: an eye, or both eyes as one stroke. +enum FaceMark { + case circle(cx: Double, cy: Double, r: Double) + case rect(x: Double, y: Double, width: Double, height: Double, rx: Double) + case stroke(String, width: Double) + + /// Draws the mark in the 40-unit square `context` is scaled to. `cap` ends a + /// stroked mark: a bot's face leaves them square, as the web's avatar does, + /// while the look picker's eyes round them, as the web's `EyesGlyph` does. + func draw(in context: GraphicsContext, with shading: GraphicsContext.Shading, cap: CGLineCap) { + switch self { + case let .circle(cx, cy, r): + context.fill(Path(ellipseIn: CGRect(x: cx - r, y: cy - r, width: 2 * r, height: 2 * r)), with: shading) + case let .rect(x, y, width, height, rx): + context.fill(Path(roundedRect: CGRect(x: x, y: y, width: width, height: height), cornerRadius: rx), with: shading) + case let .stroke(data, width): + context.stroke(SVGPath.cachedPath(data), with: shading, style: StrokeStyle(lineWidth: width, lineCap: cap)) + } + } +} + +/// The side of the square faces are drawn in, as `FACE_VIEWBOX_SIZE` in `@sugabots/avatars`. +private let faceViewboxSize = 40.0 + +/// A bot's face: its head in its colour, with its eyes, `size` points square. +struct BotFace: View { + let look: BotLook + var size: CGFloat = 24 + + var body: some View { + Canvas { context, canvas in + let palette = BotLooks.palette(for: look.color) + let head = BotLooks.head(for: look.shape) + let marks = BotLooks.faces(for: look.face) + context.scaleBy(x: canvas.width / faceViewboxSize, y: canvas.height / faceViewboxSize) + + for part in head.parts { + context.fill(part.path, with: .color(palette.face)) + } + + let eyes = head.eyes + let centre = faceViewboxSize / 2 + var eyeContext = context + eyeContext.translateBy(x: eyes.x, y: eyes.y) + eyeContext.scaleBy(x: eyes.scale, y: eyes.scale) + eyeContext.translateBy(x: -centre, y: -centre) + for mark in marks { + mark.draw(in: eyeContext, with: .color(palette.eyes), cap: .butt) + } + } + .frame(width: size, height: size) + .accessibilityHidden(true) + } +} + +/// How a bot looks: its colour, eyes and head. +struct BotLook: Hashable { + var color: AgentColor + var face: AgentFace + var shape: AgentShape +} + +extension Agent { + var look: BotLook { BotLook(color: color, face: face, shape: shape) } +} + +extension AgentParticipant { + var look: BotLook { BotLook(color: color, face: face, shape: shape) } +} + +/// A person's initial on a grey disc, covered by their picture when they have +/// one, or else their Gravatar when their email has one, as the web draws them. +struct PersonAvatar: View { + let name: String + /// Absent where the person is not known by an address, such as an empty thread's header. + var email: String? + var image: String? + var size: CGFloat = 24 + + var body: some View { + ZStack { + Circle().fill(Palette.personAvatar) + Text(Initials.of(name)) + .font(Typeface.rubik(max(9, (size * 0.34).rounded()), .bold)) + .foregroundStyle(Palette.personAvatarForeground) + if let picture { + // A failed load, such as an address with no Gravatar, leaves the initial showing. + AsyncImage(url: picture) { phase in + if let loaded = phase.image { + loaded.resizable().scaledToFill() + } + } + .clipShape(Circle()) + } + } + .frame(width: size, height: size) + .accessibilityHidden(true) + } + + private var picture: URL? { + if let image, let url = URL(string: image) { return url } + return email.map { Gravatar.url(for: $0, pixels: Int(size * Self.gravatarPixelsPerPoint)) } + } + + /// How many image pixels a Gravatar is drawn with for each point, so it stays sharp on every iPhone screen. + private static let gravatarPixelsPerPoint: CGFloat = 3 +} + +extension Initials { + /// The first letter of `name`, upper case, for a tile with room for one, such as a pod's; "?" for a blank name. + static func first(of name: String) -> String { + name.trimmingCharacters(in: .whitespaces).first.map { String($0).uppercased() } ?? "?" + } +} + +/// Somebody's face: a bot's, or a person's avatar. Nobody, or a kind this app +/// doesn't know, leaves the space empty, so what follows lines up with its neighbours. +struct ParticipantFace: View { + let participant: ThreadParticipant? + let size: CGFloat + + var body: some View { + switch participant { + case let .agent(agent): BotFace(look: agent.look, size: size) + case let .person(person): PersonAvatar(name: person.name, email: person.email, image: person.image, size: size) + case .unknown, nil: Color.clear.frame(width: size, height: size) + } + } +} + +/// A channel's face: a `#` on a rounded tile. +struct ChannelFace: View { + let size: CGFloat + + var body: some View { + Icon(.hash, size: size * 26 / 60, strokeWidth: 2) + .foregroundStyle(Palette.softForeground) + .frame(width: size, height: size) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: size * 0.3, style: .continuous)) + .accessibilityHidden(true) + } +} + +/// A pod's tile, as the web's rail draws it: its initial in its colour on a +/// tint of it, or a person for a Personal pod. +struct PodTile: View { + let pod: Pod + var size: CGFloat = 46 + var cornerRadius: CGFloat = 14 + + var body: some View { + let palette = pod.color.flatMap { BotLooks.pods[$0.rawValue] } + Group { + if pod.kind == .personal { + Icon(.user, size: size * 20 / 46, strokeWidth: 2) + } else { + Text(Initials.first(of: pod.name)) + .font(Typeface.rubik(size * 18 / 46, .semibold)) + } + } + .foregroundStyle(palette?.swatch ?? Palette.foreground) + .frame(width: size, height: size) + .background(palette?.tile.resolved ?? Palette.tile, in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)) + .accessibilityHidden(true) + } +} diff --git a/apps/ios/Sugabots/Design/Icon.swift b/apps/ios/Sugabots/Design/Icon.swift new file mode 100644 index 000000000..39d98e550 --- /dev/null +++ b/apps/ios/Sugabots/Design/Icon.swift @@ -0,0 +1,35 @@ +import SwiftUI + +/// A Lucide icon as the web draws it: stroked in the current foreground +/// style, its stroke scaling with its size, as `lucide-react`'s does. +struct Icon: View { + let icon: Lucide + var size: CGFloat = 16 + /// In the icon's own 24-point square, as `strokeWidth` is on the web. + var strokeWidth: CGFloat = 2 + + init(_ icon: Lucide, size: CGFloat = 16, strokeWidth: CGFloat = 2) { + self.icon = icon + self.size = size + self.strokeWidth = strokeWidth + } + + var body: some View { + IconShape(icon: icon) + .stroke(style: StrokeStyle(lineWidth: strokeWidth * size / 24, lineCap: .round, lineJoin: .round)) + .frame(width: size, height: size) + .accessibilityHidden(true) + } +} + +private struct IconShape: Shape { + let icon: Lucide + + func path(in rect: CGRect) -> Path { + var path = Path() + for data in icon.paths { path.addPath(SVGPath.cachedPath(data)) } + return path.applying( + CGAffineTransform(translationX: rect.minX, y: rect.minY).scaledBy(x: rect.width / 24, y: rect.height / 24) + ) + } +} diff --git a/apps/ios/Sugabots/Design/LookGlyphs.swift b/apps/ios/Sugabots/Design/LookGlyphs.swift new file mode 100644 index 000000000..a7c3a64e2 --- /dev/null +++ b/apps/ios/Sugabots/Design/LookGlyphs.swift @@ -0,0 +1,128 @@ +import SwiftUI + +/// A head's shape alone, filled in the current foreground, as the web's `ShapeGlyph`. +struct ShapeGlyph: View { + let shape: AgentShape + var size: CGFloat = 20 + + var body: some View { + Canvas { context, canvas in + let head = BotLooks.head(for: shape) + context.scaleBy(x: canvas.width / 40, y: canvas.height / 40) + for part in head.parts { + context.fill(part.path, with: .foreground) + } + } + .frame(width: size, height: size) + .accessibilityHidden(true) + } +} + +/// A pair of eyes alone, without a head, cropped to the band they sit in, as the web's `EyesGlyph`. +struct EyesGlyph: View { + let face: AgentFace + var width: CGFloat = 34 + + /// The band of the 40-unit face the eyes sit in, as the web's `viewBox="6 12 28 16"`. + private static let band = CGRect(x: 6, y: 12, width: 28, height: 16) + + var body: some View { + Canvas { context, canvas in + let marks = BotLooks.faces(for: face) + context.scaleBy(x: canvas.width / Self.band.width, y: canvas.height / Self.band.height) + context.translateBy(x: -Self.band.minX, y: -Self.band.minY) + for mark in marks { + mark.draw(in: context, with: .foreground, cap: .round) + } + } + .frame(width: width, height: width * Self.band.height / Self.band.width) + .accessibilityHidden(true) + } +} + +/// Which part of a look is being chosen. +enum LookPart: Hashable { + case shape, eyes +} + +/// Every head shape, drawn bare in the look's colour, or every pair of eyes, +/// drawn alone, with the colours along the foot, as the web's `LookStep`. +struct LookStep: View { + @Binding var part: LookPart + @Binding var look: BotLook + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 16) { + ForEach([LookPart.shape, .eyes], id: \.self) { one in + Button(one == .shape ? "Shape" : "Eyes") { part = one } + .font(Typeface.rubik(15, .semibold)) + .foregroundStyle(part == one ? Palette.foreground : Palette.mutedForeground) + .accessibilityAddTraits(part == one ? [.isSelected, .isHeader] : .isHeader) + } + Spacer() + } + .frame(height: 22) + .padding(.horizontal, 20) + .padding(.top, 20) + .padding(.bottom, 16) + ScrollView { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 4), spacing: 8) { + if part == .shape { + ForEach(AgentShape.known, id: \.self) { shape in + tile(label: shape.rawValue, chosen: shape == look.shape) { look.shape = shape } content: { + ShapeGlyph(shape: shape, size: 44).foregroundStyle(BotLooks.palette(for: look.color).face) + } + } + } else { + ForEach(AgentFace.known, id: \.self) { face in + tile(label: face.rawValue, chosen: face == look.face) { look.face = face } content: { + EyesGlyph(face: face, width: 44).foregroundStyle(Palette.foreground) + } + } + } + } + .padding(.horizontal, 20) + .padding(.bottom, 16) + } + colourRow + .padding(.horizontal, 16) + .padding(.vertical, 14) + .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).strokeBorder(Palette.borderStrong)) + .padding(.horizontal, 20) + .padding(.bottom, 20) + } + } + + /// A square to choose one part from, ringed while it is chosen, as `LookStep`'s `Tile`. + private func tile(label: String, chosen: Bool, choose: @escaping () -> Void, @ViewBuilder content: () -> some View) -> some View { + Button(action: choose) { + content() + .frame(width: 68, height: 68) + .background(chosen ? Palette.chip : .clear, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay { if chosen { RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.subtleForeground, lineWidth: 1.5) } } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + .accessibilityAddTraits(chosen ? .isSelected : []) + } + + /// The bot colours as round swatches, two rows of eight, the chosen one ringed, as `ColourRow`. + private var colourRow: some View { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 8), spacing: 12) { + ForEach(AgentColor.known, id: \.self) { color in + let face = BotLooks.palette(for: color).face + Button { look.color = color } label: { + Circle() + .fill(face) + .frame(width: 28, height: 28) + .overlay { if look.color == color { Circle().strokeBorder(face, lineWidth: 2).padding(-4) } } + } + .buttonStyle(.plain) + .accessibilityLabel(color.rawValue) + .accessibilityAddTraits(look.color == color ? .isSelected : []) + } + } + } +} diff --git a/apps/ios/Sugabots/Design/Palette.swift b/apps/ios/Sugabots/Design/Palette.swift new file mode 100644 index 000000000..aac90c49f --- /dev/null +++ b/apps/ios/Sugabots/Design/Palette.swift @@ -0,0 +1,89 @@ +import SwiftUI +import UIKit + +/// The web app's colour tokens (`packages/web/src/app.css`), each as light +/// and dark draw it, in `Palette.generated.swift`. Which one shows follows the +/// theme chosen on You, dark unless changed, as on the web. +enum Palette { + static func themed(light: UIColor, dark: UIColor) -> Color { + Color(UIColor { $0.userInterfaceStyle == .dark ? dark : light }) + } +} + +/// The theme chosen on You, as the web keeps it: dark, light, or the device's. +enum Theme: String, CaseIterable, Identifiable { + case dark, light, system + + static let storageKey = "theme" + + var id: String { rawValue } + + var label: String { + switch self { + case .dark: "Dark" + case .light: "Light" + case .system: "System" + } + } + + var colorScheme: ColorScheme? { + switch self { + case .dark: .dark + case .light: .light + case .system: nil + } + } +} + +/// The web's type: Rubik, and JetBrains Mono for code, addresses and requests. +enum Typeface { + static func rubik(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font { + .custom("Rubik", size: size).weight(weight) + } + + static func mono(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font { + .custom("JetBrains Mono", size: size).weight(weight) + } + + /// Registers the fonts shipped as web fonts, which `UIAppFonts` can't list. + static func registerWebFonts() { + for url in Bundle.main.urls(forResourcesWithExtension: "woff2", subdirectory: nil) ?? [] { + CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil) + } + } +} + +/// A colour as each appearance draws it, for the bot palettes generated from `@sugabots/avatars`. +struct ThemedColor { + let light: Color + let dark: Color + + /// The colour for the appearance showing. + var resolved: Color { + Palette.themed(light: UIColor(light), dark: UIColor(dark)) + } +} + +extension UIColor { + /// `#rrggbb`. Anything else is a programming error in a literal, drawn magenta so it shows. + convenience init(hex: String, alpha: CGFloat = 1) { + let digits = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex + guard digits.count == 6, let value = UInt32(digits, radix: 16) else { + self.init(red: 1, green: 0, blue: 1, alpha: 1) + return + } + self.init( + red: CGFloat((value >> 16) & 0xFF) / 255, + green: CGFloat((value >> 8) & 0xFF) / 255, + blue: CGFloat(value & 0xFF) / 255, + alpha: alpha + ) + } +} + +extension Color { + /// `#rrggbb`, drawn the same in either appearance. + init(hex: String) { + self.init(UIColor(hex: hex)) + } +} diff --git a/apps/ios/Sugabots/Design/ProviderTile.swift b/apps/ios/Sugabots/Design/ProviderTile.swift new file mode 100644 index 000000000..bc6c6e271 --- /dev/null +++ b/apps/ios/Sugabots/Design/ProviderTile.swift @@ -0,0 +1,31 @@ +import SwiftUI + +/// A model provider's mark, as the web's `ProviderTile`: its logo in an +/// outlined 28-point tile, or a 44-point one on a chip, or its initial where +/// it has no logo. +struct ProviderTile: View { + let name: String + let preset: String? + var large = false + + var body: some View { + let shape = RoundedRectangle(cornerRadius: large ? 11 : 7, style: .continuous) + Group { + if let preset, let logo = ProviderLogos.assets[preset] { + Image(logo.image) + .resizable() + .scaledToFit() + .frame(width: large ? 22 : 14, height: large ? 22 : 14) + .scaleEffect(logo.scale) + } else { + Text(Initials.first(of: name)) + .font(Typeface.rubik(large ? 15 : 12, .semibold)) + .foregroundStyle(Palette.softForeground) + } + } + .frame(width: large ? 44 : 28, height: large ? 44 : 28) + .background(large ? Palette.chip : .clear, in: shape) + .overlay { if !large { shape.strokeBorder(Palette.borderStrong) } } + .accessibilityHidden(true) + } +} diff --git a/apps/ios/Sugabots/Design/SVGPath.swift b/apps/ios/Sugabots/Design/SVGPath.swift new file mode 100644 index 000000000..9858751f0 --- /dev/null +++ b/apps/ios/Sugabots/Design/SVGPath.swift @@ -0,0 +1,242 @@ +import SwiftUI + +/// SVG path data as a `Path`: the commands move, line, horizontal, vertical, +/// cubic, smooth cubic, quadratic, arc and close, absolute and relative, which +/// cover the bots' heads and eyes, Lucide's icons and the connection marks. +enum SVGPath { + /// `data` parsed once and kept, for data written into the app, such as an + /// icon's or a head's, which is drawn again on every layout. Data built + /// while the app runs, such as eyes part way through a blink, goes to + /// `path(_:)`, so the cache stays as small as the app's own shapes. + static func cachedPath(_ data: String) -> Path { + cache.path(data) + } + + private static let cache = PathCache() + + /// Parsed paths by their data. SwiftUI may ask for a shape's path off the main thread, so the cache takes a lock. + private final class PathCache: @unchecked Sendable { + private var paths: [String: Path] = [:] + private let lock = NSLock() + + func path(_ data: String) -> Path { + lock.lock() + defer { lock.unlock() } + if let path = paths[data] { return path } + let path = SVGPath.path(data) + paths[data] = path + return path + } + } + + /// `data` parsed, up to its first malformed command. + static func path(_ data: String) -> Path { + var path = Path() + var reader = Reader(data) + var current = CGPoint.zero + var start = CGPoint.zero + var lastControl: CGPoint? + var command: Character = "M" + + while let next = reader.nextCommand(continuing: command) { + command = next + let relative = command.isLowercase + let origin = relative ? current : .zero + func point() -> CGPoint? { + guard let x = reader.number(), let y = reader.number() else { return nil } + return CGPoint(x: origin.x + x, y: origin.y + y) + } + var control: CGPoint? + + switch command.uppercased() { + case "M": + guard let to = point() else { return path } + path.move(to: to) + current = to + start = to + // Pairs after a move's first are lines. + command = relative ? "l" : "L" + case "L": + guard let to = point() else { return path } + path.addLine(to: to) + current = to + case "H": + guard let x = reader.number() else { return path } + current = CGPoint(x: (relative ? current.x : 0) + x, y: current.y) + path.addLine(to: current) + case "V": + guard let y = reader.number() else { return path } + current = CGPoint(x: current.x, y: (relative ? current.y : 0) + y) + path.addLine(to: current) + case "C": + guard let first = point(), let second = point(), let to = point() else { return path } + path.addCurve(to: to, control1: first, control2: second) + control = second + current = to + case "S": + let first = reflected(lastControl, about: current) + guard let second = point(), let to = point() else { return path } + path.addCurve(to: to, control1: first, control2: second) + control = second + current = to + case "Q": + guard let middle = point(), let to = point() else { return path } + path.addQuadCurve(to: to, control: middle) + current = to + case "A": + guard + let rx = reader.number(), let ry = reader.number(), let rotation = reader.number(), + let large = reader.flag(), let sweep = reader.flag(), let to = point() + else { return path } + addArc(to: &path, from: current, to: to, radii: CGSize(width: rx, height: ry), + rotationDegrees: rotation, largeArc: large, sweep: sweep) + current = to + case "Z": + path.closeSubpath() + current = start + default: + return path + } + lastControl = control + } + return path + } + + private static func reflected(_ control: CGPoint?, about point: CGPoint) -> CGPoint { + guard let control else { return point } + return CGPoint(x: 2 * point.x - control.x, y: 2 * point.y - control.y) + } + + /// An elliptical arc as cubic curves, by the endpoint-to-centre conversion in SVG's implementation notes. + private static func addArc( + to path: inout Path, from start: CGPoint, to end: CGPoint, radii: CGSize, + rotationDegrees: Double, largeArc: Bool, sweep: Bool + ) { + var rx = abs(radii.width) + var ry = abs(radii.height) + guard rx > 0, ry > 0, start != end else { + path.addLine(to: end) + return + } + let phi = rotationDegrees * .pi / 180 + let cosPhi = cos(phi) + let sinPhi = sin(phi) + let dx = (start.x - end.x) / 2 + let dy = (start.y - end.y) / 2 + let x1 = cosPhi * dx + sinPhi * dy + let y1 = -sinPhi * dx + cosPhi * dy + + let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry) + if lambda > 1 { + rx *= lambda.squareRoot() + ry *= lambda.squareRoot() + } + let numerator = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1 + let denominator = rx * rx * y1 * y1 + ry * ry * x1 * x1 + let coefficient = (largeArc == sweep ? -1 : 1) * max(0, numerator / denominator).squareRoot() + let cx1 = coefficient * rx * y1 / ry + let cy1 = coefficient * -ry * x1 / rx + let centre = CGPoint( + x: cosPhi * cx1 - sinPhi * cy1 + (start.x + end.x) / 2, + y: sinPhi * cx1 + cosPhi * cy1 + (start.y + end.y) / 2 + ) + + func angle(_ ux: Double, _ uy: Double, _ vx: Double, _ vy: Double) -> Double { + let sign: Double = ux * vy - uy * vx < 0 ? -1 : 1 + let dot = (ux * vx + uy * vy) / ((ux * ux + uy * uy).squareRoot() * (vx * vx + vy * vy).squareRoot()) + return sign * acos(min(1, max(-1, dot))) + } + let theta = angle(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry) + var delta = angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry) + if !sweep, delta > 0 { delta -= 2 * .pi } + if sweep, delta < 0 { delta += 2 * .pi } + + let segments = max(1, Int(ceil(abs(delta) / (.pi / 2)))) + let step = delta / Double(segments) + let handle = 4 / 3 * tan(step / 4) + let centreX = Double(centre.x) + let centreY = Double(centre.y) + func onEllipse(_ t: Double) -> CGPoint { + let along = rx * cos(t) + let across = ry * sin(t) + return CGPoint(x: centreX + along * cosPhi - across * sinPhi, y: centreY + along * sinPhi + across * cosPhi) + } + func derivative(_ t: Double) -> CGPoint { + let along = -rx * sin(t) + let across = ry * cos(t) + return CGPoint(x: along * cosPhi - across * sinPhi, y: along * sinPhi + across * cosPhi) + } + var t = theta + for _ in 0.. Character? { + skipSeparators() + guard index < characters.count else { return nil } + let character = characters[index] + if character.isLetter { + index += 1 + return character + } + return continuing + } + + mutating func flag() -> Bool? { + skipSeparators() + guard index < characters.count, characters[index] == "0" || characters[index] == "1" else { return nil } + defer { index += 1 } + return characters[index] == "1" + } + + mutating func number() -> Double? { + skipSeparators() + var text = "" + var seenDot = false + var seenExponent = false + while index < characters.count { + let character = characters[index] + if character == "-" || character == "+" { + guard text.isEmpty || text.last == "e" || text.last == "E" else { break } + } else if character == "." { + guard !seenDot, !seenExponent else { break } + seenDot = true + } else if character == "e" || character == "E" { + guard !seenExponent, !text.isEmpty else { break } + seenExponent = true + } else if !character.isNumber { + break + } + text.append(character) + index += 1 + } + return Double(text) + } + + private mutating func skipSeparators() { + while index < characters.count, characters[index] == " " || characters[index] == "," { + index += 1 + } + } + } +} diff --git a/apps/ios/Sugabots/Design/WebControls.swift b/apps/ios/Sugabots/Design/WebControls.swift new file mode 100644 index 000000000..9b50c3cc2 --- /dev/null +++ b/apps/ios/Sugabots/Design/WebControls.swift @@ -0,0 +1,1147 @@ +import SwiftUI + +// The web app's controls as a phone draws them (`packages/web/src/ui`), +// at the same sizes, so a page here reads as the same page there. + +extension View { + /// Glass: a translucent fill over a blur of what lies behind, with a hairline + /// edge inside, in the environment's `glassStyle`. + func glass(in shape: S) -> some View { + modifier(Glass(shape: shape)) + } +} + +/// How glass is drawn. +enum GlassStyle { + /// The web's `glass`: its fill over a trace of the system's thinnest + /// material. At full strength the material also lightens what it blurs, + /// unlike the web's `backdrop-filter: blur()`, enough to hide the tab bar's + /// highlight in dark. + case web + /// Frosted, after Slack's header: the system's material at full strength, + /// lighter than the page, so what scrolls under it blurs into shapes. Every + /// page's controls use it, so Back looks the same on each. + case frosted +} + +private struct Glass: ViewModifier { + let shape: S + @Environment(\.glassStyle) private var style + + /// How much of the material the web's glass keeps. + private static var webMaterialStrength: Double { 0.15 } + + func body(content: Content) -> some View { + switch style { + case .web: + content + .background(Palette.glass, in: shape) + .background { shape.fill(.ultraThinMaterial).opacity(Self.webMaterialStrength) } + .overlay(shape.strokeBorder(Palette.glassEdge, lineWidth: 1)) + case .frosted: + content + .background(Frost.tint, in: shape) + .background(.regularMaterial, in: shape) + .overlay( + shape.strokeBorder( + LinearGradient(colors: [Frost.edgeTop, Frost.edgeBottom], startPoint: .top, endPoint: .bottom), + lineWidth: 1 + ) + ) + } + } +} + +/// Frosted glass's colours. +private enum Frost { + /// Lifts the glass a step off the page, a light grey in dark. + static let tint = Palette.themed(light: UIColor(white: 1, alpha: 0.3), dark: UIColor(white: 1, alpha: 0.1)) + /// Its edge: catching the light along the top, fading down the sides. + static let edgeTop = Palette.themed(light: UIColor(white: 0, alpha: 0.08), dark: UIColor(white: 1, alpha: 0.22)) + static let edgeBottom = Palette.themed(light: UIColor(white: 0, alpha: 0.04), dark: UIColor(white: 1, alpha: 0.04)) +} + +private struct GlassStyleKey: EnvironmentKey { + static let defaultValue = GlassStyle.frosted +} + +extension EnvironmentValues { + /// How glass under it is drawn: frosted, or the web's for the tab bar. + var glassStyle: GlassStyle { + get { self[GlassStyleKey.self] } + set { self[GlassStyleKey.self] = newValue } + } +} + +/// The gap above a page's header, as the web's `pt-[max(12px,env(safe-area-inset-top))]` +/// draws it in an installed app: `fromScreenTop` points from the top of the screen, +/// or the safe area where that is deeper. The header is laid out below the safe area +/// already, so the gap is what `fromScreenTop` leaves beyond it: none under a status +/// bar, and all of it in landscape or a sheet, where the top has no safe area. +private struct PageTopPadding: ViewModifier { + let fromScreenTop: CGFloat + /// How deep the safe area is above the header. + @State private var safeAreaTop: CGFloat = 0 + + func body(content: Content) -> some View { + content + .padding(.top, max(0, fromScreenTop - safeAreaTop)) + .background { + // Reaching up into the safe area, the background measures how deep it is above the header. + Color.clear + .ignoresSafeArea(edges: .top) + .onGeometryChange(for: CGFloat.self) { $0.safeAreaInsets.top } action: { safeAreaTop = $0 } + } + } +} + +/// The app window's safe area: the status bar or Dynamic Island above, and the +/// home indicator below, for what is sized outside a view, such as the tab +/// bar's room. Pages fill the window, so this is their safe area too. +@MainActor +enum WindowInsets { + static var current: UIEdgeInsets { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + return scenes.first { $0.activationState == .foregroundActive }?.keyWindow?.safeAreaInsets + ?? scenes.first?.windows.first?.safeAreaInsets + ?? .zero + } + + /// How far the tab bar reaches down into the home indicator's band, as + /// Slack's does, leaving the content more room. + static let barReach = NativeConstants.tabBarSink + + /// How far the header rises into the safe area at the top: as far as keeps + /// it `headerGapBelowIsland` below the Dynamic Island, which ends + /// `dynamicIslandClearance` above the safe area's edge. A notch or status bar gives nothing. + static var headerRise: CGFloat { + current.top > deepestTopInsetWithoutIsland ? dynamicIslandClearance - NativeConstants.headerGapBelowIsland : 0 + } + + /// The deepest safe area at the top of an iPhone without a Dynamic Island: a notch's. + private static let deepestTopInsetWithoutIsland: CGFloat = 47 + + /// How far above the safe area's top edge the Dynamic Island ends. + private static let dynamicIslandClearance: CGFloat = 11 + + /// How far the tab bar sinks into the safe area at the foot: up to `barReach`, + /// keeping `tabBarLeastGapBelow` off the screen's edge. + static var tabBarSink: CGFloat { min(barReach, max(0, current.bottom - tabBarLeastGapBelow)) } + + /// The least room the tab bar leaves between itself and the bottom of the screen. + private static let tabBarLeastGapBelow: CGFloat = 8 +} + +/// How far a page's side bars (the tab bar, the composer) sit in from the screen's edges. +let barSideInset = NativeConstants.barSideInset + +extension View { + /// The gap above a page's header: see `PageTopPadding`. Pages take 12 + /// points, a dialog's form 16, as the web's `max(…, safe area)` for each. + func pageTopPadding(_ fromScreenTop: CGFloat = 12) -> some View { + modifier(PageTopPadding(fromScreenTop: fromScreenTop)) + } + + /// A page header's room: 16 points in from the sides, or `trailing` on the + /// right where a bar button's own room makes up the rest, the page's top + /// gap above, and 8 points below. + func pageHeaderInsets(trailing: CGFloat = 16) -> some View { + padding(.leading, 16) + .padding(.trailing, trailing) + .pageTopPadding() + .padding(.bottom, 8) + } +} + +/// A phone's round glass control at a page's top corners, as the web's +/// `FLOATING_ON_PHONE` draws it: an icon on a 44-point glass circle, filled +/// stronger while pressed. Its icon is 20 points by default, with Lucide's +/// stroke; where the web gives an icon its own, so does the caller. +struct GlassRoundIcon: View { + let icon: Lucide + var size: CGFloat = 20 + var strokeWidth: CGFloat = 2 + var pressed = false + + var body: some View { + Icon(icon, size: size, strokeWidth: strokeWidth) + .foregroundStyle(Palette.foreground) + .frame(width: 44, height: 44) + .background(pressed ? Palette.hoverStrong : .clear, in: Circle()) + .glass(in: Circle()) + } +} + +/// A `GlassRoundIcon` that is a button: Back, Close, a page's + or Mark done. +/// Its icon is Back's chevron's size unless it's given another, as the web's. +struct GlassRoundButton: View { + let icon: Lucide + let label: String + var iconSize: CGFloat = 22 + var strokeWidth: CGFloat = 2.25 + let action: () -> Void + + var body: some View { + Button(action: action) { EmptyView() } + .buttonStyle(PressStyle(icon: icon, size: iconSize, strokeWidth: strokeWidth)) + .accessibilityLabel(label) + } + + /// Draws the button as its icon, filled stronger while pressed, as the web's `active:bg-hover-strong`. + private struct PressStyle: ButtonStyle { + let icon: Lucide + let size: CGFloat + let strokeWidth: CGFloat + + func makeBody(configuration: Configuration) -> some View { + GlassRoundIcon(icon: icon, size: size, strokeWidth: strokeWidth, pressed: configuration.isPressed) + .contentShape(Circle()) + } + } +} + +/// A header's round glass ⋯ that opens a menu. The menu is UIKit's: SwiftUI's +/// `Menu` places its own button clear of the safe area, wherever its frame is, +/// so in a header that reaches into the safe area it would sit lower than the +/// controls beside it. +struct GlassMenuButton: View { + struct Item { + let title: String + let systemImage: String + let action: () -> Void + } + + let label: String + let items: [Item] + + var body: some View { + GlassRoundIcon(icon: .ellipsis) + .overlay { MenuTarget(label: label, items: items) } + } + + /// A clear button over the glass that opens the menu as it's tapped. + private struct MenuTarget: UIViewRepresentable { + let label: String + let items: [Item] + + func makeUIView(context _: Context) -> UIButton { + let button = UIButton(type: .custom) + button.showsMenuAsPrimaryAction = true + return button + } + + func updateUIView(_ button: UIButton, context _: Context) { + button.accessibilityLabel = label + button.menu = UIMenu(children: items.map { item in + UIAction(title: item.title, image: UIImage(systemName: item.systemImage)) { _ in item.action() } + }) + } + } +} + +/// Back, at a page's top left on a phone: a glass circle with a chevron. +struct PhoneBackButton: View { + var label = "Back" + var action: (() -> Void)? + @Environment(\.dismiss) private var dismiss + + var body: some View { + GlassRoundButton(icon: .chevronLeft, label: label) { + if let action { action() } else { dismiss() } + } + } +} + +/// Back as words with a chevron, at the top left of the pages outside a +/// workspace and of setup's steps, as the web's `AuthLayout` and onboarding draw it. +struct TextBackButton: View { + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: 2) { + Icon(.chevronLeft, size: 16, strokeWidth: 2.4) + Text("Back") + } + .font(Typeface.rubik(14.5, .medium)) + .foregroundStyle(Palette.foreground) + } + .buttonStyle(.plain) + } +} + +/// A quiet text action under a form, such as Forgot password or Skip for now. +struct QuietLinkStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(Typeface.rubik(14, .medium)) + .foregroundStyle(Palette.mutedForeground) + .padding(6) + .opacity(configuration.isPressed ? 0.7 : 1) + } +} + +/// The web's `Button`, in its variants, at a phone's height for a page's main action. +struct WebButtonStyle: ButtonStyle { + enum Variant { + /// Filled with the foreground: the one strong action. + case primary + case secondary + /// A step stronger than secondary, to read on a card's fill. + case muted + case ghost + case destructive + } + + enum Size { + case small + case regular + case large + /// A phone dialog's footer: full width and 44 tall. + case phone + /// A full-screen page's action at its top right: 44 tall and fully + /// round, as the web's `h-11 rounded-full px-5 text-[15px]`. + case pill + } + + var variant = Variant.primary + var size = Size.regular + /// Across the whole width, as a form's main action at its foot. + var fullWidth = false + @Environment(\.isEnabled) private var isEnabled + + func makeBody(configuration: Configuration) -> some View { + let pressed = configuration.isPressed + configuration.label + .font(Typeface.rubik(fontSize, variant == .ghost || variant == .destructive ? .medium : .semibold)) + .lineLimit(1) + .padding(.horizontal, horizontalPadding) + .frame(height: height) + .frame(maxWidth: size == .phone || fullWidth ? .infinity : nil) + .foregroundStyle(foreground) + .background(background(pressed: pressed), in: RoundedRectangle(cornerRadius: size == .pill ? height / 2 : 8, style: .continuous)) + .opacity(!isEnabled && (variant == .ghost || variant == .destructive) ? 0.5 : 1) + .contentShape(Rectangle()) + } + + private var height: CGFloat { + switch size { + case .small: 29 + case .regular: 36 + case .large: 48 + case .phone, .pill: 44 + } + } + + private var fontSize: CGFloat { + switch size { + case .small: 13 + case .regular: 14 + // The web's `text-lg`. + case .large: 15 + case .phone, .pill: 15 + } + } + + private var horizontalPadding: CGFloat { + switch size { + case .small: 14 + case .regular, .phone: 16 + case .large, .pill: 20 + } + } + + private var foreground: Color { + switch variant { + case .primary: isEnabled ? Palette.primaryForeground : Palette.disabledForeground + case .secondary, .muted: isEnabled ? Palette.foreground : Palette.disabledForeground + case .ghost: Palette.mutedForeground + case .destructive: Palette.destructiveText + } + } + + private func background(pressed: Bool) -> Color { + switch variant { + case .primary: !isEnabled ? Palette.chip : pressed ? Palette.primaryHover : Palette.primary + case .secondary: pressed ? Palette.hover : Palette.chip + case .muted: pressed ? Palette.hoverStrong : Palette.hover + case .ghost: pressed ? Palette.hover : .clear + case .destructive: pressed ? Palette.destructiveHover : .clear + } + } +} + +/// The top of a page that fills the screen, as the web's phone New bot and +/// Look editor and a dialog's form: a round button at the left, the title +/// centred on one line, and perhaps the page's action, a `.pill` button, at +/// the right; `topPadding` from the top of the screen, as `pageTopPadding`. +struct ScreenHeader: View { + let title: String + var topPadding: CGFloat = 12 + @ViewBuilder var leading: Leading + @ViewBuilder var trailing: Trailing + + /// The room either side of the title, for a round button and the gap beside it. + private static var titleSideClearance: CGFloat { 56 } + + var body: some View { + ZStack { + Text(title) + .font(Typeface.rubik(17, .semibold)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .padding(.horizontal, Self.titleSideClearance) + .accessibilityAddTraits(.isHeader) + HStack { + leading + Spacer() + trailing + } + } + .padding(.horizontal, 16) + .pageTopPadding(topPadding) + } +} + +/// A dialog's form as a phone shows it, the whole screen: Close at the top +/// left and the title centred, the body scrolling under them, and the action +/// across the foot. +struct DialogForm: View { + let title: String + /// The footer's button, by its title and what it does, or nil for a form that acts as it goes. + var action: (title: String, run: () -> Void)? + var actionDisabled = false + /// Shown in place of Close, for a step after the first. + var onBack: (() -> Void)? + /// Whether Close shows; hidden while a step can't be left. + var closable = true + var gap: CGFloat = 14 + @ViewBuilder var content: Body + @Environment(\.dismiss) private var dismiss + + var body: some View { + VStack(spacing: 0) { + ScreenHeader(title: title, topPadding: 16) { + if let onBack { + GlassRoundButton(icon: .chevronLeft, label: "Back", action: onBack) + } else if closable { + GlassRoundButton(icon: .x, label: "Close", iconSize: 20) { dismiss() } + } + } trailing: { + EmptyView() + } + .padding(.bottom, 12) + ScrollView { + VStack(alignment: .leading, spacing: gap) { content } + .padding(.horizontal, 16) + .padding(.top, 4) + .padding(.bottom, 20) + } + .scrollDismissesKeyboard(.interactively) + if let action { + Button(action: action.run) { Text(action.title) } + .buttonStyle(WebButtonStyle(size: .phone)) + .disabled(actionDisabled) + .padding(.horizontal, 16) + .padding(.top, 12) + .padding(.bottom, 16) + } + } + .background(Palette.panel.ignoresSafeArea()) + } +} + +// MARK: Settings + +extension View { + /// A card's chrome: `fill` behind, the corners rounded, held by `border`. + func cardChrome(fill: Color, border: Color) -> some View { + let shape = RoundedRectangle(cornerRadius: 12, style: .continuous) + return background(fill).clipShape(shape).overlay(shape.strokeBorder(border)) + } + + /// A settings card's chrome: the barely lifted fill, its corners rounded, held by its border. + func settingsCard() -> some View { + cardChrome(fill: Palette.settingsCard, border: Palette.settingsCardBorder) + } + + /// A settings row's room: `SettingsRowMetrics.sideInset` at the sides, + /// `vertical` above and below, and at least `minHeight` tall. + func settingsRowPadding(vertical: CGFloat = 12, minHeight: CGFloat = SettingsRowMetrics.minHeight) -> some View { + padding(.horizontal, SettingsRowMetrics.sideInset) + .padding(.vertical, vertical) + .frame(minHeight: minHeight) + } +} + +/// The sizes a settings card's rows share, as the web's settings rows on a phone. +enum SettingsRowMetrics { + /// The room at a row's left and right. + static let sideInset: CGFloat = 16 + /// The least height of a row. + static let minHeight: CGFloat = 56 + /// The least height of a row whose control is a menu, a stepper or a secret's field. + static let compactMinHeight: CGFloat = 46 + /// The least width of the label at the start of a row that holds a control, so a card's controls line up. + static let labelWidth: CGFloat = 96 +} + +/// A settings card: rows on a barely lifted fill, held by its border. +struct SettingsGroup: View { + var label: String? + var description: String? + var note: String? + @ViewBuilder var action: Action + @ViewBuilder var content: Content + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + if label != nil || Action.self != EmptyView.self { + HStack(spacing: 8) { + if let label { + Text(label) + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityAddTraits(.isHeader) + } + action + } + .padding(.horizontal, 2) + .padding(.bottom, description == nil ? 10 : 4) + } + if let description { + Text(description) + .font(Typeface.rubik(13)) + .lineSpacing(3) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 2) + .padding(.bottom, 10) + } + VStack(spacing: 0) { content } + .settingsCard() + if let note { + Text(note) + .font(Typeface.rubik(13)) + .lineSpacing(3) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 2) + .padding(.top, 10) + } + } + } +} + +extension SettingsGroup where Action == EmptyView { + init(label: String? = nil, description: String? = nil, note: String? = nil, @ViewBuilder content: () -> Content) { + self.init(label: label, description: description, note: note, action: { EmptyView() }, content: content) + } +} + +/// The line between a settings card's rows; leave it off after the last. +struct SettingsDivider: View { + var body: some View { + Rectangle().fill(Palette.border).frame(height: 1) + } +} + +/// Rows in a settings card, with a line between each and none after the last. +struct DividedRows: View { + let data: Data + /// What tells one row from another, as `ForEach`'s `id`. + let id: KeyPath + @ViewBuilder let row: (Data.Element) -> Row + + var body: some View { + ForEach(Array(data.enumerated()), id: (\EnumeratedSequence.Element.element).appending(path: id)) { index, element in + if index > 0 { SettingsDivider() } + row(element) + } + } +} + +extension DividedRows where Data.Element: Identifiable, ID == Data.Element.ID { + init(data: Data, @ViewBuilder row: @escaping (Data.Element) -> Row) { + self.init(data: data, id: \.id, row: row) + } +} + +/// A row of a settings card: perhaps an icon, its label with a line under it, +/// what it holds at its end, and a chevron when it opens a page. +struct SettingsRow: View { + let label: String + var sub: String? + var chevron = false + @ViewBuilder var leading: Leading + @ViewBuilder var trailing: Trailing + + var body: some View { + HStack(spacing: 14) { + leading + VStack(alignment: .leading, spacing: 2) { + Text(label) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + if let sub { + Text(sub) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + trailing + if chevron { + Icon(.chevronRight, size: 14, strokeWidth: 2).foregroundStyle(Palette.subtleForeground) + } + } + .settingsRowPadding() + .contentShape(Rectangle()) + } +} + +extension SettingsRow where Leading == EmptyView, Trailing == EmptyView { + init(label: String, sub: String? = nil, chevron: Bool = false) { + self.init(label: label, sub: sub, chevron: chevron, leading: { EmptyView() }, trailing: { EmptyView() }) + } +} + +extension SettingsRow where Leading == EmptyView { + init(label: String, sub: String? = nil, chevron: Bool = false, @ViewBuilder trailing: () -> Trailing) { + self.init(label: label, sub: sub, chevron: chevron, leading: { EmptyView() }, trailing: trailing) + } +} + +extension SettingsRow where Trailing == EmptyView { + init(label: String, sub: String? = nil, chevron: Bool = false, @ViewBuilder leading: () -> Leading) { + self.init(label: label, sub: sub, chevron: chevron, leading: leading, trailing: { EmptyView() }) + } +} + +/// A settings row shaded under a finger, so a tap shows it landed. +struct SettingsRowPressStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .background(configuration.isPressed ? Palette.rowSelected : .clear) + } +} + +/// A settings row with its label at the left and a control filling the rest. +struct SettingsControlRow: View { + let label: String + /// Stacks the control under the label, for one too wide to sit beside it. + var stacked = false + @ViewBuilder var control: Control + + var body: some View { + let layout = stacked ? AnyLayout(VStackLayout(alignment: .leading, spacing: 8)) : AnyLayout(HStackLayout(spacing: 14)) + layout { + Text(label) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .frame(minWidth: SettingsRowMetrics.labelWidth, alignment: .leading) + .fixedSize() + control + } + .settingsRowPadding(vertical: 10) + } +} + +/// A settings row that is a text field. +struct SettingsFieldRow: View { + let label: String + @Binding var value: String + let placeholder: String + var maxLength: Int? + var mono = false + var secret = false + + var body: some View { + SettingsControlRow(label: label) { + Group { + if secret { + SecureField("", text: limited, prompt: prompt) + } else { + TextField("", text: limited, prompt: prompt) + .autocorrectionDisabled() + } + } + .font(mono ? Typeface.mono(16) : Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .accessibilityLabel(label) + } + } + + private var prompt: Text { + Text(placeholder).foregroundStyle(Palette.subtleForeground) + } + + private var limited: Binding { + maxLength.map { $value.limited(to: $0) } ?? $value + } +} + +extension Binding { + /// The text cut to `maxLength` characters as it's typed, as a web field's `maxLength`. + func limited(to maxLength: Int) -> Binding { + Binding(get: { wrappedValue }, set: { wrappedValue = String($0.prefix(maxLength)) }) + } +} + +/// What a setting is, in grey at a row's end. +struct SettingsValue: View { + let text: String + + var body: some View { + Text(text) + .font(Typeface.rubik(15)) + .foregroundStyle(Palette.mutedForeground) + .lineLimit(1) + // As the web's `shrink-0`: the value keeps its width, and the label beside it wraps. + .fixedSize() + } +} + +/// A small outlined button at a row's end. +struct SettingsRowButtonStyle: ButtonStyle { + @Environment(\.isEnabled) private var isEnabled + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 12) + .frame(height: 30) + .background(configuration.isPressed ? Palette.rowSelected : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong)) + .opacity(isEnabled ? 1 : 0.5) + } +} + +/// A radio's mark: a ring, filled with a dot when chosen. +struct SettingsRadioMark: View { + let checked: Bool + + var body: some View { + Circle() + .strokeBorder(checked ? Palette.foreground : Palette.borderDashed, lineWidth: 1) + .frame(width: 16, height: 16) + .overlay { if checked { Circle().fill(Palette.foreground).frame(width: 8, height: 8) } } + .accessibilityHidden(true) + } +} + +/// A choice among a card's rows, as the web's provider radios: the choice's +/// initial, its name, perhaps a word beside it such as In use, a line under +/// it, and the radio's mark at the end. +struct SettingsRadioRow: View { + let name: String + let description: String + var badge: String? + let checked: Bool + let choose: () -> Void + + var body: some View { + Button(action: choose) { + HStack(spacing: 14) { + SettingsRowIcon { Text(Initials.first(of: name)) } + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 8) { + Text(name).font(Typeface.rubik(13, .medium)).foregroundStyle(Palette.foreground) + if let badge { Text(badge).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) } + } + Text(description).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + SettingsRadioMark(checked: checked) + } + .settingsRowPadding() + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + .accessibilityAddTraits(checked ? .isSelected : []) + } +} + +/// A small square mark at a row's start, such as an initial or a +. +struct SettingsRowIcon: View { + @ViewBuilder var content: Content + + var body: some View { + content + .font(Typeface.rubik(12, .semibold)) + .foregroundStyle(Palette.softForeground) + .frame(width: 28, height: 28) + .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(Palette.borderStrong)) + .accessibilityHidden(true) + } +} + +/// The last row of a card that adds another of what it lists. +struct SettingsAddRow: View { + let label: String + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: 14) { + SettingsRowIcon { Icon(.plus, size: 14, strokeWidth: 2) } + Text(label).font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + Spacer(minLength: 0) + } + .settingsRowPadding() + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + } +} + +/// How a test went: a green or red dot and what it said. +struct SettingsTestOutcome: View { + let good: Bool + let text: String + + var body: some View { + HStack(spacing: 6) { + Circle().fill(good ? Palette.success : Palette.destructive).frame(width: 6, height: 6) + Text(text).lineLimit(1) + } + .font(Typeface.rubik(12)) + .foregroundStyle(good ? Palette.mutedForeground : Palette.destructiveText) + } +} + +/// A green pill saying something is on, such as Connected. +struct SettingsStatusBadge: View { + let text: String + + var body: some View { + HStack(spacing: 6) { + Circle().fill(Palette.success).frame(width: 6, height: 6) + Text(text) + } + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.successText) + .padding(.horizontal, 8) + .frame(height: 22) + .background(Palette.success.opacity(0.12), in: Capsule()) + } +} + +/// A card for something that can't be undone: what it does, and its red action. +struct SettingsDanger: View { + let label: String + let description: String + /// What its red button says. + let actionTitle: String + var disabledReason: String? + let onTap: () -> Void + + var body: some View { + HStack(spacing: 16) { + VStack(alignment: .leading, spacing: 2) { + Text(label).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground) + Text(disabledReason ?? description) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + Button(actionTitle, action: onTap) + .buttonStyle(WebButtonStyle(variant: .destructive, size: .small)) + .disabled(disabledReason != nil) + .accessibilityLabel(label) + } + .settingsRowPadding() + .settingsCard() + } +} + +/// A settings page on a phone: Back floating at the top left, perhaps an +/// action at the top right, then the title, a line under it, and the groups. +struct SettingsPage: View { + var title: String? + var description: String? + /// A picture before the title, such as a bot's face. + var hero: Hero? + /// Whether the page has its own Back; the top of a stack has none. + var back = true + @ViewBuilder var headerAction: HeaderAction + @ViewBuilder var content: Content + + init( + title: String? = nil, + description: String? = nil, + hero: Hero?, + back: Bool = true, + @ViewBuilder headerAction: () -> HeaderAction, + @ViewBuilder content: () -> Content + ) { + self.title = title + self.description = description + self.hero = hero + self.back = back + self.headerAction = headerAction() + self.content = content() + } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 32) { + if let title { + HStack(spacing: 14) { + if let hero { hero.frame(width: 44, height: 44) } + VStack(alignment: .leading, spacing: hero == nil ? 4 : 2) { + // The web's `text-base` on a 30-point line, tracked tight. + Text(title) + .font(Typeface.rubik(16, .semibold)) + .tracking(-0.4) + .frame(minHeight: 30, alignment: .leading) + .foregroundStyle(Palette.foreground) + .lineLimit(hero == nil ? nil : 1) + if let description { + Text(description) + .font(Typeface.rubik(13)) + .lineSpacing(3) + .foregroundStyle(Palette.mutedForeground) + } + } + } + } + content + } + .padding(.horizontal, 16) + .padding(.top, 12) + .padding(.bottom, 80) + } + .safeAreaInset(edge: .top, spacing: 0) { + if back || HeaderAction.self != EmptyView.self { + HStack { + if back { PhoneBackButton() } + Spacer() + headerAction + } + .pageHeaderInsets() + } + } + .background(Palette.background.ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + } +} + +extension SettingsPage where Hero == EmptyView { + init( + title: String? = nil, + description: String? = nil, + back: Bool = true, + @ViewBuilder headerAction: () -> HeaderAction, + @ViewBuilder content: () -> Content + ) { + self.init(title: title, description: description, hero: nil, back: back, headerAction: headerAction, content: content) + } +} + +extension SettingsPage where HeaderAction == EmptyView { + init(title: String? = nil, description: String? = nil, hero: Hero, back: Bool = true, @ViewBuilder content: () -> Content) { + self.init(title: title, description: description, hero: hero, back: back, headerAction: { EmptyView() }, content: content) + } +} + +extension SettingsPage where HeaderAction == EmptyView, Hero == EmptyView { + init(title: String? = nil, description: String? = nil, back: Bool = true, @ViewBuilder content: () -> Content) { + self.init(title: title, description: description, hero: nil, back: back, headerAction: { EmptyView() }, content: content) + } +} + +/// A settings row that is a switch, named by its label. +struct SwitchRow: View { + let label: String + @Binding var isOn: Bool + var fontSize: CGFloat = 16 + + var body: some View { + HStack(spacing: 12) { + Text(label) + .font(Typeface.rubik(fontSize)) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity, alignment: .leading) + WebToggle(label: label, isOn: $isOn) + } + .settingsRowPadding(vertical: 10) + } +} + +/// The web's `SettingsChoiceRow` on a phone: the label over a segmented choice across the row. +struct SettingsChoiceRow: View { + let label: String + let options: [(value: Value, label: String)] + let value: Value? + let choose: (Value) -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text(label).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground) + SegmentedChoice(label: label, options: options, value: value, fill: true, choose: choose) + } + .settingsRowPadding(vertical: 10) + } +} + +/// The web's `Note`: an aside on the list colour, with an info mark. +struct InfoNote: View { + let text: String + + var body: some View { + HStack(alignment: .top, spacing: 12) { + Icon(.info, size: 16).foregroundStyle(Palette.subtleForeground).padding(.top, 2) + Text(text) + .font(Typeface.rubik(14)) + .lineSpacing(4) + .foregroundStyle(Palette.softForeground) + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } +} + +/// A settings row whose value is picked from a menu, its arrow at the end, as the web's `MenuRow`. +struct MenuRow: View { + let label: String + let options: [(value: Value, label: String)] + let value: Value + @ViewBuilder var mark: (Value) -> Mark + let choose: (Value) -> Void + + var body: some View { + Menu { + ForEach(Array(options.enumerated()), id: \.offset) { _, option in + Button { choose(option.value) } label: { + if option.value == value { Label(option.label, systemImage: "checkmark") } else { Text(option.label) } + } + } + } label: { + HStack(spacing: 12) { + Text(label) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .frame(minWidth: SettingsRowMetrics.labelWidth, alignment: .leading) + HStack(spacing: 10) { + mark(value) + Text(options.first { $0.value == value }?.label ?? "") + .font(Typeface.rubik(14.5)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Icon(.chevronDown, size: 15, strokeWidth: 2.4).foregroundStyle(Palette.subtleForeground) + } + .settingsRowPadding(vertical: 10, minHeight: SettingsRowMetrics.compactMinHeight) + .contentShape(Rectangle()) + } + .accessibilityLabel("\(label): \(options.first { $0.value == value }?.label ?? "")") + } +} + +extension MenuRow where Mark == EmptyView { + init(label: String, options: [(value: Value, label: String)], value: Value, choose: @escaping (Value) -> Void) { + self.init(label: label, options: options, value: value, mark: { _ in EmptyView() }, choose: choose) + } +} + +/// A round − or + beside a stepped value. +struct StepButton: View { + let icon: Lucide + let label: String + let action: (() -> Void)? + + var body: some View { + Button { action?() } label: { + Icon(icon, size: 14, strokeWidth: 2.4) + .foregroundStyle(Palette.foreground) + .frame(width: 30, height: 30) + .background(Palette.chip, in: Circle()) + } + .buttonStyle(.plain) + .disabled(action == nil) + .opacity(action == nil ? 0.45 : 1) + .accessibilityLabel(label) + } +} + +/// A row with a value between − and +. +struct StepperRow: View { + let label: String + let value: String + let lessLabel: String + let moreLabel: String + /// Nil when the value is as low as it goes. + let onLess: (() -> Void)? + /// Nil when the value is as high as it goes. + let onMore: (() -> Void)? + + var body: some View { + HStack(spacing: 12) { + Text(label).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground).frame(minWidth: SettingsRowMetrics.labelWidth, alignment: .leading) + Spacer(minLength: 0) + StepButton(icon: .minus, label: lessLabel, action: onLess) + Text(value) + .font(Typeface.rubik(16, .semibold)) + .monospacedDigit() + .foregroundStyle(Palette.foreground) + .frame(minWidth: 64) + .accessibilityLabel(label) + .accessibilityValue(value) + StepButton(icon: .plus, label: moreLabel, action: onMore) + } + .settingsRowPadding(vertical: 10, minHeight: SettingsRowMetrics.compactMinHeight) + } +} + +/// A search box: a magnifier and the field, as the web's search inputs. +struct SearchField: View { + enum Style { + /// On a page: a chip-filled box. + case filled + /// At the top of a settings card: an outlined box on the page's colour. + case inCard + } + + let placeholder: String + @Binding var text: String + var style = Style.filled + + var body: some View { + let inCard = style == .inCard + HStack(spacing: inCard ? 8 : 9) { + Icon(.search, size: inCard ? 14 : 15).foregroundStyle(inCard ? Palette.subtleForeground : Palette.mutedForeground) + TextField("", text: $text, prompt: Text(placeholder).foregroundStyle(inCard ? Palette.subtleForeground : Palette.mutedForeground)) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .submitLabel(.search) + .accessibilityLabel(placeholder) + } + .padding(.horizontal, inCard ? 10 : 12) + .padding(.vertical, inCard ? 0 : 9) + .frame(height: inCard ? 34 : nil) + .background(inCard ? Palette.background : Palette.chip, in: RoundedRectangle(cornerRadius: inCard ? 10 : 12, style: .continuous)) + .overlay { if inCard { RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.borderStrong) } } + } +} + +/// A failure in a form, in red, as the web's `Alert`. +struct FormAlert: View { + let text: String + + var body: some View { + Text(text) + .font(Typeface.rubik(13)) + .lineSpacing(2) + .foregroundStyle(Palette.destructiveText) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityAddTraits(.isStaticText) + } +} diff --git a/apps/ios/Sugabots/Emoji/EmojiData.swift b/apps/ios/Sugabots/Emoji/EmojiData.swift new file mode 100644 index 000000000..1d28c4f22 --- /dev/null +++ b/apps/ios/Sugabots/Emoji/EmojiData.swift @@ -0,0 +1,176 @@ +import Foundation + +/// One emoji, as `@sugabots/emoji` lists it. +struct Emoji: Decodable, Hashable, Identifiable { + /// A skin tone, as the dataset names it. + enum SkinTone: String, CaseIterable, Decodable { + case light + case mediumLight = "medium-light" + case medium + case mediumDark = "medium-dark" + case dark + } + + let emoji: String + /// Its name, as "Party popper". + let label: String + /// The index of its category in `EmojiDataset.categories`. + let category: Int + /// The Emoji version that added it, which decides whether this device can draw it. + let version: Double + /// Words it is found by, besides its name and shortcodes. + let tags: [String] + /// Its `:shortcodes:`, without the colons, lower case. + let shortcodes: [String] + /// The same emoji in each skin tone, for one that has them. + let skins: [String: String]? + /// Whether it is a country's or region's flag. + let countryFlag: Bool? + + var id: String { emoji } + + /// The emoji in `tone`, or as it is when it has no skin tones or none is chosen. + func inTone(_ tone: SkinTone?) -> String { + guard let tone, let toned = skins?[tone.rawValue] else { return emoji } + return toned + } +} + +/// The emoji the app offers, wherever one is chosen, as the web's +/// `useAvailableEmoji`: those of `@sugabots/emoji` this device can draw, in +/// their categories, read once from the copy built into the app. +struct EmojiDataset: Decodable { + struct Category: Decodable, Hashable { + let index: Int + let label: String + } + + let categories: [Category] + /// Each skin tone's name, as "Medium-dark skin tone". + let skinTones: [String: String] + let emojis: [Emoji] + + /// The emoji, read the first time they are asked for. `Emoji.json` is built + /// into the app, so failing to read it is a broken build: it stops a debug + /// build, and leaves a release build with no emoji. + static let shared: EmojiDataset = { + let dataset: EmojiDataset + do { + guard let url = Bundle.main.url(forResource: "Emoji", withExtension: "json") else { + throw CocoaError(.fileNoSuchFile) + } + dataset = try JSONDecoder().decode(EmojiDataset.self, from: Data(contentsOf: url)) + } catch { + assertionFailure("Emoji.json, built into the app, can't be read: \(error)") + return EmojiDataset(categories: [], skinTones: [:], emojis: []) + } + let newest = newestDrawableVersion + return EmojiDataset( + categories: dataset.categories, + skinTones: dataset.skinTones, + emojis: dataset.emojis.filter { $0.version <= newest } + ) + }() + + /// The newest Emoji version this version of iOS draws; its fonts gain a version's emoji all at once. + private static var newestDrawableVersion: Double { + if #available(iOS 18.4, *) { return 16 } + if #available(iOS 17.4, *) { return 15.1 } + return 15 + } + + /// The emoji whose name or words hold `search`, best first, as the web's + /// picker ranks them: one named so ahead of one tagged so, and one tagged + /// with more such words ahead of one with fewer. All of them, in order, without a search. + func searched(_ search: String) -> [Emoji] { + let needle = search.trimmingCharacters(in: .whitespaces).lowercased() + guard !needle.isEmpty else { return emojis } + var scored: [(emoji: Emoji, score: Int, order: Int)] = [] + for (order, emoji) in emojis.enumerated() { + let named = emoji.label.lowercased().contains(needle) ? 10 : 0 + let tagged = (emoji.tags + emoji.shortcodes).filter { $0.lowercased().contains(needle) }.count + if named + tagged > 0 { scored.append((emoji, named + tagged, order)) } + } + scored.sort { first, second in + first.score != second.score ? first.score > second.score : first.order < second.order + } + return scored.map(\.emoji) + } + + /// The emoji `text` is, in any skin tone, ignoring variation selectors, as frimousse looks one up. + func details(of text: String) -> Emoji? { + Self.byText[Self.withoutSelectors(text)] + } + + private static let byText: [String: Emoji] = { + var found: [String: Emoji] = [:] + for emoji in shared.emojis { + found[withoutSelectors(emoji.emoji)] = emoji + for toned in (emoji.skins ?? [:]).values where found[withoutSelectors(toned)] == nil { + found[withoutSelectors(toned)] = emoji + } + } + return found + }() + + private static func withoutSelectors(_ text: String) -> String { + String(text.unicodeScalars.filter { $0.value != 0xFE0E && $0.value != 0xFE0F }.map(Character.init)) + } +} + +/// Emoji by `:shortcode:`, as `@sugabots/emoji`'s `findByShortcode` and +/// `emojiNamed`, for the composer's suggestions and completion. +enum EmojiShortcodes { + /// How many suggestions show at once. + private static let maxMatches = 8 + + /// The emoji whose shortcodes match `query`, best first: one that is it, + /// then one that starts with it, then one with a word that starts with it. + static func matching(_ query: String) -> [Emoji] { + let lowered = query.lowercased() + var ranked: [(emoji: Emoji, rank: Int, order: Int)] = [] + for (order, emoji) in EmojiDataset.shared.emojis.enumerated() { + let best = emoji.shortcodes.map { rank(of: $0, for: lowered) }.min() ?? noMatch + if best < noMatch { ranked.append((emoji, best, order)) } + } + ranked.sort { first, second in + first.rank != second.rank ? first.rank < second.rank : first.order < second.order + } + return ranked.prefix(maxMatches).map(\.emoji) + } + + /// The emoji a whole shortcode names, as `:tada:` does. + static func named(_ shortcode: String) -> Emoji? { + let lowered = shortcode.lowercased() + return EmojiDataset.shared.emojis.first { $0.shortcodes.contains(lowered) } + } + + private static let noMatch = 3 + + private static func rank(of shortcode: String, for query: String) -> Int { + if shortcode == query { return 0 } + if shortcode.hasPrefix(query) { return 1 } + if shortcode.contains("_\(query)") { return 2 } + return noMatch + } +} + +/// The emoji last chosen on this device, from the picker or by shortcode, +/// newest first, as the web's `rememberEmoji` keeps them in its browser. +enum RecentEmoji { + private static let storageKey = "recentEmoji" + /// As many as the picker shows in a row. + private static let maxRecent = EmojiPicker.columns + + static var all: [String] { + Array((UserDefaults.standard.stringArray(forKey: storageKey) ?? []).prefix(maxRecent)) + } + + /// Records `emoji` as the one chosen last; choosing one again moves it to the front. + @discardableResult + static func remember(_ emoji: String) -> [String] { + let next = Array(([emoji] + all.filter { $0 != emoji }).prefix(maxRecent)) + UserDefaults.standard.set(next, forKey: storageKey) + return next + } +} diff --git a/apps/ios/Sugabots/Emoji/EmojiPicker.swift b/apps/ios/Sugabots/Emoji/EmojiPicker.swift new file mode 100644 index 000000000..b59ed8ea0 --- /dev/null +++ b/apps/ios/Sugabots/Emoji/EmojiPicker.swift @@ -0,0 +1,173 @@ +import SwiftUI + +/// A searchable grid of every emoji, by category, with a skin tone to pick +/// them in, and over it a row of the ones last chosen on this device, as the +/// web's `EmojiPicker` for reactions and the composer, presented as a sheet: +/// `.sheet(isPresented:) { EmojiPicker { … } }`. Typing filters the grid by +/// name, word or shortcode, and hides the recent row. +/// +/// For a reaction, pass the message's emoji as `used`: once it has +/// `Limits.maxReactionEmojiPerMessage` of them, the picker says so, and only +/// those already on it can be chosen. +@MainActor +struct EmojiPicker: View { + /// The emoji already on the message, which may still be chosen once it is full. + var used: Set = [] + /// The emoji chosen, as text, with its skin tone. + let onSelect: (String) -> Void + @State private var search = "" + @State private var recent = RecentEmoji.all + @State private var tone: Emoji.SkinTone? + + /// How many emoji each row holds, as the web's picker. + nonisolated static let columns = 9 + /// How faint an emoji the message can't take is drawn. + private static let refusedOpacity = 0.35 + /// The picker's width on the web; a phone's sheet centres it. + private static let width: CGFloat = 332 + + var body: some View { + let dataset = EmojiDataset.shared + let found = dataset.searched(search) + VStack(spacing: 0) { + SheetGrabber().padding(.bottom, 8) + if full { + Text("This message has \(Limits.maxReactionEmojiPerMessage) different reactions, the most it can have. You can still add one of those.") + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 12) + .padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .overlay(alignment: .bottom) { Rectangle().fill(Palette.borderStrong).frame(height: 1) } + } + VStack(spacing: 0) { + TextField("", text: $search, prompt: Text("Search emoji").foregroundStyle(Palette.subtleForeground)) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .submitLabel(.done) + .padding(.horizontal, 10) + .frame(height: 32) + .background(Palette.background, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(Palette.borderStrong)) + .accessibilityLabel("Search emoji") + .padding(8) + .padding(.bottom, -4) + if !recent.isEmpty, search.isEmpty { + header("Recent") + HStack(spacing: 0) { + ForEach(recent, id: \.self) { emoji in + cell(emoji, label: dataset.details(of: emoji)?.label ?? emoji) + } + Spacer(minLength: 0) + } + .padding(.horizontal, 6) + } + } + .padding(.bottom, 6) + .overlay(alignment: .bottom) { Rectangle().fill(Palette.borderStrong).frame(height: 1) } + ScrollView { + LazyVStack(alignment: .leading, spacing: 0, pinnedViews: .sectionHeaders) { + ForEach(dataset.categories, id: \.index) { category in + let inCategory = found.filter { $0.category == category.index } + if !inCategory.isEmpty { + Section { + ForEach(Array(stride(from: 0, to: inCategory.count, by: Self.columns)), id: \.self) { start in + HStack(spacing: 0) { + ForEach(inCategory[start.. some View { + Text(label) + .font(Typeface.rubik(12, .semibold)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 12) + .padding(.top, 8) + .padding(.bottom, 4) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityAddTraits(.isHeader) + } + + private func cell(_ emoji: String, label: String) -> some View { + let admitted = Self.admits(emoji, besides: used) + return Button { choose(emoji) } label: { + Text(emoji) + .font(.system(size: 20)) + .frame(width: 32, height: 32) + .contentShape(Rectangle()) + .opacity(admitted ? 1 : Self.refusedOpacity) + } + .buttonStyle(EmojiCellStyle()) + .disabled(!admitted) + .accessibilityLabel(label) + } + + /// The skin tone the grid is drawn in, as a raised hand in it; each press takes the next. + private func skinToneSelector(_ dataset: EmojiDataset) -> some View { + let tones: [Emoji.SkinTone?] = [nil] + Emoji.SkinTone.allCases + let next = tones[((tones.firstIndex(of: tone) ?? 0) + 1) % tones.count] + let hand = dataset.details(of: "✋")?.inTone(tone) ?? "✋" + return Button { tone = next } label: { + Text(hand).font(.system(size: 16)).frame(width: 28, height: 28) + } + .buttonStyle(EmojiCellStyle()) + .accessibilityLabel("Change skin tone" + (next.flatMap { dataset.skinTones[$0.rawValue] }.map { " (\($0))" } ?? "")) + } + + /// Whether a message with the reactions `used` may take `emoji`: once it + /// has `Limits.maxReactionEmojiPerMessage` different ones, only one of those. + static func admits(_ emoji: String, besides used: Set) -> Bool { + used.count < Limits.maxReactionEmojiPerMessage || used.contains(emoji) + } + + /// Whether the message already has as many different reactions as it may. + private var full: Bool { used.count >= Limits.maxReactionEmojiPerMessage } + + private func choose(_ emoji: String) { + recent = RecentEmoji.remember(emoji) + onSelect(emoji) + } +} + +/// An emoji's square, filled with the chip colour while pressed. +private struct EmojiCellStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .background(configuration.isPressed ? Palette.chip : .clear, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } +} diff --git a/apps/ios/Sugabots/Fonts/JetBrainsMono.woff2 b/apps/ios/Sugabots/Fonts/JetBrainsMono.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..cd5102a44c763f1cfe9f2b199fd5d7257491c0dd GIT binary patch literal 40404 zcmV)BK*PUxPew8T0RR910G-qT6aWAK0em8Ob4S33%u?pm-n{qoyX?y0#0(R^L z*f@YTHeQ_l|NnVOMUG1AB(2%T!H;`O$%zQ$Qr1Vxu@@!nwdE?@f4I-Z4wMKl57o!!d)u+K%j2WD z?o)n{#|b%??resiJ8ic#8uv$r5r6o}9ZgthN+?2#4ALP@M2UlL@cTj_Ru!hp`#(Sv zAv3yZc$*b%^B-I3sG%cJ{RfXj|L{2{`P=DgF6#ih1^;4_GAzf_O89^HHtpOugAI5{ zyu^&UI$byWQva*^`v2(ly*v5x=>-koBohqv*Q|w7tyooCZM&z(&(qxA{aY1dYc|GU zb3~LNU;{=ICSWEdm|!=wfl-Cogi(|r?6$k%NjLwY@FAd70a1YrvPmFoUM_bTmraf% zfpClfi9lE~R9v*8b*BQQbJZ7R;b#IX-7*J!{2^NKR5~ zt>;=v#agjq-ESJiiYJ3uE7ppY*-u2Q1Q8Ky#kzx-PdwKK*F2;_g8SJe4Pt|Y>@Q+P zBuEemB4VxkiHMkcQ?0%VKp_+ff|N+vvfFm24KdyJc>V90gf^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Wr zzh=W`YQ9YB9f>du+oC<58&VHA&_%)+c%$nXD;6aK~n| zrD2{Uki!ouOdJ=HO8dAu6?5oMY6K_oG8)4Hx;Fx1s`xR7Lks`xMr6%TjlctOoBW%S z>Xue7s(_AW&cFZ&-*QJ==ayA2sz#vTr5K2>C^&)FXhSO6HPS*U#=%fB>wER}^~-T~ z0Bk(Vm*YIcd2!7WRjh_sb(E2zmPQdcNhA3k3=gtivJerdd}*!?!<%7Xz{~F14UPZb zY~Q|V)m`V>qo{Az&HlcA=jiA#oKfKB-*eLiO>tjuM^_hYFoQSgE!!hD#)sgQ3ci3x zQ5rhb*yr~J0Y9??Obw?tUKM1OHznzt)Aeo&a(@G;SLwhdp3_I+{Tnrr6zvfashPQD zGAaeLT5rfK4=3btSSZO1N~^;&N_CehWn&IScU~p$Y`EJie-)lg^WrAn}pFI2i!45H;=9o3FN#c1C+BPm}M$;L&M&^waiuAWHtDZbvo^uJ$shGgPb`# zd8R4cUWC#koET@_LByHfyZ-=!MIsWcbRX8Qs;^tRpg7->&g_Tv{a*9T20AAAdj$#3 z?M%1i7cW>^SHG$jvr8uSBksU~{defKp`POnrEt*YKE(u6FWF8;dO}U0Ad1u_x>6mrB5h zp8)hiCw{-mK8t>6gz4e-Y|E&EO>@=CmD2ISt5&Xf@}UHIw#_hJaQ^S^b=vM5w(4rz zjc#SUJdPSj6eqN zyZFs@r)%)kFOMHPa^%Q6$Io61WtW#TAJ}IVBw!OHWEI(fzTf(cW~i(87J`12*8df- zLOW{;m2vlDPxTHOPp{(?StU!Q9V>d!D4_19$5aFq+N7%^^` kiRR8B5R}rICbZ`N7$ekpKO~S5@YXNFn1C;Uauu2X1@9U~o&W#< literal 0 HcmV?d00001 diff --git a/apps/ios/Sugabots/Home/ChannelScreens.swift b/apps/ios/Sugabots/Home/ChannelScreens.swift new file mode 100644 index 000000000..896f9578e --- /dev/null +++ b/apps/ios/Sugabots/Home/ChannelScreens.swift @@ -0,0 +1,62 @@ +import SwiftUI + +/// A conversation that is opened the first time somebody looks at it, such as +/// a pod's channel, a bot's channel or a routine's thread, shown as any +/// conversation is once it's open. +@MainActor +struct OpeningConversationScreen: View { + /// What is opened, as the failure's title names it: "Ana's channel". + let name: String + /// Finds the conversation, or opens it, answering its id and title. + let open: (WorkspaceStore) async throws -> (id: String, title: String) + @Environment(WorkspaceStore.self) private var store + @State private var opened: (id: String, title: String)? + @State private var failure: String? + + var body: some View { + Group { + if let opened { + ConversationScreen(threadId: opened.id, title: opened.title) + } else if let failure { + VStack(spacing: 0) { + HStack { HeaderBack(); Spacer() }.pageHeaderInsets() + EmptyState(title: "Could not open \(name)", text: failure) + } + } else { + ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .task { + do { + opened = try await open(store) + } catch { + failure = error.localizedDescription + } + } + } +} + +extension OpeningConversationScreen { + /// The bot's channel in the pod, titled with the bot's name. + nonisolated static func botChannel(_ agent: Agent, in pod: Pod) -> Self { + Self(name: "\(agent.name)'s channel") { store in + (try await store.botChannel(in: pod, with: agent).id, agent.name) + } + } + + /// The pod's first channel, General. + nonisolated static func podChat(_ pod: Pod) -> Self { + Self(name: "this pod's channel") { store in + let chat = try await store.openPodChat(in: pod) + return (chat.id, chat.title) + } + } + + /// A routine's own thread, where its runs post. + nonisolated static func routineFeed(_ routineId: String, in pod: Pod) -> Self { + Self(name: "this routine") { store in + let feed = try await store.routineFeed(routineId: routineId, in: pod) + return (feed.id, feed.title) + } + } +} diff --git a/apps/ios/Sugabots/Home/ConversationList.swift b/apps/ios/Sugabots/Home/ConversationList.swift new file mode 100644 index 000000000..86b3825ec --- /dev/null +++ b/apps/ios/Sugabots/Home/ConversationList.swift @@ -0,0 +1,440 @@ +import SwiftUI + +/// A pod's conversations, as the web's `ConversationList` lays them out on a +/// phone: a shared pod's channels, each with the threads between people +/// started from it, then each of its bots, which opens its channel, with its +/// routines and threads under it. +@MainActor +struct ConversationList: View { + let pod: Pod + @Environment(WorkspaceStore.self) private var store + @State private var namingChannel = false + @State private var makingBot = false + /// The channel held for renaming, or for archiving once confirmed. + @State private var channelChange: ChannelChange? + @Environment(\.openPage) private var openPage + + var body: some View { + let list = store.chatLists[pod.id] + let bots = store.bots(in: pod) + // Done threads leave the list. + let threads = (list?.threads ?? []).filter { $0.conversation.doneAt == nil } + let chats = list?.chats ?? [] + let byChat = Self.threadsByChat(chats, threads) + let groups = Self.groupByBot( + bots: bots, + threads: threads.filter { !Self.hangsUnderChat($0, byChat) }, + channels: list?.channels ?? [] + ) + VStack(alignment: .leading, spacing: 1) { + if pod.kind == .shared { + let chatsOpen = isOpen("chats") + SectionHeading( + label: "Channels", + open: chatsOpen, + news: .of(chats.map { ($0.unreadMessages, false) } + byChat.values.flatMap { $0 }.map { ($0.unreadMessages, $0.needsYou) }), + toggle: { toggle("chats") }, + actionLabel: "New channel in \(pod.name)", + action: { namingChannel = true } + ) + if chatsOpen { + VStack(spacing: 1) { + // The first channel is listed before anyone opens it, which opens it. + if !chats.contains(where: \.conversation.main) { + channelRow(name: "General", unread: 0, route: .podChat(pod)) + } + ForEach(chats) { chat in + channelRow( + name: chat.conversation.title, + unread: chat.unreadMessages, + route: .conversation(threadId: chat.conversation.id, title: chat.conversation.title) + ) + .contextMenu { channelMenu(chat.conversation) } + if let under = byChat[chat.conversation.id] { + ThreadTree(pod: pod, threads: under) + } + } + } + .padding(.leading, Self.nestedIndent) + } + } + + let botsOpen = isOpen("bots") + SectionHeading( + label: "Bots", + open: botsOpen, + news: .of(groups.flatMap { group in + group.threads.map { ($0.unreadMessages, $0.needsYou) } + + (group.channel.map { [($0.unreadMessages, $0.needsYou)] } ?? []) + }), + toggle: { toggle("bots") }, + actionLabel: pod.permissions.createAgents ? "New bot in \(pod.name)" : nil, + action: { makingBot = true } + ) + if botsOpen { + VStack(spacing: 1) { + if list != nil, groups.isEmpty { + NoBots(onNewBot: pod.permissions.createAgents ? { makingBot = true } : nil) + } + ForEach(groups) { group in + BotItem( + pod: pod, + group: group, + routines: (list?.routines ?? []).filter { $0.agent.id == group.agent?.id } + ) + } + } + .padding(.leading, Self.nestedIndent) + } + } + .sheet(isPresented: $namingChannel) { + NameSheet.channel(title: "New channel", action: "Create") { name in + let chat = try await store.startChat(in: pod, named: name) + namingChannel = false + openPage(.conversation(threadId: chat.id, title: chat.title)) + } + } + .channelChange($channelChange, in: pod) + .fullScreenCover(isPresented: $makingBot) { + NewBotScreen(pod: pod) { made in + makingBot = false + openPage(.botChannel(pod, made)) + } + } + } + + /// How far the rows sit in from their section's name, on a phone's width. + static let nestedIndent: CGFloat = 12 + + /// What holding a channel offers, as its Details does: Rename, and Archive for any but the first. + @ViewBuilder private func channelMenu(_ channel: PodChat) -> some View { + if ChannelChange.mayRename(in: pod) { + Button { channelChange = .rename(channel) } label: { Label("Rename", systemImage: "pencil") } + } + if ChannelChange.mayArchive(channel, in: pod) { + Button(role: .destructive) { channelChange = .archive(channel) } label: { Label("Archive", systemImage: "archivebox") } + } + } + + private func channelRow(name: String, unread: Int, route: Route) -> some View { + NavigationLink(value: route) { + HStack(spacing: 12) { + Icon(.hash, size: 16, strokeWidth: 1.75).padding(.horizontal, 1) + Text(name) + .font(Typeface.rubik(16, unread > 0 ? .semibold : .regular)) + .foregroundStyle(unread > 0 ? Palette.foreground : Palette.mutedForeground) + .lineLimit(1) + Spacer(minLength: 0) + UnreadMarker(unreadMessages: unread, needsYou: false).frame(width: 22) + } + .foregroundStyle(Palette.mutedForeground) + .padding(.leading, 8) + .padding(.trailing, 6) + .frame(height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.sidebarRow) + } + + private func isOpen(_ section: String) -> Bool { + !store.preferences.isFolded(section, in: pod.id) + } + + private func toggle(_ section: String) { + store.preferences.toggleFolded(section, in: pod.id) + } + + /// The threads between people started from each of `chats`, newest first, by the chat's id; only chats with one. + private static func threadsByChat(_ chats: [ChatList.Chat], _ threads: [ChatListItem]) -> [String: [ChatListItem]] { + let chatIds = Set(chats.map(\.conversation.id)) + var byChat: [String: [ChatListItem]] = [:] + for row in threads where row.agent == nil { + guard let chat = row.conversation.startedInChatId, chatIds.contains(chat) else { continue } + byChat[chat, default: []].append(row) + } + return byChat + } + + private static func hangsUnderChat(_ row: ChatListItem, _ byChat: [String: [ChatListItem]]) -> Bool { + guard row.agent == nil, let chat = row.conversation.startedInChatId else { return false } + return byChat[chat] != nil + } + + /// A group for each of the pod's bots, and any other bot with a thread + /// here, by name, then the threads between people. + private static func groupByBot(bots: [Agent], threads: [ChatListItem], channels: [ChatList.Channel]) -> [BotGroup] { + var groups: [String: BotGroup] = [:] + func key(_ agent: Agent?) -> String { agent?.id ?? BotGroup.peopleKey } + for bot in bots { groups[bot.id] = BotGroup(agent: bot) } + for channel in channels { groups[channel.agent.id, default: BotGroup(agent: channel.agent)].channel = channel } + for row in threads { groups[key(row.agent), default: BotGroup(agent: row.agent)].threads.append(row) } + return groups.values.sorted { a, b in + guard let first = a.agent else { return false } + guard let second = b.agent else { return true } + return first.name.localizedCompare(second.name) == .orderedAscending + } + } +} + +/// A bot with its channel, once somebody opened it, and its open threads, +/// newest first; or the threads between people, when `agent` is nil. +struct BotGroup: Identifiable { + static let peopleKey = "people" + + let agent: Agent? + var channel: ChatList.Channel? + var threads: [ChatListItem] = [] + + var id: String { agent?.id ?? Self.peopleKey } +} + +/// What is new across some rows, as a folded section says it. +private struct News { + let unreadMessages: Int + let needsYou: Bool + + var any: Bool { unreadMessages > 0 || needsYou } + + static func of(_ rows: [(unread: Int, needsYou: Bool)]) -> News { + News(unreadMessages: rows.reduce(0) { $0 + $1.unread }, needsYou: rows.contains { $0.needsYou }) + } +} + +/// A section's name in small grey type, which folds it away or opens it, +/// with its one action at the end. Folded, it says what is new in it. +private struct SectionHeading: View { + let label: String + let open: Bool + let news: News + let toggle: () -> Void + /// Absent when the person may not take the action. + let actionLabel: String? + let action: () -> Void + + var body: some View { + let lit = !open && news.any + HStack(spacing: 0) { + Button(action: toggle) { + HStack(spacing: 10) { + Icon(.chevronRight, size: 14, strokeWidth: 2.25) + .rotationEffect(.degrees(open ? 90 : 0)) + .frame(width: 18, height: 18) + Text(label).font(Typeface.rubik(14, lit ? .semibold : .medium)) + Spacer(minLength: 0) + } + .foregroundStyle(lit ? Palette.foreground : Palette.subtleForeground) + .padding(.leading, 8) + .frame(maxHeight: .infinity) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(.isHeader) + .accessibilityValue(open ? "Expanded" : "Collapsed") + if !open { + UnreadMarker(unreadMessages: news.unreadMessages, needsYou: news.needsYou).frame(width: 22) + } + if let actionLabel { + SmallIconButton(icon: .plus, label: actionLabel, action: action).frame(width: 22) + } + } + .padding(.trailing, 6) + .frame(height: 36) + .padding(.top, 8) + .animation(.easeOut(duration: 0.15), value: open) + } +} + +/// The Bots section while the pod has none: a row that adds the first, its +/// face a dashed circle, or a line saying there are none. +private struct NoBots: View { + let onNewBot: (() -> Void)? + + var body: some View { + let row = HStack(spacing: 12) { + Circle() + .strokeBorder(Palette.borderStrong, style: StrokeStyle(lineWidth: 1, dash: [2, 2])) + .frame(width: 18, height: 18) + .overlay { if onNewBot != nil { Icon(.plus, size: 10, strokeWidth: 2.4) } } + Text(onNewBot == nil ? "No bots yet" : "Add a bot").font(Typeface.rubik(16)) + Spacer(minLength: 0) + } + .foregroundStyle(Palette.mutedForeground) + .padding(.leading, 8) + .padding(.trailing, 6) + .frame(height: 44) + .contentShape(Rectangle()) + if let onNewBot { + Button(action: onNewBot) { row }.buttonStyle(.sidebarRow) + } else { + row + } + } +} + +/// A bot on one line, which opens its channel, with its threads under it; or +/// the threads between people. At its end what is new in its channel, a red +/// dot when one of its routines' latest run failed, and a + that starts a +/// thread with it. Held, a bot offers its notifications. Its routines are under +/// ⋯ in its channel, the app's own place for them; the web lists them here. +@MainActor +private struct BotItem: View { + let pod: Pod + let group: BotGroup + let routines: [ListedRoutine] + @Environment(WorkspaceStore.self) private var store + + var body: some View { + let channel = group.channel + let unread = channel?.unreadMessages ?? 0 + let waiting = (channel?.needsYou ?? false) || routines.contains(where: \.mentionsYou) + let attention = unread > 0 || waiting + let routineFailed = routines.contains(where: \.routine.failed) + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 0) { + NavigationLink(value: destination) { + HStack(spacing: 12) { + if let agent = group.agent { + BotFace(look: agent.look, size: 18) + } else { + Icon(.users, size: 16, strokeWidth: 1.75).padding(.horizontal, 1) + } + Text(group.agent?.name ?? "People") + .font(Typeface.rubik(16, attention ? .semibold : .regular)) + .lineLimit(1) + if let place, store.notificationSettings?.isMuted(place) ?? false { + Icon(.bellOff, size: 13, strokeWidth: 1.75) + .foregroundStyle(Palette.subtleForeground) + .accessibilityLabel("Muted") + } + Spacer(minLength: 0) + } + .foregroundStyle(attention ? Palette.foreground : Palette.mutedForeground) + .padding(.leading, 8) + .frame(maxHeight: .infinity) + .contentShape(Rectangle()) + } + // Darkens while pressed, as a channel's row does, so a tap shows it landed. + .buttonStyle(.sidebarRow) + if routineFailed { + FailedRoutineDot().frame(width: 22).accessibilityLabel("A routine's latest run failed") + } + if attention { + UnreadMarker(unreadMessages: unread, needsYou: waiting).frame(width: 22) + } + NavigationLink(value: Route.newThread(pod, agent: group.agent)) { + Icon(.plus, size: 14, strokeWidth: 2.2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 22, height: 22) + .contentShape(Rectangle()) + } + .buttonStyle(IconPressStyle()) + .accessibilityLabel(group.agent.map { "New thread with \($0.name)" } ?? "New thread with people") + } + .padding(.trailing, 6) + .frame(height: 44) + .contextMenu { + if let place { NotificationMenu(place: place) } + } + if !group.threads.isEmpty { + ThreadTree(pod: pod, threads: group.threads) + } + } + + } + + /// The bot's channel once opened, or opening it; the threads between people have none. + private var destination: Route? { + guard let agent = group.agent else { return nil } + if let channel = group.channel { + return .conversation(threadId: channel.conversation.id, title: channel.conversation.title) + } + return .botChannel(pod, agent) + } + + /// Only a pod's own bots have notifications of their own; the rest follow the pod. + private var place: NotificationPlace? { + group.agent.map { .bot(id: $0.id, podId: $0.podId) } + } +} + +/// Threads hanging under a bot or a channel: the first few, then how many more. +@MainActor +private struct ThreadTree: View { + let pod: Pod + /// Newest first. + let threads: [ChatListItem] + @State private var unclipped = false + + /// How many threads show before Show more, as the web's `THREADS_SHOWN`. + private static let threadsBeforeShowMore = Limits.threadsShown + + var body: some View { + let shown = unclipped ? threads : Array(threads.prefix(Self.threadsBeforeShowMore)) + let hidden = threads.count - shown.count + VStack(alignment: .leading, spacing: 1) { + ForEach(shown) { row in + NavigationLink(value: Route.conversation(threadId: row.conversation.id, title: row.conversation.title)) { + threadRow(lit: row.unreadMessages > 0 || row.needsYou) { + // In a Personal pod a conversation is with the bot, so goes by its name. + Text(pod.kind == .personal ? row.agent?.name ?? row.conversation.title : row.conversation.title) + .lineLimit(1) + Spacer(minLength: 0) + UnreadMarker(unreadMessages: row.unreadMessages, needsYou: row.needsYou).frame(width: 22) + } + } + .buttonStyle(PressableRowStyle(cornerRadius: 6)) + } + if hidden > 0 { + Button { unclipped = true } label: { + Text("Show \(hidden) more") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 8) + .frame(maxWidth: .infinity, minHeight: 28, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } + .padding(.leading, ConversationList.nestedIndent) + .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 1) } + .padding(.leading, 17) + .padding(.top, 1) + } + + private func threadRow(lit: Bool, @ViewBuilder content: () -> some View) -> some View { + HStack(spacing: 8) { content() } + .font(Typeface.rubik(15, lit ? .semibold : .regular)) + .foregroundStyle(lit ? Palette.foreground : Palette.mutedForeground) + .padding(.leading, 8) + .padding(.trailing, 6) + .frame(height: 40) + .contentShape(Rectangle()) + } +} + +/// The red dot for a routine whose latest run failed. +struct FailedRoutineDot: View { + var body: some View { + Circle().fill(Palette.destructiveText).frame(width: 6, height: 6) + } +} + +/// At a row's end: a dot while it waits on the person, as a decision or a +/// mention does. Unread messages show in the row's bold name, so they are +/// only counted for VoiceOver. +struct UnreadMarker: View { + let unreadMessages: Int + let needsYou: Bool + + var body: some View { + if needsYou { + Circle() + .fill(Palette.foreground) + .frame(width: 6, height: 6) + .accessibilityLabel(unreadMessages > 0 ? "\(unreadMessages) unread, needs you" : "Needs you") + } else if unreadMessages > 0 { + Color.clear.frame(width: 0, height: 0).accessibilityLabel("\(unreadMessages) unread") + } + } +} diff --git a/apps/ios/Sugabots/Home/HomeScreen.swift b/apps/ios/Sugabots/Home/HomeScreen.swift new file mode 100644 index 000000000..cb2d98e16 --- /dev/null +++ b/apps/ios/Sugabots/Home/HomeScreen.swift @@ -0,0 +1,153 @@ +import SwiftUI + +/// Home, as the web's `MobileHome`: every pod down a rail at the left, and +/// beside it the one chosen, with its artifacts, then its channels and its +/// bots, each bot with its routines and threads under it. +struct HomeScreen: View { + @Environment(WorkspaceStore.self) private var store + + var body: some View { + let pods = store.podsInRailOrder + let pod = pods.first { $0.id == store.preferences.homePodId } ?? pods.first + HStack(spacing: 0) { + PodRail(pods: pods, current: pod) { store.preferences.homePodId = $0.id } + Group { + if let pod { + PodPanel(pod: pod).id(pod.id) + } else { + EmptyState(title: store.loadError == nil ? "Loading pods…" : "Could not load the pods", text: store.loadError) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background { + // Down to the screen's foot, under the tabs; the web's inset shadow is a line along the top and the left only. + UnevenRoundedRectangle(topLeadingRadius: 20, style: .continuous) + .fill(Palette.list) + .overlay( + UnevenRoundedRectangle(topLeadingRadius: 20, style: .continuous) + .stroke(Palette.border, lineWidth: 1) + .padding(.trailing, -1) + .padding(.bottom, -1) + ) + .ignoresSafeArea(edges: .bottom) + } + } + .pageTopPadding() + .background(Palette.background.ignoresSafeArea()) + } +} + +/// Every pod as a tile, shared first, then Personal. A bar at the rail's +/// edge marks the one open, and a short one a pod with something new. The + +/// at the foot makes a pod, for somebody who may. +private struct PodRail: View { + let pods: [Pod] + let current: Pod? + let choose: (Pod) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var creating = false + + var body: some View { + ScrollView(showsIndicators: false) { + VStack(spacing: 10) { + ForEach(pods) { pod in + let isCurrent = pod.id == current?.id + let news = store.hasNews(in: pod) + Button { choose(pod) } label: { + PodTile(pod: pod) + } + .buttonStyle(.plain) + // Held, its notifications, as the web's sidebar gives a pod on a right click. + .contextMenu { NotificationMenu(place: .pod(id: pod.id)) } + .frame(maxWidth: .infinity) + .overlay(alignment: .leading) { + if isCurrent || news { + UnevenRoundedRectangle(bottomTrailingRadius: 4, topTrailingRadius: 4) + .fill(Palette.foreground) + .frame(width: 4, height: isCurrent ? 36 : 8) + } + } + .animation(.easeOut(duration: 0.15), value: isCurrent) + .accessibilityLabel(news ? "\(pod.name), something new" : pod.name) + .accessibilityAddTraits(isCurrent ? .isSelected : []) + } + if store.permissions?.createPods ?? false { + Rectangle().fill(Palette.border).frame(width: 28, height: 1).padding(.vertical, 2) + Button { creating = true } label: { + Icon(.plus, size: 20, strokeWidth: 2) + .foregroundStyle(Palette.subtleForeground) + .frame(width: 46, height: 46) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } + .buttonStyle(.plain) + .accessibilityLabel("New pod") + } + } + .padding(.top, 6) + .padding(.bottom, 16) + } + .frame(width: 68) + .refreshable { await store.refreshAll() } + .sheet(isPresented: $creating) { + NewPodSheet { pod in + creating = false + choose(pod) + } + } + } +} + +/// The pod chosen: its name, which opens its settings, then Artifacts and its conversations. +@MainActor +private struct PodPanel: View { + let pod: Pod + @Environment(WorkspaceStore.self) private var store + + var body: some View { + VStack(spacing: 0) { + // Pushed on Home, so Back comes straight back here, rather than opened under You. + NavigationLink(value: Route.podSettings(pod)) { + HStack(spacing: 6) { + Text(pod.name) + .font(Typeface.rubik(22, .semibold)) + .tracking(-0.44) + .lineLimit(1) + Icon(.chevronRight, size: 16, strokeWidth: 2) + .foregroundStyle(Palette.subtleForeground) + } + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(.plain) + .accessibilityLabel("\(pod.name) settings") + .padding(.leading, 18) + .padding(.trailing, 12) + .padding(.top, 18) + .padding(.bottom, 12) + + ScrollView { + VStack(alignment: .leading, spacing: 10) { + NavigationLink(value: Route.artifacts(pod)) { + HStack(spacing: 12) { + Icon(.library, size: 20, strokeWidth: 1.75) + Text("Artifacts").font(Typeface.rubik(16)) + Spacer(minLength: 0) + } + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 12) + .frame(height: 44) + .contentShape(Rectangle()) + } + .buttonStyle(.sidebarRow) + Rectangle().fill(Palette.border).frame(height: 1).padding(.horizontal, 12) + ConversationList(pod: pod) + } + .padding(.leading, 6) + .padding(.trailing, 8) + .padding(.bottom, 16) + } + .refreshable { await store.refreshAll() } + } + .task { await store.refreshChatList(pod) } + } +} diff --git a/apps/ios/Sugabots/Home/HomeSheets.swift b/apps/ios/Sugabots/Home/HomeSheets.swift new file mode 100644 index 000000000..91bdbd0f1 --- /dev/null +++ b/apps/ios/Sugabots/Home/HomeSheets.swift @@ -0,0 +1,270 @@ +import SwiftUI + +/// Naming something, new or renamed, in a dialog with one field: a channel, +/// as the web's `ChatNameDialog`, or a routine, as its `RenameDialog`. +@MainActor +struct NameSheet: View { + let title: String + /// The name it has now; empty for something new. + var name = "" + let action: String + let placeholder: String + let maxLength: Int + /// A line under the field, such as who will read it. + var note: String? + let save: (String) async throws -> Void + @State private var draft = "" + @State private var saving = false + @State private var failure: String? + + var body: some View { + let next = draft.trimmingCharacters(in: .whitespaces) + DialogForm(title: title, action: (title: action, run: submit), actionDisabled: saving || next.isEmpty || next == name, gap: 12) { + SettingsGroup { + SettingsFieldRow(label: "Name", value: $draft, placeholder: placeholder, maxLength: maxLength) + } + if let note { + Text(note) + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 4) + } + if let failure { FormAlert(text: failure) } + } + .onAppear { draft = name } + } + + private func submit() { + let trimmed = draft.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty, !saving else { return } + saving = true + failure = nil + Task { + do { + try await save(trimmed) + } catch let failure as APIFailure where failure.status == 403 { + self.failure = "Only someone who runs this pod can do that." + } catch { + failure = error.localizedDescription + } + saving = false + } + } +} + +extension NameSheet { + /// Naming a pod's channel, as the web's `ChatNameDialog`. + nonisolated static func channel(title: String, name: String = "", action: String, save: @escaping (String) async throws -> Void) -> NameSheet { + NameSheet( + title: title, + name: name, + action: action, + placeholder: "e.g. Pricing", + maxLength: Limits.chatNameMaxLength, + note: "Everyone in the pod can read and write in it.", + save: save + ) + } +} + +/// Renaming or archiving one of a pod's channels, which holding it on Home +/// and its Details both offer. +enum ChannelChange { + case rename(PodChat) + case archive(PodChat) + + /// Whether the person may rename the channels of `pod`. + static func mayRename(in pod: Pod) -> Bool { pod.permissions.rename } + + /// Whether the person may archive `channel`: as renaming it, but never the pod's first. + static func mayArchive(_ channel: PodChat, in pod: Pod) -> Bool { mayRename(in: pod) && !channel.main } +} + +extension View { + /// The sheet that renames a channel and the dialog that archives it, open + /// while `change` names one. `archived` runs once a channel is archived + /// and its dialog has closed. + func channelChange(_ change: Binding, in pod: Pod, archived: @escaping () -> Void = {}) -> some View { + modifier(ChannelChangeDialogs(change: change, pod: pod, archived: archived)) + } +} + +@MainActor +private struct ChannelChangeDialogs: ViewModifier { + @Binding var change: ChannelChange? + let pod: Pod + let archived: () -> Void + @Environment(WorkspaceStore.self) private var store + /// Whether the dialog closes on a channel it archived, so `archived` runs once it has gone. + @State private var archivedOne = false + + func body(content: Content) -> some View { + content + .sheet(item: Binding(get: { if case let .rename(channel) = change { channel } else { nil } }, set: { if $0 == nil { change = nil } })) { channel in + NameSheet.channel(title: "Rename channel", name: channel.title, action: "Save") { renamed in + try await store.renameChat(channel.id, to: renamed, in: pod) + change = nil + } + } + .confirmDelete( + isPresented: Binding(get: { archiving != nil }, set: { presented in + guard !presented else { return } + change = nil + if archivedOne { + archivedOne = false + archived() + } + }), + title: "Archive \(archiving?.title ?? "")?", + description: "It leaves the pod's list for everyone. Threads started from it stay.", + confirmLabel: "Archive" + ) { + guard let archiving else { return } + try await store.archiveChat(archiving.id, in: pod) + archivedOne = true + } + } + + private var archiving: PodChat? { + if case let .archive(channel) = change { channel } else { nil } + } +} + +/// Making a pod, as the web's `NewPodDialog`: its name and colour, over a preview of its tile. +@MainActor +struct NewPodSheet: View { + let created: (Pod) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var name = "" + @State private var chosenColor: String? + @State private var creating = false + @State private var failure: String? + + var body: some View { + let color = chosenColor ?? leastUsedColor + let usable = !slugify(name).isEmpty + DialogForm(title: "New pod", action: (title: "Create", run: submit), actionDisabled: !usable || creating, gap: 12) { + HStack { + Spacer() + PodTile(pod: preview(color: color), size: 64, cornerRadius: 16) + Spacer() + } + .padding(.top, 4) + .padding(.bottom, 8) + SettingsGroup(note: "You'll add bots, people and connections next.") { + SettingsFieldRow(label: "Name", value: $name, placeholder: "e.g. Support", maxLength: Limits.podNameMaxLength) + SettingsDivider() + SettingsControlRow(label: "Colour", stacked: true) { + ColourSwatches(colors: PodColor.known.map(\.rawValue), swatch: { BotLooks.pods[$0]?.swatch ?? .gray }, value: color) { chosenColor = $0 } + } + } + if let failure { FormAlert(text: failure) } + } + } + + /// The colour fewest pods have, as `leastUsedPodColor` picks it. + private var leastUsedColor: String { + let uses = { (color: String) in store.pods.filter { $0.color?.rawValue == color }.count } + let colors = PodColor.known.map(\.rawValue) + return colors.reduce(colors[0]) { uses($1) < uses($0) ? $1 : $0 } + } + + /// The pod as the rail will show it: its initial, once named, on its colour. + private func preview(color: String) -> Pod { + Pod( + id: "", workspaceId: store.workspace.id, kind: .shared, name: name.isEmpty ? " " : name, slug: "", + color: PodColor(rawValue: color), permissions: .nothingAllowed, createdAt: .now + ) + } + + private func submit() { + guard !slugify(name).isEmpty, !creating else { return } + creating = true + failure = nil + Task { + do { + created(try await store.createPod(named: name, color: PodColor(rawValue: chosenColor ?? leastUsedColor))) + } catch let failure as APIFailure where failure.status == 409 { + self.failure = "A pod with that name already exists. Try another name." + } catch let failure as APIFailure where failure.status == 403 { + self.failure = "Only a workspace admin can create a pod." + } catch { + failure = error.localizedDescription + } + creating = false + } + } +} + +/// A pod's or bot's notifications, as the web's context menu offers them: +/// the level to follow or choose, then muting it for a while and the way to +/// every notification setting. Empty until the person's notification +/// settings have loaded. +@MainActor +struct NotificationMenu: View { + let place: NotificationPlace + @Environment(WorkspaceStore.self) private var store + @Environment(Toaster.self) private var toaster + @Environment(\.openPage) private var openPage + + var body: some View { + if let settings = store.notificationSettings { + menu(settings) + } + } + + @ViewBuilder private func menu(_ settings: NotificationSettings) -> some View { + let chosen = settings.levelChosen(for: place) + let followed = settings.levelAbove(place) + Section("Notify you about…") { + Button { setLevel(nil) } label: { + Label("Default (\(followed.label.lowercased()))", systemImage: chosen == nil ? "checkmark" : followed.symbol) + } + ForEach(NotificationLevel.known) { level in + Button { setLevel(level) } label: { + Label(level.label, systemImage: chosen == level ? "checkmark" : level.symbol) + } + } + } + Menu { + if let until = settings.mutedUntil(place) { + Button { mute(until: nil) } label: { + Label("Unmute · Muted until \(MuteDuration.formatUntil(until))", systemImage: "bell") + } + } else if (chosen ?? followed) != .nothing { + ForEach(MuteDuration.all, id: \.label) { duration in + Button { mute(until: duration.until(.now)) } label: { + Label("Mute \(duration.label.lowercased())", systemImage: "clock") + } + } + } + Divider() + Button { openPage(.settings(.notifications)) } label: { Label("Notification settings", systemImage: "gearshape") } + } label: { + Label("More options", systemImage: "ellipsis") + } + } + + private func setLevel(_ level: NotificationLevel?) { + Task { + do { try await store.setNotificationLevel(level, for: place) } catch { toaster.show(error.localizedDescription) } + } + } + + private func mute(until: Date?) { + Task { + do { try await store.mute(place, until: until) } catch { toaster.show(error.localizedDescription) } + } + } +} + +/// How a notification level is named and drawn in the menus that choose it. +extension NotificationLevel { + var symbol: String { + switch self { + case .all: "bell.badge" + case .mentions: "at" + case .nothing, .unknown: "bell.slash" + } + } +} diff --git a/apps/ios/Sugabots/Info.plist b/apps/ios/Sugabots/Info.plist new file mode 100644 index 000000000..0bf7bac78 --- /dev/null +++ b/apps/ios/Sugabots/Info.plist @@ -0,0 +1,17 @@ + + + + + UIAppFonts + + Rubik.ttf + + NSLocalNetworkUsageDescription + Sugabots connects to a Sugabots server on your network, such as one running on your computer. + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + + diff --git a/apps/ios/Sugabots/NewBot/ModelPicker.swift b/apps/ios/Sugabots/NewBot/ModelPicker.swift new file mode 100644 index 000000000..626ba8be7 --- /dev/null +++ b/apps/ios/Sugabots/NewBot/ModelPicker.swift @@ -0,0 +1,182 @@ +import SwiftUI + +/// The models to search, as the web's `ModelPicker`: Suggested first, the +/// default and those most bots think with, then each provider's under its +/// logo. Each shows what it can do, and a radio for the one chosen. +@MainActor +struct ModelPicker: View { + let models: [WorkspaceModel] + let value: String? + let defaultModel: String? + let loading: Bool + let choose: (String) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var search = "" + + /// How many models Suggested holds: the default, then those most bots use. + private static let suggestedCount = 3 + + var body: some View { + let words = search.trimmingCharacters(in: .whitespaces).lowercased() + let usersOf = { (modelId: String) in store.agents.filter { $0.model == modelId && $0.systemAgentKey == nil }.count } + let found = models.filter { model in + words.isEmpty || [model.displayName ?? "", model.modelId, model.providerName].contains { $0.lowercased().contains(words) } + } + let suggested: [WorkspaceModel] = + words.isEmpty + ? Array( + models.enumerated() + .sorted { a, b in + let aDefault = a.element.modelId == defaultModel, bDefault = b.element.modelId == defaultModel + if aDefault != bDefault { return aDefault } + let (aUsers, bUsers) = (usersOf(a.element.modelId), usersOf(b.element.modelId)) + return aUsers != bUsers ? aUsers > bUsers : a.offset < b.offset + } + .map(\.element) + .enumerated() + .filter { $0.offset == 0 || usersOf($0.element.modelId) > 0 } + .map(\.element) + .prefix(Self.suggestedCount) + ) + : [] + let rest = found.filter { !suggested.contains($0) } + let providers = rest.map(\.providerName).reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } } + VStack(spacing: 0) { + VStack(alignment: .leading, spacing: 16) { + Text("Model").font(Typeface.rubik(15, .semibold)).foregroundStyle(Palette.foreground).frame(height: 22) + HStack(spacing: 8) { + Icon(.search, size: 15, strokeWidth: 1.75).foregroundStyle(Palette.subtleForeground) + TextField("", text: $search, prompt: Text("Search \(models.count) \(models.count == 1 ? "model" : "models")").foregroundStyle(Palette.subtleForeground)) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .onSubmit { if let first = found.first { choose(first.modelId) } } + .accessibilityLabel("Search models") + } + .padding(.horizontal, 12) + .frame(height: 40) + .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.borderStrong)) + } + .padding(.horizontal, 20) + .padding(.top, 20) + .padding(.bottom, 12) + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + if found.isEmpty { + Text( + loading ? "Loading models…" + : models.isEmpty ? "No models are switched on yet. Connect one in Settings under Models." + : "No models match." + ) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 8) + .padding(.vertical, 12) + } + if !suggested.isEmpty { + group("Suggested", mark: AnyView(Icon(.star, size: 14, strokeWidth: 1.75)), models: suggested) + } + ForEach(providers, id: \.self) { provider in + let inGroup = rest.filter { $0.providerName == provider } + group(provider, mark: AnyView(ProviderMark(model: inGroup[0])), models: inGroup) + } + } + .padding(.horizontal, 12) + .padding(.bottom, 16) + } + } + } + + private func group(_ label: String, mark: AnyView, models: [WorkspaceModel]) -> some View { + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + mark + Text(label) + } + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 8) + .padding(.top, 8) + .padding(.bottom, 6) + .accessibilityAddTraits(.isHeader) + ForEach(models) { model in + ModelRow(model: model, chosen: model.modelId == value, isDefault: model.modelId == defaultModel) { choose(model.modelId) } + } + } + .padding(.bottom, 8) + } +} + +/// A model to choose: its name, Default on the workspace's default, under it what it can do, and a radio. +private struct ModelRow: View { + let model: WorkspaceModel + let chosen: Bool + let isDefault: Bool + let choose: () -> Void + + /// What a model can do, as the icons on its row draw it, with the words VoiceOver says. + private static let capabilities: [(capability: String, icon: Lucide, label: String)] = [ + ("tools", .wrench, "uses tools"), + ("vision", .eye, "reads images"), + ("reasoning", .brain, "reasons"), + ("images", .image, "makes images"), + ("audio", .audioLines, "hears and speaks"), + ] + + var body: some View { + let shown = model.capabilities.compactMap { capability in Self.capabilities.first { $0.capability == capability.rawValue } } + Button(action: choose) { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 8) { + Text(model.name).font(Typeface.rubik(14, .medium)).foregroundStyle(Palette.foreground).lineLimit(1) + if isDefault { + Text("Default") + .font(Typeface.rubik(10.5, .medium)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 6) + .frame(height: 16) + .overlay(RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(Palette.borderStrong)) + } + } + if !shown.isEmpty { + HStack(spacing: 6) { + ForEach(shown, id: \.capability) { Icon($0.icon, size: 13, strokeWidth: 1.75) } + } + .foregroundStyle(Palette.subtleForeground) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + Circle() + .strokeBorder(chosen ? Palette.foreground : Palette.disabledForeground, lineWidth: 1.5) + .frame(width: 18, height: 18) + .overlay { if chosen { Circle().fill(Palette.foreground).frame(width: 8, height: 8) } } + } + .padding(.horizontal, 8) + .padding(.vertical, 8) + .frame(minHeight: 56) + .background(chosen ? Palette.chip : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(pressed: Palette.chip, cornerRadius: 8)) + .accessibilityLabel(([model.name] + (isDefault ? ["Default"] : []) + shown.map(\.label)).joined(separator: ", ")) + .accessibilityAddTraits(chosen ? .isSelected : []) + } +} + +/// A model's provider, as its logo, or its initial when it has none. +struct ProviderMark: View { + let model: WorkspaceModel + + var body: some View { + if let preset = model.providerPreset?.rawValue, let logo = ProviderLogos.assets[preset] { + Image(logo.image).resizable().scaledToFit().frame(width: 14, height: 14).scaleEffect(logo.scale) + } else { + Text(model.providerName.trimmingCharacters(in: .whitespaces).prefix(1).uppercased()) + .font(Typeface.rubik(9)) + .frame(width: 14, height: 14) + .background(Palette.chipStrong, in: RoundedRectangle(cornerRadius: 3, style: .continuous)) + } + } +} diff --git a/apps/ios/Sugabots/NewBot/NewBotScreen.swift b/apps/ios/Sugabots/NewBot/NewBotScreen.swift new file mode 100644 index 000000000..eb0b30443 --- /dev/null +++ b/apps/ios/Sugabots/NewBot/NewBotScreen.swift @@ -0,0 +1,136 @@ +import SwiftUI + +/// Making a bot, over the whole screen, as the web's `NewAgentDialog` on a +/// phone: Close, New bot and Create across the top on a tint of the bot's +/// colour, the bot as it will be, which opens its look, and its name; then the +/// models it can think with, the suggested first, then each provider's. +/// Made without a prompt, it starts by asking its creator what it's for. +@MainActor +struct NewBotScreen: View { + let pod: Pod + let created: (Agent) -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var look = NewBotScreen.randomLook() + @State private var customising = false + @State private var part = LookPart.shape + @State private var chosenModel: String? + @State private var modelsFailed = false + @State private var creating = false + @State private var failure: String? + @FocusState private var naming: Bool + + + var body: some View { + let models = store.enabledModels + let offered = models?.models ?? [] + // The default model may be missing when its provider is disabled; fall back to the first offered. + let model = chosenModel ?? offered.first { $0.modelId == models?.defaultModel }?.modelId ?? offered.first?.modelId + let trimmed = name.trimmingCharacters(in: .whitespaces) + let canCreate = !trimmed.isEmpty && model != nil && !creating + // A tint of the bot's colour, so the bot is shown in its own light. + let stage = BotLooks.palette(for: look.color).face.opacity(0.09) + VStack(spacing: 0) { + VStack(spacing: 0) { + ScreenHeader(title: customising ? "Look" : "New bot") { + if customising { + GlassRoundButton(icon: .chevronLeft, label: "Back") { customising = false } + } else { + GlassRoundButton(icon: .x, label: "Close", iconSize: 20) { dismiss() } + } + } trailing: { + if !customising { + Button("Create") { create(model: model) } + .buttonStyle(WebButtonStyle(size: .pill)) + .disabled(!canCreate) + } + } + .padding(.bottom, 8) + VStack(spacing: 16) { + Button { customising = true } label: { + BotFace(look: look, size: 112) + .scaleEffect(naming || customising ? 0.5 : 1, anchor: .top) + .frame(height: naming || customising ? 56 : 112, alignment: .top) + .overlay(alignment: .bottomTrailing) { + if !customising, !naming { + Icon(.pencil, size: 14) + .foregroundStyle(Palette.foreground) + .frame(width: 32, height: 32) + .glass(in: Circle()) + .offset(x: 4, y: 4) + } + } + .animation(.easeOut(duration: 0.3), value: naming || customising) + } + .buttonStyle(.plain) + .disabled(customising) + .accessibilityLabel("Change the look") + if !customising { + TextField("", text: $name.limited(to: Limits.agentNameMaxLength), prompt: Text("Name your bot").foregroundStyle(Palette.subtleForeground)) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .autocorrectionDisabled() + .focused($naming) + .padding(.horizontal, 16) + .frame(height: 48) + .background(Palette.panel, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(naming ? Palette.primaryTintBorder : Palette.borderStrong)) + .accessibilityLabel("Name") + if let failure { FormAlert(text: failure) } + if modelsFailed { FormAlert(text: "Models could not be loaded. Close this and try again.") } + } + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, 20) + } + .background(stage.background(Palette.list).ignoresSafeArea(edges: .top)) + .animation(.easeOut(duration: 0.2), value: look.color) + Rectangle().fill(Palette.border).frame(height: 1) + Group { + if customising { + LookStep(part: $part, look: $look) + } else { + ModelPicker(models: offered, value: model, defaultModel: models?.defaultModel, loading: models == nil && !modelsFailed) { chosenModel = $0 } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Palette.panel.ignoresSafeArea(edges: .bottom)) + } + .background(Palette.panel.ignoresSafeArea()) + .task { + do { + try await store.refreshModels() + modelsFailed = false + } catch { + // The models last loaded, if any, are still offered. + modelsFailed = store.enabledModels == nil + } + } + } + + private func create(model: String?) { + let trimmed = name.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty, let model else { return } + creating = true + failure = nil + Task { + do { + created(try await store.createBot(in: pod, name: trimmed, look: look, model: model)) + } catch let failure as APIFailure where failure.status == 409 { + self.failure = "A bot with that name already exists. Try another name." + } catch let failure as APIFailure where failure.status == 403 { + self.failure = "Only a workspace admin can create a bot." + } catch { + failure = error.localizedDescription + } + creating = false + } + } + + /// A look to start from: any colour, head and eyes. + static func randomLook() -> BotLook { + BotLook(color: AgentColor.known.randomElement()!, face: AgentFace.known.randomElement()!, shape: AgentShape.known.randomElement()!) + } +} diff --git a/apps/ios/Sugabots/Onboarding/OnboardingScreen.swift b/apps/ios/Sugabots/Onboarding/OnboardingScreen.swift new file mode 100644 index 000000000..a33510ba4 --- /dev/null +++ b/apps/ios/Sugabots/Onboarding/OnboardingScreen.swift @@ -0,0 +1,751 @@ +import SwiftUI + +/// Setting up a workspace, the first or another, as the web's `Onboarding`: +/// its name, a provider and model, the first bot, inviting people, and the +/// bot ready to chat. Coming back part way through picks up where the +/// workspace says it got to. +@MainActor +struct OnboardingScreen: View { + enum Step: Int, CaseIterable { + case workspace, model, bot, invite, ready + + /// The steps the dots count, which leave out Ready. + static let counted: [Step] = [.workspace, .model, .bot, .invite] + } + + @State var setup: WorkspaceSetup + @Environment(Session.self) private var session + @State private var store: WorkspaceStore? + @State private var chosen: Step? + @State private var personalPod: Pod? + @State private var firstBot: Agent? + @State private var botHasModel = false + @State private var loading = false + @State private var failure: String? + @State private var confirmingLeave = false + + /// The Personal pod's bot starts as this placeholder, and becomes yours on the bot step. + static let placeholderBotName = "Personal Assistant" + + var body: some View { + let step = chosen ?? (setup.made == nil ? .workspace : botHasModel ? .bot : .model) + let index = Step.counted.firstIndex(of: step) + VStack(spacing: 0) { + header(index: index, step: step) + GeometryReader { geometry in + ScrollView { + // In the middle of the screen while it fits, as the web's frame centres a step. + VStack(spacing: 22) { content(step) } + .frame(maxWidth: 440) + .padding(.horizontal, 16) + .padding(.vertical, 40) + .frame(maxWidth: .infinity, minHeight: geometry.size.height) + } + } + .scrollDismissesKeyboard(.interactively) + } + .background(Palette.background.ignoresSafeArea()) + .confirmDelete( + isPresented: $confirmingLeave, + title: "Leave setup?", + description: "\(setup.made?.name ?? "This workspace") has been made but isn't set up yet. It stays in your workspaces, and opening it picks up setup where you left off.", + confirmLabel: "Leave" + ) { await cancel() } + .task(id: setup.made?.id) { await load() } + } + + // MARK: Frame + + private func header(index: Int?, step: Step) -> some View { + ZStack { + if let index { + HStack(spacing: 6) { + ForEach(Array(Step.counted.enumerated()), id: \.offset) { offset, _ in + Capsule() + .fill(offset == index ? Palette.foreground : offset < index ? Palette.mutedForeground : Palette.borderStrong) + .frame(width: offset == index ? 22 : 6, height: 6) + } + } + .animation(.easeOut(duration: 0.2), value: index) + .accessibilityElement() + .accessibilityLabel("Step \(index + 1) of \(Step.counted.count)") + } + HStack { + if let index, index > 0 { + TextBackButton { chosen = Step.counted[index - 1] } + } + Spacer() + if setup.returnTo != nil, step != .ready { + Button("Cancel") { + // Leaving a workspace that's made but not set up asks first, as the web's guard does. + if setup.made != nil { confirmingLeave = true } else { Task { await cancel() } } + } + .font(Typeface.rubik(14.5, .medium)) + .foregroundStyle(Palette.foreground) + } + } + } + .padding(.horizontal, 16) + .padding(.top, 28) + } + + @ViewBuilder + private func content(_ step: Step) -> some View { + if loading { + Text("Loading your setup…").font(Typeface.rubik(15)).foregroundStyle(Palette.mutedForeground) + } else if let failure { + FormAlert(text: failure) + Button("Try again") { Task { await load() } }.buttonStyle(WebButtonStyle(variant: .secondary)) + } else { + switch step { + case .workspace: + WorkspaceStep(setup: setup) { made in + setup.made = made + chosen = .model + } + case .model: + if let store { + ModelStep(bot: firstBot) { + chosen = .bot + Task { await load() } + } + .environment(store) + } + case .bot, .invite, .ready: + if let store, let personalPod { + switch step { + case .bot: + BotStep(bot: firstBot) { bot in + firstBot = bot + chosen = .invite + } + .environment(store) + case .invite: + InviteStep { chosen = .ready }.environment(store) + default: + if let firstBot { + ReadyStep(bot: firstBot) { try await finish(pod: personalPod, bot: firstBot) } + } + } + } else if let store { + PersonalPodMissing { await load() }.environment(store) + } + } + } + } + + // MARK: Doing + + /// Reads the workspace being set up: its Personal pod, its first bot, and whether that bot has a model it may use. + private func load() async { + guard let made = setup.made else { return } + let store = storeOpen(on: made) + loading = personalPod == nil + do { + async let pods = store.podRecords() + async let agents = setup.client.agents.list(workspace: made.id) + async let models = store.refreshModels() + let (podList, agentList, modelList) = try await (pods, agents, models) + personalPod = podList.first { $0.kind == .personal && $0.ownerId == setup.user.id } + firstBot = agentList.first { $0.podId == personalPod?.id && $0.systemAgentKey == nil } + botHasModel = modelList.models.contains { $0.modelId == firstBot?.model } + failure = nil + } catch { + failure = error.localizedDescription + } + loading = false + } + + /// The store the steps work in for `made`: the one already open on it, or a new one. + private func storeOpen(on made: Workspace) -> WorkspaceStore { + if let store, store.workspace.id == made.id { return store } + let workspaces = setup.workspaces.contains { $0.id == made.id } ? setup.workspaces : setup.workspaces + [made] + let opened = WorkspaceStore(client: setup.client, user: setup.user, workspaces: workspaces, workspace: made) + store = opened + return opened + } + + /// Marks setup done and opens the workspace at the first bot's channel, as + /// the web does. Throws, staying on the step, when setup can't be marked done. + private func finish(pod: Pod, bot: Agent) async throws { + guard let made = setup.made else { return } + try await setup.client.onboarding.complete(workspaceId: made.id, podId: pod.id, agentId: bot.id) + await session.finishWorkspaceSetup(opening: made, showing: Session.ChannelToOpen(pod: pod, bot: bot)) + } + + /// Goes back to the workspace setup was opened from, deleting one made but not set up, where the person may. + private func cancel() async { + if let made = setup.made, made.setupCompletedAt == nil { + let access = try? await setup.client.workspaceAccess(workspace: made.id) + if access?.permissions.deleteWorkspace == true { + try? await setup.client.workspaces.delete(workspace: made.id) + } + } + await session.finishWorkspaceSetup(opening: setup.returnTo) + } +} + +// MARK: Parts + +/// A step's title, large and centred, with a line under it, as `StepHeading`. +private struct StepHeading: View { + let title: String + var text: String? + + var body: some View { + VStack(spacing: 22) { + Text(title) + .font(Typeface.rubik(30, .bold)) + .tracking(-0.6) + .lineSpacing(30 * 0.15 - 4) + .accessibilityAddTraits(.isHeader) + if let text { + Text(text).font(Typeface.rubik(15)).lineSpacing(15 * 0.55 - 4).foregroundStyle(Palette.mutedForeground) + } + } + .multilineTextAlignment(.center) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity) + } +} + +/// A step's one field, on the list colour, as `fieldClass`. +private struct OnboardingField: View { + let label: String + let placeholder: String + @Binding var text: String + var maxLength = 64 + /// Takes the keyboard when the step opens, for a step that asks one question. + var focusOnAppear = false + @FocusState private var focused: Bool + + var body: some View { + TextField("", text: $text.limited(to: maxLength), prompt: Text(placeholder).foregroundStyle(Palette.mutedForeground)) + .focused($focused) + .onAppear { if focusOnAppear { focused = true } } + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 16) + .padding(.vertical, 14) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + .accessibilityLabel(label) + } +} + +// MARK: Workspace + +/// Naming the workspace, which makes it, or renames one made already, as `WorkspaceStep`. +@MainActor +private struct WorkspaceStep: View { + let setup: WorkspaceSetup + let made: (Workspace) -> Void + @State private var name = "" + @State private var pending = false + @State private var failure: String? + + var body: some View { + let trimmed = name.trimmingCharacters(in: .whitespaces) + StepHeading(title: "Name your workspace", text: "It's just you for now. You can invite people later.") + OnboardingField( + label: "Workspace name", + placeholder: setup.user.name.split(separator: " ").first.map { "e.g. \($0)'s bots" } ?? "e.g. Acme", + text: $name, + focusOnAppear: true + ) + .onSubmit(submit) + if let failure { FormAlert(text: failure) } + Button(pending ? "Saving…" : "Continue", action: submit) + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(slugify(trimmed).isEmpty || pending) + .onAppear { if name.isEmpty { name = setup.made?.name ?? "" } } + } + + private func submit() { + let trimmed = name.trimmingCharacters(in: .whitespaces) + let slug = slugify(trimmed) + guard !slug.isEmpty, !pending else { return } + if let existing = setup.made, trimmed == existing.name { return made(existing) } + pending = true + failure = nil + Task { + do { + let record = + if let existing = setup.made { + try await setup.client.workspaces.update(workspace: existing.id, name: trimmed, slug: slug) + } else { + try await setup.client.workspaces.create(name: trimmed, slug: slug, timeZone: TimeZone.current.identifier) + } + made(record) + } catch let failure as APIFailure where failure.status == 409 { + self.failure = "That workspace address is already taken." + } catch { + failure = error.localizedDescription + } + pending = false + } + } +} + +// MARK: Model + +/// Connecting a provider and choosing the first bot's model, as `ModelStep`. +@MainActor +private struct ModelStep: View { + let bot: Agent? + let chosen: () -> Void + @Environment(WorkspaceStore.self) private var store + @State private var providers: [ModelProvider] = [] + @State private var connectedId: String? + @State private var adding = false + + var body: some View { + Group { + // Read from the workspace's providers rather than kept, so a sign-in finished while choosing brings its models in. + if let connected = providers.first(where: { $0.id == connectedId }) { + ChooseModelStep(provider: connected, bot: bot, chosen: chosen, reload: load) { connectedId = nil } + } else { + connectStep + } + } + .task { await load() } + } + + private var connectStep: some View { + let connected = providers.filter { $0.connected && !$0.models.isEmpty } + return VStack(spacing: 22) { + StepHeading(title: "Connect a provider", text: "Bots think with a model from a provider you already use. Pick one to start; you can add more later.") + if !connected.isEmpty { + SettingsGroup(label: "Connected") { + DividedRows(data: connected) { provider in + Button { connectedId = provider.id } label: { + SettingsRow(label: provider.name, sub: "\(provider.models.count) models", chevron: true, leading: { + ProviderTile(name: provider.name, preset: provider.preset?.rawValue) + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + Button("Choose a provider") { adding = true } + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + } + .fullScreenCover(isPresented: $adding) { + AddProviderSheet(providers: providers, startWith: nil) { provider in + adding = false + Task { + // A list that can't be fetched yet leaves the starter models, which is enough to begin. + _ = try? await store.client.modelProviders.fetchModels(workspace: store.workspace.id, providerId: provider.id) + await load() + connectedId = provider.id + } + } + .environment(store) + } + } + + private func load() async { + providers = (try? await store.client.modelProviders.list(workspace: store.workspace.id)) ?? providers + } +} + +/// Choosing the first bot's model from a connected provider, as `ChooseModelStep`; +/// a plan-paid provider signs in here first. +@MainActor +private struct ChooseModelStep: View { + let provider: ModelProvider + let bot: Agent? + let chosen: () -> Void + let reload: () async -> Void + let otherProvider: () -> Void + @Environment(WorkspaceStore.self) private var store + @State private var chosenId: String? + @State private var search = "" + @State private var pending = false + @State private var failure: String? + + var body: some View { + let choices = provider.models.filter { !$0.effectiveCapabilities.contains(.embeddings) } + let large = choices.count > 20 + let needle = search.trimmingCharacters(in: .whitespaces).lowercased() + let shown = choices.filter { needle.isEmpty || "\($0.modelId) \($0.displayName ?? "")".lowercased().contains(needle) } + let selected = chosenId ?? choices.first { $0.enabled && $0.modelId == bot?.model }?.id + StepHeading(title: "Choose a model", text: "Your first bot thinks with this. You can switch on more of \(provider.name)'s models later.") + if choices.isEmpty, provider.lacksCredential, let service = provider.signInService { + ProviderSignInRow(provider: provider, service: service, signOutBlocked: nil, changed: reload) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } else if choices.isEmpty { + FormAlert(text: "\(provider.name) lists no models yet. Check it has some, or use another provider.") + } else { + VStack(spacing: 0) { + if large { + SearchField(placeholder: "Search \(choices.count) models", text: $search).padding(12) + SettingsDivider() + } + ScrollView { + VStack(spacing: 0) { + if shown.isEmpty { + Text("No models match.").font(Typeface.rubik(12.5)).foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 16).padding(.vertical, 12) + } + DividedRows(data: shown) { model in + Button { chosenId = model.id } label: { + HStack(spacing: 12) { + Text(model.name).font(Typeface.rubik(14.5, .medium)).foregroundStyle(Palette.foreground).lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + Circle() + .strokeBorder(model.id == selected ? Palette.primary : Palette.borderDashed, lineWidth: model.id == selected ? 6 : 1.5) + .frame(width: 20, height: 20) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(model.id == selected ? .isSelected : []) + } + } + } + .frame(maxHeight: large ? 208 : nil) + .fixedSize(horizontal: false, vertical: !large) + } + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) + } + if let failure { FormAlert(text: failure) } + Button(pending ? "Saving…" : "Continue") { + if let model = choices.first(where: { $0.id == selected }) { choose(model) } + } + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(selected == nil || pending) + Button("Use another provider", action: otherProvider).buttonStyle(QuietLinkStyle()) + } + + private func choose(_ model: ProviderModel) { + pending = true + failure = nil + Task { + do { + if !model.enabled { + _ = try await store.client.modelProviders.updateModel(workspace: store.workspace.id, providerId: provider.id, modelId: model.id, enabled: true) + } + if let bot { _ = try await store.client.agents.update(agentId: bot.id, model: .present(model.modelId)) } + chosen() + } catch { + failure = error.localizedDescription + } + pending = false + } + } +} + +// MARK: Bot + +/// Making the first bot: its look and name, as `BotStep`. The Personal pod's +/// placeholder bot becomes yours. +@MainActor +private struct BotStep: View { + let bot: Agent? + let created: (Agent) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var look = BotLook(color: .green, face: .pill, shape: .circle) + @State private var name = "" + @State private var pending = false + @State private var failure: String? + + var body: some View { + let trimmed = name.trimmingCharacters(in: .whitespaces) + StepHeading(title: "Make your first bot") + BotFace(look: look, size: 96) + VStack(spacing: 0) { + LookPicker(look: $look) + } + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + OnboardingField(label: "Name", placeholder: "Give it a name", text: $name) + if bot == nil { FormAlert(text: "Your Personal pod has no bot to set up. Reload to try again.") } + if let failure { FormAlert(text: failure) } + Button(pending ? "Creating…" : "Create bot", action: submit) + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(bot == nil || trimmed.isEmpty || pending) + .onAppear { + if let bot, bot.name != OnboardingScreen.placeholderBotName, name.isEmpty { + look = bot.look + name = bot.name + } + } + } + + private func submit() { + guard let bot else { return } + pending = true + failure = nil + Task { + do { + let updated = try await store.client.agents.update( + agentId: bot.id, + name: name.trimmingCharacters(in: .whitespaces), + color: .present(look.color), + face: .present(look.face), + shape: .present(look.shape) + ) + created(updated) + } catch { + failure = error.localizedDescription + } + pending = false + } + } +} + +/// A bot's colour, shape and eyes in rows, as the web's `LookPicker` on a phone. +private struct LookPicker: View { + @Binding var look: BotLook + + var body: some View { + SettingsControlRow(label: "Colour", stacked: true) { + ColourSwatches(colors: AgentColor.known.map(\.rawValue), swatch: { BotLooks.palette(for: AgentColor(rawValue: $0)).face }, value: look.color.rawValue, columns: 8) { look.color = AgentColor(rawValue: $0) } + } + SettingsDivider() + SettingsControlRow(label: "Shape", stacked: true) { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 6) { + ForEach(AgentShape.known, id: \.self) { shape in + choice(chosen: look.shape == shape, label: shape.rawValue) { look.shape = shape } content: { + ShapeGlyph(shape: shape, size: 20) + } + .aspectRatio(1, contentMode: .fit) + } + } + } + SettingsDivider() + SettingsControlRow(label: "Eyes", stacked: true) { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 5), spacing: 6) { + ForEach(AgentFace.known, id: \.self) { face in + choice(chosen: look.face == face, label: face.rawValue) { look.face = face } content: { + EyesGlyph(face: face) + } + .frame(height: 44) + } + } + } + } + + private func choice(chosen: Bool, label: String, action: @escaping () -> Void, @ViewBuilder content: () -> some View) -> some View { + Button(action: action) { + content() + .foregroundStyle(chosen ? Palette.foreground : Palette.softForeground) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(chosen ? Palette.personAvatar : Palette.chip, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + .accessibilityAddTraits(chosen ? .isSelected : []) + } +} + +// MARK: Invite + +/// Inviting people, as `InviteStep`: addresses gathered as chips, sent as members, or skipped. +@MainActor +private struct InviteStep: View { + let done: () -> Void + @Environment(WorkspaceStore.self) private var store + @State private var emails: [String] = [] + @State private var draft = "" + @State private var failed: [InviteFailure] = [] + @State private var sending = false + + var body: some View { + let count = emails.count + StepHeading(title: "Bring your friends", text: "Invite people to your workspace. You can add them to pods later.") + ChipFlow(spacing: 6) { + ForEach(emails, id: \.self) { email in + HStack(spacing: 6) { + Text(email).font(Typeface.rubik(13.5)) + Button { emails.removeAll { $0 == email } } label: { + Icon(.x, size: 10, strokeWidth: 3).foregroundStyle(Palette.softForeground).frame(width: 18, height: 18) + } + .buttonStyle(.plain) + .accessibilityLabel("Remove \(email)") + } + .padding(.leading, 10) + .padding(.trailing, 6) + .padding(.vertical, 4) + .background(Palette.borderStrong, in: Capsule()) + } + TextField("", text: $draft, prompt: Text(count == 0 ? "Email addresses" : "").foregroundStyle(Palette.mutedForeground)) + .font(Typeface.rubik(16)) + .keyboardType(.emailAddress) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .disabled(sending) + .onSubmit(addDraft) + .onChange(of: draft) { _, typed in if typed.hasSuffix(",") || typed.hasSuffix(" ") { addDraft() } } + .frame(minWidth: 160) + .padding(.horizontal, 4) + .padding(.vertical, 6) + .accessibilityLabel("Email addresses") + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + .frame(maxWidth: .infinity, minHeight: 52, alignment: .leading) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + if !failed.isEmpty { FormAlert(text: failed.map { "\($0.email): \($0.reason)" }.joined(separator: "\n")) } + Button(sending ? "Sending…" : count == 0 ? "Continue" : "Send \(count) \(count == 1 ? "invite" : "invites")", action: submit) + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(sending) + Button("Skip for now", action: done).buttonStyle(QuietLinkStyle()) + } + + private func addDraft() { + let typed = emailAddresses(in: draft) + guard !typed.isEmpty else { return } + for email in typed where !emails.contains(email) { emails.append(email) } + draft = "" + } + + private func submit() { + var all = emails + for email in emailAddresses(in: draft) where !all.contains(email) { all.append(email) } + guard !all.isEmpty else { return done() } + sending = true + Task { + let failures = await store.invite(all, as: .member) + sending = false + if failures.isEmpty { return done() } + // What went out is done; what's left is what to fix or skip. + failed = failures + emails = failures.map(\.email) + draft = "" + } + } +} + +/// Children laid out in rows, wrapping to the next when one is full, for the invite step's chips. +private struct ChipFlow: Layout { + var spacing: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize { + let rows = rows(for: subviews, width: proposal.width ?? .infinity) + let height = rows.reduce(0) { $0 + $1.height } + spacing * CGFloat(max(0, rows.count - 1)) + return CGSize(width: proposal.width ?? rows.map(\.width).max() ?? 0, height: height) + } + + func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) { + var y = bounds.minY + for row in rows(for: subviews, width: bounds.width) { + var x = bounds.minX + for index in row.indices { + let size = subviews[index].sizeThatFits(.unspecified) + // The last in a row, such as the field, takes what's left of it. + let width = index == row.indices.last ? max(size.width, bounds.maxX - x) : size.width + subviews[index].place(at: CGPoint(x: x, y: y + (row.height - size.height) / 2), proposal: ProposedViewSize(width: width, height: size.height)) + x += width + spacing + } + y += row.height + spacing + } + } + + private struct Row { + var indices: [Int] = [] + var width: CGFloat = 0 + var height: CGFloat = 0 + } + + private func rows(for subviews: Subviews, width: CGFloat) -> [Row] { + var rows: [Row] = [Row()] + for index in subviews.indices { + let size = subviews[index].sizeThatFits(.unspecified) + let needed = rows[rows.count - 1].indices.isEmpty ? size.width : rows[rows.count - 1].width + spacing + size.width + if needed > width, !rows[rows.count - 1].indices.isEmpty { + rows.append(Row()) + } + let row = rows.count - 1 + rows[row].width += (rows[row].indices.isEmpty ? 0 : spacing) + size.width + rows[row].height = max(rows[row].height, size.height) + rows[row].indices.append(index) + } + return rows + } +} + +// MARK: Ready + +/// The first bot ready to chat, greeting you, as `ReadyStep`. +private struct ReadyStep: View { + let bot: Agent + let start: () async throws -> Void + @State private var starting = false + @State private var failure: String? + + var body: some View { + let palette = BotLooks.palette(for: bot.color) + StepHeading(title: "\(bot.name) is ready") + VStack(alignment: .leading, spacing: 3) { + Text(bot.name).font(Typeface.rubik(11.5, .medium)).foregroundStyle(Palette.mutedForeground).padding(.leading, 42).padding(.bottom, 4) + HStack(alignment: .bottom, spacing: 8) { + BotFace(look: bot.look, size: 34) + VStack(alignment: .leading, spacing: 3) { + ForEach(["Hi, I'm \(bot.name).", "I've only just been set up. Help me work out what I'm for?"], id: \.self) { line in + Text(line) + .font(Typeface.rubik(15)) + .foregroundStyle(palette.text.resolved) + .padding(.horizontal, 14) + .padding(.vertical, 10) + .background( + palette.tint.resolved, + in: UnevenRoundedRectangle(topLeadingRadius: 20, bottomLeadingRadius: 6, bottomTrailingRadius: 20, topTrailingRadius: 20, style: .continuous) + ) + } + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 18) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + if let failure { FormAlert(text: failure) } + Button("Start chatting") { + starting = true + failure = nil + Task { + do { try await start() } catch { failure = error.localizedDescription } + starting = false + } + } + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(starting) + } +} + +/// Making the Personal pod again, which the first bot lives in, as `PersonalPodMissing`. +@MainActor +private struct PersonalPodMissing: View { + let made: () async -> Void + @Environment(WorkspaceStore.self) private var store + @State private var modelId: String? + @State private var pending = false + @State private var failure: String? + + var body: some View { + StepHeading(title: "Your Personal pod is missing", text: "It is where your first bot lives. Make it again to carry on.") + if let failure { FormAlert(text: failure) } + Button("Make it") { + guard let modelId else { return } + pending = true + Task { + do { + _ = try await store.client.pods.ensurePersonal(workspace: store.workspace.id, model: modelId) + await made() + } catch { + failure = error.localizedDescription + } + pending = false + } + } + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(modelId == nil || pending) + .task { + _ = try? await store.refreshModels() + modelId = store.enabledModels?.models.first?.modelId + } + } +} diff --git a/apps/ios/Sugabots/Onboarding/WorkspaceSetup.swift b/apps/ios/Sugabots/Onboarding/WorkspaceSetup.swift new file mode 100644 index 000000000..82b8e0b0b --- /dev/null +++ b/apps/ios/Sugabots/Onboarding/WorkspaceSetup.swift @@ -0,0 +1,43 @@ +import Foundation + +/// Setting a workspace up, as the web's `/onboarding`: the person, the +/// workspaces they have, the one being set up once it's made, and the one to +/// go back to if they cancel. +struct WorkspaceSetup { + let client: APIClient + let user: SessionUser + let workspaces: [Workspace] + /// The workspace being set up; nil until its name is given. + var made: Workspace? + /// Where Cancel goes; nil for somebody making their first, who can't cancel. + var returnTo: Workspace? + + /// What opening `workspace` shows: its setup, while it isn't set up and the + /// person may finish it, as the web sends them to `/onboarding`; else the + /// workspace, opening `channel` on Home when it is one of `workspace`'s. + @MainActor + static func stateOpening( + _ workspace: Workspace, + client: APIClient, + user: SessionUser, + workspaces: [Workspace], + showing channel: Session.ChannelToOpen? = nil + ) async -> Session.State { + if workspace.setupCompletedAt == nil { + let access = try? await client.workspaceAccess(workspace: workspace.id) + if access?.permissions.manageProviders == true { + return .settingUp(WorkspaceSetup( + client: client, + user: user, + workspaces: workspaces, + made: workspace, + returnTo: workspaces.first { $0.id != workspace.id } + )) + } + } + return .signedIn( + WorkspaceStore(client: client, user: user, workspaces: workspaces, workspace: workspace), + openingChannel: channel?.pod.workspaceId == workspace.id ? channel : nil + ) + } +} diff --git a/apps/ios/Sugabots/Routines/NewRoutineScreen.swift b/apps/ios/Sugabots/Routines/NewRoutineScreen.swift new file mode 100644 index 000000000..e62cc4d53 --- /dev/null +++ b/apps/ios/Sugabots/Routines/NewRoutineScreen.swift @@ -0,0 +1,332 @@ +import SwiftUI + +/// A routine being made in `pod`, for `agent` when it was begun from that +/// bot's routines, as the web's `NewRoutine` and `NewRoutinePage`. Nothing is +/// saved until Create, which opens the new routine's own thread in this +/// page's place. +@MainActor +struct NewRoutineScreen: View { + let pod: Pod + let agent: Agent? + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var instructions = "" + @State private var agentId: String? + /// The triggers added so far, each ready to save, by a key of its own. + @State private var triggers: [(key: String, input: TriggerInput)] = [] + /// The sheet open on a trigger, by its key, or on adding one. + @State private var openTrigger: TriggerKey? + /// Nil until chosen, so the result follows the first trigger's default. + @State private var chosenResults: RoutineResults? + /// Nil for the pod's first chat. + @State private var chatId: String? + @State private var writingInstructions = false + @State private var creating = false + @State private var failure: String? + @State private var created: Routine? + + var body: some View { + let crew = store.bots(in: pod) + if !pod.permissions.manageRoutines || crew.isEmpty { + VStack(spacing: 0) { + PodPageHeader(title: "New routine") + EmptyState( + title: "No routine can be made here", + text: pod.permissions.manageRoutines + ? "\(pod.name) has no bots to run one yet." + : "Only people who manage \(pod.name)'s routines can make one." + ) + } + .background(Palette.background.ignoresSafeArea()) + } else if let created { + OpeningConversationScreen.routineFeed(created.id, in: pod) + } else { + form(crew: crew) + } + } + + private func form(crew: [Agent]) -> some View { + let bot = crew.first { $0.id == (agentId ?? agent?.id) } ?? crew.first + // Begun from one bot's routines, it can only be that bot's. + let botFixed = agent.map { fixed in crew.contains { $0.id == fixed.id } } ?? false + let results = chosenResults ?? (triggers.first.map { $0.input.triggerKind == .cron ? .postToChat : .keepInRun } ?? .postToChat) + let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) + let trimmedInstructions = instructions.trimmingCharacters(in: .whitespacesAndNewlines) + let ready = bot != nil && !trimmedName.isEmpty && !trimmedInstructions.isEmpty + let title = trimmedName.isEmpty ? "New routine" : trimmedName + return SettingsPage( + title: title, + description: botFixed && bot != nil + ? "Something \(bot?.name ?? "") does without being asked. Set it up, then create it." + : "Set it up, then create it." + ) { + SettingsGroup { + SettingsFieldRow(label: "Name", value: $name, placeholder: "e.g. Friday pipeline review", maxLength: Limits.maxRoutineNameCharacters) + SettingsDivider() + if botFixed, let bot { + SettingsRow(label: "Bot", trailing: { SettingsValue(text: bot.name) }) + } else { + BotChoiceRow(chosen: bot, pod: pod, choices: crew) { chosen in + agentId = chosen + // Another bot's pod may not have the repositories its triggers watch. + triggers.removeAll { $0.input.triggerKind == .github } + } + } + SettingsDivider() + Button { writingInstructions = true } label: { + SettingsRow(label: "Instructions", chevron: true, trailing: { + SettingsValue(text: trimmedInstructions.isEmpty ? "Add" : "Edit") + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + TriggersGroup( + triggers: triggers.map { (key: $0.key, trigger: $0.input) }, + editable: true, + open: { openTrigger = TriggerKey(key: $0) }, + add: { openTrigger = TriggerKey(key: nil) } + ) + SettingsGroup { + SwitchRow(label: "Also post result in the pod's channel", isOn: Binding( + get: { results == .postToChat }, + set: { chosenResults = $0 ? .postToChat : .keepInRun } + ), fontSize: 13) + if results == .postToChat { + RoutineChatRow(pod: pod, chatId: $chatId) + } + } + if let failure { FormAlert(text: failure) } + HStack(spacing: 8) { + Spacer() + Button("Cancel") { dismiss() } + .buttonStyle(WebButtonStyle(variant: .secondary)) + .disabled(creating) + Button("Create routine") { + create(bot: bot, routine: NewRoutine( + name: trimmedName, + instructions: trimmedInstructions, + results: results, + chatId: .present(results == .postToChat ? chatId : nil), + triggers: triggers.map(\.input.apiValue) + )) + } + .buttonStyle(WebButtonStyle()) + .disabled(!ready || creating) + } + } + .navigationDestination(isPresented: $writingInstructions) { + RoutineInstructionsPage(botName: bot?.name, value: $instructions) + } + .fullScreenCover(item: $openTrigger) { open in + let editing = triggers.first { $0.key == open.key } + TriggerSheet( + pod: pod, + editing: editing.map { TriggerDraft.of($0.input) }, + save: { input in + if let editing, let index = triggers.firstIndex(where: { $0.key == editing.key }) { + triggers[index].input = input + } else { + triggers.append((UUID().uuidString, input)) + } + }, + remove: editing.map { editing in { triggers.removeAll { $0.key == editing.key } } } + ) + } + } + + private func create(bot: Agent?, routine: NewRoutine) { + guard let bot else { return } + creating = true + failure = nil + Task { + do { + let result = try await store.createRoutine(agentId: bot.id, routine: routine) + created = result.routine + } catch { + failure = error.localizedDescription + } + creating = false + } + } + + /// Which trigger's sheet is open: one by its key, or nil while adding one. + struct TriggerKey: Identifiable { + let key: String? + var id: String { key ?? "adding" } + } +} + +/// The routine's bot. With more than one to choose, it opens in place to the +/// pod's bots; with one, it only shows it. +private struct BotChoiceRow: View { + let chosen: Agent? + let pod: Pod + let choices: [Agent] + let choose: (String) -> Void + @State private var open = false + + /// The room inside each of the pod's bots, round its face and name. + private static let choiceInset: CGFloat = 4 + /// Where the pod's bots start: past the row's label, so they hang under the chosen one. + private static let choicesLeading = SettingsRowMetrics.sideInset + SettingsRowMetrics.labelWidth + choiceInset + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Button { open.toggle() } label: { + HStack(spacing: 12) { + Text("Bot").font(Typeface.rubik(16)).foregroundStyle(Palette.foreground).frame(minWidth: SettingsRowMetrics.labelWidth, alignment: .leading) + summary + if choices.count > 1 { + Icon(.chevronRight, size: 15, strokeWidth: 2.4) + .foregroundStyle(Palette.subtleForeground) + .rotationEffect(.degrees(open ? 90 : 0)) + .animation(.easeOut(duration: 0.15), value: open) + } + } + .settingsRowPadding(vertical: 10) + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + .disabled(choices.count < 2) + .accessibilityValue(open ? "Expanded" : "Collapsed") + if open { + Text(pod.name) + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, Self.choiceInset) + .padding(.bottom, 4) + .padding(.leading, Self.choicesLeading) + ForEach(choices) { agent in + Button { + choose(agent.id) + open = false + } label: { + HStack(spacing: 10) { + BotFace(look: agent.look, size: 24) + Text(agent.name).font(Typeface.rubik(13)).foregroundStyle(Palette.foreground).frame(maxWidth: .infinity, alignment: .leading) + if agent.id == chosen?.id { Icon(.check, size: 16, strokeWidth: 2.4).foregroundStyle(Palette.foreground) } + } + .padding(.horizontal, Self.choiceInset) + .padding(.vertical, 6) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(pressed: Palette.rowHover, cornerRadius: 12)) + .accessibilityAddTraits(agent.id == chosen?.id ? .isSelected : []) + .padding(.leading, Self.choicesLeading) + .padding(.trailing, 8) + } + Color.clear.frame(height: 6) + } + } + } + + private var summary: some View { + HStack(spacing: 10) { + if let chosen { + BotFace(look: chosen.look, size: 24) + Text(chosen.name).font(Typeface.rubik(13)).foregroundStyle(Palette.foreground).lineLimit(1) + Text(pod.name).font(Typeface.rubik(12.5)).foregroundStyle(Palette.mutedForeground).lineLimit(1) + } else { + Text("Choose a bot").font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } +} + +/// Which of the pod's chats a routine's results go to, offered once the pod +/// has more than one: its first, the one marked `main`, which a nil `chatId` +/// stands for, or another. +struct RoutineChatRow: View { + let pod: Pod + @Binding var chatId: String? + @Environment(WorkspaceStore.self) private var store + + var body: some View { + let chats = pod.kind == .shared ? store.chatLists[pod.id]?.chats ?? [] : [] + if chats.count >= 2 { + let chosen = chats.first { $0.conversation.id == chatId } ?? chats.first { $0.conversation.main } + SettingsDivider() + SettingsControlRow(label: "Chat") { + Spacer(minLength: 0) + Menu { + ForEach(chats) { chat in + Button { + chatId = chat.conversation.main ? nil : chat.conversation.id + } label: { + if chat.id == chosen?.id { Label(chat.conversation.title, systemImage: "checkmark") } else { Text(chat.conversation.title) } + } + } + } label: { + HStack(spacing: 6) { + Text(chosen?.conversation.title ?? "").lineLimit(1) + Icon(.chevronDown, size: 14).foregroundStyle(Palette.mutedForeground) + } + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.foreground) + .padding(.horizontal, 10) + .frame(height: 32) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + .accessibilityLabel("Chat: \(chosen?.conversation.title ?? "")") + } + } + } +} + +/// A routine's instructions as they are written, in a group under which a +/// note says what to write and how much room is left, as the web's textarea +/// for them. It is taller on a page of its own than in a dialog. +struct RoutineInstructionsField: View { + @Binding var text: String + var editable = true + let minHeight: CGFloat + /// The room around the text. + let inset: CGFloat + + var body: some View { + SettingsGroup(note: editable ? Self.note(text) : nil) { + TextField( + "", + text: $text.limited(to: Limits.maxRoutineInstructionsCharacters), + prompt: Text("e.g. Summarise this week's replies and flag anything that has stalled.").foregroundStyle(Palette.subtleForeground), + axis: .vertical + ) + .font(Typeface.rubik(16)) + .lineSpacing(6) + .foregroundStyle(Palette.foreground) + .disabled(!editable) + .frame(minHeight: minHeight, alignment: .topLeading) + .padding(inset) + .padding(4) + .accessibilityLabel("Instructions") + } + } + + /// What to say, and how much room is left. + private static func note(_ instructions: String) -> String { + let count = { (number: Int) in number.formatted(.number.locale(Locale(identifier: "en"))) } + return "Say what to look at, what to do, and what a good result looks like. \(count(instructions.count)) of \(count(Limits.maxRoutineInstructionsCharacters)) characters." + } +} + +/// What a routine tells its bot each time it runs, on a page of its own with room to write. +struct RoutineInstructionsPage: View { + let botName: String? + @Binding var value: String + var editable = true + @Environment(\.dismiss) private var dismiss + + var body: some View { + SettingsPage(title: "Instructions", description: "What \(botName ?? "the bot") does each time this runs.") { + RoutineInstructionsField(text: $value, editable: editable, minHeight: 380, inset: 14) + if editable { + HStack { + Spacer() + Button("Done") { dismiss() }.buttonStyle(WebButtonStyle()) + } + } + } + } +} diff --git a/apps/ios/Sugabots/Routines/RoutineControls.swift b/apps/ios/Sugabots/Routines/RoutineControls.swift new file mode 100644 index 000000000..23f55c705 --- /dev/null +++ b/apps/ios/Sugabots/Routines/RoutineControls.swift @@ -0,0 +1,49 @@ +import SwiftUI + +/// How a run went, or that its routine is paused, as a dot and a word, as the +/// web's `RunOutcome`. +struct RunStatusLabel: View { + enum Outcome { + case passed, failed, running, cancelled, paused + + /// A run's state, as the dot beside it says it. + init(state: RoutineExecutionState) { + switch state { + case .completed: self = .passed + case .failed: self = .failed + case .cancelled: self = .cancelled + case .queued, .running, .unknown: self = .running + } + } + + var label: String { + switch self { + case .passed: "Passed" + case .failed: "Failed" + case .running: "Running" + case .cancelled: "Cancelled" + case .paused: "Paused" + } + } + + var dot: Color { + switch self { + case .passed: Palette.success + case .failed: Palette.destructiveText + case .running: Palette.subtleForeground + case .cancelled, .paused: Palette.disabledForeground + } + } + } + + let outcome: Outcome + + var body: some View { + HStack(spacing: 6) { + Circle().fill(outcome.dot).frame(width: 6, height: 6) + Text(outcome.label) + } + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + } +} diff --git a/apps/ios/Sugabots/Routines/RoutinePanel.swift b/apps/ios/Sugabots/Routines/RoutinePanel.swift new file mode 100644 index 000000000..88f6073eb --- /dev/null +++ b/apps/ios/Sugabots/Routines/RoutinePanel.swift @@ -0,0 +1,526 @@ +import SwiftUI + +/// A routine beside its own thread, set up in place, as the web's +/// `RoutinePanel` on a phone: Back and ⋯ (Rename, Duplicate, Delete routine) +/// at the top, then whether it is on, what it is told, what starts it, where +/// its results go, and Run now. Somebody who may not manage its bot's +/// routines sees it without being able to change it. +@MainActor +struct RoutinePanel: View { + let agent: Agent + let pod: Pod + /// The routine's own thread. + let conversationId: String + /// How the routine stands, as its thread knows it. + let standing: ThreadDetails.Routine + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var routines: [Routine]? + /// Paused or on as last changed here, until the thread's own standing catches up. + @State private var stateOverride: RoutineState? + @State private var pending = false + @State private var failure: String? + @State private var dialog: Dialog? + @State private var confirmingDelete = false + @Environment(\.openPage) private var openPage + #if DEBUG + @Environment(\.debugDialog) private var debugDialog + #endif + + private enum Dialog: Identifiable { + case rename + case instructions + /// A trigger, by its id, or a new one while nil. + case trigger(String?) + + var id: String { + switch self { + case .rename: "rename" + case .instructions: "instructions" + case let .trigger(id): "trigger:\(id ?? "new")" + } + } + } + + var body: some View { + let routine = routines?.first { $0.id == standing.id } + let mayManage = pod.permissions.manageRoutines + let active = (stateOverride ?? standing.state) == .enabled + ScrollView { + VStack(alignment: .leading, spacing: 0) { + Text(routine?.name ?? "Routine") + .font(Typeface.rubik(14, .semibold)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .padding(.leading, 16) + .padding(.trailing, 12) + .frame(height: 52) + VStack(alignment: .leading, spacing: 12) { + if let failure { FormAlert(text: failure) } + PanelCard { + HStack(spacing: 10) { + Circle().fill(active ? Palette.success : Palette.disabledForeground).frame(width: 6, height: 6) + Text(active ? "Active" : standing.pausedAfterFailures ? "Paused after two failures" : "Paused") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity, alignment: .leading) + WebToggle(label: "Routine on", isOn: Binding(get: { active }, set: { on in + control { try await setPaused(!on) } + })) + .disabled(!mayManage || pending) + } + .padding(.horizontal, 14) + .frame(height: 48) + } + if let routine { + instructions(routine, editable: mayManage) + triggers(routine, editable: mayManage) + PanelCard { + VStack(spacing: 0) { + HStack(spacing: 12) { + Text("Also post result in the pod's channel") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.foreground) + .frame(maxWidth: .infinity, alignment: .leading) + WebToggle(label: "Also post result in the pod's channel", isOn: Binding( + get: { routine.results == .postToChat }, + set: { posted in update(routine, results: posted ? .postToChat : .keepInRun) } + )) + } + .padding(.horizontal, 14) + .padding(.vertical, 10) + .frame(minHeight: 48) + if routine.results == .postToChat { + RoutineChatRow(pod: pod, chatId: Binding( + get: { routine.chatId }, + set: { chatId in update(routine, chatId: .present(chatId)) } + )) + } + } + .disabled(!mayManage) + } + } + if pod.permissions.runRoutines { + Button { + control { try await store.runRoutine(standing.id, agentId: agent.id) } + } label: { + HStack(spacing: 6) { + Image(systemName: "play.fill").font(.system(size: 10)) + Text("Run now") + } + .frame(maxWidth: .infinity) + } + .buttonStyle(WebButtonStyle(variant: .secondary)) + .disabled(pending) + } + } + .padding(.horizontal, 16) + .padding(.top, 4) + .padding(.bottom, 24) + } + } + .safeAreaInset(edge: .top, spacing: 0) { + HStack { + PhoneBackButton() + Spacer() + if mayManage, let routine { moreMenu(routine) } + } + .pageHeaderInsets() + } + .background(Palette.background.ignoresSafeArea()) + .toolbar(.hidden, for: .navigationBar) + .task { + do { + try await load() + } catch { + failure = error.localizedDescription + } + #if DEBUG + openDebugDialog() + #endif + } + .fullScreenCover(item: $dialog) { open in + if let routine { sheet(open, routine: routine) } + } + .confirmDelete( + isPresented: $confirmingDelete, + title: "Delete \(routine?.name ?? "")?", + description: "It stops running. Runs already in its bot's chat stay there." + ) { + try await store.deleteRoutine(standing.id, agentId: agent.id) + dismiss() + } + } + + private func moreMenu(_ routine: Routine) -> some View { + Menu { + Button { dialog = .rename } label: { Label("Rename", systemImage: "pencil") } + Button { duplicate(routine) } label: { Label("Duplicate", systemImage: "doc.on.doc") }.disabled(pending) + Button(role: .destructive) { confirmingDelete = true } label: { Label("Delete routine", systemImage: "trash") } + } label: { + GlassRoundIcon(icon: .ellipsis) + } + .accessibilityLabel("More for \(routine.name)") + } + + /// What the routine tells its bot: a row that opens them all to change, or the text itself for those who may not. + @ViewBuilder private func instructions(_ routine: Routine, editable: Bool) -> some View { + if editable { + Button { dialog = .instructions } label: { + PanelCard { + HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 2) { + Text("Instructions").font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + Text(routine.instructions).font(Typeface.rubik(14)).foregroundStyle(Palette.softForeground).lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Icon(.chevronRight, size: 16).foregroundStyle(Palette.subtleForeground) + } + .padding(.horizontal, 14) + .padding(.vertical, 12) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Edit instructions") + } else { + FoldedInstructions(text: routine.instructions) + } + } + + private func triggers(_ routine: Routine, editable: Bool) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text("Triggers").font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground).padding(.horizontal, 2) + PanelCard { + VStack(spacing: 0) { + if routine.triggers.isEmpty { + Text("None. It runs only when someone runs it.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 14) + .padding(.vertical, 12) + } + DividedRows(data: routine.triggers, id: \.id) { trigger in + if let kind = trigger.triggerKind { + triggerRow( + mark: TriggerKindMark(kind: kind), + label: kind.label, + sub: ScheduleWords.triggerLabel(trigger.input), + action: editable ? { dialog = .trigger(trigger.id) } : nil + ) + } else { + // A kind from a newer server than this app knows, which it can neither describe nor change. + triggerRow(mark: SettingsRowIcon { Icon(.circleHelp, size: 14, strokeWidth: 2) }, label: "Trigger", sub: nil, action: nil) + } + } + if editable { + SettingsDivider() + triggerRow( + mark: SettingsRowIcon { Icon(.plus, size: 14, strokeWidth: 2) }, + label: "Add trigger", + sub: nil, + action: { dialog = .trigger(nil) } + ) + } + } + } + } + .padding(.top, 4) + } + + @ViewBuilder private func triggerRow(mark: some View, label: String, sub: String?, action: (() -> Void)?) -> some View { + let row = HStack(spacing: 10) { + mark + VStack(alignment: .leading, spacing: 0) { + Text(label).font(Typeface.rubik(13)).foregroundStyle(Palette.foreground).lineLimit(1) + if let sub { Text(sub).font(Typeface.rubik(12)).foregroundStyle(Palette.mutedForeground).lineLimit(1) } + } + .frame(maxWidth: .infinity, alignment: .leading) + if action != nil, sub != nil { Icon(.chevronRight, size: 14, strokeWidth: 2.2).foregroundStyle(Palette.subtleForeground) } + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + .contentShape(Rectangle()) + if let action { + Button(action: action) { row }.buttonStyle(PressableRowStyle(pressed: Palette.rowHover)) + } else { + row + } + } + + @ViewBuilder private func sheet(_ open: Dialog, routine: Routine) -> some View { + switch open { + case .rename: + NameSheet( + title: "Rename routine", + name: routine.name, + action: "Save", + placeholder: "e.g. Friday pipeline review", + maxLength: Limits.maxRoutineNameCharacters + ) { name in + _ = try await store.updateRoutine(routine.id, agentId: agent.id, name: name) + try await load() + dialog = nil + } + case .instructions: + InstructionsSheet(botName: agent.name, instructions: routine.instructions) { instructions in + _ = try await store.updateRoutine(routine.id, agentId: agent.id, instructions: instructions) + try await load() + dialog = nil + } + case let .trigger(triggerId): + triggerSheet(routine: routine, triggerId: triggerId) + } + } + + /// One of the routine's triggers, or a new one. A webhook's address and secret save as they change, so its sheet is Done. + @ViewBuilder private func triggerSheet(routine: Routine, triggerId: String?) -> some View { + let editing = routine.triggers.first { $0.id == triggerId } + let save: (TriggerInput) async throws -> Void = { input in + if let editing { + _ = try await store.updateTrigger(editing.id, with: input, routineId: routine.id, agentId: agent.id) + } else { + _ = try await store.addTrigger(input, to: routine.id, agentId: agent.id) + } + try await load() + } + let remove: (() async throws -> Void)? = editing.map { editing in + { + _ = try await store.removeTrigger(editing.id, routineId: routine.id, agentId: agent.id) + try await load() + } + } + if let editing, case let .webhook(webhook) = editing { + let settings = WebhookGroups(agent: agent, pod: pod, routineId: routine.id, triggerId: editing.id, auth: WebhookAuthChoice(webhook.auth)) { auth in + _ = try await store.updateTrigger(editing.id, with: .webhook(auth: auth, secret: nil), routineId: routine.id, agentId: agent.id) + try await load() + } + TriggerSheet(pod: pod, editing: TriggerDraft.of(editing.input), mode: .savesItself(settings), remove: remove) + } else { + TriggerSheet(pod: pod, editing: editing.map { TriggerDraft.of($0.input) }, save: save, remove: remove) + } + } + + private func load() async throws { + routines = try await store.routines(of: agent.id) + } + + #if DEBUG + /// Opens the dialog `SUGABOTS_OPEN` names, so it can be screenshotted. + private func openDebugDialog() { + guard let routine = routines?.first(where: { $0.id == standing.id }) else { return } + switch debugDialog { + case "rename": dialog = .rename + case "instructions": dialog = .instructions + case "delete": confirmingDelete = true + case "trigger": dialog = .trigger(routine.triggers.first { $0.triggerKind == .cron }?.id) + case "webhook": dialog = .trigger(routine.triggers.first { $0.triggerKind == .webhook }?.id) + default: break + } + } + #endif + + private func setPaused(_ paused: Bool) async throws { + _ = try await store.updateRoutine(standing.id, agentId: agent.id, state: paused ? .paused : .enabled) + stateOverride = paused ? .paused : .enabled + } + + private func control(_ work: @escaping () async throws -> Void) { + pending = true + failure = nil + Task { + do { try await work() } catch { failure = error.localizedDescription } + pending = false + } + } + + private func update(_ routine: Routine, results: RoutineResults? = nil, chatId: Omittable = .omitted) { + control { + _ = try await store.updateRoutine(routine.id, agentId: agent.id, results: results, chatId: chatId) + try await load() + } + } + + private func duplicate(_ routine: Routine) { + control { + let copy = routine.copy(siblingNames: (routines ?? []).map(\.name)) + let created = try await store.createRoutine(agentId: agent.id, routine: copy) + openPage(.routine(pod, routineId: created.routine.id)) + } + } +} + +/// A card in the panel: one of the routine's settings or a group of them. +private struct PanelCard: View { + @ViewBuilder var content: Content + + var body: some View { + content + .frame(maxWidth: .infinity, alignment: .leading) + .cardChrome(fill: Palette.card, border: Palette.border) + } +} + +/// Instructions for someone who may not change them: folded to four lines past 200 characters until asked for the rest. +private struct FoldedInstructions: View { + let text: String + @State private var open = false + + private static let foldedOver = 200 + + var body: some View { + let folds = text.count > Self.foldedOver + PanelCard { + VStack(alignment: .leading, spacing: 6) { + Text("Instructions").font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + Text(text).font(Typeface.rubik(13)).lineSpacing(4).foregroundStyle(Palette.softForeground).lineLimit(folds && !open ? 4 : nil) + if folds { + ShowMoreButton(open: $open) + } + } + .padding(.horizontal, 14) + .padding(.top, 12) + .padding(.bottom, 14) + } + } +} + +/// What the routine tells its bot each time it runs, with room to write. +private struct InstructionsSheet: View { + let botName: String + let instructions: String + let save: (String) async throws -> Void + @State private var draft = "" + @State private var saving = false + @State private var failure: String? + + var body: some View { + let next = draft.trimmingCharacters(in: .whitespacesAndNewlines) + DialogForm(title: "Instructions", action: (title: saving ? "Saving…" : "Save", run: { + saving = true + failure = nil + Task { + do { try await save(next) } catch { failure = error.localizedDescription } + saving = false + } + }), actionDisabled: saving || next.isEmpty || next == instructions, gap: 12) { + Text("What \(botName) does each time this runs.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity) + RoutineInstructionsField(text: $draft, minHeight: 240, inset: 12) + if let failure { FormAlert(text: failure) } + } + .onAppear { draft = instructions } + } +} + +/// An existing webhook trigger's groups: its address and where it comes from, +/// then its auth, which saves with `changeAuth` as it changes, and its secret, +/// which saves when the field is left, under what a caller must send. +@MainActor +struct WebhookGroups: View { + let agent: Agent + let pod: Pod + let routineId: String + let triggerId: String + let auth: WebhookAuthChoice + let changeAuth: (WebhookAuthChoice) async throws -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(Toaster.self) private var toaster + @State private var saved: RoutineCurrentSecret? + @State private var draft = "" + @State private var secretFailure: String? + /// Why loading the secret or saving the auth last failed. + @State private var failure: String? + + var body: some View { + Group { + groups + if let failure { FormAlert(text: failure) } + } + .task { await loadSecret() } + } + + /// `auth` as a binding whose changes save, saying so when they fail. + private var savedAuth: Binding { + Binding(get: { auth }, set: { changed in + failure = nil + Task { + do { try await changeAuth(changed) } catch { failure = error.localizedDescription } + } + }) + } + + @ViewBuilder private var groups: some View { + let canManage = pod.permissions.manageRoutines + let address = store.webhookAddress(of: triggerId) + SettingsGroup { + SettingsControlRow(label: "Address") { + Text(address).font(Typeface.mono(13)).foregroundStyle(Palette.foreground).lineLimit(1).truncationMode(.middle) + Spacer(minLength: 0) + Button { + UIPasteboard.general.string = address + toaster.show("Copied") + } label: { Icon(.copy, size: 15).frame(width: 30, height: 30) } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("Copy address") + } + SettingsDivider() + WebhookSourceRow(auth: savedAuth) + } + if canManage, let saved { + let hasSecret = if case .none = saved { false } else { true } + let savedSecret = if case let .set(set) = saved { set.secret } else { "" } + let next = draft.trimmingCharacters(in: .whitespaces) + let ready = WebhookDraft(auth: auth, secret: next).secretReady + SettingsGroup(note: hasSecret ? auth.note : WebhookDraft.noSecretNote) { + WebhookAuthRows(auth: savedAuth) + SettingsDivider() + SecretFieldRow( + label: auth.secretLabel, + placeholder: auth.secretPlaceholder, + value: $draft, + error: secretFailure ?? (ready ? nil : WebhookDraft.secretTooShortNote), + onCommit: { commit(next: next, saved: savedSecret, ready: ready) } + ) + } + } else { + SettingsGroup(note: auth.note) { + WebhookAuthRows(auth: savedAuth) + SettingsDivider() + SettingsControlRow(label: auth.secretLabel) { + if !canManage { + Text("Set by people who manage routines").font(Typeface.rubik(14)).foregroundStyle(Palette.mutedForeground).lineLimit(1) + } + Spacer(minLength: 0) + } + } + } + } + + private func commit(next: String, saved: String, ready: Bool) { + guard next != saved, ready else { return } + Task { + do { + secretFailure = nil + _ = try await store.replaceWebhookSecret(of: triggerId, routineId: routineId, agentId: agent.id, with: next.isEmpty ? .removed : .given(next)) + await loadSecret() + } catch { + secretFailure = error.localizedDescription + } + } + } + + private func loadSecret() async { + guard pod.permissions.manageRoutines else { return } + do { + saved = try await store.webhookSecret(of: triggerId, routineId: routineId, agentId: agent.id) + } catch { + failure = error.localizedDescription + return + } + if case let .set(set) = saved { draft = set.secret } else { draft = "" } + } +} diff --git a/apps/ios/Sugabots/Routines/RoutinesScreen.swift b/apps/ios/Sugabots/Routines/RoutinesScreen.swift new file mode 100644 index 000000000..6e0d24bfd --- /dev/null +++ b/apps/ios/Sugabots/Routines/RoutinesScreen.swift @@ -0,0 +1,150 @@ +import SwiftUI + +/// A pod's routines, or one bot's, as the web's `RoutinesPage` on a phone: +/// Back to the pod, the title, and New routine for someone who may make one, +/// then each routine with how it stands. Each opens its own thread. +@MainActor +struct RoutinesScreen: View { + let pod: Pod + var agent: Agent? + @Environment(WorkspaceStore.self) private var store + @State private var fullRoutines: [String: Routine] = [:] + /// Why the routines' schedules or last runs couldn't be read, so a row's "Not run yet" isn't taken at its word. + @State private var failure: String? + + var body: some View { + let list = store.chatLists[pod.id] + let routines = (list?.routines ?? []).filter { agent == nil || $0.agent.id == agent?.id } + VStack(spacing: 0) { + PodPageHeader(title: agent.map { "\($0.name)'s routines" } ?? "Routines") { + if pod.permissions.manageRoutines { + NavigationLink(value: Route.newRoutine(pod, agent: agent)) { + GlassRoundIcon(icon: .plus, strokeWidth: 1.75) + } + .buttonStyle(.plain) + .accessibilityLabel("New routine") + } + } + if list != nil, routines.isEmpty { + EmptyState( + title: agent.map { "No routines for \($0.name) yet" } ?? "No routines in \(pod.name) yet", + icon: .refreshCcw, + text: "Ask \(agent?.name ?? "a bot") to set some up for you." + ) + .padding(.bottom, 60) + } else { + ScrollView { + if let failure { FormAlert(text: failure).padding(.horizontal, 16).padding(.top, 8) } + LazyVStack(spacing: 2) { + ForEach(routines) { row in + RoutineRow(pod: pod, row: row, routine: fullRoutines[row.routine.id]) { failure = $0.localizedDescription } + } + } + .padding(8) + } + } + } + .background(Palette.background.ignoresSafeArea()) + .task { + await store.refreshChatList(pod) + // The API lists routines in full only for a whole workspace or a single bot, so + // one request for the workspace's beats one for each of the pod's bots. + do { + let all = try await store.workspaceRoutines() + fullRoutines = Dictionary(all.map { ($0.routine.id, $0.routine) }, uniquingKeysWith: { first, _ in first }) + } catch { + failure = error.localizedDescription + } + } + } +} + +/// A routine: its bot, its name, when it last ran, and under it how it +/// stands: paused, or how its last run went, or when it runs before it has. +/// A paused one is greyer; one whose thread mentions the person is bright. +@MainActor +private struct RoutineRow: View { + let pod: Pod + let row: ListedRoutine + /// The routine in full, for when it runs, once the workspace's routines are loaded. + let routine: Routine? + let onFailure: (Error) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var lastRun: RoutineExecution? + + var body: some View { + let paused = row.routine.state == .paused + NavigationLink(value: Route.routine(pod, routineId: row.routine.id)) { + HStack(alignment: .top, spacing: 10) { + BotFace(look: row.agent.look, size: 20).opacity(paused ? 0.5 : 1) + VStack(alignment: .leading, spacing: 2) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(row.routine.name) + .font(Typeface.rubik(13, row.mentionsYou ? .semibold : .regular)) + .foregroundStyle(row.mentionsYou ? Palette.foreground : paused ? Palette.subtleForeground : Palette.mutedForeground) + .lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + if let lastRun { + Text(Times.age(lastRun.acceptedAt)).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + } + if paused { + RunStatusLabel(outcome: .paused) + } else if let lastRun { + RunStatusLabel(outcome: .init(state: lastRun.state)) + } else { + Text(routine.flatMap(ScheduleWords.scheduleLabel) ?? "Not run yet") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .lineLimit(1) + } + } + } + .padding(10) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(cornerRadius: 8)) + .accessibilityLabel(row.mentionsYou ? "\(row.routine.name), mentions you" : row.routine.name) + .task(id: row.routine.id) { + // No list of routines carries each one's last run, so each row asks for its own. + do { + lastRun = try await store.latestRun(of: row.routine.id, agentId: row.agent.id) + } catch { + // A row scrolled out of the list cancels its request, which isn't a failure. + if !Task.isCancelled { onFailure(error) } + } + } + } +} + +/// The header of a page in a pod on a phone, as the web's `PageHeader`: +/// Back to the pod, the title centred, and room for one action at the right. +struct PodPageHeader: View { + let title: String + @ViewBuilder var actions: Actions + + var body: some View { + HStack(spacing: 8) { + PhoneBackButton() + Text(title) + .font(Typeface.rubik(17, .semibold)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .frame(maxWidth: .infinity) + .accessibilityAddTraits(.isHeader) + if Actions.self == EmptyView.self { + // With no action, room as wide as one, so the title stays centred. + Color.clear.frame(width: 44, height: 44) + } else { + actions + } + } + .pageHeaderInsets() + } +} + +extension PodPageHeader where Actions == EmptyView { + init(title: String) { + self.init(title: title) { EmptyView() } + } +} diff --git a/apps/ios/Sugabots/Routines/TriggerEditing.swift b/apps/ios/Sugabots/Routines/TriggerEditing.swift new file mode 100644 index 000000000..ab5537114 --- /dev/null +++ b/apps/ios/Sugabots/Routines/TriggerEditing.swift @@ -0,0 +1,819 @@ +import SwiftUI + +// What starts a routine, as the web's `RoutineTriggers`, `RoutineTriggerKinds`, +// `RoutineSchedule`, `RoutineWebhook` and `RoutineRepository`: a list of its +// triggers, each opening a sheet to change it, and Add trigger, which +// chooses the kind and then sets it up. + +extension TriggerInput { + var triggerKind: TriggerKind { + switch self { + case .cron: .cron + case .webhook: .webhook + case .github: .github + } + } +} + +extension RoutineTrigger { + /// Its kind, or nil for a kind from a newer server than this app knows. + var triggerKind: TriggerKind? { + switch self { + case .cron: .cron + case .webhook: .webhook + case .github: .github + case .unknown: nil + } + } +} + +/// A kind of trigger's mark: its integration's logo, or an icon for Sugabots' own. +struct TriggerKindMark: View { + let kind: TriggerKind + + var body: some View { + if let connection = kind.connection { + ConnectionMark(presetId: connection.rawValue, name: kind.label, size: .tile) + } else { + Icon(kind == .cron ? .clock : .webhook, size: 15, strokeWidth: 2.2) + .foregroundStyle(Palette.softForeground) + .frame(width: 34, height: 34) + .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.borderStrong)) + .accessibilityHidden(true) + } + } +} + +/// A trigger as written in a sheet, before it is saved. +enum TriggerDraft: Hashable { + case cron(reading: ScheduleReading, timezone: String) + case webhook(WebhookDraft) + case github(RepositoryDraft) + + /// A new trigger of `kind`, as it starts: a daily schedule, a signed webhook, a repository to pick. + static func new(_ kind: TriggerKind) -> TriggerDraft { + switch kind { + case .cron: .cron(reading: .picked(ScheduleWords.defaultSchedule()), timezone: TimeZone.current.identifier) + case .webhook: .webhook(WebhookDraft()) + case .github: .github(RepositoryDraft()) + } + } + + /// `trigger` as a draft to change. A webhook's secret is changed apart from it, so it starts blank. + static func of(_ trigger: TriggerInput) -> TriggerDraft { + switch trigger { + case let .cron(schedule, timezone): .cron(reading: ScheduleWords.read(schedule), timezone: timezone) + case let .webhook(auth, secret): .webhook(WebhookDraft(auth: auth, secret: secret ?? "")) + case let .github(connectionId, repository, events): + .github(RepositoryDraft(connectionId: connectionId, repository: repository, events: events)) + } + } + + var kind: TriggerKind { + switch self { + case .cron: .cron + case .webhook: .webhook + case .github: .github + } + } + + /// What the draft saves as, or why it can't be saved yet. + var written: Result { + switch self { + case let .cron(reading, timezone): + return ScheduleWords.ready(reading) + ? .success(.cron(schedule: ScheduleWords.scheduleOf(reading), timezone: timezone)) + : .failure(NotReady(note: "Pick at least one day for it to run on.")) + case let .webhook(draft): + guard draft.secretReady else { return .failure(NotReady(note: WebhookDraft.secretTooShortNote)) } + let trimmed = draft.secret.trimmingCharacters(in: .whitespaces) + return .success(.webhook(auth: draft.auth, secret: trimmed.isEmpty ? nil : trimmed)) + case let .github(draft): + guard let connectionId = draft.connectionId, let repository = draft.repository else { + return .failure(NotReady(note: "Pick the repository it runs on.")) + } + guard !draft.events.isEmpty else { return .failure(NotReady(note: RepositoryDraft.pickAnEventNote)) } + return .success(.github(connectionId: connectionId, repository: repository, events: draft.events)) + } + } + + struct NotReady: Error, Hashable { + let note: String + } +} + +/// A routine's triggers, each opening it to change, then Add trigger, for someone who may change them. +struct TriggersGroup: View { + let triggers: [(key: String, trigger: TriggerInput)] + let editable: Bool + var note: String? + let open: (String) -> Void + let add: () -> Void + + var body: some View { + SettingsGroup(label: "Triggers", note: note) { + if triggers.isEmpty { + SettingsRow(label: "No triggers", sub: "It runs only when someone runs it.") + if editable { SettingsDivider() } + } + DividedRows(data: triggers, id: \.key) { listed in + let row = SettingsRow( + label: ScheduleWords.triggerLabel(listed.trigger), + sub: listed.trigger.triggerKind.label, + chevron: editable, + leading: { TriggerKindMark(kind: listed.trigger.triggerKind) } + ) + if editable { + Button { open(listed.key) } label: { row }.buttonStyle(SettingsRowPressStyle()) + } else { + row + } + } + if editable { + if !triggers.isEmpty { SettingsDivider() } + SettingsAddRow(label: "Add trigger", action: add) + } + } + } +} + +/// Adding a trigger, a step at a time: its kind, then setting it up; or +/// changing one, straight at the second step, with Remove. The sheet closes +/// once its action or `remove` finishes, and says why when they fail. +struct TriggerSheet: View { + /// How the sheet's step sets the trigger up. + enum Mode { + /// Every setting is written in a draft, which Add trigger or Save hands to `save`. + case draft(save: (TriggerInput) async throws -> Void) + /// `settings` in place of a draft's groups, for an existing trigger whose + /// settings save as they change, such as a webhook's auth and secret; the + /// sheet's action is Done. + case savesItself(Settings) + } + + /// The bot's pod, whose connections decide which integrations' triggers it may have. + let pod: Pod + /// The trigger being changed, as a draft; nil while adding one. + let editing: TriggerDraft? + let mode: Mode + var remove: (() async throws -> Void)? + @Environment(\.dismiss) private var dismiss + @State private var draft: TriggerDraft? + @State private var pending = false + @State private var failure: String? + + var body: some View { + Group { + if let draft { + DialogForm( + title: draft.kind.label, + onBack: editing == nil && !pending ? { self.draft = nil } : nil, + closable: !pending, + gap: 20 + ) { + switch mode { + case .draft: + DraftGroups(pod: pod, draft: Binding(get: { draft }, set: { self.draft = $0 })) + case let .savesItself(settings): + settings + } + if let failure { FormAlert(text: failure) } + } + .safeAreaInset(edge: .bottom, spacing: 0) { + // Remove beside the action, each half the width, as the web's footer on a phone. + HStack(spacing: 8) { + if let remove { + Button("Remove") { settle(remove) } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .phone)) + .disabled(pending) + } + action(for: draft) + } + .padding(.horizontal, 16) + .padding(.top, 12) + .padding(.bottom, 16) + .background(Palette.panel) + } + } else { + TriggerKindStep(pod: pod) { kind in draft = .new(kind) } + } + } + .onAppear { if draft == nil { draft = editing } } + } + + /// The footer's main button: Add trigger or Save for a draft, once it is ready; Done for settings that save themselves. + @ViewBuilder private func action(for draft: TriggerDraft) -> some View { + switch mode { + case let .draft(save): + let written = draft.written + Button(editing == nil ? "Add trigger" : "Save") { + guard case let .success(input) = written else { return } + settle { try await save(input) } + } + .buttonStyle(WebButtonStyle(size: .phone)) + .disabled(pending || (try? written.get()) == nil) + case .savesItself: + Button("Done") { dismiss() } + .buttonStyle(WebButtonStyle(size: .phone)) + .disabled(pending) + } + } + + private func settle(_ action: @escaping () async throws -> Void) { + pending = true + failure = nil + Task { + do { + try await action() + dismiss() + } catch { + failure = error.localizedDescription + pending = false + } + } + } +} + +extension TriggerSheet where Settings == EmptyView { + /// A sheet that writes the trigger as a draft and hands it to `save`. + init(pod: Pod, editing: TriggerDraft?, save: @escaping (TriggerInput) async throws -> Void, remove: (() async throws -> Void)? = nil) { + self.init(pod: pod, editing: editing, mode: .draft(save: save), remove: remove) + } +} + +/// The groups that set up a draft of its kind, under what it still needs or what it does. +private struct DraftGroups: View { + let pod: Pod + @Binding var draft: TriggerDraft + + var body: some View { + let notReady: String? = if case let .failure(reason) = draft.written { reason.note } else { nil } + switch draft { + case let .cron(reading, timezone): + ScheduleGroups(reading: reading, note: notReady ?? ScheduleWords.note(reading, timezone: timezone)) { schedule in + draft = .cron(reading: .picked(schedule), timezone: timezone) + } + case let .webhook(webhook): + NewWebhookGroups( + draft: Binding(get: { webhook }, set: { draft = .webhook($0) }), + note: notReady ?? (webhook.secret.trimmingCharacters(in: .whitespaces).isEmpty ? WebhookDraft.noSecretNote : webhook.auth.note) + ) + case let .github(repository): + RepositoryGroups(pod: pod, draft: Binding(get: { repository }, set: { draft = .github($0) })) + } + } +} + +/// The first step of adding a trigger: choosing its kind, found by typing part +/// of its name, from Sugabots' own and those of the integrations `pod` is +/// connected to, with a way to connect it to more. +private struct TriggerKindStep: View { + let pod: Pod + let choose: (TriggerKind) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var query = "" + @State private var connected: Set = [] + @State private var connectionsFailure: String? + @State private var openedSettings: Pod? + + var body: some View { + let typed = query.trimmingCharacters(in: .whitespaces) + let needle = typed.lowercased() + let matches = { (kind: TriggerKind) in + needle.isEmpty || kind.label.lowercased().contains(needle) || kind.sub.lowercased().contains(needle) + } + let own = TriggerKind.allCases.filter { $0.connection == nil && matches($0) } + let integrations = TriggerKind.allCases.filter { kind in + kind.connection.map(connected.contains) ?? false && matches(kind) + } + DialogForm(title: "Add a trigger", gap: 20) { + SearchField(placeholder: "Search triggers", text: $query) + if !own.isEmpty { + SettingsGroup(label: "Built in") { + DividedRows(data: own) { kind in + row(kind) + } + } + } + SettingsGroup(label: "From this pod's connections") { + ForEach(integrations) { kind in + row(kind) + SettingsDivider() + } + Button { openedSettings = pod } label: { + SettingsRow( + label: !integrations.isEmpty + ? "Connect another app" + : needle.isEmpty ? "No connections with triggers yet" : "No connection matches “\(typed)”", + sub: !integrations.isEmpty ? "In \(pod.name)'s settings" : "Connect an app in \(pod.name)'s settings", + trailing: { Icon(.arrowUpRight, size: 15).foregroundStyle(Palette.subtleForeground) } + ) + } + .buttonStyle(SettingsRowPressStyle()) + } + if let connectionsFailure { FormAlert(text: connectionsFailure) } + } + .task { + do { + connected = Set(try await store.connections(in: pod.id).map(\.kind)) + } catch { + connectionsFailure = error.localizedDescription + } + } + .sheet(item: $openedSettings) { pod in + PageStack { RouteDestination(route: .podSettings(pod)) } + } + } + + private func row(_ kind: TriggerKind) -> some View { + Button { choose(kind) } label: { + SettingsRow(label: kind.label, sub: kind.sub, chevron: true, leading: { TriggerKindMark(kind: kind) }) + } + .buttonStyle(SettingsRowPressStyle()) + } +} + +// MARK: Schedule + +/// A schedule's groups: how often it repeats and every how many, on which +/// days, then at which times, with `note` under the last. A schedule written +/// as cron shows as written until a repeat is picked in its place. +struct ScheduleGroups: View { + let reading: ScheduleReading + let note: String + let change: (CalendarSchedule) -> Void + + var body: some View { + let schedule = reading.schedule + SettingsGroup(note: schedule == nil ? note : nil) { + SettingsChoiceRow( + label: "Repeat", + options: ScheduleWords.repeatOptions, + value: schedule?.repeatKind + ) { change(ScheduleWords.withRepeat(reading, $0)) } + if case let .written(expression, label) = reading { + SettingsDivider() + VStack(alignment: .leading, spacing: 4) { + Text(label).font(Typeface.rubik(14.5)).foregroundStyle(Palette.foreground) + Text(expression).font(Typeface.mono(13)).foregroundStyle(Palette.mutedForeground) + Text("Pick a repeat to replace it.").font(Typeface.rubik(12.5)).foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 16) + .padding(.vertical, 12) + } + if let schedule { RepeatRows(schedule: schedule, change: change) } + } + if let schedule { + SettingsGroup(note: note) { + TimesRow(times: schedule.times) { times in + var changed = schedule + changed.times = times + change(changed) + } + } + } + } +} + +/// Every how many days, weeks or months, and for a weekly or monthly schedule, on which days. +private struct RepeatRows: View { + let schedule: CalendarSchedule + let change: (CalendarSchedule) -> Void + + /// The days of the month a schedule can pick: the 1st to the 28th, then the last day. + private static let lastNumberedDay = 28 + + var body: some View { + let max = ScheduleWords.maxEvery(schedule.repeatKind) + SettingsDivider() + StepperRow( + label: "Every", + value: ScheduleWords.formatEvery(schedule), + lessLabel: "Closer together", + moreLabel: "Further apart", + onLess: schedule.every > 1 ? { changeEvery(schedule.every - 1) } : nil, + onMore: schedule.every < max ? { changeEvery(schedule.every + 1) } : nil + ) + if schedule.repeatKind == .weekly { + SettingsDivider() + VStack(alignment: .leading, spacing: 8) { + Text("Days").font(Typeface.rubik(16)).foregroundStyle(Palette.foreground) + HStack(spacing: 0) { + ForEach(Array(ScheduleWords.days.enumerated()), id: \.offset) { index, day in + if index > 0 { Spacer(minLength: 6) } + let selected = schedule.days.contains(day.value) + Button { + var changed = schedule + changed.days = selected ? schedule.days.filter { $0 != day.value } : schedule.days + [day.value] + change(changed) + } label: { + Text(day.letter) + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(selected ? Palette.primaryForeground : Palette.softForeground) + .frame(width: 32, height: 32) + .background(selected ? Palette.primary : Palette.chip, in: Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel(day.long) + .accessibilityAddTraits(selected ? .isSelected : []) + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + if schedule.repeatKind == .monthly { + SettingsDivider() + StepperRow( + label: "On the", + value: ScheduleWords.formatDayOfMonth(schedule.dayOfMonth), + lessLabel: "A day earlier", + moreLabel: "A day later", + onLess: { stepDay(-1) }, + onMore: { stepDay(1) } + ) + } + } + + /// How often counts from today, so a change of pace starts now. + private func changeEvery(_ every: Int) { + var changed = schedule + changed.every = every + changed.startsOn = ScheduleWords.today() + change(changed) + } + + /// The 1st to the 28th, then the last day, round again either way. + private func stepDay(_ step: Int) { + let count = Self.lastNumberedDay + 1 + let position: Int = if case let .day(number) = schedule.dayOfMonth { number } else { count } + let next = ((position - 1 + step + count) % count) + 1 + var changed = schedule + changed.dayOfMonth = next == count ? .last : .day(next) + change(changed) + } +} + +/// The times a schedule runs at, each a chip picked from the half hours, with +/// an × to remove it while another is left, and + Add for one more. +private struct TimesRow: View { + let times: [Int] + let change: ([Int]) -> Void + + private static let pickable = Array(stride(from: 0, to: 24 * 60, by: ScheduleWords.timeStepMinutes)) + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Times").font(Typeface.rubik(16)).foregroundStyle(Palette.foreground) + FlowLayout(spacing: 8) { + ForEach(Array(times.enumerated()), id: \.offset) { index, time in + let others = times.enumerated().filter { $0.offset != index }.map(\.element) + let options = Self.pickable.contains(time) ? Self.pickable : (Self.pickable + [time]).sorted() + HStack(spacing: 0) { + Menu { + ForEach(options, id: \.self) { option in + Button { + change(times.enumerated().map { $0.offset == index ? option : $0.element }) + } label: { + if option == time { Label(ScheduleWords.formatTime(option), systemImage: "checkmark") } else { Text(ScheduleWords.formatTime(option)) } + } + .disabled(others.contains(option)) + } + } label: { + Text(ScheduleWords.formatTime(time)) + .font(Typeface.rubik(14, .semibold)) + .monospacedDigit() + .foregroundStyle(Palette.foreground) + .padding(.leading, 12) + .padding(.trailing, 4) + .frame(height: 32) + } + .accessibilityLabel("Time \(index + 1)") + if times.count > 1 { + Button { change(others) } label: { + Icon(.x, size: 14).frame(width: 24, height: 24).contentShape(Circle()) + } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("Remove \(ScheduleWords.formatTime(time))") + } else { + Spacer().frame(width: 8) + } + } + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + if times.count < Limits.maxRoutineScheduleTimes { + Button("+ Add") { change(times + [ScheduleWords.nextTime(times)]) } + .font(Typeface.rubik(14, .medium)) + .foregroundStyle(Palette.primaryForeground) + .padding(.horizontal, 12) + .frame(height: 32) + .background(Palette.primary, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .accessibilityLabel("Add a time") + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } +} + +// MARK: Webhook + +/// A webhook trigger as written, before it is saved. +struct WebhookDraft: Hashable { + var auth = WebhookAuthChoice.default + /// Blank for none, so the address alone runs it. + var secret = "" + + static let secretTooShortNote = "A secret needs at least \(Limits.minWebhookSecretCharacters) characters." + static let noSecretNote = "With no secret, anyone who has the address can run it. Add one so only the sender can." + + /// Whether the secret can be saved: a source's, however long; one made up, long enough; or none. + var secretReady: Bool { + let trimmed = secret.trimmingCharacters(in: .whitespaces) + return trimmed.isEmpty || auth.isSource || trimmed.count >= Limits.minWebhookSecretCharacters + } +} + +extension WebhookAuthChoice { + /// What each generic kind asks for when it is chosen. + static func genericDefault(_ kind: String) -> WebhookAuthChoice { + switch kind { + case "api_key": .apiKey(header: "X-API-Key") + case "bearer": .bearer + case "basic": .basic(username: "sugabots") + default: .default + } + } + + /// "generic" for any sender, else the source. + var source: String { isSource ? kind : "generic" } + + /// What the secret is called: every source's is a signing secret. + var secretLabel: String { + isSource ? "Signing secret" : Self.secretLabels[kind] ?? "Secret" + } + + /// How the secret looks: a source's format, or the prefix of a kind's own secrets. + var secretPlaceholder: String? { + if isSource { return Self.sourceSecretPlaceholders[kind] } + guard let prefix = Self.secretPrefixes[kind], !prefix.isEmpty else { return nil } + return "\(prefix)…" + } + + /// What a caller must do to be let in; nil for a source from a newer server than this app knows. + var note: String? { + switch self { + case let .source(source): + Self.sourceNotes[source] + case let .hmac(header, algorithm, encoding): + "Sign the raw request body with the secret using HMAC \(Self.label(Self.algorithmOptions, algorithm)), and send the digest in \(header), written in \(Self.label(Self.encodingOptions, encoding).lowercased())." + case let .apiKey(header): "Send the key in the \(header) header." + case .bearer: "Send the token in the Authorization header as Bearer." + case .basic: "Send the username and password with HTTP Basic auth." + } + } + + static func label(_ options: [(value: String, label: String)], _ value: String) -> String { + options.first { $0.value == value }?.label ?? value + } +} + +/// The webhook groups of a routine being made: where it comes from, then its auth and secret, under `note`. +struct NewWebhookGroups: View { + @Binding var draft: WebhookDraft + let note: String? + + var body: some View { + SettingsGroup { + SettingsControlRow(label: "Address") { + Text("Made when you create it").font(Typeface.rubik(14.5)).foregroundStyle(Palette.mutedForeground) + Spacer(minLength: 0) + } + SettingsDivider() + WebhookSourceRow(auth: $draft.auth) + } + SettingsGroup(note: note) { + WebhookAuthRows(auth: $draft.auth) + SettingsDivider() + SecretFieldRow(label: draft.auth.secretLabel, placeholder: draft.auth.secretPlaceholder, value: $draft.secret) + } + } +} + +/// Where the webhook comes from: a known source, with its logo, or Generic for any other sender. +struct WebhookSourceRow: View { + @Binding var auth: WebhookAuthChoice + + var body: some View { + MenuRow( + label: "Source", + options: WebhookAuthChoice.sourceOptions, + value: auth.source, + mark: { source in + if source == "generic" { + Icon(.webhook, size: 14, strokeWidth: 2.2) + .foregroundStyle(Palette.softForeground) + .frame(width: 24, height: 24) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + } else { + ConnectionMark(presetId: source, name: WebhookAuthChoice.sourceLabels[source] ?? source, size: .md) + } + } + ) { source in + auth = source == "generic" ? .default : .source(source) + } + } +} + +/// For a generic webhook, the auth to ask callers for and what it needs. +struct WebhookAuthRows: View { + @Binding var auth: WebhookAuthChoice + + var body: some View { + if !auth.isSource { + SettingsDivider() + MenuRow(label: "Auth", options: WebhookAuthChoice.authOptions, value: auth.kind) { auth = .genericDefault($0) } + } + switch auth { + case let .hmac(header, algorithm, encoding): + SettingsDivider() + CommittedFieldRow(label: "Header", value: header, placeholder: "X-Signature") { auth = .hmac(header: $0, algorithm: algorithm, encoding: encoding) } + SettingsDivider() + MenuRow(label: "Algorithm", options: WebhookAuthChoice.algorithmOptions, value: algorithm) { auth = .hmac(header: header, algorithm: $0, encoding: encoding) } + SettingsDivider() + MenuRow(label: "Encoding", options: WebhookAuthChoice.encodingOptions, value: encoding) { auth = .hmac(header: header, algorithm: algorithm, encoding: $0) } + case let .apiKey(header): + SettingsDivider() + CommittedFieldRow(label: "Header", value: header, placeholder: "X-API-Key") { auth = .apiKey(header: $0) } + case let .basic(username): + SettingsDivider() + CommittedFieldRow(label: "Username", value: username, placeholder: "sugabots") { auth = .basic(username: $0) } + default: + EmptyView() + } + } +} + +/// A short field, such as a header's name, that commits trimmed when it's left; blank or unchanged puts it back. +struct CommittedFieldRow: View { + let label: String + let value: String + let placeholder: String + let commit: (String) -> Void + @State private var draft: String? + @FocusState private var focused: Bool + + var body: some View { + SettingsControlRow(label: label) { + TextField("", text: Binding(get: { draft ?? value }, set: { draft = $0 }), prompt: Text(placeholder).foregroundStyle(Palette.mutedForeground)) + .font(Typeface.mono(16)) + .foregroundStyle(Palette.foreground) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .focused($focused) + .onSubmit(finish) + .onChange(of: focused) { _, isFocused in if !isFocused { finish() } } + .accessibilityLabel(label) + } + } + + private func finish() { + let trimmed = (draft ?? value).trimmingCharacters(in: .whitespaces) + draft = nil + if !trimmed.isEmpty, trimmed != value { commit(trimmed) } + } +} + +/// A secret's field, hidden until shown, with Show and Copy once it has +/// something in it; `onCommit` runs when the field is submitted or left. +struct SecretFieldRow: View { + let label: String + let placeholder: String? + @Binding var value: String + var error: String? + var onCommit: (() -> Void)? + @State private var shown = false + @FocusState private var focused: Bool + @Environment(Toaster.self) private var toaster + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 12) { + Text(label).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground).frame(minWidth: SettingsRowMetrics.labelWidth, alignment: .leading).fixedSize() + Group { + if shown { + TextField("", text: $value, prompt: prompt) + } else { + SecureField("", text: $value, prompt: prompt) + } + } + .font(Typeface.mono(16)) + .foregroundStyle(Palette.foreground) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .focused($focused) + .onSubmit { onCommit?() } + .onChange(of: focused) { _, isFocused in if !isFocused { onCommit?() } } + .accessibilityLabel(label) + if !value.isEmpty { + Button { shown.toggle() } label: { Icon(shown ? .eyeOff : .eye, size: 15).frame(width: 30, height: 30) } + .buttonStyle(IconPressStyle()) + .accessibilityLabel(shown ? "Hide" : "Show") + Button { + UIPasteboard.general.string = value.trimmingCharacters(in: .whitespaces) + toaster.show("Copied") + } label: { Icon(.copy, size: 15).frame(width: 30, height: 30) } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("Copy \(label.lowercased())") + } + } + if let error { Text(error).font(Typeface.rubik(12.5)).foregroundStyle(Palette.destructiveText) } + } + .settingsRowPadding(vertical: 10, minHeight: SettingsRowMetrics.compactMinHeight) + } + + private var prompt: Text { + Text(placeholder ?? "").font(Typeface.rubik(14.5)).foregroundStyle(Palette.mutedForeground) + } +} + +// MARK: Repository + +/// A repository trigger as written, before its repository is chosen. +struct RepositoryDraft: Hashable { + var connectionId: String? + var repository: String? + var events: [RepositoryEvent] = [.pullRequestOpened] + + static let pickAnEventNote = "Pick at least one thing for it to run on." +} + +/// The repository and events groups, for a routine on a bot in `pod`, from its GitHub connection's repositories. +struct RepositoryGroups: View { + let pod: Pod + @Binding var draft: RepositoryDraft + @Environment(WorkspaceStore.self) private var store + @State private var loaded: (connectionId: String?, repositories: [String])? + @State private var failure: String? + + var body: some View { + Group { + if let failure { + FormAlert(text: failure) + } else if let loaded { + if let connectionId = loaded.connectionId, !loaded.repositories.isEmpty { + SettingsGroup(label: "Repository", note: "\(pod.name)'s repositories.") { + DividedRows(data: loaded.repositories, id: \.self) { repository in + Button { + draft.connectionId = connectionId + draft.repository = repository + } label: { + HStack { + Text(repository).font(Typeface.mono(13.5)).foregroundStyle(Palette.foreground).frame(maxWidth: .infinity, alignment: .leading) + if draft.connectionId == connectionId, draft.repository?.lowercased() == repository.lowercased() { + Icon(.check, size: 16, strokeWidth: 2.4).foregroundStyle(Palette.foreground) + } + } + .settingsRowPadding() + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + SettingsGroup( + label: "Runs when", + note: draft.events.isEmpty ? RepositoryDraft.pickAnEventNote : "What the bots' own pushes, comments and pull requests cause doesn't run it." + ) { + DividedRows(data: RepositoryDraft.events, id: \.value) { listed in + let event = RepositoryEvent(rawValue: listed.value) + SwitchRow(label: listed.label, isOn: Binding( + get: { draft.events.contains(event) }, + set: { on in + draft.events = on + ? RepositoryDraft.events.map { RepositoryEvent(rawValue: $0.value) }.filter { $0 == event || draft.events.contains($0) } + : draft.events.filter { $0 != event } + } + ), fontSize: 14.5) + } + } + } else { + InfoNote(text: "\(pod.name) isn't connected to any GitHub repositories yet. Someone who manages its connections can connect GitHub in the pod's settings.") + } + } + } + .task { + do { + let connectionId = try await store.connections(in: pod.id).first { $0.kind == .github }?.id + var repositories: [String] = [] + if let connectionId { + repositories = try await store.repositories(in: pod.id, connectionId: connectionId).repositories.map(\.repository) + } + loaded = (connectionId, repositories) + } catch { + failure = error.localizedDescription + } + } + } +} diff --git a/apps/ios/Sugabots/Routines/TriggerKinds.generated.swift b/apps/ios/Sugabots/Routines/TriggerKinds.generated.swift new file mode 100644 index 000000000..a165c8b59 --- /dev/null +++ b/apps/ios/Sugabots/Routines/TriggerKinds.generated.swift @@ -0,0 +1,46 @@ +// Generated by apps/codegen/generate-trigger-kinds.ts from packages/web/src/lib/routine-trigger-words.ts. Do not edit. + +/// A kind of trigger a routine may have, as `TRIGGER_KINDS` lists them: Sugabots' own first. +enum TriggerKind: String, CaseIterable, Identifiable { + case cron + case webhook + case github + + var id: String { rawValue } + + var label: String { + switch self { + case .cron: "Schedule" + case .webhook: "Webhook" + case .github: "GitHub" + } + } + + /// What it runs on, in the line under its label. + var sub: String { + switch self { + case .cron: "On the days and at the times you pick" + case .webhook: "When something calls its address" + case .github: "When something happens on a repository: pull requests, issues, checks, pushes" + } + } + + /// The kind of connection the bot's pod needs for it, for an integration's trigger. + var connection: ConnectionKind? { + switch self { + case .cron: nil + case .webhook: nil + case .github: .github + } + } +} + +extension WebhookAuthChoice { + /// What a caller must do to be let in, for each source that signs its own way, as `WEBHOOK_SOURCE_NOTES`. + static let sourceNotes: [String: String] = [ + "github": "Add the address as a webhook in GitHub, with the content type application/json, and give it the same secret.", + "stripe": "Add the address as an endpoint in Stripe, and paste its signing secret.", + "slack": "Set the address as your Slack app's Request URL, and paste its Signing Secret.", + "linear": "Add the address as a webhook in Linear, and paste its signing secret.", + ] +} diff --git a/apps/ios/Sugabots/Settings/AgentSettings.swift b/apps/ios/Sugabots/Settings/AgentSettings.swift new file mode 100644 index 000000000..c8d83c804 --- /dev/null +++ b/apps/ios/Sugabots/Settings/AgentSettings.swift @@ -0,0 +1,474 @@ +import SwiftUI + +extension BuiltInTool { + static let webKeys = catalog.filter(\.usesWeb).map(\.key) +} + +/// A bot's settings, as the web's `AgentSettingsPage`: its card, with its +/// look, name, description, model and instructions, its tools, what it +/// inherits, its routines, and Delete. Model and Instructions open in its place. +@MainActor +struct AgentSettingsScreen: View { + let pod: Pod + /// The bot as the list that opened this page had it. + let listedAgent: Agent + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + /// The bot as last fetched or saved. + @State private var agent: Agent? + @State private var record: Pod? + @State private var models: WorkspaceModelsResponse? + @State private var members: [WorkspaceMember]? + @State private var connections: [Connection]? + @State private var routineCount: Int? + @State private var webOff = false + @State private var computersOff = false + @State private var failure: String? + /// A switch's or a model's save, which holds the switches and models until it's done. + @State private var switching = SettingsAction() + @State private var editingLook = false + @State private var confirmingDelete = false + @State private var page: Page? + + enum Page: Hashable { + case model, instructions + } + + var body: some View { + Group { + if let agent { card(agent) } else { SettingsPage { if let failure { FormAlert(text: failure) } } } + } + .navigationDestination(item: $page) { page in + if let agent { + switch page { + case .model: modelPage(agent) + case .instructions: InstructionsPage(agent: agent, editable: may.updateAgents) { try await save(AgentUpdate(prompt: .present($0))) } + } + } + } + .task { + await load() + if DebugSheet.look.isWanted { editingLook = true } + } + } + + private var may: PodPermissions { + record?.permissions ?? .nothingAllowed + } + + // MARK: The card + + private func card(_ agent: Agent) -> some View { + let workspaceName = store.workspace.name + let modelName = agent.model.map { id in models?.models.first { $0.modelId == id }?.name ?? id } + return SettingsPage( + title: agent.name, + description: agent.givenDescription, + hero: AnyView(face(agent)) + ) { + if let failure { FormAlert(text: failure) } + SettingsGroup(label: "Profile") { + ProfileField(label: "Name", value: agent.name, maxLength: Limits.agentNameMaxLength, required: true, editable: may.updateAgents) { try await save(AgentUpdate(name: $0)) } + SettingsDivider() + ProfileField(label: "Description", value: agent.description ?? "", placeholder: "One line on what it's for", maxLength: Limits.descriptionMaxLength, wide: true, editable: may.updateAgents) { + try await save(AgentUpdate(description: .present($0))) + } + SettingsDivider() + Button { page = .model } label: { + SettingsRow(label: "Model", sub: "From the models set up for \(workspaceName)", chevron: true, trailing: { + SettingsValue(text: modelName ?? "None chosen") + }) + } + .buttonStyle(SettingsRowPressStyle()) + SettingsDivider() + Button { page = .instructions } label: { + SettingsRow(label: "Instructions", sub: "How it should behave and what to focus on", chevron: true) + } + .buttonStyle(SettingsRowPressStyle()) + SettingsDivider() + addedBy(agent) + } + builtInTools(agent, workspaceName: workspaceName) + inheritedTools + SettingsGroup { + NavigationLink(value: Route.routines(pod, agent: agent)) { + SettingsRow(label: "Routines", sub: "What \(agent.name) does without being asked. Set up on its Routines page.", chevron: true, trailing: { + if let routineCount { SettingsValue(text: routineCount == 0 ? "None" : "\(routineCount)") } + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + if may.deleteAgents { + SettingsDanger(label: "Delete bot", description: "Its chat, routines and settings go with it.", actionTitle: "Delete") { confirmingDelete = true } + } + } + .confirmDelete( + isPresented: $confirmingDelete, + title: "Delete \(agent.name)?", + description: "Its chat, routines and settings go with it. This can't be undone." + ) { + try await store.client.agents.remove(agentId: agent.id) + await store.refreshAll() + // Back to Bots, so Back never returns to it. + dismiss() + } + .fullScreenCover(isPresented: $editingLook) { + LookEditor(agent: agent) { change in try await save(change) } + } + } + + @ViewBuilder + private func face(_ agent: Agent) -> some View { + if may.updateAgents { + Button { editingLook = true } label: { + BotFace(look: agent.look, size: 44) + .overlay(alignment: .bottomTrailing) { + // Cut out of the face by a ring of the page's own colour. + Icon(.pencil, size: 11, strokeWidth: 2.2) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 18, height: 18) + .background(Palette.chip, in: Circle()) + .padding(2) + .background(Palette.background, in: Circle()) + .offset(x: 6, y: 6) + } + } + .buttonStyle(.plain) + .accessibilityLabel("Change look") + } else { + BotFace(look: agent.look, size: 44) + } + } + + private func addedBy(_ agent: Agent) -> some View { + let adder = members?.first { $0.user.id == agent.createdById }?.user + // Said once the roster has answered, rather than guessed before it. + let who: String? = agent.createdById == nil ? "With the workspace" : adder?.name ?? (members == nil ? nil : "Someone no longer here") + return SettingsRow(label: "Added by", sub: agent.createdAt.formatted(.dateTime.day().month(.abbreviated).year()), trailing: { + if let who { + HStack(spacing: 8) { + if let adder { PersonAvatar(name: adder.name, email: adder.email, image: adder.image, size: 20) } + SettingsValue(text: who) + } + } + }) + } + + private func builtInTools(_ agent: Agent, workspaceName: String) -> some View { + let isOn = { (keys: [String]) in keys.contains { !agent.disabledTools.contains($0) } } + return SettingsGroup(label: "Built-in tools") { + toolRow( + "Computer", + sub: computersOff ? "Computers are off for \(workspaceName)" : "Run commands, browse and edit files on the pod's computer", + on: agent.usesSandbox && !computersOff, + canChange: may.manageSandbox, + offReason: computersOff ? "Computers are off for \(workspaceName)" : nil + ) { next in switching.run { try await save(AgentUpdate(usesSandbox: .present(next))) } } + // How it uses its computer's browser, so only while it has one. + if agent.usesSandbox && !computersOff { + SettingsDivider() + toolRow( + "Natural browsing", + sub: "Show a cursor, scroll smoothly and type at a typing pace, so people watching can follow along. Slower.", + on: agent.naturalBrowsing, + canChange: may.updateAgents + ) { next in switching.run { try await save(AgentUpdate(naturalBrowsing: .present(next))) } } + } + SettingsDivider() + toolRow( + "Web search", + sub: webOff ? "Web search is off for \(workspaceName)" : "Look things up and cite pages", + on: isOn(BuiltInTool.webKeys) && !webOff, + canChange: may.updateAgents, + offReason: webOff ? "Web search is off for \(workspaceName)" : nil + ) { next in setTools(BuiltInTool.webKeys, on: next) } + ForEach(BuiltInTool.catalog.filter { !$0.usesWeb }, id: \.key) { tool in + SettingsDivider() + toolRow(tool.name, sub: tool.description, on: isOn([tool.key]), canChange: may.updateAgents) { next in setTools([tool.key], on: next) } + } + } + } + + private func toolRow(_ label: String, sub: String, on: Bool, canChange: Bool, offReason: String? = nil, change: @escaping (Bool) -> Void) -> some View { + SettingsRow(label: label, sub: sub, leading: { EmptyView() }, trailing: { + if canChange { + WebToggle(label: "\(on ? "Turn off" : "Turn on") \(label)", isOn: on, change: change).disabled(offReason != nil || switching.pending) + } else { + SettingsValue(text: on ? "On" : "Off") + } + }) + .foregroundStyle(offReason != nil ? Palette.mutedForeground : Palette.foreground) + } + + private var inheritedTools: some View { + let reachable = connections?.filter { $0.toolCounts.allow + $0.toolCounts.ask > 0 } + return SettingsGroup(label: "Inherited from \(pod.name)", note: "Every bot in \(pod.name) shares these. What each connection allows is set on the pod.") { + NavigationLink(value: Route.settings(.podPage(pod, .connections))) { + HStack(spacing: 2) { + Text("Edit in \(pod.name)") + Icon(.arrowUpRight, size: 13, strokeWidth: 2) + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + } + .buttonStyle(.plain) + } content: { + if reachable?.isEmpty == true { SettingsEmptyRow(text: "No connections yet") } + if let reachable { + DividedRows(data: reachable) { connection in + let tools = connection.toolCounts.allow + connection.toolCounts.ask + SettingsRow( + label: connection.name, + sub: "\(tools) \(tools == 1 ? "tool" : "tools")", + leading: { ConnectionMark(presetId: connection.presetId, name: connection.name, size: .md) }, + trailing: { SettingsValue(text: "Inherited") } + ) + } + } + } + } + + // MARK: Model + + private func modelPage(_ agent: Agent) -> some View { + let offered = models?.models ?? [] + let providers = offered.map(\.providerName).reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } } + // A model chosen before it was switched off is still the one in use, so it is shown on its own. + let stranded = agent.model.flatMap { model in offered.contains { $0.modelId == model } ? nil : model } + return SettingsPage(title: "Model", description: "What \(agent.name) thinks with.") { + if let failure { FormAlert(text: failure) } + if let stranded { + SettingsGroup(label: "In use", note: "This model is no longer switched on for the workspace.") { modelRow(stranded, label: stranded, chosen: agent.model) } + } + if models != nil, offered.isEmpty { + SettingsGroup { SettingsRow(label: "No models are switched on yet.") } + } + ForEach(providers, id: \.self) { provider in + SettingsGroup(label: provider) { + let ofProvider = offered.filter { $0.providerName == provider } + DividedRows(data: ofProvider) { model in + modelRow(model.modelId, label: model.name, chosen: agent.model) + } + } + } + if models != nil { + Text(store.permissions?.manageProviders == true + ? "Only models switched on for the workspace appear here. Add providers and switch on more in Models." + : "Only models switched on for the workspace appear here. To use another, ask a workspace admin to switch it on.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + } + } + } + + private func modelRow(_ modelId: String, label: String, chosen: String?) -> some View { + Button { switching.run { try await save(AgentUpdate(model: .present(modelId))) } } label: { + SettingsRow(label: label, trailing: { + if modelId == chosen { Icon(.check, size: 16, strokeWidth: 2.6).foregroundStyle(Palette.foreground) } + }) + } + .buttonStyle(SettingsRowPressStyle()) + .disabled(!may.updateAgents || modelId == chosen || switching.pending) + } + + // MARK: Doing + + private func load() async { + do { + agent = try await store.client.agents.get(agentId: listedAgent.id) + failure = nil + } catch { + failure = error.localizedDescription + } + record = try? await store.podRecord(pod.id) + models = try? await store.refreshModels() + members = try? await store.workspaceMembers() + connections = try? await store.connections(in: pod.id) + routineCount = (try? await store.routines(of: listedAgent.id))?.count + webOff = (try? await store.client.searchProviders.webAccess(workspace: store.workspace.id))?.enabled == false + computersOff = (try? await store.computersEnabled()) == false + } + + private func save(_ change: AgentUpdate) async throws { + do { + agent = try await store.client.agents.update( + agentId: listedAgent.id, + name: change.name, + handle: change.handle, + description: change.description, + color: change.color, + face: change.face, + shape: change.shape, + model: change.model, + prompt: change.prompt, + disabledTools: change.disabledTools, + usesSandbox: change.usesSandbox, + naturalBrowsing: change.naturalBrowsing + ) + failure = nil + await store.refreshAll() + } catch { + failure = error.localizedDescription + throw error + } + } + + /// Turns the tools `keys` names on or off, from the bot's tools as they + /// stand when the save starts, so it builds on any change saved before it. + private func setTools(_ keys: [String], on: Bool) { + switching.run { + guard let current = agent?.disabledTools else { return } + let disabled = on ? current.filter { !keys.contains($0) } : Array(Set(current + keys)).sorted() + try await save(AgentUpdate(disabledTools: .present(disabled))) + } + } +} + +/// A name or description edited where it stands, saved when the field is left, as `ProfileField`. +private struct ProfileField: View { + let label: String + let value: String + var placeholder = "" + let maxLength: Int + var required = false + var wide = false + let editable: Bool + let commit: (String) async throws -> Void + @State private var draft = "" + @FocusState private var focused: Bool + + var body: some View { + HStack(spacing: 14) { + Text(label) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.foreground) + .frame(width: wide ? 96 : nil, alignment: .leading) + .frame(maxWidth: wide ? nil : .infinity, alignment: .leading) + if editable { + TextField("", text: $draft.limited(to: maxLength), prompt: Text(placeholder).foregroundStyle(Palette.subtleForeground)) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .editsInPlace(draft: $draft, saved: value, allowsEmpty: !required, focused: $focused, save: commit) + .padding(.horizontal, 10) + .frame(height: 32) + .frame(maxWidth: wide ? .infinity : 240) + .background(Palette.settingsRowHover, in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 9, style: .continuous).strokeBorder(focused ? Palette.ring : Palette.borderStrong)) + .accessibilityLabel(label) + } else { + Text(value.isEmpty ? "None yet" : value).font(Typeface.rubik(15)).foregroundStyle(Palette.mutedForeground) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 56) + } +} + +/// A bot's instructions, as the web's `Instructions` page: a long field and Save. +@MainActor +private struct InstructionsPage: View { + let agent: Agent + let editable: Bool + let save: (String) async throws -> Void + @State private var draft: String + @State private var saving = SettingsAction() + + init(agent: Agent, editable: Bool, save: @escaping (String) async throws -> Void) { + self.agent = agent + self.editable = editable + self.save = save + _draft = State(initialValue: agent.prompt) + } + + var body: some View { + SettingsPage(title: "Instructions", description: "How \(agent.name) should work. It follows these in every chat.") { + if let failure = saving.failure { FormAlert(text: failure) } + SettingsGroup( + note: editable + ? "Write it like a note to a new teammate: what it's for, how to sound, and what to never do. \(draft.count.formatted()) of \(Limits.promptMaxLength.formatted()) characters." + : nil + ) { + TextEditor(text: $draft.limited(to: Limits.promptMaxLength)) + .font(Typeface.rubik(16)) + .lineSpacing(16 * 0.65 - 6) + .foregroundStyle(Palette.foreground) + .scrollContentBackground(.hidden) + .disabled(!editable) + .frame(minHeight: 380) + .padding(10) + .overlay(alignment: .topLeading) { + if draft.isEmpty { + Text("No instructions yet.").font(Typeface.rubik(16)).foregroundStyle(Palette.subtleForeground).padding(18).allowsHitTesting(false) + } + } + .accessibilityLabel("Instructions") + } + if editable { + HStack { + Spacer() + Button(saving.pending ? "Saving…" : "Save") { + let instructions = draft + saving.run { try await save(instructions) } + } + .buttonStyle(WebButtonStyle()) + .disabled(draft == agent.prompt || saving.pending) + } + } + } + } +} + +/// A bot's look on a page of its own, as the web's phone `LookEditor`: Close +/// and Save across the top, the bot on its colour, then its shape, face and colour. +@MainActor +private struct LookEditor: View { + let agent: Agent + let save: (AgentUpdate) async throws -> Void + @Environment(\.dismiss) private var dismiss + @State private var look: BotLook + @State private var part = LookPart.shape + @State private var saving = SettingsAction() + + init(agent: Agent, save: @escaping (AgentUpdate) async throws -> Void) { + self.agent = agent + self.save = save + _look = State(initialValue: agent.look) + } + + var body: some View { + var change = AgentUpdate() + if look.color != agent.color { change.color = .present(look.color) } + if look.shape != agent.shape { change.shape = .present(look.shape) } + if look.face != agent.face { change.face = .present(look.face) } + // A tint of the bot's colour, faint, so the bot is in its own light without shouting. + let stage = BotLooks.palette(for: look.color).face.opacity(0.05) + return VStack(spacing: 0) { + VStack(spacing: 12) { + ScreenHeader(title: "Look") { + GlassRoundButton(icon: .x, label: "Cancel", iconSize: 20) { dismiss() } + } trailing: { + Button(saving.pending ? "Saving…" : "Save") { submit(change) } + .buttonStyle(WebButtonStyle(size: .pill)) + .disabled(change == AgentUpdate() || saving.pending) + } + BotFace(look: look, size: 88).padding(.top, 8) + if let failure = saving.failure { FormAlert(text: failure).padding(.horizontal, 16) } + } + .padding(.bottom, 20) + .background(Palette.list.overlay(stage).ignoresSafeArea()) + LookStep(part: $part, look: $look) + .frame(maxHeight: .infinity, alignment: .top) + .background(Palette.panel.ignoresSafeArea()) + .overlay(alignment: .top) { Rectangle().fill(Palette.border).frame(height: 1) } + } + } + + private func submit(_ change: AgentUpdate) { + guard change != AgentUpdate() else { return } + saving.run { + try await save(change) + dismiss() + } + } +} diff --git a/apps/ios/Sugabots/Settings/ConnectionPage.swift b/apps/ios/Sugabots/Settings/ConnectionPage.swift new file mode 100644 index 000000000..9dfb2e846 --- /dev/null +++ b/apps/ios/Sugabots/Settings/ConnectionPage.swift @@ -0,0 +1,537 @@ +import SwiftUI + +/// One connection, as the web's `ConnectionPage`: who it's signed in as, its +/// address and secret, a test, GitHub's repositories, how its tools may run, +/// and Disconnect. Individual tools opens in its place. +@MainActor +struct ConnectionSettingsScreen: View { + let pod: Pod + /// The connection as the list that opened this page had it. + let listedConnection: Connection + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @Environment(\.dismiss) private var dismiss + @Environment(\.scenePhase) private var scenePhase + @State private var fetchedConnection: Connection? + @State private var canManage = false + @State private var tools = ConnectionTools() + @State private var action = SettingsAction() + @State private var replacingSecret = false + @State private var newSecret = "" + @State private var removing = false + @State private var testing = false + @State private var tested: ConnectionTestResult? + @State private var openingTools = false + + /// The connection as last fetched, or until then, as it was listed. + private var connection: Connection { fetchedConnection ?? listedConnection } + + /// `projectLinks.documentation`'s troubleshooting section for connections. + private static let troubleshooting = URL(string: "https://sugabots.ai/docs/connections#troubleshooting")! + + var body: some View { + let isServer = connection.kind != .github + let preset = ConnectionPreset.matching(url: connection.url) + SettingsPage( + title: connection.name, + description: connection.connectedBy.map { "Connected by \($0)" } ?? "In \(pod.name)", + hero: AnyView(ConnectionMark(presetId: connection.presetId, name: connection.name, size: .lg)) + ) { + if let failure = action.failure ?? tools.accessFailure { FormAlert(text: failure) } + VStack(alignment: .leading, spacing: 0) { + SettingsGroup(label: connection.auth == .oauth || !isServer ? "Account" : "Connection") { + if connection.auth == .oauth || !isServer { + account(connection, isServer: isServer) + } + // A catalog app is known by its name; only a server added by URL is told apart by it. + if preset == nil && isServer { + if connection.auth == .oauth { SettingsDivider() } + SettingsRow(label: "Address", trailing: { + Text(connection.url).font(Typeface.mono(13)).foregroundStyle(Palette.mutedForeground).lineLimit(1).truncationMode(.middle) + }) + } + if isServer && connection.auth == .header { + SettingsDivider() + SettingsRow( + label: connection.secretHeader == nil ? "Access token" : "Secret", + sub: connection.secretHeader.map { "Sent in the \($0) header" } ?? "None yet", + trailing: { + if canManage { + Button(Self.secretAction(connection)) { replacingSecret = true }.buttonStyle(SettingsRowButtonStyle()) + } + } + ) + } + if replacingSecret { secretForm(connection) } + } + if isServer { testConnection(connection).padding(.horizontal, 2).padding(.top, 10) } + } + if connection.kind == .github { + RepositoriesGroup(connection: connection, canManage: canManage) + } + toolSettings(connection) + if canManage { + SettingsDanger(label: "Disconnect \(connection.name)", description: "Bots in this pod lose access straight away.", actionTitle: "Disconnect") { removing = true } + } + } + .confirmDelete( + isPresented: $removing, + title: "Disconnect \(connection.name)?", + description: connection.kind == .github + ? "Bots in this pod can no longer use its tools or its repositories. The pod's app stays on GitHub until you delete it there: Delete GitHub App in its advanced settings." + : "Bots in this pod can no longer use its tools. Connecting it again means signing in or entering its details again.", + confirmLabel: "Disconnect" + ) { + try await store.removeConnection(connection) + dismiss() + } + .navigationDestination(isPresented: $openingTools) { + IndividualToolsScreen(connection: connection, tools: tools, canManage: canManage) + } + .task { await load() } + .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await load() } } } + } + + // MARK: Parts + + /// What the account row says under its label while nobody is signed in. + private static func notSignedInNote(_ connection: Connection, isServer: Bool) -> String? { + if connection.signedIn { return nil } + if isServer { return "Bots can't use \(connection.name) until someone signs in." } + return "Bots can't use GitHub until the pod's app is installed on the account it works on." + } + + private func account(_ connection: Connection, isServer: Bool) -> some View { + SettingsRow(label: isServer ? "Signed in as" : "Installed by", sub: Self.notSignedInNote(connection, isServer: isServer), trailing: { + HStack(spacing: 12) { + if connection.signedIn { + if let name = connection.connectedBy { + HStack(spacing: 8) { + PersonAvatar(name: name, size: 20) + SettingsValue(text: name) + } + } else { + SettingsValue(text: "Someone no longer here") + } + } + if canManage { + if isServer { + if connection.auth == .oauth || !connection.signedIn { + Button(connection.signedIn ? "Reconnect" : "Sign in") { signIn(connection) } + .buttonStyle(SettingsRowButtonStyle()) + .disabled(action.pending) + } + } else { + Button(connection.signedIn ? "Manage access" : "Install on GitHub") { install(connection) } + .buttonStyle(SettingsRowButtonStyle()) + .disabled(action.pending) + } + } + } + }) + } + + private func secretForm(_ connection: Connection) -> some View { + let needsToken = connection.secretHeader == nil + return VStack(spacing: 0) { + SettingsDivider() + HStack(spacing: 12) { + SecureField("", text: $newSecret, prompt: Text(needsToken ? "Paste the access token" : "Paste the new secret").foregroundStyle(Palette.subtleForeground)) + .font(Typeface.mono(16)) + .accessibilityLabel("\(connection.name) secret") + Button("Cancel") { + replacingSecret = false + newSecret = "" + } + .buttonStyle(WebButtonStyle(variant: .ghost, size: .small)) + Button("Save") { saveSecret(connection) } + .buttonStyle(WebButtonStyle(size: .small)) + .disabled(newSecret.isEmpty || action.pending) + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 56) + } + } + + private func testConnection(_ connection: Connection) -> some View { + let reachable: Bool? = tested?.reachable ?? (connection.status == .error ? false : nil) + let failureText = tested.map { $0.error ?? "The server did not answer." } ?? connection.lastTestError ?? "The last check failed." + return HStack(spacing: 12) { + Button("Test connection") { test(connection) } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + .disabled(testing) + if testing { + Text("Checking…").font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground) + } else if reachable == true { + SettingsTestOutcome(good: true, text: connection.kind == .http ? "The address is allowed. A check sends no request to it." : "Connection successful") + } else if reachable == false { + SettingsTestOutcome(good: false, text: failureText) + Button("How to fix this") { openURL(Self.troubleshooting) } + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.foreground) + } + } + } + + @ViewBuilder + private func toolSettings(_ connection: Connection) -> some View { + switch tools.list { + case let .failed(failure): + FormAlert(text: failure) + case let .loaded(list): + let kinds = ToolKind.of(list) + if kinds.isEmpty { + SettingsGroup(label: "Tools") { SettingsEmptyRow(text: "No actions found yet") } + } else { + ForEach(kinds, id: \.kind) { kind in + SettingsGroup(label: kind.heading, note: kind.kind == .change ? "Ask first sends the action to Approvals before it runs." : nil) { + SettingsRow(label: kind.all, sub: kind.sub, trailing: { + AccessToggle(label: kind.heading, value: kind.setting, canManage: canManage) { access in + let following = kind.tools.filter { $0.access == kind.setting } + Task { await tools.setAccess(Dictionary(uniqueKeysWithValues: following.map { ($0.name, access) }), of: connection, store: store) } + } + }) + } + } + let apart = ToolKind.setApart(kinds).count + SettingsGroup { + Button { openingTools = true } label: { + SettingsRow( + label: "Individual tools", + sub: canManage ? "Set one tool differently from its group" : "Tools set apart from their group", + chevron: true, + trailing: { if apart > 0 { SettingsValue(text: "\(apart) changed") } } + ) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + case .loading: + VStack(spacing: 12) { + ForEach(0..<2, id: \.self) { _ in + Color.clear + .frame(height: 92) + .settingsCard() + } + } + .accessibilityLabel("Loading tools") + } + } + + // MARK: Doing + + private static func secretAction(_ connection: Connection) -> String { + if connection.secretHeader == nil { return "Add access token" } + return connection.hasSecret ? "Replace secret" : "Add secret" + } + + private func load() async { + if let all = try? await store.connections(in: pod.id), let fresh = all.first(where: { $0.id == listedConnection.id }) { + fetchedConnection = fresh + } + canManage = (try? await store.podRecord(pod.id))?.permissions.manageConnections ?? false + await tools.load(connection, store: store) + } + + private func signIn(_ connection: Connection) { + action.run { + if let url = try await store.startSignIn(connection) { openURL(url) } else { await load() } + } + } + + private func install(_ connection: Connection) { + action.run { + let install = try await store.client.gitHubConnections.installUrl(podId: pod.id, connectionId: connection.id) + if let url = URL(string: install.url) { openURL(url) } + } + } + + private func saveSecret(_ connection: Connection) { + action.run { + try await store.saveSecret(newSecret, of: connection) + replacingSecret = false + newSecret = "" + await load() + } + } + + private func test(_ connection: Connection) { + testing = true + Task { + do { + tested = try await store.testConnection(connection) + action.failure = nil + } catch { + action.failure = error.localizedDescription + } + testing = false + await load() + } + } +} + +/// A connection's tools and how each may run, shared by its page and its +/// Individual tools, so a change made on either shows on both. +@MainActor +@Observable +final class ConnectionTools { + private(set) var list: Loadable<[ConnectionToolSetting]> = .loading + /// What the last change of access failed with, until the next succeeds. + private(set) var accessFailure: String? + + func load(_ connection: Connection, store: WorkspaceStore) async { + list = await .of { try await store.connectionTools(connection) } + } + + /// Shows `access` straight away and saves it. If the server refuses, the + /// tools it names go back to what they were; any other tool keeps what it has. + func setAccess(_ access: [String: ConnectionAccess], of connection: Connection, store: WorkspaceStore) async { + guard let tools = list.value else { return } + let before = Dictionary(uniqueKeysWithValues: tools.filter { access[$0.name] != nil }.map { ($0.name, $0.access) }) + list = .loaded(tools.applying(access)) + do { + try await store.setToolAccess(access, of: connection) + accessFailure = nil + } catch { + if let now = list.value { list = .loaded(now.applying(before)) } + accessFailure = error.localizedDescription + } + } +} + +/// How a tool may run: a choice for those who may change it, or its word. +struct AccessToggle: View { + let label: String + let value: ConnectionAccess + let canManage: Bool + let change: (ConnectionAccess) -> Void + + var body: some View { + if canManage { + SegmentedChoice(label: label, options: [ConnectionAccess.allow, .ask, .off].map { ($0, $0.words) }, value: value, choose: change) + } else { + Text(value.words).font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + } + } +} + +/// Individual tools, as the web's `IndividualTools`: a search, then the tools +/// set apart from their group, then each group's others. +@MainActor +private struct IndividualToolsScreen: View { + let connection: Connection + let tools: ConnectionTools + let canManage: Bool + @Environment(WorkspaceStore.self) private var store + @State private var query = "" + + var body: some View { + let needle = query.trimmingCharacters(in: .whitespaces).lowercased() + let matches = { (tool: ConnectionToolSetting) in + needle.isEmpty || tool.name.lowercased().contains(needle) || tool.name.replacingOccurrences(of: "_", with: " ").lowercased().contains(needle) + } + let list = tools.list.value ?? [] + let kinds = ToolKind.of(list) + let apart = ToolKind.setApart(kinds) + let shownApart = apart.filter { matches($0.tool) } + let anyShown = !shownApart.isEmpty || kinds.contains { $0.tools.contains(where: matches) } + SettingsPage( + title: "Individual tools", + description: "Set a tool of \(connection.name) differently from its group.", + hero: AnyView(ConnectionMark(presetId: connection.presetId, name: connection.name, size: .lg)) + ) { + if let failure = tools.accessFailure { FormAlert(text: failure) } + VStack(spacing: 0) { + SearchField(placeholder: "Search \(list.count) \(connection.name) tools", text: $query, style: .inCard) + .padding(10) + SettingsDivider() + if !shownApart.isEmpty { + section(heading: "Changed (\(shownApart.count))", description: "Set apart from their group.") { + if canManage { + Button("Reset all") { change(Dictionary(uniqueKeysWithValues: apart.map { ($0.tool.name, $0.setting) })) } + .buttonStyle(SettingsRowButtonStyle()) + } + } rows: { + ForEach(shownApart, id: \.tool.name) { item in row(item.tool, setting: item.setting, changed: true) } + } + } + ForEach(kinds, id: \.kind) { kind in + let shown = kind.tools.filter { $0.access == kind.setting && matches($0) } + if !shown.isEmpty { + section(heading: kind.heading, description: "Follow the group's setting, \(kind.setting.words), until one is set differently.") { + EmptyView() + } rows: { + ForEach(shown) { tool in row(tool, setting: kind.setting, changed: false) } + } + } + } + if !anyShown { + Text("No tools match.").font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground).padding(.vertical, 32) + } + } + .settingsCard() + } + } + + private func section(heading: String, description: String, @ViewBuilder action: () -> some View, @ViewBuilder rows: () -> some View) -> some View { + VStack(spacing: 0) { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text(heading).font(Typeface.rubik(13, .medium)).foregroundStyle(Palette.foreground) + Text(description).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + action() + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .background(Palette.chip) + SettingsDivider() + rows() + } + } + + private func row(_ tool: ConnectionToolSetting, setting: ConnectionAccess, changed: Bool) -> some View { + VStack(spacing: 0) { + HStack(spacing: 14) { + VStack(alignment: .leading, spacing: 2) { + // Off fades to a quieter colour, not by opacity, which would take it below a readable contrast. + Text(tool.name).font(Typeface.mono(14)).foregroundStyle(tool.access == .off ? Palette.mutedForeground : Palette.foreground).lineLimit(1) + if changed { + Text("Default: \(setting.words.lowercased())").font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + AccessToggle(label: tool.name, value: tool.access, canManage: canManage) { change([tool.name: $0]) } + } + .padding(.leading, 36) + .padding(.trailing, 16) + .padding(.vertical, 12) + .frame(minHeight: 56) + SettingsDivider() + } + } + + private func change(_ access: [String: ConnectionAccess]) { + Task { await tools.setAccess(access, of: connection, store: store) } + } +} + +private extension [ConnectionToolSetting] { + /// The tools with `access` given to those it names, as they'll be once the server agrees. + func applying(_ access: [String: ConnectionAccess]) -> [ConnectionToolSetting] { + map { tool in + access[tool.name].map { ConnectionToolSetting(name: tool.name, readOnly: tool.readOnly, destructive: tool.destructive, access: $0) } ?? tool + } + } +} + +/// A GitHub connection's repositories, as `GitHubRepositoriesGroup`: each with +/// who added it, Remove, and Add repository from what the pod's app reaches. +@MainActor +private struct RepositoriesGroup: View { + let connection: Connection + let canManage: Bool + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @State private var listed: ConnectionRepositories? + @State private var loadFailure: String? + @State private var action = SettingsAction() + @State private var choosing = false + + var body: some View { + Group { + if let listed, let account = listed.account { + VStack(alignment: .leading, spacing: 0) { + SettingsGroup(label: "Repositories") { + if listed.repositories.isEmpty { SettingsRow(label: "None yet") } + DividedRows(data: listed.repositories) { item in + RemovableRow( + name: item.repository, + nameSize: 13.5, + sub: "Added by \(item.addedByName ?? "someone who has left")", + removal: canManage ? .init(label: "Remove \(item.repository)") { remove(item.repository) } : nil + ) + .disabled(action.pending) + } + if canManage { + if !listed.repositories.isEmpty { SettingsDivider() } + SettingsAddRow(label: "Add repository") { choosing = true } + .disabled(action.pending) + } + } + HStack(spacing: 0) { + Text("Bots in this pod read these from its sandbox, and work on them with the tools below. They come from \(account) on GitHub, through ") + + Text("the pod's app").foregroundColor(Palette.foreground).fontWeight(.medium) + + Text(".") + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 2) + .padding(.top, 10) + .onTapGesture { if let url = URL(string: connection.appSettingsUrl ?? connection.url) { openURL(url) } } + } + } + if let failure = action.failure ?? loadFailure { FormAlert(text: failure) } + } + .sheet(isPresented: $choosing) { + ChooseRepository(connection: connection, taken: Set(listed?.repositories.map { $0.repository.lowercased() } ?? [])) { repository in + choosing = false + add(repository) + } + } + .task { await load() } + } + + private func load() async { + do { + listed = try await store.repositories(in: connection.podId, connectionId: connection.id) + loadFailure = nil + } catch { + loadFailure = error.localizedDescription + } + } + + private func add(_ repository: String) { + action.run { + listed = try await store.client.gitHubConnections.addRepository(podId: connection.podId, connectionId: connection.id, repository: repository) + } + } + + private func remove(_ repository: String) { + action.run { + listed = try await store.client.gitHubConnections.removeRepository(podId: connection.podId, connectionId: connection.id, repository: repository) + } + } + + /// The repositories the pod's app reaches that aren't added yet, to search and pick one of. + private struct ChooseRepository: View { + let connection: Connection + let taken: Set + let choose: (String) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var reachable: [AccountRepository]? + @State private var query = "" + + var body: some View { + let needle = query.trimmingCharacters(in: .whitespaces).lowercased() + let shown = (reachable ?? []).filter { !taken.contains($0.repository.lowercased()) && (needle.isEmpty || $0.repository.lowercased().contains(needle)) } + DialogForm(title: "Add repository") { + SearchField(placeholder: "Search repositories", text: $query) + SettingsGroup { + if reachable == nil { SettingsEmptyRow(text: "Loading…") } + DividedRows(data: shown) { repository in + Button { choose(repository.repository) } label: { + SettingsRow(label: repository.repository, trailing: { + if repository.private { SettingsValue(text: "Private") } + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + .task { reachable = try? await store.client.gitHubConnections.reachableRepositories(podId: connection.podId, connectionId: connection.id) } + } + } +} diff --git a/apps/ios/Sugabots/Settings/ConnectionsSettings.swift b/apps/ios/Sugabots/Settings/ConnectionsSettings.swift new file mode 100644 index 000000000..cbd5ef0fd --- /dev/null +++ b/apps/ios/Sugabots/Settings/ConnectionsSettings.swift @@ -0,0 +1,380 @@ +import SwiftUI + +/// A pod's Connections, as the web's `ConnectionsSettings`: each with its mark +/// and how it stands, Sign in or Fix where it needs it, and Add connection. +/// Signing in to a server goes through the browser, where its sign-in returns +/// to the web; the list is fetched again when the app comes back. +@MainActor +struct PodConnectionsPage: View { + let record: Pod + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @Environment(\.scenePhase) private var scenePhase + @State private var connections: [Connection]? + @State private var failure: String? + @State private var adding = false + @State private var rowFailures: [String: String] = [:] + + var body: some View { + let canManage = record.permissions.manageConnections + SettingsPage(title: "Connections", description: "Shared by every bot in \(record.name).") { + if canManage { SettingsAddButton(label: "Add connection") { adding = true } } + } content: { + if let failure { + FormAlert(text: failure) + } else if let connections { + SettingsGroup(note: "Bots act as whoever connected each one. Open one to choose for each tool.") { + DividedRows(data: connections) { connection in row(connection, canManage: canManage) } + if connections.isEmpty { SettingsEmptyRow(text: "No connections in this pod yet") } + } + } + } + .fullScreenCover(isPresented: $adding) { + AddConnectionSheet( + pod: record, + taken: Set((connections ?? []).compactMap { ConnectionPreset.matching(url: $0.url)?.id }), + offersGitHub: !(connections ?? []).contains { $0.kind == .github } + ) { await load() } + } + .task { + await load() + if DebugSheet.addConnection.isWanted { adding = true } + } + .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await load() } } } + } + + private func line(for connection: Connection) -> String { + if !connection.signedIn { return "Not signed in yet" } + if connection.status == .error { return connection.lastTestError ?? "The last check failed" } + return connection.toolCounts.summary ?? "No actions found yet" + } + + private func row(_ connection: Connection, canManage: Bool) -> some View { + let needsSignIn = !connection.signedIn + let failing = connection.signedIn && connection.status == .error + let failure = rowFailures[connection.id] + let text = failure ?? line(for: connection) + return NavigationLink(value: Route.settings(.connection(record, connection))) { + HStack(spacing: 14) { + ConnectionMark(presetId: connection.presetId, name: connection.name, size: .tile) + VStack(alignment: .leading, spacing: 2) { + Text(connection.name).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground).lineLimit(1) + Text(text) + .font(Typeface.rubik(13)) + .foregroundStyle(failing || failure != nil ? Palette.destructiveText : Palette.subtleForeground) + .lineLimit(failing || failure != nil ? 2 : nil) + } + .frame(maxWidth: .infinity, alignment: .leading) + if canManage && (needsSignIn || failing) { + Button(needsSignIn ? "Sign in" : connection.auth == .oauth ? "Reconnect" : "Fix") { reconnect(connection) } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + } + Icon(.chevronRight, size: 14).foregroundStyle(Palette.subtleForeground) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: 56) + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + .accessibilityLabel("\(connection.name), \(text). Open tools") + } + + /// Signs a server that signs in back in through the browser; any other is fixed on its own page. + private func reconnect(_ connection: Connection) { + guard connection.auth == .oauth else { + openURL(store.webURL("settings/pods/\(record.slug)/connections/\(connection.id)")) + return + } + Task { + do { + if let url = try await store.startSignIn(connection) { openURL(url) } else { await load() } + rowFailures[connection.id] = nil + } catch { + rowFailures[connection.id] = error.localizedDescription + } + } + } + + private func load() async { + do { + connections = try await store.connections(in: record.id) + failure = nil + } catch { + failure = error.localizedDescription + } + } +} + +/// Adding a connection, as the web's `AddConnectionDialog`: a searchable list +/// of apps and GitHub, then an app's sign-in, or a server or endpoint by its address. +@MainActor +private struct AddConnectionSheet: View { + enum Choice: Hashable { + case preset(ConnectionPreset) + case byURL(ByURLStep.Target) + } + + let pod: Pod + let taken: Set + let offersGitHub: Bool + let added: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @Environment(\.dismiss) private var dismiss + @State private var choice: Choice? + @State private var query = "" + + var body: some View { + switch choice { + case let .preset(preset): AppStep(pod: pod, preset: preset, back: { choice = nil }, done: added) + case let .byURL(target): ByURLStep(pod: pod, target: target, back: { choice = nil }, done: added) + case nil: appList + } + } + + private var appList: some View { + let needle = query.trimmingCharacters(in: .whitespaces).lowercased() + let matches = { (name: String, description: String) in + needle.isEmpty || name.lowercased().contains(needle) || description.lowercased().contains(needle) + } + let shown = ConnectionPreset.catalog.filter { !taken.contains($0.id) && matches($0.name, $0.description) } + let gitHubShown = offersGitHub && matches("GitHub", "Repositories, issues and pull requests") + return DialogForm(title: "Add to \(pod.name)", gap: 14) { + SearchField(placeholder: "Search apps", text: $query) + VStack(spacing: 20) { + if gitHubShown || !shown.isEmpty { + SettingsGroup { + if gitHubShown { + // GitHub's app is made on GitHub from a form the web posts, so it's set up on the web. + Button { openURL(store.webURL("settings/pods/\(pod.slug)/connections")) } label: { + SettingsRow(label: "GitHub", sub: "Repositories, issues and pull requests", chevron: true, leading: { + ConnectionMark(presetId: "github", name: "GitHub", size: .tile) + }) + } + .buttonStyle(SettingsRowPressStyle()) + if !shown.isEmpty { SettingsDivider() } + } + DividedRows(data: shown) { preset in + Button { choice = .preset(preset) } label: { + SettingsRow(label: preset.name, sub: preset.description, chevron: true, leading: { + ConnectionMark(presetId: preset.id, name: preset.name, size: .tile) + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + if !gitHubShown, shown.isEmpty, !needle.isEmpty { + Text("No app matches “\(query.trimmingCharacters(in: .whitespaces))”.") + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 4) + } + SettingsGroup(label: "Something else") { + somethingElse(icon: .code, label: "Connect by URL", sub: "Any MCP server, by its address") { choice = .byURL(.mcpServer) } + SettingsDivider() + somethingElse(icon: .globe, label: "HTTP endpoint", sub: "Any web API, by its base address") { choice = .byURL(.httpEndpoint) } + } + } + } + } + + private func somethingElse(icon: Lucide, label: String, sub: String, action: @escaping () -> Void) -> some View { + Button(action: action) { + SettingsRow(label: label, sub: sub, chevron: true, leading: { + Icon(icon, size: 15, strokeWidth: 2.2) + .foregroundStyle(Palette.softForeground) + .frame(width: 34, height: 34) + .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.borderStrong)) + }) + } + .buttonStyle(SettingsRowPressStyle()) + } +} + +/// Connecting a catalog app: its mark, and Connect, which adds it to the pod +/// and opens its sign-in in the browser. +@MainActor +private struct AppStep: View { + let pod: Pod + let preset: ConnectionPreset + let back: () -> Void + let done: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @Environment(\.dismiss) private var dismiss + @State private var connecting = SettingsAction() + + var body: some View { + DialogForm(title: preset.name, onBack: connecting.pending ? nil : back) { + VStack(spacing: 6) { + ConnectionMark(presetId: preset.id, name: preset.name) + Text(preset.description).font(Typeface.rubik(13.5)).foregroundStyle(Palette.mutedForeground) + } + .frame(maxWidth: .infinity) + .padding(.bottom, 4) + if let failure = connecting.failure { FormAlert(text: failure) } + Button(action: connect) { + HStack(spacing: 6) { + Text("Connect \(preset.name)") + Icon(.arrowUpRight, size: 14) + } + } + .buttonStyle(WebButtonStyle(size: .large)) + .frame(maxWidth: .infinity) + .disabled(connecting.pending) + .padding(.top, 8) + Text("You'll sign in to \(preset.name) next.") + .font(Typeface.rubik(12.5)) + .foregroundStyle(Palette.subtleForeground) + .frame(maxWidth: .infinity) + } + } + + private func connect() { + connecting.run { + if let url = try await store.connectSigningIn(in: pod.id, name: preset.name, url: preset.url) { openURL(url) } + await done() + dismiss() + } + } +} + +/// A server or HTTP endpoint by its address, as `ByUrlStep`: its name and +/// address, how it signs in, Test and Add. +@MainActor +private struct ByURLStep: View { + enum Method: String, Hashable { + case token, oauth, header + + var note: String { + switch self { + case .token: "Paste the access token or API key the server gave you." + case .oauth: "You'll sign in to the server next." + case .header: "The secret is sent in this header exactly as you type it." + } + } + } + + /// What is connected by its address. + enum Target: Hashable { + /// An MCP server, whose tools bots use. + case mcpServer + /// A web API, which bots send requests to under its base address. + case httpEndpoint + } + + let pod: Pod + let target: Target + let back: () -> Void + let done: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @Environment(\.dismiss) private var dismiss + @State private var name = "" + @State private var url = "" + @State private var method = Method.token + @State private var secretHeader = "" + @State private var secret = "" + @State private var outcome: TestResult? + @State private var adding = SettingsAction() + @State private var testing = false + + var body: some View { + let endpoint = target == .httpEndpoint + let ready = !name.trimmingCharacters(in: .whitespaces).isEmpty && !url.trimmingCharacters(in: .whitespaces).isEmpty + let methods: [(Method, String)] = endpoint ? [(.token, "Token"), (.header, "Header")] : [(.token, "Token"), (.oauth, "Sign in"), (.header, "Header")] + DialogForm( + title: endpoint ? "HTTP endpoint" : "Connect by URL", + action: (title: method == .oauth ? "Sign in" : "Add", run: submit), + actionDisabled: !ready || adding.pending, + onBack: adding.pending ? nil : back + ) { + SettingsGroup(note: endpoint ? "Bots can send GET, POST, PUT, PATCH and DELETE requests to paths under this address. They never see the secret." : nil) { + SettingsFieldRow(label: "Name", value: $name, placeholder: "e.g. Team wiki") + SettingsDivider() + SettingsFieldRow(label: "Server URL", value: clearing($url), placeholder: endpoint ? "https://api.example.com/v1" : "https://mcp.example.com/mcp", mono: true) + } + SettingsGroup(note: method.note) { + SettingsRow(label: "Sign in with", trailing: { + SegmentedChoice(label: "How to sign in to the server", options: methods.map { ($0.0, $0.1) }, value: method) { + method = $0 + outcome = nil + } + }) + if method == .token { + SettingsDivider() + SettingsFieldRow(label: "Access token", value: clearing($secret), placeholder: "Optional", mono: true, secret: true) + } + if method == .header { + SettingsDivider() + SettingsFieldRow(label: "Header name", value: clearing($secretHeader), placeholder: "X-API-Key", mono: true) + SettingsDivider() + SettingsFieldRow(label: "Secret", value: clearing($secret), placeholder: "Optional", mono: true, secret: true) + } + } + if let failure = adding.failure { + FormAlert(text: failure) + } else if let outcome { + TestResultLine(result: outcome) + } + if method != .oauth, !endpoint { + Button(testing ? "Testing…" : "Test", action: test) + .buttonStyle(WebButtonStyle(variant: .secondary, size: .phone)) + .disabled(url.trimmingCharacters(in: .whitespaces).isEmpty || testing) + } + } + } + + /// A binding that also clears what the last Test found, which a change makes out of date. + private func clearing(_ binding: Binding) -> Binding { + Binding(get: { binding.wrappedValue }, set: { + binding.wrappedValue = $0 + outcome = nil + }) + } + + /// The secret and the header it's sent in, as the chosen method sends them. + private var credentials: (header: String?, secret: String?) { + switch method { + case .token: + let token = secret.trimmingCharacters(in: .whitespaces) + return token.isEmpty ? (nil, nil) : ("Authorization", WorkspaceStore.bearerAuthorization(token)) + case .header, .oauth: + return (secretHeader.isEmpty ? nil : secretHeader, secret.isEmpty ? nil : secret) + } + } + + private func test() { + testing = true + Task { + do { + let tested = try await store.testUnsavedConnection(in: pod.id, url: url, secretHeader: credentials.header, secret: credentials.secret) + outcome = TestResult(passed: tested.reachable, text: tested.reachable ? "Connection successful" : tested.error ?? "The server did not answer.") + } catch { + outcome = TestResult(passed: false, text: error.localizedDescription) + } + testing = false + } + } + + private func submit() { + adding.run { + if method == .oauth { + if let signIn = try await store.connectSigningIn(in: pod.id, name: name, url: url) { openURL(signIn) } + } else { + let (secretHeader, secret) = credentials + let connection: NewConnection = + switch target { + case .httpEndpoint: .http(.init(name: name, url: url, secretHeader: secretHeader, secret: secret)) + case .mcpServer: .mcp(.init(kind: "mcp", name: name, url: url, secretHeader: secretHeader, secret: secret)) + } + try await store.createConnection(in: pod.id, connection: connection) + } + await done() + dismiss() + } + } +} diff --git a/apps/ios/Sugabots/Settings/DebugOpen.swift b/apps/ios/Sugabots/Settings/DebugOpen.swift new file mode 100644 index 000000000..71bceb63b --- /dev/null +++ b/apps/ios/Sugabots/Settings/DebugOpen.swift @@ -0,0 +1,22 @@ +import SwiftUI + +/// A sheet a settings page can open of its own for a screenshot, named by +/// `SUGABOTS_SHEET` in a development build's launch environment. +@MainActor +enum DebugSheet: String { + case timeZone = "timezone" + case invite + case look + case addConnection = "addconnection" + + /// Whether `SUGABOTS_SHEET` names this sheet and it hasn't been opened yet, + /// so a page opens it the first time it appears. Always false outside + /// development builds. + var isWanted: Bool { + #if DEBUG + DebugLaunch.once("SUGABOTS_SHEET", is: rawValue) + #else + false + #endif + } +} diff --git a/apps/ios/Sugabots/Settings/GeneralSettings.swift b/apps/ios/Sugabots/Settings/GeneralSettings.swift new file mode 100644 index 000000000..3b009209e --- /dev/null +++ b/apps/ios/Sugabots/Settings/GeneralSettings.swift @@ -0,0 +1,286 @@ +import SwiftUI + +/// Your profile, as the web's `ProfileSettings`: your name, email and theme, +/// Notifications, your invite link, and Sign out. +@MainActor +struct ProfileSettingsScreen: View { + @Environment(Session.self) private var session + @Environment(WorkspaceStore.self) private var store + @AppStorage(Theme.storageKey) private var theme = Theme.dark + + var body: some View { + let user = store.user + SettingsPage( + title: user.name, + description: user.email, + hero: AnyView(PersonAvatar(name: user.name, email: user.email, image: user.image, size: 44)) + ) { + SettingsGroup(label: "Account") { + SettingsNameRow(name: user.name, maxLength: Limits.userNameMaxLength) { next in + try await store.rename(to: next) + } + SettingsDivider() + SettingsRow(label: "Email", trailing: { SettingsValue(text: user.email) }) + } + SettingsGroup(label: "Appearance") { + SettingsRow(label: "Theme", trailing: { + SegmentedChoice(label: "Theme", options: Theme.allCases.map { ($0, $0.label) }, value: theme) { theme = $0 } + }) + } + SettingsGroup { + NavigationLink(value: Route.settings(.notifications)) { + SettingsRow(label: "Notifications", chevron: true) + } + .buttonStyle(SettingsRowPressStyle()) + } + ReferralLinkGroup() + SettingsDanger(label: "Sign out", description: "Signs you out on this device.", actionTitle: "Sign out") { + Task { await session.signOut() } + } + } + } +} + +/// Your invite link, to copy, and a way to replace it, as `ReferralLinkSettings`. +@MainActor +private struct ReferralLinkGroup: View { + @Environment(WorkspaceStore.self) private var store + @State private var link: String? + @State private var reset = SettingsAction() + + var body: some View { + Group { + if let link { + VStack(alignment: .leading, spacing: 0) { + VStack(alignment: .leading, spacing: 12) { + VStack(alignment: .leading, spacing: 4) { + Text("Share your invite link").font(Typeface.rubik(14, .medium)).foregroundStyle(Palette.foreground) + Text("Anyone with it can sign up and get a workspace of their own.") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.mutedForeground) + } + HStack(spacing: 10) { + Text(link.replacingOccurrences(of: "^https?://", with: "", options: .regularExpression)) + .font(Typeface.mono(13)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: .infinity, alignment: .leading) + CopyButton(text: link) { copied in + HStack(spacing: 6) { + Icon(copied ? .check : .copy, size: 14) + Text(copied ? "Copied" : "Copy") + } + .font(Typeface.rubik(13, .semibold)) + .foregroundStyle(Palette.background) + .padding(.horizontal, 14) + .frame(height: 29) + .background(Palette.foreground, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + .buttonStyle(.plain) + } + .padding(.leading, 14) + .padding(.trailing, 6) + .frame(height: 44) + .background(Palette.background, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.settingsCardBorder)) + } + .padding(16) + .settingsCard() + HStack(spacing: 12) { + Text(reset.failure ?? "Shared it somewhere you shouldn't have?") + Spacer() + Button { + reset.run { self.link = try await store.resetReferralLink() } + } label: { + HStack(spacing: 6) { + Icon(.rotateCcw, size: 14) + Text(reset.pending ? "Resetting…" : "Reset link") + } + .font(Typeface.rubik(12, .medium)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 4) + .padding(.vertical, 2) + } + .buttonStyle(.plain) + .disabled(reset.pending) + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 2) + .padding(.top, 10) + } + } + } + .task { link = try? await store.referralLink() } + } +} + +/// The workspace's General, as the web's `GeneralSettings`: its name, which +/// those who may update the workspace rename where it stands, its time zone +/// and your access, and deleting it for its owner. +@MainActor +struct GeneralSettingsScreen: View { + @Environment(Session.self) private var session + @Environment(WorkspaceStore.self) private var store + @State private var record: Workspace? + @State private var members: Int? + @State private var choosingTimeZone = false + @State private var confirmingDelete = false + + var body: some View { + let canUpdate = store.permissions?.updateWorkspace ?? false + let name = store.workspace.name + SettingsPage(title: "General", description: summary) { + SettingsGroup { + if canUpdate { + SettingsNameRow(name: name, maxLength: Limits.workspaceNameMaxLength) { next in + try await store.renameWorkspace(to: next) + } + } else { + SettingsRow(label: "Name", trailing: { SettingsValue(text: name) }) + } + SettingsDivider() + Button { choosingTimeZone = true } label: { + SettingsRow(label: "Time zone", sub: "Routines run on this clock", chevron: canUpdate, trailing: { + SettingsValue(text: record?.timeZone ?? "") + }) + } + .buttonStyle(SettingsRowPressStyle()) + // The sheet starts from the zone the record holds, so it waits for it. + .disabled(!canUpdate || record == nil) + SettingsDivider() + SettingsRow(label: "Your access", trailing: { SettingsValue(text: WorkspaceRole.label(store.role)) }) + } + if store.permissions?.deleteWorkspace ?? false { + SettingsDanger(label: "Delete workspace", description: "Removes every pod, bot and thread in \(name).", actionTitle: "Delete") { + confirmingDelete = true + } + } + } + .fullScreenCover(isPresented: $choosingTimeZone) { + if let record { + TimeZoneSheet(current: record.timeZone) { Task { await load() } } + } + } + .confirmDelete( + isPresented: $confirmingDelete, + title: "Delete \(name)?", + description: "Its pods, bots, conversations and connections are deleted, and everyone in it loses it. This can't be undone." + ) { + try await store.deleteWorkspace() + await session.restore() + } + .task { + await load() + if record != nil, DebugSheet.timeZone.isWanted { choosingTimeZone = true } + } + } + + private var summary: String? { + guard let members, record != nil else { return nil } + let pods = store.pods.count + let plural = { (count: Int, noun: String) in "\(count) \(noun)\(count == 1 ? "" : "s")" } + return "Workspace with \(plural(members, "member")) and \(plural(pods, "pod"))" + } + + private func load() async { + async let record = try? store.workspaceRecord() + async let accessRefreshed: Void = store.refreshAccess() + async let members = try? store.workspaceMembers() + self.record = await record + await accessRefreshed + self.members = await members?.count + } +} + +/// Choosing the workspace's time zone, as the web's `TimeZoneDialog`: this +/// device's zone and the regions, each opening its zones, or a search of all. +@MainActor +struct TimeZoneSheet: View { + let current: String + let saved: () -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var region: TimeZoneRegion? + @State private var chosen: String? + @State private var query = "" + @State private var scheduled = 0 + @State private var saving = SettingsAction() + + private let choices = TimeZoneChoice.all(at: .now) + + var body: some View { + let selected = chosen ?? current + let moving = chosen != nil && chosen != current + let needle = query.trimmingCharacters(in: .whitespaces).lowercased() + DialogForm( + title: region?.name ?? "Time zone", + action: (title: saving.pending ? "Saving…" : "Save", run: save), + actionDisabled: !moving || saving.pending, + onBack: region == nil ? nil : { browse(nil) } + ) { + SearchField(placeholder: "Search \(region?.name ?? "time zones")", text: $query) + if needle.isEmpty, region == nil { + if let device = choices.first(where: { $0.zone == TimeZone.current.identifier }) { + SettingsGroup { zoneRow(device, selected: selected) } + } + SettingsGroup(label: "Regions") { + let regions = TimeZoneRegion.of(choices) + DividedRows(data: regions, id: \.name) { each in + Button { browse(each) } label: { + SettingsRow(label: each.name, chevron: true, trailing: { + SettingsValue(text: each.choices.first { $0.zone == selected }?.place ?? "\(each.choices.count) zones") + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } else { + let searched = (region?.choices ?? choices).filter { $0.matches(needle) } + SettingsGroup { + DividedRows(data: searched, id: \.zone) { choice in + zoneRow(choice, selected: selected) + } + if searched.isEmpty { + SettingsRow(label: "No time zone matches “\(query.trimmingCharacters(in: .whitespaces))”") + } + } + } + if scheduled > 0 { + Text("All routines scheduled on \(TimeZoneChoice.place(of: current)) time will now run in whichever zone you pick.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + } + if let failure = saving.failure { FormAlert(text: failure) } + } + .task { scheduled = Int((try? await store.workspaceTimeZone())?.scheduledRoutines ?? 0) } + } + + private func zoneRow(_ choice: TimeZoneChoice, selected: String) -> some View { + Button { chosen = choice.zone } label: { + SettingsRow(label: choice.place, sub: choice.zone, trailing: { + SettingsValue(text: choice.offset) + Icon(.check, size: 16, strokeWidth: 2.4) + .foregroundStyle(Palette.foreground) + .opacity(choice.zone == selected ? 1 : 0) + .accessibilityLabel(choice.zone == selected ? "Chosen" : "") + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + + private func browse(_ next: TimeZoneRegion?) { + region = next + query = "" + } + + private func save() { + guard let chosen, chosen != current else { return } + saving.run { + try await store.changeTimeZone(to: chosen) + saved() + dismiss() + } + } +} diff --git a/apps/ios/Sugabots/Settings/MembersSettings.swift b/apps/ios/Sugabots/Settings/MembersSettings.swift new file mode 100644 index 000000000..12a2d60f3 --- /dev/null +++ b/apps/ios/Sugabots/Settings/MembersSettings.swift @@ -0,0 +1,336 @@ +import SwiftUI + +/// People, as the web's `WorkspaceMembersSettings` roster: everyone in the +/// workspace, who's invited, and Invite people for those who may. +@MainActor +struct MembersSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var members: Loadable<[WorkspaceMember]> = .loading + @State private var invitations: [WorkspaceInvitation] = [] + @State private var inviting = false + + var body: some View { + let canManage = store.permissions?.manageMembers ?? false + SettingsPage(title: "People", description: "Everyone in the workspace. Add them to pods to give them bots.") { + if canManage { SettingsAddButton(label: "Invite people") { inviting = true } } + } content: { + switch members { + case .failed: + FormAlert(text: "Members could not be loaded. Reload this page to try again.") + case .loading: + SettingsNotice(text: "Loading members…") + case let .loaded(members): + SettingsGroup(label: "Members") { + DividedRows(data: members) { member in + NavigationLink(value: Route.settings(.member(id: member.id))) { + SettingsRow( + label: member.user.id == store.user.id ? "\(member.user.name) (you)" : member.user.name, + sub: member.user.email, + chevron: true, + leading: { PersonAvatar(name: member.user.name, email: member.user.email, image: member.user.image, size: 24) }, + trailing: { SettingsValue(text: member.role.label) } + ) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + if !invitations.isEmpty { + InvitationsGroup(invitations: invitations, canManage: canManage) { await load() } + } + } + .fullScreenCover(isPresented: $inviting) { + InviteSheet(canManageAdmins: store.permissions?.manageAdmins ?? false) { await load() } + } + .task { + await load() + if DebugSheet.invite.isWanted { inviting = true } + } + } + + private func load() async { + await store.refreshAccess() + members = await .of { try await store.workspaceMembers() } + invitations = (try? await store.invitations()) ?? [] + } +} + +/// Who's invited, with Resend and Revoke for those who may. +@MainActor +private struct InvitationsGroup: View { + let invitations: [WorkspaceInvitation] + let canManage: Bool + let changed: () async -> Void + @Environment(WorkspaceStore.self) private var store + @State private var resent: Set = [] + @State private var action = SettingsAction() + + var body: some View { + SettingsGroup(label: "Invited", note: "Invites expire after \(Limits.inviteLifetimeDays) days.") { + DividedRows(data: invitations) { invitation in + SettingsRow( + label: invitation.email, + sub: resent.contains(invitation.id) ? "Sent again" : invitation.expiryText(at: .now), + leading: { PersonAvatar(name: invitation.email, email: invitation.email, size: 32) }, + trailing: { + if canManage { + HStack(spacing: 4) { + Button("Resend") { resend(invitation) } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + Button { revoke(invitation) } label: { + Icon(.x, size: 14).frame(width: 24, height: 24).contentShape(Circle()) + } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("Revoke the invitation for \(invitation.email)") + } + .disabled(action.pending) + } + } + ) + } + if let failure = action.failure { + SettingsDivider() + FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 12) + } + } + } + + private func resend(_ invitation: WorkspaceInvitation) { + action.run { + try await store.invite(invitation.email, as: invitation.role, resend: true) + resent.insert(invitation.id) + } + } + + private func revoke(_ invitation: WorkspaceInvitation) { + action.run { + try await store.cancelInvitation(invitation) + await changed() + } + } +} + +/// The roles one may give, as `roleOptions`: Admin only for those who may make admins. +private func roleOptions(canManageAdmins: Bool) -> [(value: WorkspaceRole, label: String)] { + WorkspaceRole.assignable.filter { canManageAdmins || $0 != .admin }.map { ($0, $0.label) } +} + +/// Inviting people by email, as the web's `InviteDialog`: every address +/// given, in one role; what fails is left to fix and send again. +@MainActor +private struct InviteSheet: View { + let canManageAdmins: Bool + let sent: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var text = "" + @State private var role = WorkspaceRole.member + @State private var failed: [InviteFailure] = [] + @State private var sending = false + + var body: some View { + let emails = inviteEntries(in: text) + DialogForm(title: "Invite people", action: (title: "Send", run: { send(emails) }), actionDisabled: sending || emails.isEmpty, closable: !sending) { + TextField("", text: $text, prompt: Text("Email addresses, separated by commas").foregroundStyle(Palette.mutedForeground)) + .font(Typeface.rubik(16)) + .keyboardType(.emailAddress) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .disabled(sending) + .padding(.horizontal, 16) + .padding(.vertical, 14) + .settingsCard() + .accessibilityLabel("Email addresses") + SettingsGroup(note: role.description) { + SettingsRow(label: "Role", trailing: { + SegmentedChoice(label: "Role", options: roleOptions(canManageAdmins: canManageAdmins), value: role) { role = $0 } + }) + } + if !failed.isEmpty { + FormAlert(text: failed.map { "\($0.email): \($0.reason)" }.joined(separator: "\n")) + } + } + } + + private func send(_ emails: [String]) { + guard !emails.isEmpty else { return } + sending = true + Task { + let failures = await store.invite(emails, as: role.asAssignable) + sending = false + await sent() + if failures.isEmpty { + dismiss() + return + } + // What went out is done; what is left is what to fix and send again. + failed = failures + text = failures.map(\.email).joined(separator: ", ") + } + } +} + +/// One person, as the web's `MemberPage`: their role, the shared pods they're +/// in, when they joined, handing ownership on, and leaving or removing them. +@MainActor +struct MemberSettingsScreen: View { + let memberId: String + @Environment(Session.self) private var session + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + /// Everyone in the workspace, which this person is found in. + @State private var members: Loadable<[WorkspaceMember]> = .loading + @State private var roleChange = SettingsAction() + @State private var confirming = false + @State private var transferring = false + + var body: some View { + switch members { + case .loading: + SettingsPage { EmptyView() }.task { await load() } + case let .failed(failure): + SettingsPage { EmptyState(title: "Could not load this person", text: failure).frame(minHeight: 320) } + case let .loaded(members): + if let member = members.first(where: { $0.id == memberId }) { + page(member) + } else { + SettingsPage { EmptyState(title: "No such person here", text: "They may have left the workspace, or been removed from it.").frame(minHeight: 320) } + } + } + } + + private func page(_ member: WorkspaceMember) -> some View { + let may = store.permissions + let isYou = member.user.id == store.user.id + let isOwner = member.role == .owner + let mayManageThem = member.isManageable(withPermissions: may, byUser: store.user.id) + let mayLeave = isYou && !isOwner + let sharedPods = store.pods.filter { $0.kind == .shared } + let name = member.user.name + return SettingsPage( + title: name, + description: member.user.email, + hero: AnyView(PersonAvatar(name: name, email: member.user.email, image: member.user.image, size: 44)) + ) { + SettingsGroup( + label: "Role", + note: isYou && isOwner ? "\(member.role.description) To leave, transfer ownership to somebody else first." : member.role.description + ) { + SettingsRow(label: "Role", trailing: { + if mayManageThem { + SegmentedChoice(label: "Role for \(name)", options: roleOptions(canManageAdmins: may?.manageAdmins ?? false), value: member.role) { setRole($0, of: member) } + .disabled(roleChange.pending) + } else { + SettingsValue(text: member.role.label) + } + }) + if let roleFailure = roleChange.failure { + SettingsDivider() + FormAlert(text: roleFailure).padding(.horizontal, 16).padding(.vertical, 12) + } + } + if !sharedPods.isEmpty { + SettingsGroup( + label: "Pods", + note: member.role.administers ? "Administrators are in every shared pod." : "They can talk to every bot in the pods they are in." + ) { + DividedRows(data: sharedPods) { pod in + PodMembershipRow(pod: pod, userId: member.user.id, name: name, canManage: (may?.manageMembers ?? false) && !member.role.administers) + } + } + } + SettingsGroup(label: "Details") { + SettingsRow(label: "Joined", trailing: { SettingsValue(text: member.joinedAt.formatted(.dateTime.day().month(.abbreviated).year())) }) + } + if (may?.transferOwnership ?? false) && !isYou { + SettingsGroup(label: "Ownership", note: "The owner decides who administers the workspace, and is the only one who can hand it on.") { + Button { transferring = true } label: { SettingsRow(label: "Make \(name) the owner", chevron: true) } + .buttonStyle(SettingsRowPressStyle()) + } + } + if mayLeave || mayManageThem { + SettingsDanger( + label: isYou ? "Leave workspace" : "Remove from workspace", + description: isYou ? "You lose access to every pod in the workspace." : "They lose access to every pod straight away.", + actionTitle: isYou ? "Leave" : "Remove" + ) { confirming = true } + } + } + .confirmDelete( + isPresented: $transferring, + title: "Make \(name) the owner?", + description: "You stay on as an admin. Only \(name) can decide who else administers the workspace, or hand it back to you.", + confirmLabel: "Transfer" + ) { + try await store.transferOwnership(to: member) + await load() + } + .confirmDelete( + isPresented: $confirming, + title: isYou ? "Leave this workspace?" : "Remove \(name)?", + description: isYou + ? "You lose every pod in it, and your Personal pod and its conversations are deleted. Getting back in means somebody inviting you again." + : "They lose this workspace and every pod in it, and their Personal pod and its conversations are deleted. Pods they made stay.", + confirmLabel: isYou ? "Leave" : "Remove" + ) { + if isYou { + try await store.leaveWorkspace() + await session.restore() + } else { + try await store.removeMember(member) + // Back to People, so Back never returns to somebody no longer here. + dismiss() + } + } + } + + private func load() async { + await store.refreshAccess() + members = await .of { try await store.workspaceMembers() } + } + + private func setRole(_ role: WorkspaceRole, of member: WorkspaceMember) { + roleChange.run { + try await store.setRole(role.asAssignable, of: member) + await load() + } + } +} + +/// One shared pod on a member's page: whether they're in it, which those who may can change. +@MainActor +private struct PodMembershipRow: View { + let pod: Pod + let userId: String + let name: String + let canManage: Bool + @Environment(WorkspaceStore.self) private var store + @State private var members: Loadable<[PodMember]> = .loading + @State private var membershipChange = SettingsAction() + + var body: some View { + let people = members.value + SettingsRow( + label: pod.name, + sub: membershipChange.failure ?? members.failure ?? podSummary(bots: store.bots(in: pod).count, people: people?.count), + leading: { PodInitial(kind: pod.kind, name: pod.name, color: pod.color?.rawValue, size: .row) }, + trailing: { + WebToggle(label: "\(name) is in \(pod.name)", isOn: people?.contains { $0.userId == userId } ?? false) { setMembership($0) } + .disabled(!canManage || people == nil || membershipChange.pending) + } + ) + .task { members = await .of { try await store.podMembers(pod.id) } } + } + + /// Adds them to the pod when `inPod`, or takes them out. + private func setMembership(_ inPod: Bool) { + membershipChange.run { + if inPod { + try await store.addToPod(pod.id, userId: userId) + } else { + try await store.removeFromPod(pod.id, userId: userId) + } + members = await .of { try await store.podMembers(pod.id) } + } + } +} diff --git a/apps/ios/Sugabots/Settings/ModelsSettings.swift b/apps/ios/Sugabots/Settings/ModelsSettings.swift new file mode 100644 index 000000000..838d140f8 --- /dev/null +++ b/apps/ios/Sugabots/Settings/ModelsSettings.swift @@ -0,0 +1,216 @@ +import SwiftUI + +/// Where adding a provider starts: the whole list, or one popular provider's Connect. +enum AddProviderStart: Identifiable, Hashable { + case anyProvider + case preset(ProviderPresetId) + + var id: Self { self } + + /// The provider to go straight to, or nil for the list. + var preset: ProviderPresetId? { + guard case let .preset(preset) = self else { return nil } + return preset + } +} + +/// Models, as the web's `ModelsSettings`: the defaults, then the providers, +/// connected first, the popular ones still to connect, and Add a provider. +@MainActor +struct ModelsSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var providers: Loadable<[ModelProvider]> = .loading + /// The model new bots start on, which may be none. + @State private var defaultModel: Loadable = .loading + /// The model the system bots summarise with, which may be none. + @State private var summaries: Loadable = .loading + @State private var adding: AddProviderStart? + @Environment(\.openPage) private var openPage + + var body: some View { + let all = providers.value ?? [] + let listing = ProviderListing(providers.value) + SettingsPage(title: "Models", description: "Which models bots can think with. Each bot picks one of these.") { + SettingsGroup(label: "Defaults") { + defaultRow("Default for new bots", model: name(of: defaultModel, in: all), place: .defaultModel) + if store.permissions?.configureBuiltInAgents == true { + SettingsDivider() + defaultRow("Summaries", model: name(of: summaries, in: all), place: .systemModel) + } + } + SettingsGroup(label: "Providers") { + if let failure = providers.failure { FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 12) } + ForEach(listing.connected) { provider in + NavigationLink(value: Route.settings(.provider(id: provider.id))) { + SettingsRow( + label: provider.name, + sub: provider.active ? provider.credentialLine : "Turned off", + chevron: true, + leading: { ProviderTile(name: provider.name, preset: provider.preset?.rawValue) }, + trailing: { if provider.active { SettingsStatusBadge(text: "Connected") } } + ) + } + .buttonStyle(SettingsRowPressStyle()) + SettingsDivider() + } + ForEach(listing.toConnect, id: \.self) { preset in + let name = ProviderPreset.named(preset.rawValue)?.name ?? preset.rawValue + SettingsRow(label: name, sub: "Not connected", leading: { ProviderTile(name: name, preset: preset.rawValue) }, trailing: { + Button("Connect") { adding = .preset(preset) }.buttonStyle(SettingsRowButtonStyle()) + }) + SettingsDivider() + } + Button { adding = .anyProvider } label: { + SettingsRow(label: "Add a provider", sub: "Any OpenAI-compatible endpoint, or one on your own machine", chevron: true, leading: { + SettingsRowIcon { Icon(.plus, size: 14, strokeWidth: 2) } + }, trailing: { EmptyView() }) + .foregroundStyle(Palette.mutedForeground) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + .fullScreenCover(item: $adding) { start in + AddProviderSheet(providers: all, startWith: start.preset) { provider in + adding = nil + openPage(.settings(.provider(id: provider.id))) + } + } + .task { await load() } + } + + /// A default's row: on a phone, the model it's set to under its name. + private func defaultRow(_ label: String, model: String, place: SettingsPlace) -> some View { + NavigationLink(value: Route.settings(place)) { + HStack(spacing: 14) { + VStack(alignment: .leading, spacing: 2) { + Text(label).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground) + Text(model).font(Typeface.rubik(13)).foregroundStyle(Palette.softForeground).lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + Icon(.chevronRight, size: 14).foregroundStyle(Palette.subtleForeground) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: 56) + .contentShape(Rectangle()) + } + .buttonStyle(SettingsRowPressStyle()) + } + + /// The name of the model `chosen` holds, as `chosenModelName`: nothing while it loads, and what failed if it couldn't. + private func name(of chosen: Loadable, in providers: [ModelProvider]) -> String { + switch chosen { + case .loading: return "" + case let .failed(failure): return failure + case let .loaded(modelId): + guard let modelId else { return "Not set" } + return providers.flatMap(\.models).first { $0.modelId == modelId }?.name ?? modelId + } + } + + private func load() async { + providers = await .of { try await store.client.modelProviders.list(workspace: store.workspace.id) } + defaultModel = await .of { try await store.refreshModels().defaultModel } + summaries = await .of { + try await store.client.systemAgents.list(workspace: store.workspace.id).first { $0.key == .summarise }?.model + } + } +} + +/// Choosing a model from those switched on, as the web's `ModelChoicePage`. +@MainActor +private struct ModelChoicePage: View { + let title: String + let description: String + let current: () async throws -> String? + let choose: (String) async throws -> Void + @Environment(WorkspaceStore.self) private var store + @State private var providers: Loadable<[ModelProvider]> = .loading + @State private var chosen: String? + @State private var picking = SettingsAction() + + var body: some View { + let groups = (providers.value ?? []).filter(\.connected).map { ($0, $0.models.filter(\.choosable)) }.filter { !$0.1.isEmpty } + SettingsPage(title: title, description: description) { + if let failure = picking.failure ?? providers.failure { FormAlert(text: failure) } + if groups.isEmpty, providers.value != nil { + SettingsGroup { SettingsRow(label: "No models are switched on yet.") } + } + VStack(alignment: .leading, spacing: 12) { + VStack(alignment: .leading, spacing: 32) { + ForEach(groups, id: \.0.id) { provider, models in + SettingsGroup(label: provider.name) { + DividedRows(data: models) { model in + Button { pick(model.modelId) } label: { + SettingsRow(label: model.name, trailing: { + if model.modelId == chosen { Icon(.check, size: 16, strokeWidth: 2.6).foregroundStyle(Palette.foreground) } + }) + } + .buttonStyle(SettingsRowPressStyle()) + .disabled(picking.pending || model.modelId == chosen) + } + } + } + } + Text("Only models that are switched on appear here.") + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .padding(.horizontal, 2) + } + } + .task { + providers = await .of { try await store.client.modelProviders.list(workspace: store.workspace.id) } + do { + chosen = try await current() + } catch { + picking.failure = error.localizedDescription + } + } + } + + private func pick(_ modelId: String) { + picking.run { + try await choose(modelId) + chosen = modelId + } + } +} + +/// The model new bots start on, as `DefaultModelSettings`. +@MainActor +struct DefaultModelSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + + var body: some View { + ModelChoicePage( + title: "Default for new bots", + description: "The model a new bot starts on. Each bot can move to another model in its own settings.", + current: { try await store.refreshModels().defaultModel } + ) { modelId in + _ = try await store.client.modelProviders.setDefaultModel(workspace: store.workspace.id, model: modelId) + } + } +} + +/// The model the built-in bots summarise and compact with, as `SystemModelSettings`. +@MainActor +struct SystemModelSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + + /// As `BUILT_IN_AGENT_KEYS`: both are set to the one model. + private static let builtInKeys: [SystemAgentKey] = [.summarise, .compact] + + var body: some View { + ModelChoicePage( + title: "Summaries", + description: "The model Sugabots uses behind the scenes: summaries, chat titles and compacting long chats. A fast, cheap model works best.", + current: { + try await store.client.systemAgents.list(workspace: store.workspace.id).first { $0.key == .summarise }?.model + } + ) { modelId in + for key in Self.builtInKeys { + _ = try await store.client.systemAgents.update(workspace: store.workspace.id, key: key.rawValue, model: modelId) + } + } + } +} diff --git a/apps/ios/Sugabots/Settings/NotificationsSettings.swift b/apps/ios/Sugabots/Settings/NotificationsSettings.swift new file mode 100644 index 000000000..9569e706c --- /dev/null +++ b/apps/ios/Sugabots/Settings/NotificationsSettings.swift @@ -0,0 +1,270 @@ +import SwiftUI + +/// Notifications, as the web's `NotificationsSettings`: this device, what to +/// be told about, what else, pausing, quiet hours, and each pod's level. +/// Each change shows at once and is saved in turn, the latest last; a failed +/// save puts back what the server last agreed to. +@MainActor +struct NotificationsSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var settings: Loadable = .loading + /// The settings as the server last agreed to them. + @State private var confirmed: NotificationSettings? + /// The save under way, which the next waits for. + @State private var saving: Task? + /// Counts changes, so a save can tell whether a newer one follows it. + @State private var changeCount = 0 + @State private var actionFailure: String? + + var body: some View { + SettingsPage(title: "Notifications", description: "What Sugabots tells you about, and when.") { + ThisDevice() + if let failure = actionFailure ?? settings.failure { FormAlert(text: failure) } + if let settings = settings.value { + notifyAbout(settings) + alsoNotifyAbout(settings) + pause(settings) + quietHours(settings) + podLevels(settings) + } + } + .task { + settings = await .of { try await store.client.notifications.settings() } + confirmed = settings.value + } + } + + // MARK: Groups + + private func notifyAbout(_ settings: NotificationSettings) -> some View { + SettingsGroup(label: "Notify me about", note: settings.level.note) { + SettingsControlRow(label: "Notify me about", stacked: true) { + SegmentedChoice(label: "Notify me about", options: NotificationLevel.known.map { ($0, $0.label) }, value: settings.level, fill: true) { level in + update { $0.level = level } + } + } + } + } + + private static let routineRunOptions: [(RoutineRunNotifications, String)] = [(.failures, "Failed"), (.all, "Every run"), (.none, "None")] + + private func alsoNotifyAbout(_ settings: NotificationSettings) -> some View { + SettingsGroup(label: "Also notify me when", note: "Runs of routines you made or started. Muting a pod or bot quiets these too.") { + SettingsRow(label: "A bot can't finish its reply to me", trailing: { + WebToggle(label: "A bot can't finish its reply to me", isOn: settings.turnFailures) { on in update { $0.turnFailures = on } } + }) + SettingsDivider() + SettingsControlRow(label: "My routines run", stacked: true) { + SegmentedChoice(label: "My routines run", options: Self.routineRunOptions.map { ($0.0, $0.1) }, value: settings.routineRuns, fill: true) { runs in + update { $0.routineRuns = runs } + } + } + } + } + + private func pause(_ settings: NotificationSettings) -> some View { + let until = settings.pausedUntil.flatMap { $0 > .now ? $0 : nil } + return SettingsGroup { + SettingsRow(label: "Pause notifications", sub: until.map { "Paused until \(MuteDuration.formatUntil($0))" }, trailing: { + if until != nil { + Button("Resume") { update { $0.pausedUntil = nil } } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + } else { + Menu { + ForEach(MuteDuration.all, id: \.label) { duration in + Button(duration.label) { update { $0.pausedUntil = duration.until(.now) } } + } + } label: { + Text("Pause") + } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + } + }) + } + } + + private func quietHours(_ settings: NotificationSettings) -> some View { + let quiet = settings.quietHours + let device = TimeZone.current.identifier + return SettingsGroup( + label: "Quiet hours", + note: quiet.map { "No notifications between these times each day, in \($0.timeZone)." } + ?? "Turn off notifications overnight, or whenever you're not working." + ) { + SettingsRow(label: "Quiet hours", trailing: { + WebToggle(label: "Quiet hours", isOn: quiet != nil) { on in + update { $0.quietHours = on ? QuietHours(from: Limits.defaultQuietHours.from, to: Limits.defaultQuietHours.to, timeZone: device) : nil } + } + }) + if let quiet { + SettingsDivider() + SettingsControlRow(label: "From") { + TimeOfDayPicker(label: "From", value: quiet.from) { from in + update { $0.quietHours = QuietHours(from: from, to: quiet.to, timeZone: device) } + } + } + SettingsDivider() + SettingsControlRow(label: "To") { + TimeOfDayPicker(label: "To", value: quiet.to) { to in + update { $0.quietHours = QuietHours(from: quiet.from, to: to, timeZone: device) } + } + } + } + } + } + + @ViewBuilder + private func podLevels(_ settings: NotificationSettings) -> some View { + if !store.pods.isEmpty { + SettingsGroup( + label: "Pods", + note: "A pod set to Default follows what you chose above. Touch and hold a pod or a bot on Home to change it there; a bot's choice wins over its pod's." + ) { + DividedRows(data: store.pods) { pod in + SettingsRow(label: pod.name, trailing: { + LevelPicker(place: .pod(id: pod.id), settings: settings, name: pod.name) { result in + switch result { + case let .success(updated): + self.settings = .loaded(updated) + confirmed = updated + actionFailure = nil + case let .failure(error): + actionFailure = error.localizedDescription + } + } + }) + } + } + } + } + + // MARK: Saving + + /// Applies `edit` to the settings shown, then saves them once any save under + /// way has finished, unless a newer change has come in by then. + private func update(_ edit: (inout NotificationSettings) -> Void) { + guard var next = settings.value else { return } + edit(&next) + settings = .loaded(next) + changeCount += 1 + let change = changeCount + let previous = saving + saving = Task { + await previous?.value + guard change == changeCount else { return } + await save(next, change: change) + } + } + + private func save(_ next: NotificationSettings, change: Int) async { + do { + let saved = try await store.updateNotificationPreferences( + level: next.level, + pausedUntil: next.pausedUntil, + quietHours: next.quietHours, + turnFailures: next.turnFailures, + routineRuns: next.routineRuns + ) + confirmed = saved + actionFailure = nil + // A newer change is already shown, and will be saved next. + if change == changeCount { settings = .loaded(saved) } + } catch { + actionFailure = error.localizedDescription + if change == changeCount, let confirmed { settings = .loaded(confirmed) } + } + } +} + +/// This device's notifications. The web turns them on per browser; the app +/// has no way to be notified yet, so it says so, as the web does where a +/// browser can't show them. +private struct ThisDevice: View { + var body: some View { + SettingsGroup( + label: "This device", + note: "The app can't show notifications yet. On an iPhone, add Sugabots to your Home Screen from Safari and turn them on there." + ) { + SettingsRow(label: "Notifications", sub: "Each browser and device is turned on by itself, and notifies you while Sugabots is open in it.", trailing: { + SettingsValue(text: "Not available") + }) + } + } +} + +/// A time of day as `HH:MM`, chosen with the system's wheel. A turn of the +/// wheel is passed to `change` once it has rested, not at every step. +private struct TimeOfDayPicker: View { + let label: String + let value: String + let change: (String) -> Void + @State private var turning: String? + + /// How long the wheel rests before its time is passed on. + private static var restDelay: Duration { .milliseconds(600) } + + var body: some View { + DatePicker(label, selection: Binding(get: { Self.date(turning ?? value) }, set: { turning = Self.format($0) }), displayedComponents: .hourAndMinute) + .labelsHidden() + .frame(maxWidth: .infinity, alignment: .trailing) + .task(id: turning) { + guard let turning else { return } + try? await Task.sleep(for: Self.restDelay) + guard !Task.isCancelled else { return } + self.turning = nil + if turning != value { change(turning) } + } + } + + private static func date(_ time: String) -> Date { + let parts = time.split(separator: ":").compactMap { Int($0) } + return Calendar.current.date(bySettingHour: parts.first ?? 0, minute: parts.last ?? 0, second: 0, of: .now) ?? .now + } + + private static func format(_ date: Date) -> String { + let parts = Calendar.current.dateComponents([.hour, .minute], from: date) + return String(format: "%02d:%02d", parts.hour ?? 0, parts.minute ?? 0) + } +} + +/// A place's level in a settings row, and the menu that changes it, as `NotificationLevelPicker`. +/// `changed` is told the settings as they stand after a change, or why it failed. +@MainActor +struct LevelPicker: View { + let place: NotificationPlace + let settings: NotificationSettings + let name: String + let changed: (Result) -> Void + @Environment(WorkspaceStore.self) private var store + + var body: some View { + let chosen = settings.levelChosen(for: place) + let followed = settings.levelAbove(place) + Menu { + Button { set(nil) } label: { + Label("Default (\(followed.label.lowercased()))", systemImage: chosen == nil ? "checkmark" : followed.symbol) + } + ForEach(NotificationLevel.known) { level in + Button { set(level) } label: { Label(level.label, systemImage: chosen == level ? "checkmark" : level.symbol) } + } + } label: { + HStack(spacing: 4) { + Text(chosen?.label ?? "Default") + Icon(.chevronDown, size: 14, strokeWidth: 2) + } + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + } + .accessibilityLabel("Notifications for \(name)") + } + + private func set(_ level: NotificationLevel?) { + Task { + do { + changed(.success(try await store.setNotificationLevel(level, for: place))) + } catch { + changed(.failure(error)) + } + } + } +} diff --git a/apps/ios/Sugabots/Settings/PodSettings.swift b/apps/ios/Sugabots/Settings/PodSettings.swift new file mode 100644 index 000000000..885b49034 --- /dev/null +++ b/apps/ios/Sugabots/Settings/PodSettings.swift @@ -0,0 +1,431 @@ +import SwiftUI + +/// One of a pod's settings pages, as the web's `WorkspacePodsSettings`: its +/// General, Connections, People, Bots or Computer. A page the pod doesn't +/// have, such as a Personal pod's General, gives way to its Connections. +/// Each page is given the pod as just fetched, with what you may do in it. +@MainActor +struct PodPageScreen: View { + let pod: Pod + let page: PodSettingsPage + @Environment(WorkspaceStore.self) private var store + @State private var record: Pod? + @State private var failure: String? + + var body: some View { + Group { + if let record { + let shown = PodSettingsPage.pages(for: record.kind).contains(page) ? page : .connections + switch shown { + case .general: PodGeneralPage(record: record) { await load() } + case .connections: PodConnectionsPage(record: record) + case .people: PodPeoplePage(record: record) + case .bots: PodBotsPage(record: record) + case .computer: PodComputerPage(record: record) + } + } else if let failure { + SettingsPage { EmptyState(title: "Could not load this pod", text: failure).frame(minHeight: 320) } + } else { + SettingsPage { EmptyView() } + } + } + .task { await load() } + } + + private func load() async { + do { record = try await store.podRecord(pod.id) } catch { failure = error.localizedDescription } + } +} + +// MARK: General + +/// A pod's General, as `PodDetails`: its name and colour, and deleting it. +@MainActor +private struct PodGeneralPage: View { + let record: Pod + let changed: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var people: Int? + @State private var recolour = SettingsAction() + @State private var confirmingDelete = false + + var body: some View { + let may = record.permissions + let shared = record.kind == .shared + SettingsPage( + title: record.name, + description: podSummary(bots: store.bots(in: record).count, people: shared ? people : nil), + hero: AnyView(PodInitial(kind: record.kind, name: record.name, color: record.color?.rawValue, size: .large)) + ) { + if let failure = recolour.failure { FormAlert(text: failure) } + if may.rename { + SettingsGroup(label: "Pod") { + SettingsNameRow(name: record.name, maxLength: Limits.podNameMaxLength) { name in + try await store.updatePod(record.id, name: name) + await changed() + } + } + } + if may.rename, let color = record.color?.rawValue { + SettingsGroup(label: "Look", note: "Shown on the pod's icon in the sidebar.") { + SettingsControlRow(label: "Colour") { + ColourSwatches(colors: PodColor.known.map(\.rawValue), swatch: { BotLooks.pods[$0]?.swatch ?? .gray }, value: color) { next in + recolour.run { + try await store.updatePod(record.id, color: PodColor(rawValue: next)) + await changed() + } + } + .disabled(recolour.pending) + } + } + } + if shared && may.rename { + SettingsDanger(label: "Delete pod", description: "Removes its bots, threads and artifacts.", actionTitle: "Delete") { confirmingDelete = true } + } + } + .confirmDelete( + isPresented: $confirmingDelete, + title: "Delete \(record.name)?", + description: "Its bots, their chats, routines and connections will be deleted. This can't be undone." + ) { + try await store.deletePod(record.id) + dismiss() + } + .task { people = (try? await store.podMembers(record.id))?.count } + } +} + +// MARK: People + +/// Who can see a pod, as `Members`: each with their role, and the − that takes +/// them out, or you, for those who may; Add people for those who may. +@MainActor +private struct PodPeoplePage: View { + let record: Pod + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var members: Loadable<[PodMember]> = .loading + @State private var roster: [WorkspaceMember]? + @State private var adding = SettingsAction() + @State private var removing: PodMember? + + var body: some View { + let canManage = record.permissions.manageMembers + let leaving = removing?.userId == store.user.id + SettingsPage(title: "People", description: "Who can see \(record.name) and talk to its bots.") { + if canManage { addPeople } + } content: { + if let failure = adding.failure { FormAlert(text: failure) } + SettingsGroup { + switch members { + case .loading: + EmptyView() + case let .failed(failure): + FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 12) + case let .loaded(members) where members.isEmpty: + SettingsRow(label: "Nobody can see into this pod yet") + case let .loaded(members): + DividedRows(data: members) { member in row(member, canManage: canManage) } + } + } + } + .confirmDelete( + isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }), + title: leaving ? "Leave \(record.name)?" : "Remove \(removing?.name ?? "this person") from \(record.name)?", + description: leaving + ? "You lose this pod, its bots, and your chats. An administrator can add you back." + : "They lose this pod, its bots, and their chats. You can add them back at any time.", + confirmLabel: leaving ? "Leave" : "Remove" + ) { + guard let member = removing else { return } + if leaving { + try await store.leavePod(record.id) + dismiss() + } else { + try await store.removeFromPod(record.id, userId: member.userId) + await load() + } + } + .task { await load() } + } + + private func row(_ member: PodMember, canManage: Bool) -> some View { + let isYou = member.userId == store.user.id + let mayTakeOut = isYou ? record.permissions.leave : canManage && member.removable + return SettingsRow( + label: member.name, + leading: { PersonAvatar(name: member.name, email: member.email, image: member.image, size: 24) }, + trailing: { + HStack(spacing: 14) { + // Said once the workspace roster has answered, not guessed before it. + if isYou { + SettingsValue(text: "You") + } else if let roster { + SettingsValue(text: WorkspaceRole.label(roster.first { $0.user.id == member.userId }?.role)) + } + if mayTakeOut { + Button { removing = member } label: { + Icon(.minus, size: 13, strokeWidth: 2.6) + .foregroundStyle(Palette.destructiveText) + .frame(width: 28, height: 28) + .contentShape(Circle()) + } + .buttonStyle(.plain) + .accessibilityLabel(isYou ? "Leave \(record.name)" : "Remove \(member.name)") + } + } + } + ) + } + + /// Add people, as a menu of everyone in the workspace not here yet. + private var addPeople: some View { + let inPod = Set(members.value?.map(\.userId) ?? []) + let invitable = roster?.filter { !inPod.contains($0.user.id) } ?? [] + return Menu { + if roster == nil { + Text("Loading…") + } else if invitable.isEmpty { + Text("Everyone in the workspace is here.") + } else { + ForEach(invitable) { member in + Button(member.user.name) { + adding.run { + try await store.addToPod(record.id, userId: member.user.id) + await load() + } + } + } + } + } label: { + GlassRoundIcon(icon: .plus, size: 22) + } + .disabled(adding.pending) + .accessibilityLabel("Add people") + } + + private func load() async { + members = await .of { try await store.podMembers(record.id) } + roster = try? await store.workspaceMembers() + } +} + +// MARK: Bots + +/// A pod's bots, as `PodBots`, each opening its settings; New bot for those who may. +@MainActor +private struct PodBotsPage: View { + let record: Pod + @Environment(WorkspaceStore.self) private var store + @State private var creating = false + @Environment(\.openPage) private var openPage + + var body: some View { + let bots = store.bots(in: record) + SettingsPage(title: "Bots", description: "\(bots.count) \(bots.count == 1 ? "bot" : "bots") in \(record.name)") { + if record.permissions.createAgents { SettingsAddButton(label: "New bot") { creating = true } } + } content: { + SettingsGroup { + if bots.isEmpty { SettingsEmptyRow(text: "No bots in this pod yet") } + DividedRows(data: bots) { agent in + NavigationLink(value: Route.settings(.agent(record, agent))) { + SettingsRow( + label: agent.name, + sub: agent.givenDescription, + chevron: true, + leading: { BotFace(look: agent.look, size: 24) }, + trailing: { EmptyView() } + ) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + .fullScreenCover(isPresented: $creating) { + NewBotScreen(pod: record) { made in + creating = false + openPage(.settings(.agent(record, made))) + } + } + } +} + +// MARK: Computer + +/// A pod's computer, as `PodSandboxSettings`: the sandbox, its activity, +/// Upgrade and Reset, and the hosts it may reach. +@MainActor +private struct PodComputerPage: View { + /// What Upgrade and Reset ask before they're done. + private enum Confirmation { + case upgrade, reset + } + + let record: Pod + @Environment(WorkspaceStore.self) private var store + @State private var sandbox: PodSandbox? + @State private var network: PodSandboxNetwork? + @State private var failure: String? + @State private var confirming: Confirmation? + @State private var hostAction = SettingsAction() + @State private var newHost = "" + + private static func stateWords(_ state: PodSandboxState.Present.State) -> String { + switch state { + case .running: "Running" + case .paused: "Paused" + case .lost: "Lost" + case .unreachable: "Not answering" + case .unknown: "" + } + } + + var body: some View { + SettingsPage(title: "Computer", description: "The computer \(record.name)'s bots run commands, browse and edit files on. Experimental.") { + if let failure { FormAlert(text: failure) } + if let sandbox, sandbox.providerEnabled || sandbox.sandbox.present != nil { + sandboxGroup(sandbox) + if let network { networkGroup(network) } + } + } + .confirmDelete( + isPresented: isConfirming(.upgrade), + title: "Upgrade the sandbox?", + description: "Its workspace, every thread's folder and every bot's home, moves to a new sandbox made from the current image. Running programs and open browser tabs are lost.", + confirmLabel: "Upgrade" + ) { + _ = try await store.client.podSandbox.upgrade(podId: record.id) + await load() + } + .confirmDelete( + isPresented: isConfirming(.reset), + title: "Reset the sandbox?", + description: "Everything in it is deleted: every thread's folder, every bot's home, and any work that wasn't pushed. This can't be undone.", + confirmLabel: "Reset" + ) { + _ = try await store.client.podSandbox.reset(podId: record.id) + await load() + } + .task { await load() } + } + + private func isConfirming(_ confirmation: Confirmation) -> Binding { + Binding(get: { confirming == confirmation }, set: { if !$0 { confirming = nil } }) + } + + @ViewBuilder + private func sandboxGroup(_ shown: PodSandbox) -> some View { + if let sandbox = shown.sandbox.present { + let turns = sandbox.turnsUsing + let watching = sandbox.peopleWatching + let busy = [ + turns > 0 ? "\(turns == 1 ? "A bot is" : "\(turns) bots are") using it" : nil, + watching > 0 ? "\(watching == 1 ? "1 person" : "\(watching) people") watching" : nil, + ].compactMap { $0 } + SettingsGroup(label: "Computer", note: Self.stateNote(sandbox.state)) { + SettingsRow(label: sandbox.providerName, sub: sandbox.image ?? "Image unknown", trailing: { + SettingsValue(text: Self.stateWords(sandbox.state)) + }) + SettingsDivider() + SettingsRow( + label: "Activity", + sub: busy.isEmpty ? "Last used \(Times.listInSentence(sandbox.lastUsedAt))" : busy.joined(separator: ", "), + trailing: { SettingsValue(text: "Made \(Times.listInSentence(sandbox.createdAt))") } + ) + if shown.canManage { + SettingsDivider() + Button { confirming = .upgrade } label: { + SettingsRow(label: sandbox.upgradeAvailable ? "Upgrade available" : "Upgrade", sub: "Moves the pod's work to a new sandbox made from the current image.") + } + .buttonStyle(SettingsRowPressStyle()) + .disabled(turns > 0) + SettingsDivider() + Button { confirming = .reset } label: { + SettingsRow(label: "Reset", sub: "Throws the sandbox away. The next one starts empty.") + } + .buttonStyle(SettingsRowPressStyle()) + .disabled(turns > 0) + } + } + } else { + SettingsGroup(label: "Computer") { + SettingsRow(label: "No computer yet", sub: "One is made the first time a bot here runs a command or uses its browser.") + } + } + } + + @ViewBuilder + private func networkGroup(_ network: PodSandboxNetwork) -> some View { + let canManage = record.permissions.manageSandbox + let reachable = network.workspaceHosts.filter { $0.blockedBy == nil } + if network.mode == .open { + SettingsGroup(label: "Network", note: "The workspace's sandboxes are open. Its admins choose this, and any hosts it blocks, in its sandbox settings.") { + SettingsRow(label: "Open", sub: network.blocking ? "Any host the workspace hasn't blocked" : "Any host") + } + } else { + SettingsGroup( + label: "Network", + note: canManage + ? "The sandbox connects to the workspace's hosts and these. When a bot needs another, it asks in its thread, and you can allow it there." + : "The sandbox connects to the workspace's hosts and these. When a bot needs another, it asks in its thread, and an admin of this pod decides." + ) { + ForEach(network.addedHosts) { added in + let by = added.addedByName ?? "someone who has left" + RemovableRow( + name: added.host, + sub: added.blockedBy.map { "Blocked for the workspace by \($0). Added by \(by)" } ?? "Added by \(by)", + removal: canManage ? .init(label: "Remove \(added.host)") { removeHost(added.host) } : nil + ) + .disabled(hostAction.pending) + SettingsDivider() + } + if canManage { + AddHostRow(label: "Add host", buttonTitle: "Add", draft: $newHost, add: addHost) + .disabled(hostAction.pending) + SettingsDivider() + } + HostListRow( + label: "From the workspace", + hosts: reachable.map(\.host), + summary: "\(reachable.count) hosts every pod reaches: GitHub, package registries and the workspace's own" + ) + } + if let failure = hostAction.failure { FormAlert(text: failure) } + } + } + + private static func stateNote(_ state: PodSandboxState.Present.State) -> String? { + switch state { + case .paused: "Paused while nobody uses it. It wakes when a bot next needs it." + case .lost: "The provider no longer has this sandbox. A new one is made when a bot next needs it." + case .unreachable: "The sandbox provider isn't answering, so this may be out of date." + default: nil + } + } + + private func load() async { + do { + sandbox = try await store.client.podSandbox.get(podId: record.id) + failure = nil + } catch { + failure = error.localizedDescription + } + network = try? await store.client.podSandbox.network(podId: record.id) + } + + private func addHost(_ host: String) { + hostAction.run { + _ = try await store.client.podSandbox.addHost(podId: record.id, host: host) + newHost = "" + await load() + } + } + + private func removeHost(_ host: String) { + hostAction.run { + _ = try await store.client.podSandbox.removeHost(podId: record.id, host: host) + await load() + } + } +} diff --git a/apps/ios/Sugabots/Settings/ProviderSettings.swift b/apps/ios/Sugabots/Settings/ProviderSettings.swift new file mode 100644 index 000000000..4184c6162 --- /dev/null +++ b/apps/ios/Sugabots/Settings/ProviderSettings.swift @@ -0,0 +1,872 @@ +import SwiftUI + +extension WorkspaceStore { + /// Changes a model provider; what `change` leaves nil stays as it is. + fileprivate func updateProvider(_ providerId: String, _ change: ModelProviderUpdate) async throws -> ModelProvider { + try await client.modelProviders.update( + workspace: workspace.id, + providerId: providerId, + active: change.active, + baseUrl: change.baseUrl, + apiFormat: change.apiFormat, + apiKey: change.apiKey, + customHeaders: change.customHeaders + ) + } +} + +// MARK: The provider's page + +/// A provider's page, as the web's `ProviderSettings`: on or off, how it's +/// reached and signed in to, its models, and Disconnect. +@MainActor +struct ProviderSettingsScreen: View { + let providerId: String + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var provider: ModelProvider? + @State private var missing: String? + @State private var defaultModel: String? + @State private var systemModels: [String?] = [] + @State private var switching = SettingsAction() + @State private var disconnecting = false + + var body: some View { + Group { + if let provider { + page(provider) + } else if let missing { + SettingsPage { EmptyState(title: missing, text: "It may have been disconnected. Its models are no longer offered.").frame(minHeight: 320) } + } else { + SettingsPage { EmptyView() } + } + } + .task { await load() } + } + + private func holders(_ models: [ProviderModel]) -> ModelHolders? { + ModelHolders.of(models.map(\.modelId), defaultModel: defaultModel, systemModels: systemModels) + } + + /// What the On switch's group says: why it can't be turned off, what its last change failed with, or what On means. + private func switchNote(_ provider: ModelProvider, heldOn: ModelHolders?) -> String { + if provider.active, let heldOn { return "\(provider.name) can't be turned off while it's in use. \(heldOn.reason("one of its models"))" } + if let failure = switching.failure { return failure } + return provider.active ? "Bots can use the models you switch on below." : "Bots can't use its models while it's off." + } + + private func page(_ provider: ModelProvider) -> some View { + let heldOn = holders(provider.offeredModels) + // Switching a seeded provider off only stops what it offers; removing another deletes every model it lists. + let held = holders(provider.seeded ? provider.offeredModels : provider.models) + let cannotTurnOff = provider.active && heldOn != nil + return SettingsPage(title: provider.name, hero: AnyView(ProviderTile(name: provider.name, preset: provider.preset?.rawValue, large: true))) { + SettingsGroup(note: switchNote(provider, heldOn: heldOn)) { + SettingsRow(label: provider.active ? "On" : "Off", trailing: { + WebToggle(label: "Use \(provider.name)", isOn: provider.active) { active in + switching.run { self.provider = try await store.updateProvider(providerId, ModelProviderUpdate(active: active)) } + } + .disabled(cannotTurnOff || switching.pending) + }) + } + ProviderConnectionGroup(provider: provider, held: heldOn) { await load() } + ProviderModelsGroup(provider: provider, holdersOf: { holders([$0]) }) { await load() } + SettingsDanger( + label: "Disconnect \(provider.name)", + description: "Bots using these models stop working until you pick another.", + actionTitle: "Disconnect", + disabledReason: held?.reason("one of its models") + ) { disconnecting = true } + } + .confirmDelete( + isPresented: $disconnecting, + title: "Disconnect \(provider.name)?", + description: provider.seeded + ? "\(provider.signInService != nil ? "It is signed out" : "Its key is removed") and bots can no longer use its models. You can connect it again at any time." + : "Bots can no longer use its models. Adding it again means entering its details again.", + confirmLabel: "Disconnect" + ) { + try await disconnect(provider) + // Back to Models, so Back never returns to a provider no longer connected. + dismiss() + } + } + + private func load() async { + do { + provider = try await store.client.modelProviders.get(workspace: store.workspace.id, providerId: providerId) + } catch { + if provider == nil { missing = (error as? APIFailure)?.status == 404 ? "No such provider" : "Could not load this provider" } + } + defaultModel = (try? await store.refreshModels())?.defaultModel + systemModels = (try? await store.client.systemAgents.list(workspace: store.workspace.id))?.map(\.model) ?? [] + } + + /// Takes a provider away: a seeded one is signed out, its key removed and switched off; one added by hand is removed. + private func disconnect(_ provider: ModelProvider) async throws { + if provider.seeded { + if provider.signedIn { _ = try await store.client.modelProviders.signOut(workspace: store.workspace.id, providerId: provider.id) } + var change = ModelProviderUpdate(active: false) + if provider.hasApiKey { change.apiKey = .present(nil) } + _ = try await store.updateProvider(provider.id, change) + } else { + try await store.client.modelProviders.remove(workspace: store.workspace.id, providerId: provider.id) + } + } +} + +/// A row of the Connection group, as the web's `ConnectionRow`: a grey label +/// in a column, what it holds, and its actions at the end. +struct ConnectionValueRow: View { + let label: String + @ViewBuilder var content: Content + @ViewBuilder var action: Action + + var body: some View { + HStack(spacing: 12) { + Text(label).font(Typeface.rubik(14)).foregroundStyle(Palette.mutedForeground).frame(width: 110, alignment: .leading) + content.frame(maxWidth: .infinity, alignment: .leading) + action + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 56) + } +} + +/// A link-styled action in a row, such as Change or Save. +private struct RowLink: View { + let title: String + var quiet = false + let action: () -> Void + + var body: some View { + Button(title, action: action) + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(quiet ? Palette.mutedForeground : Palette.foreground) + } +} + +/// How a provider is reached and signed in to, as the web's `Connection`: +/// its address and format for a custom or local one, its key or account, and a test. +@MainActor +private struct ProviderConnectionGroup: View { + let provider: ModelProvider + let held: ModelHolders? + let changed: () async -> Void + @Environment(WorkspaceStore.self) private var store + @State private var editingURL: String? + @State private var urlProblem: String? + @State private var replacingKey: Bool? + @State private var apiKey = "" + @State private var action = SettingsAction() + @State private var testing = false + @State private var tested: TestResult? + + var body: some View { + let optionalKey = provider.local || provider.custom + let outcome = tested ?? provider.lastTestError.map { TestResult(passed: false, text: $0) } + VStack(alignment: .leading, spacing: 0) { + SettingsGroup(label: "Connection") { + if provider.local || provider.custom { + serverURLRow + SettingsDivider() + } + if provider.custom { + ConnectionValueRow(label: "Format") { EmptyView() } action: { + SegmentedChoice(label: "API format", options: [(ProviderApiFormat.openai, "OpenAI"), (.anthropic, "Anthropic")], value: provider.apiFormat) { save(ModelProviderUpdate(apiFormat: $0)) } + .disabled(action.pending) + } + SettingsDivider() + } + if let service = provider.signInService { + ProviderSignInRow(provider: provider, service: service, signOutBlocked: held?.reason("one of its models"), changed: changed) + } else { + keyRow(optional: optionalKey) + } + if let failure = action.failure { + SettingsDivider() + FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 12) + } + } + // The result sits beside the button, so a test never moves what is below it. + HStack(spacing: 10) { + Button { test() } label: { + HStack(spacing: 6) { + if testing { ProgressView().controlSize(.mini) } + Text("Test connection") + } + } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + .disabled(testing) + if !testing, let outcome { + SettingsTestOutcome(good: outcome.passed, text: outcome.text) + } + } + .padding(.horizontal, 2) + .padding(.top, 10) + } + } + + @ViewBuilder + private var serverURLRow: some View { + if let editingURL { + ConnectionValueRow(label: "Server URL") { + VStack(alignment: .leading, spacing: 4) { + TextField("", text: Binding(get: { editingURL }, set: { self.editingURL = $0 }), prompt: Text(provider.local ? "http://localhost:11434" : "https://llm.example.com/v1").foregroundStyle(Palette.mutedForeground)) + .font(Typeface.mono(16)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(.URL) + if let urlProblem { Text(urlProblem).font(Typeface.rubik(12.5)).foregroundStyle(Palette.destructiveText) } + } + } action: { + HStack(spacing: 12) { + RowLink(title: "Save") { + guard let parsed = parseProviderBaseURL(editingURL) else { + urlProblem = notAServerAddress + return + } + urlProblem = nil + save(ModelProviderUpdate(baseUrl: parsed)) { self.editingURL = nil } + } + .disabled(action.pending) + RowLink(title: "Cancel", quiet: true) { self.editingURL = nil } + } + } + } else { + ConnectionValueRow(label: "Server URL") { + Text(provider.baseUrl).font(Typeface.mono(13)).foregroundStyle(Palette.foreground).lineLimit(1).truncationMode(.middle) + } action: { + RowLink(title: "Change") { editingURL = provider.baseUrl } + } + } + } + + @ViewBuilder + private func keyRow(optional: Bool) -> some View { + let replacing = replacingKey ?? (!provider.hasApiKey && !optional) + if replacing { + ConnectionValueRow(label: "API key") { + SecureField("", text: $apiKey, prompt: Text("Paste your key").foregroundStyle(Palette.mutedForeground)) + .font(Typeface.mono(16)) + .accessibilityLabel("\(provider.name) API key") + } action: { + HStack(spacing: 12) { + RowLink(title: "Save") { + // A key is what connects a provider that was disconnected. + var change = ModelProviderUpdate(apiKey: .present(apiKey)) + if !provider.active { change.active = true } + save(change) { + apiKey = "" + replacingKey = false + } + } + .disabled(apiKey.isEmpty || action.pending) + if provider.hasApiKey || optional { + RowLink(title: "Cancel", quiet: true) { + apiKey = "" + replacingKey = false + } + } + } + } + } else { + ConnectionValueRow(label: "API key") { + Text(provider.hasApiKey ? "••••••••" : "None").font(Typeface.mono(13)).foregroundStyle(Palette.foreground) + } action: { + HStack(spacing: 12) { + if optional && provider.hasApiKey { + RowLink(title: "Remove", quiet: true) { save(ModelProviderUpdate(apiKey: .present(nil))) }.disabled(action.pending || held != nil) + } + RowLink(title: provider.hasApiKey ? "Replace" : "Add") { replacingKey = true } + } + } + } + } + + private func save(_ change: ModelProviderUpdate, then done: @escaping () -> Void = {}) { + action.run { + _ = try await store.updateProvider(provider.id, change) + done() + await changed() + } + } + + private func test() { + testing = true + Task { + do { + let result = try await store.client.modelProviders.test(workspace: store.workspace.id, providerId: provider.id) + tested = TestResult(passed: result.reachable, text: result.reachable ? "Connection successful" : result.error ?? "It did not answer.") + action.failure = nil + } catch { + action.failure = error.localizedDescription + } + testing = false + } + } +} + +/// Signing a plan-paid provider in with a code, as the web's `ProviderSignInRow`: +/// a warning that a plan is for one person, then the code to enter on the +/// service's page, while the app asks whether it's done. +@MainActor +struct ProviderSignInRow: View { + let provider: ModelProvider + let service: String + let signOutBlocked: String? + let changed: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.openURL) private var openURL + @State private var started: ProviderSignInStarted? + @State private var warning = false + @State private var action = SettingsAction() + + /// As `ACCOUNT_SHARING_TERMS`. + private static let terms = [ + "chatgpt": ("OpenAI", "https://openai.com/policies/terms-of-use/#registration-and-access"), + "xai": ("xAI", "https://x.ai/legal/terms-of-service"), + ] + + var body: some View { + let serviceName = ProviderPreset.signInServiceNames[service] ?? service + VStack(spacing: 0) { + if let started { + code(started, serviceName: serviceName) + } else { + ConnectionValueRow(label: "Account") { + Text(provider.signedIn ? "Signed in" : "Not signed in").font(Typeface.mono(13)).foregroundStyle(Palette.foreground) + } action: { + if provider.signedIn { + RowLink(title: "Sign out", quiet: true) { signOut() }.disabled(action.pending || signOutBlocked != nil) + } else { + RowLink(title: "Sign in with \(serviceName)") { warning = true }.disabled(action.pending) + } + } + } + if let failure = action.failure { + SettingsDivider() + FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 12) + } + } + .fullScreenCover(isPresented: $warning) { + let plan = ProviderPreset.named(provider.preset?.rawValue)?.name ?? provider.name + let terms = Self.terms[service] + DialogForm(title: "Single-user installs only", action: (title: "Sign in", run: start)) { + HStack(alignment: .top, spacing: 10) { + Icon(.triangleAlert, size: 16).foregroundStyle(Palette.warning).padding(.top, 2) + (Text("A \(plan) plan is for one person. Only connect yours if nobody else uses this Sugabots install. See ") + + Text("\(terms?.0 ?? serviceName)'s terms").foregroundColor(Palette.foreground) + + Text(".")) + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .onTapGesture { if let url = terms.flatMap({ URL(string: $0.1) }) { openURL(url) } } + } + } + } + } + + private func code(_ started: ProviderSignInStarted, serviceName: String) -> some View { + VStack(alignment: .leading, spacing: 12) { + Text("Open \(serviceName)'s sign-in page and enter this code. This page carries on once you have.") + .font(Typeface.rubik(14)) + .foregroundStyle(Palette.mutedForeground) + HStack(spacing: 12) { + HStack(spacing: 4) { + Text(started.userCode).font(Typeface.mono(20)).tracking(2).foregroundStyle(Palette.foreground) + CopyButton(text: started.userCode) { copied in + Icon(copied ? .check : .copy, size: 14).frame(width: 28, height: 28) + } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("Copy code") + } + .padding(.leading, 12) + .padding(.vertical, 4) + .padding(.trailing, 4) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + Button { if let url = URL(string: started.verificationUrl) { openURL(url) } } label: { + HStack(spacing: 6) { + Icon(.externalLink, size: 14) + Text("Open sign-in page") + } + } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + } + HStack { + ProgressView().controlSize(.small) + Spacer() + Button("Cancel") { self.started = nil }.buttonStyle(WebButtonStyle(variant: .ghost, size: .small)) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .task(id: started.attempt) { await poll(started) } + } + + private func start() { + warning = false + action.run { started = try await store.client.modelProviders.startSignIn(workspace: store.workspace.id, providerId: provider.id) } + } + + /// Asks whether the sign-in is done every poll interval, until it is or fails. + private func poll(_ started: ProviderSignInStarted) async { + while !Task.isCancelled, self.started?.attempt == started.attempt { + try? await Task.sleep(for: .milliseconds(started.pollIntervalMs)) + guard !Task.isCancelled else { return } + do { + let outcome = try await store.client.modelProviders.completeSignIn( + workspace: store.workspace.id, providerId: provider.id, attempt: started.attempt + ) + if case .signedIn = outcome { + self.started = nil + await changed() + return + } + } catch { + self.started = nil + action.failure = error.localizedDescription + return + } + } + } + + private func signOut() { + action.run { + _ = try await store.client.modelProviders.signOut(workspace: store.workspace.id, providerId: provider.id) + await changed() + } + } +} + +/// A provider's models, as the web's `Models`: Refresh list, a search when +/// there are many, each with what it can do, the bots on it and its switch, +/// and for a custom provider, Add model and what each can do. +@MainActor +private struct ProviderModelsGroup: View { + let provider: ModelProvider + let holdersOf: (ProviderModel) -> ModelHolders? + let changed: () async -> Void + @Environment(WorkspaceStore.self) private var store + @State private var search = "" + @State private var adding = false + @State private var newModelId = "" + @State private var refreshing = false + @State private var modelChange = SettingsAction() + @State private var editing: ProviderModel? + /// Switched-on models lead, as they were when the page opened, so a row never moves under the switch just used. + @State private var onWhenOpened: Set? + + var body: some View { + let large = provider.models.count > Limits.modelSearchThreshold + let needle = search.trimmingCharacters(in: .whitespaces).lowercased() + let on = onWhenOpened ?? Set(provider.models.filter(\.enabled).map(\.id)) + let shown = provider.models + .filter { needle.isEmpty || $0.modelId.lowercased().contains(needle) || $0.name.lowercased().contains(needle) } + .sorted { on.contains($0.id) && !on.contains($1.id) } + SettingsGroup(label: "Models", note: "Only switched-on models show up when choosing a bot's model.") { + Button(refreshing ? "Refreshing…" : "Refresh list", action: refresh) + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(Palette.foreground) + .disabled(refreshing || provider.lacksCredential) + } content: { + if large { + SearchField(placeholder: "Search \(provider.models.count) models", text: $search, style: .inCard) + .padding(10) + SettingsDivider() + } + if shown.isEmpty { + SettingsRow(label: needle.isEmpty ? "No models yet. Refresh the list once it is connected." : "No models match.") + } + DividedRows(data: shown) { model in + row(model, large: large) + } + if provider.custom { + SettingsDivider() + if adding { + ConnectionValueRow(label: "Model ID") { + TextField("", text: $newModelId, prompt: Text("e.g. llama-3.3-70b").foregroundStyle(Palette.mutedForeground)) + .font(Typeface.mono(16)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } action: { + HStack(spacing: 12) { + RowLink(title: "Add") { addModel() }.disabled(newModelId.trimmingCharacters(in: .whitespaces).isEmpty || modelChange.pending) + RowLink(title: "Cancel", quiet: true) { adding = false } + } + } + } else { + SettingsAddRow(label: "Add model") { adding = true } + } + } + if let failure = modelChange.failure { + SettingsDivider() + FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 12) + } + } + .sheet(item: $editing) { model in + CapabilitiesSheet(model: model, providerId: provider.id) { await changed() } + } + .onAppear { if onWhenOpened == nil { onWhenOpened = on } } + } + + private func row(_ model: ProviderModel, large: Bool) -> some View { + let bots = store.agents.filter { $0.systemAgentKey == nil && $0.model == model.modelId } + let used = bots.isEmpty ? "Not used yet" : "\(bots.count) \(bots.count == 1 ? "bot" : "bots")" + let maker = model.maker.map { ProviderModel.makerNames[$0] ?? $0.prefix(1).uppercased() + $0.dropFirst() } ?? provider.name + let who = large ? maker : used + let held = model.enabled ? holdersOf(model) : nil + return HStack(spacing: 14) { + VStack(alignment: .leading, spacing: 2) { + Text(model.name).font(Typeface.rubik(16)).foregroundStyle(Palette.foreground).lineLimit(1) + HStack(spacing: 6) { + Text(held.map { "\($0.newBots ? "Default" : "Summaries") · \(who)" } ?? who) + CapabilityIcons(model: model) + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + BotFaces(bots: bots) + if provider.custom { + Button { editing = model } label: { Icon(.pencil, size: 14).frame(width: 24, height: 24) } + .buttonStyle(IconPressStyle()) + .accessibilityLabel("What \(model.name) can do") + } + WebToggle(label: "Bots can use \(model.name)", isOn: model.enabled) { setEnabled(model, $0) } + .disabled(!provider.active || held != nil || modelChange.pending) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: 56) + } + + private func refresh() { + refreshing = true + Task { + do { + _ = try await store.client.modelProviders.fetchModels(workspace: store.workspace.id, providerId: provider.id) + modelChange.failure = nil + await changed() + } catch { + modelChange.failure = error.localizedDescription + } + refreshing = false + } + } + + private func setEnabled(_ model: ProviderModel, _ enabled: Bool) { + modelChange.run { + _ = try await store.client.modelProviders.updateModel( + workspace: store.workspace.id, providerId: provider.id, modelId: model.id, enabled: enabled + ) + await changed() + } + } + + private func addModel() { + modelChange.run { + _ = try await store.client.modelProviders.addModel( + workspace: store.workspace.id, providerId: provider.id, modelId: newModelId.trimmingCharacters(in: .whitespaces) + ) + newModelId = "" + adding = false + await changed() + } + } +} + +/// What a model can do, as small icons after its line, as `CapabilityIcons`. +private struct CapabilityIcons: View { + let model: ProviderModel + + static let icons: [ProviderModelCapability: Lucide] = [.tools: .wrench, .vision: .eye, .images: .image, .audio: .mic, .reasoning: .brain, .embeddings: .grid2X2] + + var body: some View { + let on = model.effectiveCapabilities + ForEach(ModelCapability.catalog.filter { on.contains($0.capability) }, id: \.key) { capability in + if let icon = Self.icons[capability.capability] { + Icon(icon, size: 13).accessibilityLabel(capability.name) + } + } + } +} + +extension ModelCapability { + /// The capability the catalog's `key` names, as the API's models list it. + var capability: ProviderModelCapability { ProviderModelCapability(rawValue: key) } +} + +/// Up to three faces of the bots on a model, overlapping, then how many more, as `BotFaces`. +private struct BotFaces: View { + let bots: [Agent] + + var body: some View { + let shown = Array(bots.prefix(bots.count > 3 ? 2 : 3)) + let more = bots.count - shown.count + if !bots.isEmpty { + HStack(spacing: -6) { + ForEach(shown) { bot in + BotFace(look: bot.look, size: 22) + .padding(2) + .background(Palette.settingsCard, in: Circle()) + } + if more > 0 { + Text("+\(more)") + .font(Typeface.rubik(10.5, .semibold)) + .foregroundStyle(Palette.softForeground) + .padding(.horizontal, 4) + .frame(minWidth: 22, minHeight: 22) + .background(Palette.chip, in: Capsule()) + .padding(2) + .background(Palette.settingsCard, in: Capsule()) + } + } + .accessibilityHidden(true) + } + } +} + +/// What a custom provider's model can do, as the web's `CapabilitiesDialog`: +/// a hand-added one has whatever you say; a listed one can only have its own switched off. +@MainActor +private struct CapabilitiesSheet: View { + let model: ProviderModel + let providerId: String + let saved: () async -> Void + @Environment(WorkspaceStore.self) private var store + @Environment(\.dismiss) private var dismiss + @State private var chosen: [ProviderModelCapability] = [] + @State private var saving = SettingsAction() + + var body: some View { + let byHand = model.source == .manual + let offered = ModelCapability.catalog.filter { byHand || model.capabilities.contains($0.capability) } + DialogForm(title: "What it can do", action: (title: "Save", run: save), actionDisabled: saving.pending) { + Text(model.modelId).font(Typeface.mono(13)).foregroundStyle(Palette.mutedForeground) + if offered.isEmpty { + Text("The server lists nothing this model can do, so there is nothing to switch.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + } else { + SettingsGroup { + DividedRows(data: offered, id: \.key) { capability in + SettingsRow(label: capability.name, sub: capability.description, leading: { + Icon(CapabilityIcons.icons[capability.capability] ?? .wrench, size: 16).foregroundStyle(Palette.mutedForeground) + }, trailing: { + WebToggle(label: capability.name, isOn: chosen.contains(capability.capability)) { on in + chosen = on ? chosen + [capability.capability] : chosen.filter { $0 != capability.capability } + } + }) + } + } + } + if let failure = saving.failure { FormAlert(text: failure) } + } + .onAppear { chosen = model.effectiveCapabilities } + } + + private func save() { + saving.run { + let routes = store.client.modelProviders + if model.source == .manual { + _ = try await routes.updateModel(workspace: store.workspace.id, providerId: providerId, modelId: model.id, capabilities: chosen) + } else { + _ = try await routes.updateModel( + workspace: store.workspace.id, + providerId: providerId, + modelId: model.id, + disabledCapabilities: model.capabilities.filter { !chosen.contains($0) } + ) + } + await saved() + dismiss() + } + } +} + +// MARK: Adding a provider + +/// Adding a provider, as the web's `AddProviderDialog`: the catalog's +/// providers not connected yet, popular then local, and a custom one; then its key or address. +@MainActor +struct AddProviderSheet: View { + enum Choice: Hashable { + case preset(ProviderPreset) + case custom + } + + let providers: [ModelProvider] + /// The provider to go straight to, or nil for the list. + let startWith: ProviderPresetId? + let added: (ModelProvider) -> Void + @State private var choice: Choice? + + var body: some View { + let byPreset = Dictionary(providers.compactMap { provider in provider.preset.map { ($0.rawValue, provider) } }, uniquingKeysWith: { first, _ in first }) + Group { + switch choice { + case .custom: CustomProviderStep(back: { choice = nil }, added: added) + case let .preset(preset): PresetStep(preset: preset, existing: byPreset[preset.id], back: { choice = nil }, added: added) + case nil: list(byPreset) + } + } + .onAppear { + if choice == nil, let startWith, let preset = ProviderPreset.named(startWith.rawValue) { choice = .preset(preset) } + } + } + + private func list(_ byPreset: [String: ModelProvider]) -> some View { + // Ollama is on in every workspace from the start, so being reachable is not enough to leave it out: it has to have listed models. + let available = ProviderPreset.catalog.filter { preset in + guard let existing = byPreset[preset.id] else { return true } + return !existing.connected || existing.models.isEmpty + } + let groups = [("Popular", available.filter { $0.hostingKind == .remote }), ("On your own machine", available.filter { $0.hostingKind == .local })].filter { !$0.1.isEmpty } + return DialogForm(title: "Add provider") { + VStack(spacing: 20) { + ForEach(groups, id: \.0) { label, presets in + SettingsGroup(label: label) { + DividedRows(data: presets) { preset in + Button { choice = .preset(preset) } label: { + SettingsRow(label: preset.name, sub: Self.firstSentence(preset.hint), chevron: true, leading: { + ProviderTile(name: preset.name, preset: preset.id) + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + SettingsGroup(label: "Something else") { + Button { choice = .custom } label: { + SettingsRow(label: "Custom provider", sub: "Any service using the OpenAI or Anthropic format", chevron: true, leading: { + SettingsRowIcon { Icon(.code, size: 15, strokeWidth: 2.2) } + }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + } + + /// As `firstSentence`. + static func firstSentence(_ text: String) -> String { + if let stop = text.range(of: ". ") { return String(text[.. Void + let added: (ModelProvider) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var apiKey = "" + @State private var baseUrl = "" + @State private var adding = SettingsAction() + + var body: some View { + let local = preset.hostingKind == .local + let requiresKey = preset.credentialKind == .apiKey + let signsIn = preset.credentialKind == .signIn + let typed = parseProviderBaseURL(baseUrl) + let ready = (!requiresKey || !apiKey.isEmpty) && (!local || typed != nil) + DialogForm(title: preset.name, action: (title: signsIn ? "Continue" : "Add", run: submit), actionDisabled: !ready || adding.pending, onBack: adding.pending ? nil : back) { + SettingsGroup(note: preset.hint) { + if let service = preset.signIn { + SettingsRow(label: "\(ProviderPreset.signInServiceNames[service] ?? service) account", sub: "Sign in after you continue") + } + if local { + SettingsFieldRow(label: "Server URL", value: $baseUrl, placeholder: preset.baseUrl, mono: true) + } + if !signsIn { + if local { SettingsDivider() } + SettingsFieldRow(label: "API key", value: $apiKey, placeholder: requiresKey ? "Paste your key" : "Optional", mono: true, secret: true) + } + } + if local, !baseUrl.trimmingCharacters(in: .whitespaces).isEmpty, typed == nil { + FormAlert(text: notAServerAddress) + } + if let failure = adding.failure { FormAlert(text: failure) } + } + .onAppear { if baseUrl.isEmpty { baseUrl = existing?.baseUrl ?? preset.baseUrl } } + } + + private func submit() { + let local = preset.hostingKind == .local + let typed = parseProviderBaseURL(baseUrl) + adding.run { + // A seeded subscription provider, like ChatGPT, already exists; its page is where the person signs in. + if preset.credentialKind == .signIn, let existing { + added(existing) + return + } + let made: ModelProvider + if let existing { + var change = ModelProviderUpdate(active: true) + if !apiKey.isEmpty { change.apiKey = .present(apiKey) } + if local, let typed, typed != existing.baseUrl { change.baseUrl = typed } + made = try await store.updateProvider(existing.id, change) + } else { + var body = NewProviderFromPreset(preset: ProviderPresetId(rawValue: preset.id)) + if !apiKey.isEmpty { body.apiKey = apiKey } + if local, let typed, typed != preset.baseUrl { body.baseUrl = typed } + made = try await store.client.modelProviders.create(workspace: store.workspace.id, body: .newProviderFromPreset(body)) + } + added(made) + } + } +} + +/// A custom provider by its address and format, as `CustomProviderStep`. +@MainActor +private struct CustomProviderStep: View { + let back: () -> Void + let added: (ModelProvider) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var name = "" + @State private var baseUrl = "" + @State private var apiFormat = ProviderApiFormat.openai + @State private var apiKey = "" + @State private var adding = SettingsAction() + + var body: some View { + let ready = !name.trimmingCharacters(in: .whitespaces).isEmpty && parseProviderBaseURL(baseUrl) != nil + DialogForm(title: "Custom provider", action: (title: "Add", run: submit), actionDisabled: !ready || adding.pending, onBack: adding.pending ? nil : back) { + SettingsGroup { + SettingsFieldRow(label: "Name", value: $name, placeholder: "e.g. Company gateway") + SettingsDivider() + SettingsFieldRow(label: "Server URL", value: $baseUrl, placeholder: "https://llm.example.com/v1", mono: true) + SettingsDivider() + HStack(spacing: 14) { + Text("Format").font(Typeface.rubik(13)).foregroundStyle(Palette.foreground).frame(maxWidth: .infinity, alignment: .leading) + SegmentedChoice(label: "API format", options: [(ProviderApiFormat.openai, "OpenAI"), (.anthropic, "Anthropic")], value: apiFormat) { apiFormat = $0 } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 56) + SettingsDivider() + SettingsFieldRow(label: "API key", value: $apiKey, placeholder: "Optional", mono: true, secret: true) + } + if let failure = adding.failure { FormAlert(text: failure) } + } + } + + private func submit() { + guard let typed = parseProviderBaseURL(baseUrl) else { return } + adding.run { + let body = NewCustomProvider( + name: name.trimmingCharacters(in: .whitespaces), + baseUrl: typed, + apiFormat: apiFormat, + apiKey: apiKey.isEmpty ? nil : apiKey, + customHeaders: [] + ) + let made = try await store.client.modelProviders.create(workspace: store.workspace.id, body: .newCustomProvider(body)) + added(made) + } + } +} diff --git a/apps/ios/Sugabots/Settings/SandboxSettings.swift b/apps/ios/Sugabots/Settings/SandboxSettings.swift new file mode 100644 index 000000000..d8200c89d --- /dev/null +++ b/apps/ios/Sugabots/Settings/SandboxSettings.swift @@ -0,0 +1,519 @@ +import SwiftUI + +extension SandboxProviderSettings { + /// A provider's settings with nothing chosen but `preset`, or nil for a preset this app doesn't know. + static func empty(for preset: SandboxProviderPresetId) -> SandboxProviderSettings? { + switch preset { + case .opensandbox: .opensandbox(Opensandbox()) + case .e2b: .e2b(E2b()) + case .unknown: nil + } + } + + /// Which hosts the provider's computers reach; nil until chosen, which means open. + var networkMode: SandboxNetworkMode? { + get { + switch self { + case let .opensandbox(fields): fields.networkMode + case let .e2b(fields): fields.networkMode + case .unknown: nil + } + } + set { + switch self { + case var .opensandbox(fields): + fields.networkMode = newValue + self = .opensandbox(fields) + case var .e2b(fields): + fields.networkMode = newValue + self = .e2b(fields) + case .unknown: + break + } + } + } +} + +/// A change to a computer provider: what is left nil, or kept, stays as it is. +private struct SandboxProviderChange { + var enabled: Bool? + var apiKey = FieldChange.keep + var settings: SandboxProviderSettings? +} + +extension SandboxPreset { + static func named(_ id: SandboxProviderPresetId) -> SandboxPreset { catalog.first { $0.id == id.rawValue } ?? catalog[0] } +} + +/// A size an E2B computer can't have. +private struct SizeOutOfRange: LocalizedError { + let unit: String + var errorDescription: String? { "Enter a whole number of \(unit), from 1 to 64." } +} + +/// Computers, as the web's `SandboxSettings`: the switch, the provider and its +/// settings, the network the computers reach, and the bots using one. +@MainActor +struct SandboxSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var providers: Loadable<[SandboxProvider]> = .loading + @State private var chosen: SandboxProviderPresetId? + @State private var action = SettingsAction() + @State private var tested: TestResult? + @State private var removingKey = false + @State private var removing = false + + /// The sizes an E2B computer can have, in vCPUs or GiB. + private static let sizeRange = 1...64 + + var body: some View { + SettingsPage(title: "Computers", description: "Give bots their own computer to run commands, browse and edit files.") { + switch providers { + case .loading: EmptyView() + case let .failed(failure): FormAlert(text: failure) + case let .loaded(providers): groups(providers) + } + } + .task { await load() } + } + + @ViewBuilder + private func groups(_ providers: [SandboxProvider]) -> some View { + let enabled = providers.first(where: \.enabled) + let chosen = chosen ?? enabled?.preset ?? providers.first?.preset ?? .opensandbox + let configured = providers.first { $0.preset == chosen } + let preset = SandboxPreset.named(chosen) + let ready = configured?.hasApiKey == true + let settings = configured?.settings ?? SandboxProviderSettings.empty(for: chosen) + HStack(alignment: .top, spacing: 10) { + Icon(.info, size: 15).foregroundStyle(Palette.subtleForeground).padding(.top, 1) + Text("Computers are experimental. How they work, and what they keep, may change between releases.") + } + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(maxWidth: .infinity, alignment: .leading) + .settingsCard() + .padding(.top, -24) + SettingsGroup(note: Self.movingNote(from: enabled, to: preset, chosen: chosen, ready: ready)) { + HStack(spacing: 14) { + VStack(alignment: .leading, spacing: 2) { + Text("Bots can use a computer").font(Typeface.rubik(16, .medium)).foregroundStyle(Palette.foreground) + Text(ready ? "Each pod gets its own private computer" : "\(preset.name) needs an API key first. Add it below.") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + WebToggle(label: "Bots can use a computer", isOn: enabled?.preset == chosen) { on in switchTo(on, chosen: chosen, configured: configured, enabled: enabled) } + .disabled(!ready || action.pending) + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: 56) + } + providerChoice(chosen: chosen, enabled: enabled?.preset) + providerSettings(preset: preset, chosen: chosen, configured: configured, settings: settings) + if let failure = action.failure { FormAlert(text: failure) } + if let settings { + SandboxNetworkGroups(mode: settings.networkMode ?? .open, preset: chosen) { mode in + var next = settings + next.networkMode = mode + action.run { try await configure(SandboxProviderChange(settings: next), configured: configured, chosen: chosen) } + } + .disabled(action.pending) + } + botsUsingAComputer + } + + /// What the switch's group says when turning it on would move computers from the provider in use to `preset`. + private static func movingNote(from enabled: SandboxProvider?, to preset: SandboxPreset, chosen: SandboxProviderPresetId, ready: Bool) -> String? { + guard ready, let enabled, enabled.preset != chosen else { return nil } + return "Turning this on moves computers from \(enabled.name) to \(preset.name). Each pod gets a new one, without the old one's files." + } + + private func providerChoice(chosen: SandboxProviderPresetId, enabled: SandboxProviderPresetId?) -> some View { + SettingsGroup(label: "Provider") { + DividedRows(data: SandboxPreset.catalog, id: \.id) { candidate in + let candidateId = SandboxProviderPresetId(rawValue: candidate.id) + SettingsRadioRow(name: candidate.name, description: candidate.description, badge: candidateId == enabled ? "In use" : nil, checked: candidateId == chosen) { + action.failure = nil + tested = nil + self.chosen = candidateId + } + .disabled(action.pending) + } + } + } + + /// What the provider's group says under it: how its last test went, or what its settings are for. + private func providerNote(_ preset: SandboxProviderPresetId, configured: SandboxProvider?) -> String { + if let tested { return tested.text } + switch configured?.status { + case .connected: return "The last test connected." + case .error: return configured?.lastTestError ?? "The last test failed." + default: break + } + if preset == .e2b { + return "Leave the URLs empty for E2B Cloud. For E2B Embed, give both. A new size takes effect once the template is prepared again and a pod's computer is reset." + } + return "The server's own API key, from its configuration. Leave the image empty to use the default." + } + + private func providerSettings(preset: SandboxPreset, chosen: SandboxProviderPresetId, configured: SandboxProvider?, settings: SandboxProviderSettings?) -> some View { + let hasKey = configured?.hasApiKey == true + let save = { (next: SandboxProviderSettings) in + try await action.perform { try await configure(SandboxProviderChange(settings: next), configured: configured, chosen: chosen) } + } + return SettingsGroup(label: preset.name, note: providerNote(chosen, configured: configured)) { + VStack(spacing: 0) { + if case let .opensandbox(fields) = settings { + TextEntryRow(label: "Server URL", value: .text(saved: fields.serverUrl ?? preset.baseUrl), placeholder: preset.baseUrl ?? "") { url in + var next = fields + next.serverUrl = url + try await save(.opensandbox(next)) + } + SettingsDivider() + } + TextEntryRow( + label: "API key", + value: .secret(isSaved: hasKey), + placeholder: "Paste your key", + save: { key in try await action.perform { try await configure(SandboxProviderChange(apiKey: .set(key)), configured: configured, chosen: chosen) } }, + remove: hasKey ? { removingKey = true } : nil + ) + switch settings { + case let .opensandbox(fields): + SettingsDivider() + clearableRow(preset.imageLabel, saved: fields.image, placeholder: preset.defaultImage) { image in + var next = fields + next.image = image + try await save(.opensandbox(next)) + } + case let .e2b(fields): + SettingsDivider() + clearableRow(preset.imageLabel, saved: fields.template, placeholder: preset.defaultImage) { template in + var next = fields + next.template = template + try await save(.e2b(next)) + } + SettingsDivider() + clearableRow("API URL", saved: fields.apiUrl, placeholder: "E2B Cloud") { url in + var next = fields + next.apiUrl = url + try await save(.e2b(next)) + } + SettingsDivider() + clearableRow("Computer URL", saved: fields.sandboxUrl, placeholder: "E2B Cloud") { url in + var next = fields + next.sandboxUrl = url + try await save(.e2b(next)) + } + SettingsDivider() + sizeRow("vCPUs", saved: fields.cpuCount.map(String.init), placeholder: "\(SandboxPreset.defaultSize.cpuCount)", unit: "vCPUs") { count in + var next = fields + next.cpuCount = count + try await save(.e2b(next)) + } + SettingsDivider() + sizeRow("Memory", saved: fields.memoryGiB.map { "\($0) GiB" }, placeholder: "\(SandboxPreset.defaultSize.memoryGiB) GiB", unit: "GiB") { memory in + var next = fields + next.memoryGiB = memory + try await save(.e2b(next)) + } + if let configured, hasKey { + SettingsDivider() + TemplateRow(providerId: configured.id) + } + case .unknown, nil: + EmptyView() + } + if let configured, hasKey { + SettingsDivider() + Button { test(configured) } label: { + SettingsRow(label: "Test connection", sub: "Checks the provider answers and accepts the key.") + } + .buttonStyle(SettingsRowPressStyle()) + } + if configured != nil { + SettingsDivider() + Button { removing = true } label: { + SettingsRow(label: "Remove \(preset.name)", sub: "Removes its computers and settings.") + } + .buttonStyle(SettingsRowPressStyle()) + } + } + .disabled(action.pending) + .confirmDelete( + isPresented: $removingKey, + title: "Remove the \(preset.name) key?", + description: "Bots stop getting computers from this provider until another key is added.", + confirmLabel: "Remove" + ) { + try await configure(SandboxProviderChange(apiKey: .clear), configured: configured, chosen: chosen) + } + .confirmDelete( + isPresented: $removing, + title: "Remove \(preset.name)?", + description: "Every pod's computer at this provider is destroyed, with its files, including work that wasn't pushed.", + confirmLabel: "Remove" + ) { + guard let configured else { return } + try await store.client.sandboxProviders.remove(workspace: store.workspace.id, providerId: configured.id) + await load() + } + } + } + + /// A setting that may be emptied for its default, which `set` is given as nil. + private func clearableRow(_ label: String, saved: String?, placeholder: String, set: @escaping (String?) async throws -> Void) -> some View { + TextEntryRow(label: label, value: .text(saved: saved), placeholder: placeholder, save: { try await set($0) }, clear: { try await set(nil) }) + } + + /// An E2B computer's size: a whole number in `sizeRange`, which may be emptied for the default. + private func sizeRow(_ label: String, saved: String?, placeholder: String, unit: String, set: @escaping (Int?) async throws -> Void) -> some View { + TextEntryRow( + label: label, + value: .text(saved: saved), + placeholder: placeholder, + save: { typed in + let number = Int(typed.replacingOccurrences(of: "\\s*GiB$", with: "", options: [.regularExpression, .caseInsensitive])) + guard let number, Self.sizeRange.contains(number) else { + try await action.perform { throw SizeOutOfRange(unit: unit) } + return + } + try await set(number) + }, + clear: { try await set(nil) } + ) + } + + @ViewBuilder + private var botsUsingAComputer: some View { + let using = store.agents.compactMap { agent in + agent.usesSandbox && agent.systemAgentKey == nil ? store.pod(id: agent.podId).map { (agent, $0) } : nil + } + SettingsGroup(label: "Bots using a computer", note: "Switch a computer on or off in each bot's settings.") { + if using.isEmpty { SettingsEmptyRow(text: "None yet") } + DividedRows(data: using, id: \.0.id) { item in + NavigationLink(value: Route.settings(.agent(item.1, item.0))) { + SettingsRow(label: item.0.name, sub: item.1.name, chevron: true, leading: { BotFace(look: item.0.look, size: 24) }) + } + .buttonStyle(SettingsRowPressStyle()) + } + } + } + + // MARK: Doing + + private func load() async { + providers = await .of { try await store.client.sandboxProviders.list(workspace: store.workspace.id) } + } + + /// Saves a change to the chosen provider, making it first if it has never been set up, then reloads them. + private func configure(_ change: SandboxProviderChange, configured: SandboxProvider?, chosen: SandboxProviderPresetId) async throws { + let routes = store.client.sandboxProviders + if let configured { + _ = try await routes.update( + workspace: store.workspace.id, providerId: configured.id, enabled: change.enabled, apiKey: change.apiKey.apiValue, settings: change.settings + ) + } else if let settings = change.settings ?? .empty(for: chosen) { + let apiKey: String? = if case let .set(key) = change.apiKey { key } else { nil } + _ = try await routes.create(workspace: store.workspace.id, settings: settings, enabled: change.enabled, apiKey: apiKey) + } + await load() + } + + private func switchTo(_ on: Bool, chosen: SandboxProviderPresetId, configured: SandboxProvider?, enabled: SandboxProvider?) { + action.run { + if on { + try await configure(SandboxProviderChange(enabled: true), configured: configured, chosen: chosen) + } else if let enabled { + try await configure(SandboxProviderChange(enabled: false), configured: enabled, chosen: enabled.preset) + } + } + } + + private func test(_ provider: SandboxProvider) { + action.run { + let result = try await store.client.sandboxProviders.test(workspace: store.workspace.id, providerId: provider.id) + tested = TestResult(passed: result.reachable, text: result.reachable ? "Connected in \(result.latencyMs) ms." : result.error ?? "The provider didn't answer.") + await load() + } + } +} + +/// E2B's template: preparing or rebuilding Sugabots' image in the account, as `TemplateRow`. +@MainActor +private struct TemplateRow: View { + let providerId: String + @Environment(WorkspaceStore.self) private var store + @State private var state: SandboxTemplate.State? + @State private var loadFailure: String? + @State private var preparing = SettingsAction() + + var body: some View { + let canPrepare = state == .missing || state == .failed || state == .ready + Button(action: prepare) { + SettingsRow(label: Self.label(state, canPrepare: canPrepare), sub: preparing.failure ?? loadFailure ?? Self.description(state), trailing: { + if let badge = Self.badge(state) { SettingsValue(text: badge) } + }) + } + .buttonStyle(SettingsRowPressStyle()) + .disabled(!canPrepare || preparing.pending) + .task { await load() } + } + + private static func label(_ state: SandboxTemplate.State?, canPrepare: Bool) -> String { + if state == .ready { return "Rebuild template" } + return canPrepare ? "Prepare template" : "Sugabots template" + } + + private static func description(_ state: SandboxTemplate.State?) -> String { + switch state { + case .ready: "Ready. Rebuilding takes Sugabots' latest image, which pods' computers move to when upgraded." + case .building: "Building in your E2B account. This takes a few minutes." + case .failed: "The last build failed. Try again." + default: "Builds Sugabots' computer image into a template in your E2B account." + } + } + + private static func badge(_ state: SandboxTemplate.State?) -> String? { + switch state { + case .ready: "Ready" + case .building: "Building" + default: nil + } + } + + private func load() async { + do { + state = try await store.client.sandboxProviders.template(workspace: store.workspace.id, providerId: providerId).state + loadFailure = nil + } catch { + loadFailure = error.localizedDescription + } + } + + private func prepare() { + preparing.run { + _ = try await store.client.sandboxProviders.prepareTemplate(workspace: store.workspace.id, providerId: providerId) + await load() + } + } +} + +/// The workspace's network for computers, as the web's `SandboxNetworkSection`: +/// open, or an allowlist with its hosts and the trusted ones, then the blocked +/// hosts. The network is fetched again whenever `mode` changes. +@MainActor +private struct SandboxNetworkGroups: View { + /// Which hosts the chosen provider's computers reach. + let mode: SandboxNetworkMode + /// The chosen provider, which says whether the open network can block hosts. + let preset: SandboxProviderPresetId + let setMode: (SandboxNetworkMode) -> Void + @Environment(WorkspaceStore.self) private var store + @State private var settings: Loadable = .loading + @State private var action = SettingsAction() + @State private var allowDraft = "" + @State private var blockDraft = "" + + var body: some View { + Group { + if let settings = settings.value { + let open = settings.mode == .open + if open { + SettingsGroup( + label: "Network", + note: settings.blocking + ? "Switching to an allowlist keeps your blocked hosts, and the hosts allowed apply again." + : "This provider can't block hosts, so the blocked hosts don't apply while it's open. They're kept, with the allowed hosts, for if it goes back to the allowlist." + ) { modeRow } + } else { + SettingsGroup( + label: "Network", + note: "Every pod's computer connects to these hosts, and each pod adds its own under Computer in its settings. Blocked hosts still apply. When a bot needs another, it asks in its thread." + ) { + modeRow + ForEach(settings.addedHosts) { added in + SettingsDivider() + RemovableRow( + name: added.host, + sub: "Added by \(added.addedByName ?? "someone who has left")", + removal: .init(label: "Remove \(added.host)") { + change { try await $0.removeHost(workspace: store.workspace.id, host: added.host) } + } + ) + } + SettingsDivider() + AddHostRow(label: "Allow host", buttonTitle: "Allow", draft: $allowDraft) { host in + change(then: { allowDraft = "" }) { try await $0.addHost(workspace: store.workspace.id, host: host) } + } + SettingsDivider() + HostListRow( + label: "Trusted hosts", + hosts: settings.trustedHosts, + summary: "\(settings.trustedHosts.count) hosts every workspace reaches: GitHub, package registries and Linux mirrors" + ) + } + } + if settings.blocking { + SettingsGroup( + label: "Blocked hosts", + note: open + ? "No pod's computer connects to these, or to their subdomains." + : "No pod's computer connects to these, whatever it allows, and bots' requests for them are refused. Blocking a host also keeps out any wildcard that covers it." + ) { + ForEach(settings.blockedHosts) { blocked in + RemovableRow( + name: blocked.host, + sub: "Blocked by \(blocked.blockedByName ?? "someone who has left")", + removal: .init(label: "Unblock \(blocked.host)") { + change { try await $0.unblockHost(workspace: store.workspace.id, host: blocked.host) } + } + ) + SettingsDivider() + } + AddHostRow(label: "Block host", buttonTitle: "Block", draft: $blockDraft) { host in + change(then: { blockDraft = "" }) { try await $0.blockHost(workspace: store.workspace.id, host: host) } + } + } + } + } + if let failure = action.failure ?? settings.failure { FormAlert(text: failure) } + } + .disabled(action.pending) + .task(id: mode) { await load() } + } + + /// Open or Allowlist, with what the chosen one lets through. + private var modeRow: some View { + SettingsRow(label: mode == .allowlist ? "Allowlist" : "Open", sub: Self.modeSummary(mode, preset: preset), trailing: { + SegmentedChoice(label: "Network", options: [(SandboxNetworkMode.open, "Open"), (.allowlist, "Allowlist")], value: mode, choose: setMode) + }) + } + + private static func modeSummary(_ mode: SandboxNetworkMode, preset: SandboxProviderPresetId) -> String { + if mode == .allowlist { return "Only the hosts allowed" } + return preset == .e2b ? "Any host. E2B can't block hosts" : "Any host but the blocked ones" + } + + private func load() async { + let loaded: Loadable = await .of { try await store.client.sandboxProviders.network(workspace: store.workspace.id) } + // A failed reload keeps the network shown, with what failed under it. + if case let .failed(failure) = loaded, settings.value != nil { + action.failure = failure + } else { + settings = loaded + } + } + + /// Makes a change to the network, which answers with it as it now stands, then runs `done`. + private func change(then done: @escaping () -> Void = {}, _ write: @escaping (APIClient.SandboxProvidersRoutes) async throws -> SandboxNetworkSettings) { + action.run { + settings = .loaded(try await write(store.client.sandboxProviders)) + done() + } + } +} diff --git a/apps/ios/Sugabots/Settings/SettingsControls.swift b/apps/ios/Sugabots/Settings/SettingsControls.swift new file mode 100644 index 000000000..aa5e40bfd --- /dev/null +++ b/apps/ios/Sugabots/Settings/SettingsControls.swift @@ -0,0 +1,500 @@ +import SwiftUI + +// Controls the web's settings pages use beyond `Design/WebControls.swift`. + +/// The web's `SegmentedControl`: choices in a chip, the chosen one lifted. +struct SegmentedChoice: View { + let label: String + let options: [(value: Value, label: String)] + let value: Value? + /// Stretches the choices across the row, as on a phone's narrow rows. + var fill = false + let choose: (Value) -> Void + @Environment(\.isEnabled) private var isEnabled + + var body: some View { + HStack(spacing: 0) { + ForEach(options, id: \.value) { option in + let chosen = option.value == value + Button { choose(option.value) } label: { + Text(option.label) + .font(Typeface.rubik(12.5, .medium)) + // Stretched across a row, a long choice wraps rather than being cut short, as on the web. + .lineLimit(fill ? 2 : 1) + .multilineTextAlignment(.center) + .foregroundStyle(chosen ? Palette.foreground : Palette.mutedForeground) + .padding(.horizontal, 11) + .padding(.vertical, 5) + // The web's 5px either side of a line of `text-sm`. + .frame(maxWidth: fill ? .infinity : nil, minHeight: 28, maxHeight: fill ? .infinity : nil) + .background(chosen ? Palette.personAvatar : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(chosen ? .isSelected : []) + } + } + .padding(2) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + // Beside a label, the choices keep their width, as the web's `shrink-0`. + .fixedSize(horizontal: !fill, vertical: false) + .opacity(isEnabled ? 1 : 0.5) + .accessibilityElement(children: .contain) + .accessibilityLabel(label) + } +} + +/// The web's `Toggle`, as a phone draws a switch: the system's own. +struct WebToggle: View { + let label: String + let isOn: Bool + let change: (Bool) -> Void + + init(label: String, isOn: Bool, change: @escaping (Bool) -> Void) { + self.label = label + self.isOn = isOn + self.change = change + } + + /// A switch bound to a value it changes itself. + init(label: String, isOn: Binding) { + self.init(label: label, isOn: isOn.wrappedValue) { isOn.wrappedValue = $0 } + } + + var body: some View { + // The system's switch in the system's green: the app's accent, near white in dark, would hide its white knob. + Toggle(label, isOn: Binding(get: { isOn }, set: change)) + .labelsHidden() + .tint(Color(uiColor: .systemGreen)) + } +} + +/// The web's `SettingsNameRow`: a name edited where it stands, saved when the field is left. +struct SettingsNameRow: View { + let name: String + let maxLength: Int + let save: (String) async throws -> Void + @State private var draft = "" + @State private var failure: String? + @FocusState private var focused: Bool + + var body: some View { + VStack(spacing: 0) { + SettingsControlRow(label: "Name") { + TextField("", text: $draft.limited(to: maxLength)) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.foreground) + .editsInPlace(draft: $draft, saved: name, focused: $focused) { next in + failure = nil + do { try await save(next) } catch { + failure = error.localizedDescription + throw error + } + } + .accessibilityLabel("Name") + } + if let failure { + SettingsDivider() + FormAlert(text: failure).padding(.horizontal, 16).padding(.vertical, 10) + } + } + } +} + +extension View { + /// Makes a text field one edited where it stands, as the web's + /// `SettingsNameRow` and `ProfileField`: Done or leaving the field saves + /// what's typed, trimmed. Nothing changed, or nothing typed unless + /// `allowsEmpty`, puts back what's saved, as does a failed save. While the + /// field isn't being typed in, `draft` follows `saved`; while a save is + /// under way, the field can't be typed in. + func editsInPlace( + draft: Binding, + saved: String, + allowsEmpty: Bool = false, + focused: FocusState.Binding, + save: @escaping (String) async throws -> Void + ) -> some View { + modifier(EditInPlace(draft: draft, saved: saved, allowsEmpty: allowsEmpty, focused: focused, save: save)) + } +} + +private struct EditInPlace: ViewModifier { + @Binding var draft: String + let saved: String + let allowsEmpty: Bool + var focused: FocusState.Binding + let save: (String) async throws -> Void + @State private var saving = false + + func body(content: Content) -> some View { + content + .focused(focused) + .submitLabel(.done) + .disabled(saving) + .onSubmit { focused.wrappedValue = false } + .onAppear { draft = saved } + .onChange(of: saved) { _, value in if !focused.wrappedValue { draft = value } } + .onChange(of: focused.wrappedValue) { _, isFocused in if !isFocused { commit() } } + } + + private func commit() { + guard !saving else { return } + let next = draft.trimmingCharacters(in: .whitespaces) + guard next != saved, allowsEmpty || !next.isEmpty else { + draft = saved + return + } + draft = next + saving = true + Task { + do { try await save(next) } catch { draft = saved } + saving = false + } + } +} + +/// A page's settings text in grey under its groups, or a loading line. +struct SettingsNotice: View { + let text: String + + var body: some View { + Text(text).font(Typeface.rubik(13)).foregroundStyle(Palette.mutedForeground) + } +} + +/// A grey row saying a list is empty, such as "No bots in this pod yet". +struct SettingsEmptyRow: View { + let text: String + + var body: some View { + Text(text) + .font(Typeface.rubik(16)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity, minHeight: 56, alignment: .leading) + .padding(.horizontal, 16) + } +} + +/// The round + at a settings page's top right on a phone, as `SettingsAddButton` there. +struct SettingsAddButton: View { + let label: String + let action: () -> Void + + var body: some View { + GlassRoundButton(icon: .plus, label: label, strokeWidth: 2, action: action) + } +} + +/// Something added to a list in code type, such as a host or a repository, +/// with who added it under it and, where it may be taken out here, the × that +/// does, as the web's `AddedHostRow` and `BlockedHostRow`. +struct RemovableRow: View { + /// The × at a row's end: what it is called for VoiceOver, and what it does. + struct Removal { + let label: String + let action: () -> Void + } + + let name: String + /// The web sets hosts at 13 and repositories at 13.5. + var nameSize: CGFloat = 13 + let sub: String + /// Absent where it can't be taken out here. + var removal: Removal? + + var body: some View { + HStack(spacing: 14) { + VStack(alignment: .leading, spacing: 2) { + Text(name).font(Typeface.mono(nameSize)).foregroundStyle(Palette.foreground) + Text(sub).font(Typeface.rubik(13)).foregroundStyle(Palette.subtleForeground) + } + .frame(maxWidth: .infinity, alignment: .leading) + if let removal { + Button(action: removal.action) { Icon(.x, size: 16).frame(width: 24, height: 24) } + .buttonStyle(IconPressStyle()) + .accessibilityLabel(removal.label) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: 56) + } +} + +/// A host to type in and the button that sends it, such as Allow or Block, as +/// the web's `AddHostRow`. The host goes trimmed and lower-cased; the caller +/// empties `draft` once it is added. +struct AddHostRow: View { + let label: String + let buttonTitle: String + @Binding var draft: String + let add: (String) -> Void + @Environment(\.isEnabled) private var isEnabled + + var body: some View { + let host = draft.trimmingCharacters(in: .whitespaces).lowercased() + SettingsControlRow(label: label) { + TextField("", text: $draft, prompt: Text("api.example.com or *.example.com").foregroundStyle(Palette.mutedForeground)) + .font(Typeface.mono(16)) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .onSubmit { if !host.isEmpty, isEnabled { add(host) } } + Button(buttonTitle) { add(host) } + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(Palette.link) + .disabled(host.isEmpty) + } + } +} + +/// How many hosts a list holds and what they are, opening to name them all, +/// as the web's Trusted hosts and From the workspace rows. +struct HostListRow: View { + let label: String + let hosts: [String] + /// What the row says while closed, such as "12 hosts every pod reaches". + let summary: String + @State private var open = false + + var body: some View { + Button { open.toggle() } label: { + SettingsRow(label: label, sub: open ? hosts.joined(separator: ", ") : summary, chevron: !open) + } + .buttonStyle(SettingsRowPressStyle()) + } +} + +/// A setting typed where it stands and saved when the field is left, as the +/// web's `TextEntryRow`. A secret shows dots once one is saved, until Replace. +struct TextEntryRow: View { + /// What the row holds. + enum Value { + /// Text shown as typed, such as an address, with what is saved, if anything. + case text(saved: String?) + /// A secret, such as a key, of which only whether one is saved is known. + case secret(isSaved: Bool) + } + + let label: String + let value: Value + let placeholder: String + /// Saves what's typed, trimmed. A failure puts back the saved text, or keeps + /// a secret's typing to try again. + let save: (String) async throws -> Void + /// Takes the saved text away when the field is emptied, for a setting with a + /// default; absent where emptying the field only puts the saved text back. + var clear: (() async throws -> Void)? + /// Asks to take a saved secret away; absent where it can't be. + var remove: (() -> Void)? + @State private var draft = "" + @State private var replacing = false + @State private var saving = false + @FocusState private var focused: Bool + + private var savedText: String? { + guard case let .text(saved) = value else { return nil } + return saved + } + + private var isSecret: Bool { + guard case .secret = value else { return false } + return true + } + + var body: some View { + HStack(spacing: 12) { + Text(label).font(Typeface.rubik(13)).foregroundStyle(Palette.foreground).frame(width: 82, alignment: .leading) + if case .secret(isSaved: true) = value, !replacing { + Text("••••••••").font(Typeface.mono(13)).foregroundStyle(Palette.mutedForeground).frame(maxWidth: .infinity, alignment: .leading) + Button("Replace") { replacing = true } + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(Palette.foreground) + if let remove { + Button("Remove", action: remove) + .font(Typeface.rubik(12.5, .medium)) + .foregroundStyle(Palette.destructiveText) + } + } else { + Group { + if isSecret { + SecureField("", text: $draft, prompt: Text(placeholder).foregroundStyle(Palette.subtleForeground)) + } else { + TextField("", text: $draft, prompt: Text(placeholder).foregroundStyle(Palette.subtleForeground)) + } + } + .font(Typeface.mono(16)) + .foregroundStyle(Palette.foreground) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .focused($focused) + .submitLabel(.done) + .onSubmit { focused = false } + .disabled(saving) + .accessibilityLabel(label) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 48) + .onAppear { draft = savedText ?? "" } + .onChange(of: savedText) { _, saved in if !focused { draft = saved ?? "" } } + .onChange(of: focused) { _, isFocused in if !isFocused { commit() } } + } + + private func commit() { + guard !saving else { return } + let typed = draft.trimmingCharacters(in: .whitespaces) + if typed.isEmpty { + if savedText != nil, let clear { + run(clear) + } else { + draft = savedText ?? "" + } + return + } + guard typed != savedText else { return } + run { try await save(typed) } + } + + private func run(_ work: @escaping () async throws -> Void) { + saving = true + Task { + do { + try await work() + if isSecret { + draft = "" + replacing = false + } + } catch { + if !isSecret { draft = savedText ?? "" } + } + saving = false + } + } +} + +/// Something a settings page does on a tap, such as saving or removing, with +/// whether it is under way and what its last run failed with. A tap while one +/// runs is ignored, so controls that start it can be held with `.disabled(pending)` +/// and a quick second tap never sends it twice. +@MainActor +@Observable +final class SettingsAction { + /// What `perform` throws when a run is already under way. + struct Busy: Error {} + + private(set) var pending = false + /// What the last run failed with, until the next starts. + var failure: String? + + /// Starts `work`, unless a run is under way. + func run(_ work: @escaping () async throws -> Void) { + guard !pending else { return } + Task { try? await perform(work) } + } + + /// Runs `work` and waits for it, keeping what it fails with in `failure` + /// and throwing it on; throws `Busy` without running it while a run is under way. + func perform(_ work: () async throws -> Void) async throws { + guard !pending else { throw Busy() } + pending = true + failure = nil + defer { pending = false } + do { + try await work() + } catch { + failure = error.localizedDescription + throw error + } + } +} + +/// Something a page loads: loading, loaded, or failed with what to say. +enum Loadable { + case loading + case loaded(Value) + case failed(String) + + var value: Value? { + guard case let .loaded(value) = self else { return nil } + return value + } + + var failure: String? { + guard case let .failed(failure) = self else { return nil } + return failure + } + + /// What `load` returns, or what it failed with. + static func of(_ load: () async throws -> Value) async -> Loadable { + do { return .loaded(try await load()) } catch { return .failed(error.localizedDescription) } + } +} + +/// What to do with a field a change can leave alone, set, or empty, such as a provider's key. +enum FieldChange { + case keep + case set(Value) + case clear + + /// As the API takes such a field: omitted to leave it, present but nil to empty it. + var apiValue: Omittable { + switch self { + case .keep: .omitted + case let .set(value): .present(value) + case .clear: .present(nil) + } + } +} + +/// How a test of a provider or connection went: whether it got through, and what to say. +struct TestResult: Equatable { + let passed: Bool + let text: String +} + +/// A test's result on a line of its own, as the web's `Success`, a green +/// tick and what passed, or its `Alert`, in red. +struct TestResultLine: View { + let result: TestResult + + var body: some View { + if result.passed { + HStack(spacing: 6) { + Icon(.circleCheck, size: 16) + Text(result.text) + } + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(Palette.successText) + } else { + FormAlert(text: result.text) + } + } +} + +/// A button that copies `text`, and for a moment after says it has, as the +/// web's copy buttons. `label` draws it, told whether it has just copied. +struct CopyButton: View { + let text: String + @ViewBuilder let label: (_ copied: Bool) -> Label + @State private var copied = false + + /// How long it says it has copied. + private static var copiedFeedback: Duration { .seconds(2) } + + var body: some View { + Button { + UIPasteboard.general.string = text + copied = true + } label: { + label(copied) + } + .task(id: copied) { + guard copied else { return } + try? await Task.sleep(for: Self.copiedFeedback) + if !Task.isCancelled { copied = false } + } + .onChange(of: text) { copied = false } + } +} diff --git a/apps/ios/Sugabots/Settings/SettingsRoutes.swift b/apps/ios/Sugabots/Settings/SettingsRoutes.swift new file mode 100644 index 000000000..4e3574730 --- /dev/null +++ b/apps/ios/Sugabots/Settings/SettingsRoutes.swift @@ -0,0 +1,124 @@ +import SwiftUI + +/// A settings page, as the web's `/settings/…` and `/you/…` paths name them. +enum SettingsPlace: Hashable { + /// `/settings/profile`: your name, theme, invite link and Sign out. + case profile + /// `/settings/notifications`. + case notifications + /// `/settings/$section` for one of the workspace's sections. + case workspace(WorkspaceSection) + /// `/settings/members/$member`, by the membership's id. + case member(id: String) + /// `/settings/providers/$provider`. + case provider(id: String) + /// `/settings/providers/default`: the model new bots start on. + case defaultModel + /// `/settings/providers/system`: the model summaries are written with. + case systemModel + /// `/you/pods/$pod`: a pod's parts, as You lists them. + case pod(Pod) + /// `/settings/pods/$pod/$page`. + case podPage(Pod, PodSettingsPage) + /// `/settings/pods/$pod/connections/$connection`. + case connection(Pod, Connection) + /// `/settings/pods/$pod/agents/$agent`. + case agent(Pod, Agent) +} + +/// The workspace's sections, as `workspaceSettingSections`, with what each needs. +enum WorkspaceSection: String, CaseIterable, Hashable { + case general, members, providers, sandboxes, search, usage + + var label: String { + switch self { + case .general: "General" + case .members: "People" + case .providers: "Models" + case .sandboxes: "Computers" + case .search: "Web search" + case .usage: "Usage" + } + } + + func allowed(by permissions: WorkspacePermissions) -> Bool { + switch self { + case .general, .members: true + case .providers, .sandboxes, .search: permissions.manageProviders + case .usage: permissions.manageUsage + } + } + + /// What the section says to somebody it isn't `allowed(by:)`. + var barredNotice: String { + switch self { + case .general, .members: "" + case .providers: "Only workspace administrators can manage models." + case .sandboxes: "Only workspace administrators can manage computers." + case .search: "Only workspace administrators can manage web search." + case .usage: "Only workspace administrators can see what the workspace spends." + } + } +} + +/// The page a `SettingsPlace` opens. +struct SettingsDestination: View { + let place: SettingsPlace + + var body: some View { + switch place { + case .profile: ProfileSettingsScreen() + case .notifications: NotificationsSettingsScreen() + case let .workspace(section): WorkspaceSectionScreen(section: section) + case let .member(id): MemberSettingsScreen(memberId: id) + case let .provider(id): ProviderSettingsScreen(providerId: id) + case .defaultModel: DefaultModelSettingsScreen() + case .systemModel: SystemModelSettingsScreen() + case let .pod(pod): YouPodScreen(pod: pod) + case let .podPage(pod, page): PodPageScreen(pod: pod, page: page) + case let .connection(pod, connection): ConnectionSettingsScreen(pod: pod, listedConnection: connection) + case let .agent(pod, agent): AgentSettingsScreen(pod: pod, listedAgent: agent) + } + } +} + +/// A pod's settings as its name on Home opens them, as `/settings/pods/$pod`: +/// its General, or a Personal pod's Connections, which has none. +struct PodSettingsScreen: View { + let pod: Pod + + var body: some View { + PodPageScreen(pod: pod, page: pod.kind == .personal ? .connections : .general) + } +} + +/// A workspace section's page, or, once your permissions are known and don't +/// allow it, why it can't be seen, as `WorkspaceSettings` decides. +@MainActor +struct WorkspaceSectionScreen: View { + let section: WorkspaceSection + @Environment(WorkspaceStore.self) private var store + + var body: some View { + Group { + if let permissions = store.permissions, !section.allowed(by: permissions) { + SettingsPage(title: section.label) { FormAlert(text: section.barredNotice) } + } else { + page + } + } + .task { await store.refreshAccess() } + } + + @ViewBuilder + private var page: some View { + switch section { + case .general: GeneralSettingsScreen() + case .members: MembersSettingsScreen() + case .providers: ModelsSettingsScreen() + case .sandboxes: SandboxSettingsScreen() + case .search: WebSearchSettingsScreen() + case .usage: UsageSettingsScreen() + } + } +} diff --git a/apps/ios/Sugabots/Settings/SettingsRules.swift b/apps/ios/Sugabots/Settings/SettingsRules.swift new file mode 100644 index 000000000..7c25be58e --- /dev/null +++ b/apps/ios/Sugabots/Settings/SettingsRules.swift @@ -0,0 +1,299 @@ +import Foundation + +// The settings pages' rules, copied from the web's model-provider, connection, +// member, usage and pod-settings helpers. + +// MARK: Model providers + +/// What a provider from the catalog needs before bots can use it, as the catalog's `credential` names it. +enum ProviderCredential: String { + /// A key, required. + case apiKey = "api-key" + /// A key only if its server was started with one. + case optional + /// A sign-in to somebody's plan, such as ChatGPT's. + case signIn = "sign-in" +} + +/// Where a provider from the catalog runs, as the catalog's `hosting` names it. +enum ProviderHosting: String { + /// On the provider's own servers. + case remote + /// On a machine of the workspace's own. + case local +} + +extension ProviderPreset { + /// What `credential` names, or nil for a kind this app doesn't know. + var credentialKind: ProviderCredential? { ProviderCredential(rawValue: credential) } + /// What `hosting` names, or nil for a kind this app doesn't know. + var hostingKind: ProviderHosting? { ProviderHosting(rawValue: hosting) } + /// The service a provider made from it signs in to, when it is paid for by a plan rather than a key. + var signInService: String? { credentialKind == .signIn ? signIn : nil } +} + +extension ProviderModel: Identifiable { + var name: String { displayName ?? modelId } + /// As `effectiveCapabilities`: what it can do, less what has been switched off. + var effectiveCapabilities: [ProviderModelCapability] { capabilities.filter { !disabledCapabilities.contains($0) } } + /// Whether a bot can think with it: on, and not only for embeddings. + var choosable: Bool { enabled && !effectiveCapabilities.contains(.embeddings) } + /// As `makerOf`: `meta-llama` of `meta-llama/llama-3`. + var maker: String? { + guard let slash = modelId.firstIndex(of: "/"), slash != modelId.startIndex else { return nil } + return String(modelId[.. String { + let holders = newBots && systemBots ? "New bots and system agents use" : newBots ? "New bots use" : "System agents use" + return "\(holders) \(subject). Choose another model for them under Models → Default first." + } + + /// Who must keep running on any of `modelIds`, all together, or nil when none is held. + /// `defaultModel` is what new bots start on, and `systemModels` what each system bot runs on. + static func of(_ modelIds: [String], defaultModel: String?, systemModels: [String?]) -> ModelHolders? { + let newBots = modelIds.contains { $0 == defaultModel } + let systemBots = modelIds.contains { id in systemModels.contains(id) } + return newBots || systemBots ? ModelHolders(newBots: newBots, systemBots: systemBots) : nil + } +} + +/// What to say when `parseProviderBaseURL` can't read a typed address. +let notAServerAddress = "That is not a server address. A host and port, like 192.168.1.10:11434, is enough." + +/// As `parseProviderBaseUrl`: `typed` as a server's base URL, or nil if it isn't one. +/// A bare host and port is given `http://` and the OpenAI-compatible path. +func parseProviderBaseURL(_ typed: String) -> String? { + let trimmed = typed.trimmingCharacters(in: .whitespaces) + guard !trimmed.isEmpty else { return nil } + let withScheme = trimmed.range(of: "^[a-z][a-z0-9+.-]*://", options: [.regularExpression, .caseInsensitive]) != nil ? trimmed : "http://\(trimmed)" + guard var components = URLComponents(string: withScheme), let scheme = components.scheme?.lowercased(), + scheme == "http" || scheme == "https", components.host?.isEmpty == false + else { return nil } + if components.path.isEmpty || components.path == "/" { components.path = ProviderPreset.openAICompatiblePath } + guard let url = components.string else { return nil } + return url.hasSuffix("/") ? String(url.dropLast()) : url +} + +/// The providers Models lists, as the web's `ModelsSettings` orders them. +struct ProviderListing { + /// As `POPULAR_PRESETS`: the providers most people connect, listed whether or not they are. + static let popularPresets: [ProviderPresetId] = [.openrouter, .anthropic, .openai, .gemini] + + /// What is connected: the popular providers holding their key or sign-in, in + /// their order, then any other connected provider and every custom one. + let connected: [ModelProvider] + /// The popular providers still to connect, each offered Connect. + let toConnect: [ProviderPresetId] + + /// The listing of `providers`, or with nil, while they load, nothing: a + /// popular provider would read Not connected whether it is or not. + init(_ providers: [ModelProvider]?) { + guard let providers else { + connected = [] + toConnect = [] + return + } + let withCredential = { (preset: ProviderPresetId) in + providers.first { $0.preset == preset && !$0.lacksCredential } + } + let others = providers.filter { provider in + guard let preset = provider.preset else { return true } + return !Self.popularPresets.contains(preset) && provider.connected + } + connected = Self.popularPresets.compactMap(withCredential) + others + toConnect = Self.popularPresets.filter { withCredential($0) == nil } + } +} + +// MARK: Connections + +extension ConnectionToolSetting { + /// As `connectionToolMutating`: whether the tool may make changes, which any not known to only read may. + var mutating: Bool { readOnly != true } +} + +/// A connection's tools of one kind, those that read or those that make changes, +/// with the access most of them have, as `toolKinds`. +struct ToolKind { + enum Kind: String, Decodable { + case read, change + } + + let kind: Kind + let tools: [ConnectionToolSetting] + /// What most of `tools` are set to: the group's setting, which a tool set apart differs from. + let setting: ConnectionAccess + + var heading: String { kind == .read ? "Tools that read" : "Tools that make changes" } + var sub: String { kind == .read ? "Look things up without changing anything" : "Create, edit, delete or send things" } + var all: String { + let count = tools.count + return kind == .read ? "All \(count) read \(count == 1 ? "tool" : "tools")" : "All \(count) change \(count == 1 ? "tool" : "tools")" + } + + /// The tools that only read, then those that may make changes, leaving out an empty kind. + static func of(_ tools: [ConnectionToolSetting]) -> [ToolKind] { + [(Kind.read, tools.filter { !$0.mutating }), (.change, tools.filter(\.mutating))].compactMap { kind, ofKind in + ofKind.isEmpty ? nil : ToolKind(kind: kind, tools: ofKind, setting: setting(of: ofKind, kind: kind)) + } + } + + /// As `settingOf`: the access most of `tools` have, leaning to allow for reading and ask for changing when tied. + static func setting(of tools: [ConnectionToolSetting], kind: Kind) -> ConnectionAccess { + let count = { (access: ConnectionAccess) in tools.filter { $0.access == access }.count } + let leaning: ConnectionAccess = kind == .read ? .allow : .ask + return [ConnectionAccess.allow, .ask, .off].reduce(leaning) { best, access in count(access) > count(best) ? access : best } + } + + /// Each tool of `kinds` set apart from its group, with its group's setting. + static func setApart(_ kinds: [ToolKind]) -> [(tool: ConnectionToolSetting, setting: ConnectionAccess)] { + kinds.flatMap { kind in kind.tools.filter { $0.access != kind.setting }.map { ($0, kind.setting) } } + } +} + +// MARK: People + +extension WorkspaceMember { + /// As the web's `mayManageThem`: whether somebody with `permissions`, signed in + /// as `viewerId`, may change this member's role or remove them. Nobody changes + /// their own role, since demoting yourself takes away the control you'd need to + /// undo it; the owner's changes only by their handing ownership on; and an + /// admin is managed only by those who may manage admins. + func isManageable(withPermissions permissions: WorkspacePermissions?, byUser viewerId: String) -> Bool { + guard let permissions, permissions.manageMembers, user.id != viewerId, role != .owner else { return false } + return role != .admin || permissions.manageAdmins + } +} + +extension WorkspaceInvitation { + private static let secondsPerDay: TimeInterval = 86_400 + + /// As the web's `expiryText`: whole days left at `now`, so one with a day and a half to go says one day. + func expiryText(at now: Date) -> String { + let left = expiresAt.timeIntervalSince(now) + if left <= 0 { return "Expired" } + let days = Int(left / Self.secondsPerDay) + if days == 0 { return "Expires within a day" } + return days == 1 ? "Expires in 1 day" : "Expires in \(days) days" + } +} + +// MARK: Usage + +/// A calendar month, which usage is asked for and stepped through by, as the API's `UsageMonth`. +struct YearMonth: Hashable, Comparable { + let year: Int + /// 1 for January to 12 for December. + let month: Int + + init(year: Int, month: Int) { + self.year = year + self.month = month + } + + /// The month `text` names as `YYYY-MM`, or nil if it names none. + init?(_ text: String) { + let parts = text.split(separator: "-") + guard parts.count == 2, let year = Int(parts[0]), let month = Int(parts[1]), (1...12).contains(month) else { return nil } + self.init(year: year, month: month) + } + + /// The month `date` falls in, in `zone`. + static func containing(_ date: Date, in zone: TimeZone) -> YearMonth { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = zone + let parts = calendar.dateComponents([.year, .month], from: date) + return YearMonth(year: parts.year ?? 0, month: parts.month ?? 1) + } + + /// As the API writes it: `2026-09`. + var text: String { String(format: "%04d-%02d", year, month) } + + /// As `shiftMonth`: the month `months` after this one, or before it for a negative `months`. + func shifted(by months: Int) -> YearMonth { + let index = year * 12 + (month - 1) + months + let (shiftedYear, monthIndex) = (index.quotientAndRemainder(dividingBy: 12)) + return monthIndex < 0 ? YearMonth(year: shiftedYear - 1, month: monthIndex + 13) : YearMonth(year: shiftedYear, month: monthIndex + 1) + } + + static func < (left: YearMonth, right: YearMonth) -> Bool { + (left.year, left.month) < (right.year, right.month) + } +} + +// MARK: Pods + +/// How many bots a pod has, and how many people once they're known, as "2 bots, 1 person". +func podSummary(bots: Int, people: Int?) -> String { + ["\(bots) \(bots == 1 ? "bot" : "bots")", people.map { "\($0) \($0 == 1 ? "person" : "people")" }].compactMap { $0 }.joined(separator: ", ") +} + +/// A pod's settings pages, as `podSettingsPages`. +enum PodSettingsPage: String, CaseIterable, Hashable { + case general, connections, people, bots, computer + + var label: String { + switch self { + case .general: "General" + case .connections: "Connections" + case .people: "People" + case .bots: "Bots" + case .computer: "Computer" + } + } + + /// The pages a pod of `kind` has, as `podHasSettingsPage` reads them: a + /// Personal pod is only ever yours, so it has no General or People. Computer + /// is counted in, since its page says when the workspace's computers are off. + static func pages(for kind: Pod.Kind) -> [PodSettingsPage] { + allCases.filter { page in !(kind == .personal && (page == .general || page == .people)) } + } + + /// As `podSettingsPagesOf`: the pages listed for a pod of `kind`, which leave + /// out Computer unless `computersEnabled` says the workspace has computers. + static func pages(for kind: Pod.Kind, computersEnabled: Bool) -> [PodSettingsPage] { + pages(for: kind).filter { computersEnabled || $0 != .computer } + } +} diff --git a/apps/ios/Sugabots/Settings/UsageSettings.swift b/apps/ios/Sugabots/Settings/UsageSettings.swift new file mode 100644 index 000000000..a61eef8ec --- /dev/null +++ b/apps/ios/Sugabots/Settings/UsageSettings.swift @@ -0,0 +1,353 @@ +import SwiftUI + +/// Usage, as the web's `UsageSettings`: the month's spend with a bar for each +/// day and a stepper between months, then a breakdown by bot, model or pod. +/// Stepping keeps the last month shown, dimmed, until the next arrives. +@MainActor +struct UsageSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var usage: WorkspaceUsage? + /// The month shown, once the workspace's clock says which is this one. + @State private var month: YearMonth? + @State private var thisMonth: YearMonth? + @State private var timeZone = TimeZone.gmt + @State private var stale = false + @State private var failure: String? + + var body: some View { + SettingsPage(title: "Usage", description: "What bots have cost so far this month.") { + if let usage, let month, let thisMonth { + SpendSummary(usage: usage, today: Self.day(.now, in: timeZone), stale: stale, month: month, latest: thisMonth) { self.month = month.shifted(by: $0) } + .padding(.top, -8) + if let failure { FormAlert(text: failure) } + Breakdown(usage: usage, stale: stale) + } else if let failure { + FormAlert(text: failure) + } else { + Color.clear + .frame(height: 228) + .settingsCard() + } + } + .task { await start() } + .task(id: month) { + guard let month else { return } + await load(month) + } + } + + /// Finds which month is this one on the workspace's clock, and shows it. + private func start() async { + if let record = try? await store.workspaceRecord(), let zone = TimeZone(identifier: record.timeZone) { timeZone = zone } + let current = YearMonth.containing(.now, in: timeZone) + thisMonth = current + month = current + } + + /// Loads `month`'s usage; one stepped away from before it arrives is dropped. + private func load(_ month: YearMonth) async { + stale = usage != nil + do { + let loaded = try await store.client.usage.month(workspace: store.workspace.id, month: month.text) + guard !Task.isCancelled else { return } + usage = loaded + failure = nil + stale = false + } catch { + guard !Task.isCancelled else { return } + // What was shown stays, dimmed, under what failed. + failure = error.localizedDescription + } + } + + /// The date in `zone` as `YYYY-MM-DD`. + static func day(_ date: Date, in zone: TimeZone) -> String { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = zone + let parts = calendar.dateComponents([.year, .month, .day], from: date) + return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0) + } +} + +/// How usage writes amounts, months and days, as `lib/usage.ts`. +private enum UsageFormat { + private static let dollars: NumberFormatter = { + let formatter = NumberFormatter() + formatter.numberStyle = .currency + formatter.currencyCode = "USD" + formatter.locale = Locale(identifier: "en_US") + return formatter + }() + + /// As `formatUsd`: under half a cent is `<$0.01`. + static func usd(_ usd: Double) -> String { + if usd > 0, usd < 0.005 { return "<\(dollars.string(from: 0.01) ?? "$0.01")" } + return dollars.string(from: NSNumber(value: usd)) ?? "$\(usd)" + } + + private static func first(of month: YearMonth) -> Date { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .gmt + return calendar.date(from: DateComponents(year: month.year, month: month.month, day: 1)) ?? .now + } + + private static func monthName(_ month: YearMonth, _ format: Date.FormatStyle.Symbol.Month) -> String { + first(of: month).formatted(Date.FormatStyle(timeZone: .gmt).month(format)) + } + + /// As `monthLabel`: `Oct 2026`. + static func month(_ month: YearMonth) -> String { "\(monthName(month, .abbreviated)) \(month.year)" } + /// As `longMonthLabel`: `October 2026`, or as the API wrote it if it names no month. + static func longMonth(_ text: String) -> String { + guard let month = YearMonth(text) else { return text } + return "\(monthName(month, .wide)) \(month.year)" + } + /// As `dayLabel`: `30 Oct`, for a `YYYY-MM-DD` date. + static func day(_ date: String) -> String { + guard let month = YearMonth(String(date.prefix(7))) else { return date } + return "\(Int(date.dropFirst(8).prefix(2)) ?? 0) \(monthName(month, .abbreviated))" + } +} + +/// The month's total over a bar for each day, as `SpendSummary`. +private struct SpendSummary: View { + let usage: WorkspaceUsage + let today: String + let stale: Bool + let month: YearMonth + let latest: YearMonth + let step: (Int) -> Void + @State private var openDate: String? + + var body: some View { + VStack(alignment: .leading, spacing: 20) { + HStack(spacing: 12) { + Text(UsageFormat.usd(usage.usd)) + .font(Typeface.rubik(32, .semibold)) + .tracking(-0.96) + .monospacedDigit() + .foregroundStyle(Palette.foreground) + .opacity(stale ? 0.4 : 1) + .frame(maxWidth: .infinity, alignment: .leading) + HStack(spacing: 4) { + stepButton(.chevronLeft, label: "Previous month") { step(-1) } + Text(UsageFormat.month(month)) + .font(Typeface.rubik(13, .medium)) + .foregroundStyle(Palette.foreground) + .frame(minWidth: 72) + stepButton(.chevronRight, label: "Next month") { step(1) }.disabled(month >= latest) + } + } + VStack(spacing: 8) { + dailySpend + if let first = usage.days.first, let last = usage.days.last { + HStack { + Text(UsageFormat.day(first.date)) + Spacer() + Text(UsageFormat.day(last.date)) + } + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .accessibilityHidden(true) + } + } + .opacity(stale ? 0.4 : 1) + } + .padding(20) + .settingsCard() + .animation(.easeOut(duration: 0.15), value: stale) + } + + private func stepButton(_ icon: Lucide, label: String, action: @escaping () -> Void) -> some View { + Button(action: action) { Icon(icon, size: 14, strokeWidth: 2).frame(width: 24, height: 24).contentShape(Circle()) } + .buttonStyle(IconPressStyle()) + .accessibilityLabel(label) + } + + /// A bar for each day, as tall as its share of the busiest day's; a tap shows its spend above it. + private var dailySpend: some View { + let busiest = usage.days.map(\.usd).max() ?? 0 + return HStack(alignment: .bottom, spacing: 0) { + ForEach(usage.days, id: \.date) { day in + GeometryReader { geometry in + VStack(spacing: 0) { + Spacer(minLength: 0) + if day.date > today { + RoundedRectangle(cornerRadius: 3).fill(Palette.chip).frame(height: 2) + } else { + RoundedRectangle(cornerRadius: 3) + .fill(day.date == today ? Palette.usageBarToday : Palette.usageBar) + .frame(height: max(2, busiest == 0 ? 2 : geometry.size.height * day.usd / busiest)) + } + } + .frame(maxWidth: .infinity) + .background(openDate == day.date ? Palette.chip : .clear, in: RoundedRectangle(cornerRadius: 3)) + } + .padding(.horizontal, 1.5) + .contentShape(Rectangle()) + .onTapGesture { if day.date <= today { openDate = openDate == day.date ? nil : day.date } } + .overlay(alignment: .top) { + if openDate == day.date { + VStack(spacing: 0) { + Text(UsageFormat.usd(day.usd)).font(Typeface.rubik(12, .semibold)).monospacedDigit() + Text(UsageFormat.day(day.date)).font(Typeface.rubik(12)).opacity(0.7) + } + .foregroundStyle(Palette.background) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(Palette.foreground, in: RoundedRectangle(cornerRadius: 6)) + .fixedSize() + .offset(y: -44) + } + } + .accessibilityElement() + .accessibilityLabel("\(UsageFormat.day(day.date)): \(UsageFormat.usd(day.usd))") + } + } + .frame(height: 96) + .padding(.horizontal, -1.5) + .accessibilityElement(children: .contain) + .accessibilityLabel(busiest > 0 ? "Spend each day. The most was \(UsageFormat.usd(busiest))." : "Spend each day. Nothing was spent.") + } +} + +/// What the month went on, by bot, model or pod, each with a bar of its share, as `Breakdown`. +private struct Breakdown: View { + /// What the month's spend is grouped by. + enum Grouping: Hashable { + case bot, model, pod + } + + struct Line: Identifiable { + let id: String + let icon: AnyView + let label: String + let sub: String + let color: Color + let usd: Double + let unpricedRequests: Int + } + + let usage: WorkspaceUsage + let stale: Bool + @State private var grouping = Grouping.bot + + var body: some View { + let lines = lines(for: grouping) + let largest = lines.map(\.usd).max() ?? 0 + SettingsGroup(label: "Breakdown", note: Self.footnote(usage.unpricedRequests)) { + SegmentedChoice(label: "Break the month down by", options: [(Grouping.bot, "Bot"), (.model, "Model"), (.pod, "Pod")], value: grouping) { grouping = $0 } + } content: { + if lines.isEmpty { + Text("Nothing was spent in \(UsageFormat.longMonth(usage.month)).") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + .frame(maxWidth: .infinity) + .padding(.vertical, 24) + } else { + DividedRows(data: lines) { line in + row(line, largest: largest) + } + .opacity(stale ? 0.4 : 1) + } + } + } + + private func row(_ line: Line, largest: Double) -> some View { + let unknown = line.usd == 0 && line.unpricedRequests > 0 + return HStack(spacing: 12) { + HStack(spacing: 12) { + line.icon.accessibilityHidden(true) + VStack(alignment: .leading, spacing: 1) { + Text(line.label).font(Typeface.rubik(13)).foregroundStyle(Palette.foreground).lineLimit(1) + Text(line.sub).font(Typeface.rubik(12)).foregroundStyle(Palette.subtleForeground).lineLimit(1) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .layoutPriority(1.4) + GeometryReader { geometry in + Capsule().fill(Palette.chipStrong) + .overlay(alignment: .leading) { + Capsule().fill(line.color).frame(width: largest > 0 ? geometry.size.width * line.usd / largest : 0) + } + } + .frame(minWidth: 40) + .frame(height: 4) + .accessibilityHidden(true) + Text(unknown ? "—" : UsageFormat.usd(line.usd)) + .font(Typeface.rubik(13)) + .monospacedDigit() + .foregroundStyle(Palette.foreground) + .frame(width: 72, alignment: .trailing) + .accessibilityLabel(unknown ? "Not priced" : UsageFormat.usd(line.usd)) + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + .frame(minHeight: 56) + } + + private func lines(for grouping: Grouping) -> [Line] { + let neutral = Palette.subtleForeground + let systemAgents = Line( + id: "system-agents", icon: AnyView(LetterTile(name: "System agents")), label: "System agents", + sub: "Summaries, titles, routing, compaction, model tests", color: neutral, + usd: usage.systemAgents.usd, unpricedRequests: usage.systemAgents.unpricedRequests + ) + let withSystemAgents = { (lines: [Line]) in + usage.systemAgents.usd > 0 || usage.systemAgents.unpricedRequests > 0 ? lines + [systemAgents] : lines + } + switch grouping { + case .bot: + return withSystemAgents(usage.bots.map { bot in + let face = bot.face ?? .pill + let shape = bot.shape ?? .circle + let icon: AnyView = bot.color.map { color in AnyView(BotFace(look: BotLook(color: color, face: face, shape: shape), size: 24)) } + ?? AnyView(LetterTile(name: bot.name ?? "Deleted bot")) + return Line( + id: bot.agentId, icon: icon, label: bot.name ?? "Deleted bot", sub: bot.podName ?? "No pod", + color: bot.color.map { BotLooks.palette(for: $0).face } ?? neutral, usd: bot.usd, unpricedRequests: bot.unpricedRequests + ) + }) + case .model: + let providerOf = { (model: ModelUsage) in model.preset?.rawValue ?? model.providerName ?? "removed" } + let order = usage.models.map(providerOf).reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } } + return usage.models.map { model in + let providerName = model.providerName ?? ProviderPreset.named(model.preset?.rawValue)?.name ?? "Removed provider" + let hue = WorkspaceUsage.providerHues[(order.firstIndex(of: providerOf(model)) ?? 0) % WorkspaceUsage.providerHues.count] + return Line( + id: "\(model.model):\(model.providerName ?? "")", icon: AnyView(ProviderTile(name: providerName, preset: model.preset?.rawValue)), + label: model.displayName ?? model.model, sub: providerName, + color: BotLooks.pods[hue]?.swatch ?? neutral, usd: model.usd, unpricedRequests: model.unpricedRequests + ) + } + case .pod: + return withSystemAgents(usage.pods.map { pod in + let label = pod.name ?? "Deleted pod" + return Line( + id: pod.podId, icon: AnyView(LetterTile(name: label)), label: label, + sub: "\(pod.botCount) \(pod.botCount == 1 ? "bot" : "bots")", + color: pod.color.flatMap { BotLooks.pods[$0.rawValue]?.swatch } ?? neutral, usd: pod.usd, unpricedRequests: pod.unpricedRequests + ) + }) + } + } + + /// As `footnote`. + private static func footnote(_ unpriced: Int) -> String { + let note = unpriced == 0 ? "" : " \(unpriced) \(unpriced == 1 ? "request" : "requests") couldn't be priced and \(unpriced == 1 ? "isn't" : "aren't") included." + return "Estimated from each provider's published prices.\(note) Your provider bills you directly." + } +} + +/// A name's initial on a chip, as Usage's `LetterTile`. +private struct LetterTile: View { + let name: String + + var body: some View { + Text(name.trimmingCharacters(in: .whitespaces).prefix(1).uppercased()) + .font(Typeface.rubik(11, .semibold)) + .foregroundStyle(Palette.mutedForeground) + .frame(width: 24, height: 24) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) + } +} diff --git a/apps/ios/Sugabots/Settings/WebSearchSettings.swift b/apps/ios/Sugabots/Settings/WebSearchSettings.swift new file mode 100644 index 000000000..555a6a25a --- /dev/null +++ b/apps/ios/Sugabots/Settings/WebSearchSettings.swift @@ -0,0 +1,193 @@ +import SwiftUI + +extension SearchPreset { + static func named(_ id: SearchProviderPresetId) -> SearchPreset { catalog.first { $0.id == id.rawValue } ?? catalog[0] } + + /// The provider this preset makes, as the API names it. + var presetId: SearchProviderPresetId { SearchProviderPresetId(rawValue: id) } + + /// As `keyHint`. + var keyHint: String { + if presetId == .exa { return "A key is optional. Without one, searches use Exa's free tier, which is rate limited." } + return requiresApiKey ? "A key is required." : "A key is optional." + } +} + +/// A change to the search provider: what is left nil, or kept, stays as it is. +private struct SearchProviderChange { + var enabled: Bool? + var baseUrl: String? + var apiKey = FieldChange.keep +} + +/// Web search, as the web's `WebSearchSettings`: the switch, then under +/// Show advanced, the provider and its key or address, and a test search. +@MainActor +struct WebSearchSettingsScreen: View { + @Environment(WorkspaceStore.self) private var store + /// The workspace's search provider, which is none until one is set up. + @State private var provider: Loadable = .loading + @State private var advancedOpen: Bool? + @State private var action = SettingsAction() + @State private var tested: TestResult? + @State private var removingKey = false + + var body: some View { + SettingsPage(title: "Web search", description: "Lets bots look things up and cite the pages they used.") { + switch provider { + case .loading: EmptyView() + case let .failed(failure): FormAlert(text: failure) + case let .loaded(provider): groups(provider) + } + } + .task { await load() } + } + + @ViewBuilder + private func groups(_ provider: SearchProvider?) -> some View { + let chosen = provider?.preset ?? SearchProviderPresetId(rawValue: SearchPreset.defaultId) + let preset = SearchPreset.named(chosen) + let needsKey = preset.requiresApiKey && provider?.hasApiKey != true + let enabled = provider?.enabled ?? false + // Opened for you when the switch is held off by a missing key, so the reason is in view. + let open = advancedOpen ?? needsKey + SettingsGroup(note: needsKey ? "\(preset.name) needs an API key first. Add it below." : nil) { + SettingsRow(label: "Bots can use the web", sub: "Search the web and read web pages", trailing: { + WebToggle(label: "Bots can use the web", isOn: enabled) { on in + action.run { try await configure(SearchProviderChange(enabled: on), provider: provider, chosen: chosen) } + } + .disabled(needsKey || action.pending) + }) + } + VStack(alignment: .leading, spacing: 28) { + Button(open ? "Hide advanced" : "Show advanced") { advancedOpen = !open } + .buttonStyle(WebButtonStyle(variant: .secondary, size: .small)) + if open { + providerChoice(chosen: chosen, enabled: enabled) + providerSettings(preset, provider: provider) + } + } + .padding(.top, -12) + if let failure = action.failure { FormAlert(text: failure) } + } + + private func providerChoice(chosen: SearchProviderPresetId, enabled: Bool) -> some View { + SettingsGroup(label: "Provider") { + DividedRows(data: SearchPreset.catalog, id: \.id) { candidate in + SettingsRadioRow(name: candidate.name, description: candidate.description, checked: candidate.presetId == chosen) { + choose(candidate, chosen: chosen, enabled: enabled) + } + .disabled(action.pending) + } + } + } + + @ViewBuilder + private func providerSettings(_ preset: SearchPreset, provider: SearchProvider?) -> some View { + let hasKey = provider?.hasApiKey == true + let save = { (change: SearchProviderChange) in + try await action.perform { try await configure(change, provider: provider, chosen: preset.presetId) } + } + VStack(alignment: .leading, spacing: 0) { + SettingsGroup(label: preset.name) { + if preset.local { + TextEntryRow(label: "Server URL", value: .text(saved: provider?.baseUrl ?? preset.baseUrl), placeholder: preset.baseUrl) { url in + try await save(SearchProviderChange(baseUrl: url)) + } + SettingsDivider() + } + TextEntryRow( + label: "API key", + value: .secret(isSaved: hasKey), + placeholder: "Paste your key", + save: { key in try await save(SearchProviderChange(apiKey: .set(key))) }, + remove: hasKey ? { removingKey = true } : nil + ) + if provider != nil, hasKey || !preset.requiresApiKey { + SettingsDivider() + Button(action: test) { SettingsRow(label: "Test search", sub: "Runs one search with these settings.") } + .buttonStyle(SettingsRowPressStyle()) + } + } + .disabled(action.pending) + standing(preset, provider: provider).padding(.horizontal, 2).padding(.top, 10) + } + .confirmDelete( + isPresented: $removingKey, + title: "Remove the \(preset.name) key?", + description: preset.requiresApiKey ? "Bots stop using the web until another key is added." : "Searches carry on without a key, within the provider's free limits.", + confirmLabel: "Remove" + ) { + try await configure(SearchProviderChange(apiKey: .clear), provider: provider, chosen: preset.presetId) + } + } + + /// How the last test went, or what a key is for, as `testStanding` and `keyHint`. + @ViewBuilder + private func standing(_ preset: SearchPreset, provider: SearchProvider?) -> some View { + if let tested { + TestResultLine(result: tested) + } else if provider?.status == .connected { + note("The last test search worked.") + } else if provider?.status == .error { + FormAlert(text: provider?.lastTestError ?? "The last test search failed.") + } else { + note(preset.keyHint) + } + } + + private func note(_ text: String) -> some View { + Text(text).font(Typeface.rubik(13)).lineSpacing(3).foregroundStyle(Palette.subtleForeground) + } + + // MARK: Doing + + private func load() async { + let loaded: Loadable = await .of { try await store.client.searchProviders.get(workspace: store.workspace.id).provider } + // A failed reload keeps the settings shown, with what failed under them. + if case let .failed(failure) = loaded, provider.value != nil { + action.failure = failure + } else { + provider = loaded + } + } + + private func choose(_ next: SearchPreset, chosen: SearchProviderPresetId, enabled: Bool) { + guard next.presetId != chosen else { return } + tested = nil + action.run { + _ = try await store.client.searchProviders.replace( + workspace: store.workspace.id, preset: next.presetId, enabled: enabled && !next.requiresApiKey + ) + await load() + } + } + + /// Changes the provider, setting one up first if there's none yet, then + /// reloads it. What a test found no longer holds after a change, so it goes. + private func configure(_ change: SearchProviderChange, provider: SearchProvider?, chosen: SearchProviderPresetId) async throws { + let routes = store.client.searchProviders + if provider != nil { + _ = try await routes.update(workspace: store.workspace.id, enabled: change.enabled, baseUrl: change.baseUrl, apiKey: change.apiKey.apiValue) + } else { + let apiKey: String? = if case let .set(key) = change.apiKey { key } else { nil } + _ = try await routes.replace( + workspace: store.workspace.id, + preset: chosen, + enabled: change.enabled ?? false, + apiKey: apiKey, + baseUrl: change.baseUrl + ) + } + tested = nil + await load() + } + + private func test() { + action.run { + let result = try await store.client.searchProviders.test(workspace: store.workspace.id) + tested = TestResult(passed: result.reachable, text: result.reachable ? "Search works" : result.error ?? "The search did not work.") + await load() + } + } +} diff --git a/apps/ios/Sugabots/SignIn/SignInScreen.swift b/apps/ios/Sugabots/SignIn/SignInScreen.swift new file mode 100644 index 000000000..eefc34bb5 --- /dev/null +++ b/apps/ios/Sugabots/SignIn/SignInScreen.swift @@ -0,0 +1,595 @@ +import SwiftUI + +/// Signing in or making an account, as the web's `Login`: the welcome first, +/// then the email form, with Forgot password and Create an account under it. +/// Between them the app asks which workspace, as Slack does, since it isn't +/// opened at the workspace's own address the way the web is. +@MainActor +struct SignInScreen: View { + private enum Page { + case welcome + case workspace + case form + case forgotPassword + /// The address of an account that exists but hasn't been proven. + case unverified(String) + } + + @Environment(Session.self) private var session + @State private var page = Page.welcome + @State private var isNew = false + @State private var address = WorkspaceAddress(name: "", ending: WorkspaceAddress.hostedEnding) + + var body: some View { + Group { + switch page { + case .welcome: + Welcome { page = .workspace } + case .workspace: + WorkspaceStep(address: $address, onBack: { page = .welcome }) { page = .form } + case .form: + LogInForm(workspace: address.resolved, isNew: $isNew, onBack: { page = .workspace }, onForgot: { page = .forgotPassword }) { page = .unverified($0) } + case .forgotPassword: + ForgotPassword(server: address.server) { page = .form } + case let .unverified(email): + AuthLayout(title: "Check your email", subtitle: "Open the link sent to \(email) to finish signing in.") { + Button("Back") { page = .form }.buttonStyle(WebButtonStyle(variant: .secondary, size: .large, fullWidth: true)) + } + } + } + .background(Palette.background.ignoresSafeArea()) + .onAppear { + // The workspace signed in to last, so signing in again is only Continue. + if address.name.isEmpty, let server = session.server { address = WorkspaceAddress(server: server) } + #if DEBUG + // A development build opens the page `SUGABOTS_OPEN` names, to screenshot it. + switch DebugLaunch.target { + case .findWorkspace: page = .workspace + case .signIn: page = .form + case .signUp: + isNew = true + page = .form + case .forgotPassword: page = .forgotPassword + default: break + } + #endif + } + } +} + +/// A workspace's address as sign-in asks for it: its name, then the ending of +/// the address its server is under. A hosted workspace is `[name].sugabots.ai`; +/// a self-hosted server has its own ending, such as `.yourcompany.com`. +struct WorkspaceAddress: Equatable { + static let hostedEnding = NativeConstants.hostedWorkspaceEnding + + var name: String + var ending: String + + init(name: String, ending: String) { + self.name = name + self.ending = ending + } + + /// Split from a whole address, such as a saved server or one pasted into the + /// name: its first label is the name and the rest, with any port, the ending. + init(server: String) { + let withoutScheme = server.trimmingCharacters(in: .whitespaces).components(separatedBy: "://").last ?? "" + let host = withoutScheme.split(separator: "/", maxSplits: 1).first.map(String.init) ?? "" + guard let dot = host.firstIndex(of: ".") else { + self.init(name: host, ending: Self.hostedEnding) + return + } + self.init(name: String(host[.. Void + let onFound: () -> Void + @Environment(Session.self) private var session + @FocusState private var focused: Bool + @State private var selfHosted = false + /// A self-hosted server's whole address, as typed. + @State private var serverAddress = "" + @State private var checking = false + @State private var failure: String? + + var body: some View { + // From the top rather than centred, so the box and Continue stay clear of the keyboard it opens. + AuthLayout( + title: "Sign in to your workspace", + subtitle: selfHosted ? "Enter the address your team opens Sugabots at." : "Enter your workspace's Sugabots address.", + centred: false, + showsMark: true, + onBack: onBack + ) { + HStack(spacing: 10) { + field + if !selfHosted { + Text(WorkspaceAddress.hostedEnding) + .font(Typeface.rubik(19, .medium)) + .foregroundStyle(Palette.foreground) + .fixedSize() + .accessibilityHidden(true) + } + } + if let failure { FormAlert(text: failure) } + Button(action: check) { + HStack(spacing: 8) { + if checking { + ProgressView().tint(Palette.primaryForeground) + } else { + Text("Continue") + Image(systemName: "arrow.right").font(.system(size: 15, weight: .semibold)) + } + } + } + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(checking || chosen.name.isEmpty) + .padding(.top, 4) + switchLink + .frame(maxWidth: .infinity) + .padding(.top, 4) + } + .onAppear { + selfHosted = address.ending != WorkspaceAddress.hostedEnding + if selfHosted { serverAddress = address.host } + focused = true + } + } + + /// The box: the name before `.sugabots.ai`, or a self-hosted server's whole address. + private var field: some View { + Group { + if selfHosted { + TextField("", text: $serverAddress, prompt: Text(verbatim: "sugabots.yourcompany.com").foregroundStyle(Palette.subtleForeground)) + .accessibilityLabel("Server address") + } else { + TextField("", text: $address.name, prompt: Text(verbatim: "your-team").foregroundStyle(Palette.subtleForeground)) + // Up against `.sugabots.ai`, so the two read as one address. + .multilineTextAlignment(.trailing) + .accessibilityLabel("Workspace name, before \(WorkspaceAddress.hostedEnding)") + } + } + .focused($focused) + .font(Typeface.rubik(19, .medium)) + .foregroundStyle(Palette.foreground) + .keyboardType(.URL) + .textContentType(.URL) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .submitLabel(.continue) + .onSubmit(check) + .padding(.horizontal, 16) + .frame(height: 56) + .background(Palette.list, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .strokeBorder(focused ? Palette.ring : Palette.borderStrong, lineWidth: focused ? 1.5 : 1) + ) + .animation(.easeOut(duration: 0.15), value: focused) + } + + /// Between a workspace on Sugabots and a self-hosted server's address. + private var switchLink: some View { + HStack(spacing: 4) { + Text(selfHosted ? "On Sugabots?" : "Self-hosted?").foregroundStyle(Palette.mutedForeground) + Button(selfHosted ? "Enter your workspace's name" : "Enter your server's address") { + failure = nil + if selfHosted { + address = WorkspaceAddress(name: address.name, ending: WorkspaceAddress.hostedEnding) + } else { + serverAddress = address.name.isEmpty ? "" : address.host + } + selfHosted.toggle() + focused = true + } + .foregroundStyle(Palette.link) + } + .font(Typeface.rubik(14)) + } + + /// The workspace as typed in either box. + private var chosen: WorkspaceAddress { + selfHosted ? WorkspaceAddress(server: serverAddress) : address.resolved + } + + private func check() { + guard !checking else { return } + let workspace = chosen + guard !workspace.name.isEmpty else { + failure = selfHosted ? "Enter your server's address." : "Enter your workspace's name." + focused = true + return + } + focused = false + checking = true + failure = nil + Task { + do { + try await session.checkServer(workspace.server) + address = workspace + onFound() + } catch { + failure = error.localizedDescription + } + checking = false + } + } +} + +/// A workspace's mark while signing in, before its own look is known: the +/// first letter of its name on a tile, or a bot while nothing is typed. +private struct WorkspaceInitial: View { + let name: String + let size: CGFloat + + var body: some View { + Group { + if let letter = name.first { + Text(String(letter).uppercased()) + .font(Typeface.rubik(size * 0.47, .semibold)) + .foregroundStyle(Palette.foreground) + .frame(width: size, height: size) + .background(Palette.tile, in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)) + } else { + BotFace(look: BotLook(color: .yellow, face: .pill, shape: .squircle), size: size) + } + } + .accessibilityHidden(true) + .animation(.easeOut(duration: 0.15), value: name.first) + } +} + +/// The workspace a form signs in to, at its top: tapping it goes back to choose another. +private struct WorkspacePill: View { + let host: String + let name: String + let change: () -> Void + + var body: some View { + Button(action: change) { + HStack(spacing: 10) { + WorkspaceInitial(name: name, size: 26) + Text(host) + .font(Typeface.rubik(14, .medium)) + .foregroundStyle(Palette.foreground) + .lineLimit(1) + .truncationMode(.middle) + Text("Change") + .font(Typeface.rubik(13)) + .foregroundStyle(Palette.mutedForeground) + } + .padding(.leading, 6) + .padding(.trailing, 14) + .frame(height: 38) + .background(Palette.list, in: Capsule()) + .overlay(Capsule().strokeBorder(Palette.border)) + } + .buttonStyle(.plain) + .frame(maxWidth: .infinity) + .accessibilityLabel("Signing in to \(host)") + .accessibilityHint("Changes the workspace") + } +} + +/// The first thing somebody new sees: a crowd of bots, the welcome, and Continue with email. +private struct Welcome: View { + let onContinue: () -> Void + + /// A bot of each colour, each with its own eyes and a little up or down, as the design lines them up. + private static let crowd: [(color: AgentColor, face: AgentFace, drop: CGFloat)] = [ + (.rose, .dot, 12), (.yellow, .pill, -2), (.purple, .arc, 8), (.sky, .pill, -6), + (.green, .square, 10), (.orange, .wink, 2), (.ice, .arc, -4), (.teal, .dot, 8), + ] + + var body: some View { + VStack(spacing: 22) { + // As wide as the screen, the crowd cut off at its sides rather than widening the page. + // Out past the page's 16-point inset to the screen's edges, clipped there. + Color.clear + .frame(maxWidth: .infinity) + .frame(height: 52 + 2 * 12) + .overlay { + HStack(spacing: 12) { + ForEach(Self.crowd, id: \.color) { bot in + BotFace(look: BotLook(color: bot.color, face: bot.face, shape: .circle), size: 52).offset(y: bot.drop) + } + } + .fixedSize() + } + .clipped() + .padding(.horizontal, -16) + .padding(.bottom, 8) + .accessibilityHidden(true) + Text("Welcome to Sugabots") + .font(Typeface.rubik(30, .bold)) + .tracking(-0.6) + .foregroundStyle(Palette.foreground) + .accessibilityAddTraits(.isHeader) + Text("Bots that work alongside your team, in chats you already know how to use.") + .font(Typeface.rubik(15)) + .lineSpacing(4) + .foregroundStyle(Palette.mutedForeground) + Button("Continue with email", action: onContinue) + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .padding(.top, 8) + } + .multilineTextAlignment(.center) + .frame(maxWidth: 440) + .padding(.horizontal, 16) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +/// Logging in, or making an account. +@MainActor +private struct LogInForm: View { + /// Where this signs in, shown under the title, and whose server it asks. + let workspace: WorkspaceAddress + @Binding var isNew: Bool + let onBack: () -> Void + let onForgot: () -> Void + let onUnverified: (String) -> Void + @Environment(Session.self) private var session + @State private var name = "" + @State private var email = "" + @State private var password = "" + @State private var error: String? + @State private var busy = false + + /// The shortest password the server's sign-up takes: better-auth's default minimum, which the web's form also asks for. + private static let minPasswordCharacters = 8 + + var body: some View { + AuthLayout(title: isNew ? "Create an account" : "Log in", onBack: onBack) { + WorkspacePill(host: workspace.host, name: workspace.name, change: onBack) + .padding(.bottom, 10) + FormCard { + if isNew { + FormRow(label: "Name") { + TextField("", text: $name) + .textContentType(.name) + .authField() + } + } + FormRow(label: "Email") { + TextField("", text: $email, prompt: Text(verbatim: "you@company.com").foregroundStyle(Palette.mutedForeground)) + .textContentType(.emailAddress) + .keyboardType(.emailAddress) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .authField() + } + FormRow(label: "Password", last: true) { + SecureField("", text: $password, prompt: isNew ? Text("\(Self.minPasswordCharacters) characters or more").foregroundStyle(Palette.mutedForeground) : nil) + .textContentType(isNew ? .newPassword : .password) + .onSubmit(submit) + .authField() + } + } + if let error { FormAlert(text: error) } + Button(isNew ? "Create account" : "Log in", action: submit) + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + // As the web's form: only busy dims it; the fields say what they need when it's pressed. + .disabled(busy) + HStack(spacing: 24) { + if !isNew { + Button("Forgot password?", action: onForgot).buttonStyle(QuietLinkStyle()) + } + Button(isNew ? "I already have an account" : "Create an account") { isNew.toggle() } + .buttonStyle(QuietLinkStyle()) + } + .frame(maxWidth: .infinity) + } + } + + /// What the web's `required` and `minLength` ask before the form can be sent. + private var ready: Bool { + !email.isEmpty && password.count >= Self.minPasswordCharacters && (!isNew || !name.trimmingCharacters(in: .whitespaces).isEmpty) + } + + private func submit() { + guard !busy else { return } + guard ready else { + error = email.isEmpty ? "Enter your email." : password.count < Self.minPasswordCharacters ? "Your password is \(Self.minPasswordCharacters) characters or more." : "Enter your name." + return + } + busy = true + error = nil + Task { + do { + if isNew { + if try await !session.signUp(server: workspace.server, name: name, email: email, password: password) { + onUnverified(email) + } + } else { + try await session.signIn(server: workspace.server, email: email, password: password) + } + } catch let failure as APIFailure where failure.isEmailUnverified { + // Refusing this attempt has already resent the link. + onUnverified(email) + } catch { + self.error = error.localizedDescription + } + busy = false + } + } +} + +/// Asking for a link to choose a new password, as the web's `ForgotPassword`. The link opens the web app. +@MainActor +private struct ForgotPassword: View { + let server: String + let onBack: () -> Void + @Environment(Session.self) private var session + @State private var email = "" + @State private var sentTo: String? + @State private var error: String? + @State private var busy = false + + var body: some View { + if let sentTo { + AuthLayout(title: "Check your email", subtitle: "If \(sentTo) has an account, a link to reset its password is on its way. It works for an hour.") { + Button("Back to log in", action: onBack).buttonStyle(WebButtonStyle(variant: .secondary, size: .large, fullWidth: true)) + } + } else { + AuthLayout(title: "Reset your password", subtitle: "Enter the email you log in with and we'll send you a link to choose a new password.", onBack: onBack) { + FormCard { + FormRow(label: "Email", last: true) { + TextField("", text: $email, prompt: Text(verbatim: "you@company.com").foregroundStyle(Palette.mutedForeground)) + .textContentType(.emailAddress) + .keyboardType(.emailAddress) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .onSubmit(submit) + .authField() + } + } + if let error { FormAlert(text: error) } + Button("Send reset link", action: submit) + .buttonStyle(WebButtonStyle(size: .large, fullWidth: true)) + .disabled(busy) + } + } + } + + private func submit() { + guard !busy else { return } + guard !email.isEmpty else { + error = "Enter your email." + return + } + busy = true + error = nil + Task { + do { + try await session.requestPasswordReset(server: server, email: email) + sentTo = email + } catch { + self.error = error.localizedDescription + } + busy = false + } + } +} + +// MARK: The web's AuthLayout + +/// The frame the pages outside a workspace sit on, as the web's `AuthLayout`: +/// Back at the top left, then the title, a line under it, and the form, centred. +struct AuthLayout: View { + let title: String + var subtitle: String? + /// Centred on the screen, or from the top for a page that opens the keyboard. + var centred = true + /// Sugabots' mark and name over the title, as a page that starts signing in has. + var showsMark = false + var onBack: (() -> Void)? + @ViewBuilder var content: Content + + var body: some View { + VStack(spacing: 0) { + HStack { + if let onBack { TextBackButton(action: onBack) } + Spacer() + } + .frame(minHeight: 20) + .padding(.horizontal, 16) + .padding(.top, 28) + ScrollView { + VStack(alignment: .leading, spacing: 14) { + VStack(spacing: 10) { + if showsMark { + HStack(spacing: 8) { + Image("Mark").resizable().frame(width: 30, height: 30) + Text("sugabots").font(Typeface.rubik(22, .bold)).tracking(-0.4).foregroundStyle(Palette.foreground) + } + .accessibilityElement(children: .ignore) + .accessibilityLabel("Sugabots") + .padding(.bottom, 18) + } + Text(title) + .font(Typeface.rubik(30, .bold)) + .tracking(-0.6) + .foregroundStyle(Palette.foreground) + .accessibilityAddTraits(.isHeader) + if let subtitle { + Text(subtitle).font(Typeface.rubik(15)).lineSpacing(4).foregroundStyle(Palette.mutedForeground) + } + } + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .padding(.bottom, 8) + content + } + .frame(maxWidth: 440) + .padding(.horizontal, 16) + .padding(.vertical, centred ? 40 : 24) + .frame(maxWidth: .infinity) + .containerRelativeFrame(.vertical, alignment: centred ? .center : .top) { height, _ in height } + } + .scrollBounceBehavior(.basedOnSize) + } + } +} + +/// The form's card: its fields on the list colour. +struct FormCard: View { + @ViewBuilder var content: Content + + var body: some View { + VStack(spacing: 0) { content } + .background(Palette.list, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } +} + +/// One labelled field in the form's card. +struct FormRow: View { + let label: String + var last = false + @ViewBuilder var field: Field + + var body: some View { + HStack(spacing: 12) { + Text(label).font(Typeface.rubik(14)).foregroundStyle(Palette.mutedForeground).frame(width: 88, alignment: .leading) + field + } + .padding(.horizontal, 16) + .padding(.vertical, 14) + .overlay(alignment: .bottom) { + if !last { Rectangle().fill(Palette.border).frame(height: 1) } + } + .accessibilityElement(children: .combine) + } +} + +private extension View { + /// A field as the form's card types it: 16 points, as a phone's fields are. + func authField() -> some View { + font(Typeface.rubik(16)).foregroundStyle(Palette.foreground) + } +} From 79dbb1b4f1beb57a411698a3fc7a282c8fb0cc7b Mon Sep 17 00:00:00 2001 From: Ryan Cartwright Date: Thu, 5 Nov 2026 15:16:06 +1100 Subject: [PATCH 2/2] =?UTF-8?q?feat(ios):=20under=20each=20bot=20with=20op?= =?UTF-8?q?en=20threads,=20list=20its=20newest=20six,=20then=20All=20threa?= =?UTF-8?q?ds,=20which=20shows=20its=20open=20and=20done=20threads,=20as?= =?UTF-8?q?=20the=20web=20does;=20reach=20them=20from=20a=20bot's=20?= =?UTF-8?q?=E2=8B=AF=20and=20Details=20too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/ios/Sugabots.xcodeproj/project.pbxproj | 4 + apps/ios/Sugabots/App/DebugLaunch.swift | 8 +- apps/ios/Sugabots/App/Route.swift | 2 + apps/ios/Sugabots/App/SugabotsApp.swift | 1 + .../Conversation/ConversationDetails.swift | 4 + .../Conversation/ConversationHeader.swift | 2 + .../Conversation/ConversationScreen.swift | 3 + apps/ios/Sugabots/Conversation/Times.swift | 32 ++++ apps/ios/Sugabots/Home/ConversationList.swift | 100 +++++++----- apps/ios/Sugabots/Home/ThreadsScreen.swift | 150 ++++++++++++++++++ .../Sugabots/Settings/SettingsControls.swift | 20 ++- 11 files changed, 277 insertions(+), 49 deletions(-) create mode 100644 apps/ios/Sugabots/Home/ThreadsScreen.swift diff --git a/apps/ios/Sugabots.xcodeproj/project.pbxproj b/apps/ios/Sugabots.xcodeproj/project.pbxproj index 81348ef61..eaaca8720 100644 --- a/apps/ios/Sugabots.xcodeproj/project.pbxproj +++ b/apps/ios/Sugabots.xcodeproj/project.pbxproj @@ -39,6 +39,7 @@ DF5C706020403B4BC8CF4043 /* Lucide.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 408EDC11EC2CA7283C513A41 /* Lucide.generated.swift */; }; 3F1B39B0B0F2F193B3058325 /* Icon.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23CE8BE1CA6F1856CFA083DD /* Icon.swift */; }; F49A6B37C174A83342DF222C /* ConversationList.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0C410CDD148CD91675A9414 /* ConversationList.swift */; }; + EA70591BD79AAE1750A8CD02 /* ThreadsScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFB2EB1B6BE7E724046B1C4F /* ThreadsScreen.swift */; }; 156CE109B161B848CDAC638D /* HomeSheets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05527E8985E2286166609041 /* HomeSheets.swift */; }; B0293DC10873EFD031D2F4E3 /* Mutes.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEE2BBA45144B7EB2E9BEB19 /* Mutes.swift */; }; 70D9A4ACF92FEA3F47DECEB1 /* Mutes.generated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02742345AC712F500BBD22C1 /* Mutes.generated.swift */; }; @@ -165,6 +166,7 @@ 408EDC11EC2CA7283C513A41 /* Lucide.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Lucide.generated.swift; sourceTree = ""; }; 23CE8BE1CA6F1856CFA083DD /* Icon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Icon.swift; sourceTree = ""; }; F0C410CDD148CD91675A9414 /* ConversationList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationList.swift; sourceTree = ""; }; + BFB2EB1B6BE7E724046B1C4F /* ThreadsScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThreadsScreen.swift; sourceTree = ""; }; 05527E8985E2286166609041 /* HomeSheets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeSheets.swift; sourceTree = ""; }; DEE2BBA45144B7EB2E9BEB19 /* Mutes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutes.swift; sourceTree = ""; }; 02742345AC712F500BBD22C1 /* Mutes.generated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutes.generated.swift; sourceTree = ""; }; @@ -434,6 +436,7 @@ DEE2BBA45144B7EB2E9BEB19 /* Mutes.swift */, 02742345AC712F500BBD22C1 /* Mutes.generated.swift */, F0C410CDD148CD91675A9414 /* ConversationList.swift */, + BFB2EB1B6BE7E724046B1C4F /* ThreadsScreen.swift */, 1AF57B4CF1C84550D1950112 /* HomeScreen.swift */, ); path = Home; @@ -693,6 +696,7 @@ B0293DC10873EFD031D2F4E3 /* Mutes.swift in Sources */, 70D9A4ACF92FEA3F47DECEB1 /* Mutes.generated.swift in Sources */, F49A6B37C174A83342DF222C /* ConversationList.swift in Sources */, + EA70591BD79AAE1750A8CD02 /* ThreadsScreen.swift in Sources */, 3F1B39B0B0F2F193B3058325 /* Icon.swift in Sources */, DF5C706020403B4BC8CF4043 /* Lucide.generated.swift in Sources */, E14A4AAEEA74D2798887ABDA /* APIClient.swift in Sources */, diff --git a/apps/ios/Sugabots/App/DebugLaunch.swift b/apps/ios/Sugabots/App/DebugLaunch.swift index cdbb789fa..6f58677fa 100644 --- a/apps/ios/Sugabots/App/DebugLaunch.swift +++ b/apps/ios/Sugabots/App/DebugLaunch.swift @@ -24,6 +24,8 @@ enum DebugLaunch { case general(pod: String) /// `bot/Pod/Bot`: the bot's channel. case bot(pod: String, bot: String) + /// `threads/Pod/Bot`: the bot's threads. + case threads(pod: String, bot: String) /// `newthread/Pod[/Bot]`. case newThread(pod: String, bot: String?) /// `conversation/`. @@ -54,7 +56,7 @@ enum DebugLaunch { /// The name of the pod the page is in, if it's in one. var podName: String? { switch self { - case let .home(pod), let .general(pod), let .bot(pod, _), let .newThread(pod, _), let .podSettings(pod), + case let .home(pod), let .general(pod), let .bot(pod, _), let .threads(pod, _), let .newThread(pod, _), let .podSettings(pod), let .routines(pod), let .newRoutine(pod), let .artifacts(pod), let .newBot(pod), let .routinePanel(pod, _), let .trigger(pod, _), let .emoji(pod, _), let .youPod(pod), let .podPage(pod, _), let .agentSettings(pod, _): @@ -87,6 +89,7 @@ enum DebugLaunch { case let ("pod", pod?, nil): return .home(pod: pod) case let ("general", pod?, _): return .general(pod: pod) case let ("bot", pod?, bot?): return .bot(pod: pod, bot: bot) + case let ("threads", pod?, bot?): return .threads(pod: pod, bot: bot) case let ("newthread", pod?, bot): return .newThread(pod: pod, bot: bot) case let ("settings", pod?, _): return .podSettings(pod: pod) case let ("routines", pod?, _): return .routines(pod: pod) @@ -154,6 +157,9 @@ enum DebugLaunch { case let .bot(_, name): guard let pod, let bot = bot(named: name, in: pod, store: store) else { return nil } return (.home, .botChannel(pod, bot)) + case let .threads(_, name): + guard let pod, let bot = bot(named: name, in: pod, store: store) else { return nil } + return (.home, .threads(pod, agent: bot)) case let .newThread(_, name): guard let pod else { return nil } return (.home, .newThread(pod, agent: name.flatMap { bot(named: $0, in: pod, store: store) })) diff --git a/apps/ios/Sugabots/App/Route.swift b/apps/ios/Sugabots/App/Route.swift index fb8ca26c9..b1e7d8504 100644 --- a/apps/ios/Sugabots/App/Route.swift +++ b/apps/ios/Sugabots/App/Route.swift @@ -16,6 +16,8 @@ enum Route: Hashable { case approval(callId: String) /// Starting a thread in a pod from its first message, with `agent`, or between people. case newThread(Pod, agent: Agent?) + /// A bot's threads, those still going or those done. + case threads(Pod, agent: Agent) /// A bot's routines, or every routine in the pod. case routines(Pod, agent: Agent?) /// Making a routine in a pod, for `agent` when begun from its routines. diff --git a/apps/ios/Sugabots/App/SugabotsApp.swift b/apps/ios/Sugabots/App/SugabotsApp.swift index ee5bf656e..0feca46a7 100644 --- a/apps/ios/Sugabots/App/SugabotsApp.swift +++ b/apps/ios/Sugabots/App/SugabotsApp.swift @@ -215,6 +215,7 @@ struct RouteDestination: View { case let .approval(callId): ApprovalPage(callId: callId) case let .conversationAt(threadId, messageId): ConversationScreen(threadId: threadId, title: "", focusMessageId: messageId) case let .sideThreadPage(conversationId, threadId): SideThreadSheet(threadId: threadId, conversationId: conversationId, entry: nil, chatAgentId: nil, asPage: true) { _ in } + case let .threads(pod, agent): ThreadsScreen(pod: pod, agent: agent) case let .routines(pod, agent): RoutinesScreen(pod: pod, agent: agent) case let .newRoutine(pod, agent): NewRoutineScreen(pod: pod, agent: agent) case let .routine(pod, routineId): OpeningConversationScreen.routineFeed(routineId, in: pod) diff --git a/apps/ios/Sugabots/Conversation/ConversationDetails.swift b/apps/ios/Sugabots/Conversation/ConversationDetails.swift index 7cc2c0ee3..773997094 100644 --- a/apps/ios/Sugabots/Conversation/ConversationDetails.swift +++ b/apps/ios/Sugabots/Conversation/ConversationDetails.swift @@ -165,6 +165,10 @@ private struct BotDetails: View { RoundActionLabel(icon: .settings, label: "Settings") } .buttonStyle(.plain) + NavigationLink(value: Route.threads(pod, agent: agent)) { + RoundActionLabel(icon: .messagesSquare, label: "Threads") + } + .buttonStyle(.plain) NavigationLink(value: Route.routines(pod, agent: agent)) { RoundActionLabel(icon: .refreshCcw, label: "Routines") } diff --git a/apps/ios/Sugabots/Conversation/ConversationHeader.swift b/apps/ios/Sugabots/Conversation/ConversationHeader.swift index e205109e1..7d94173f5 100644 --- a/apps/ios/Sugabots/Conversation/ConversationHeader.swift +++ b/apps/ios/Sugabots/Conversation/ConversationHeader.swift @@ -18,6 +18,7 @@ struct ConversationHeader: View { let openDetails: () -> Void let openComputer: () -> Void let openRoutines: () -> Void + let openThreads: () -> Void @Environment(WorkspaceStore.self) private var store @Environment(Toaster.self) private var toaster @Environment(\.dismiss) private var dismiss @@ -81,6 +82,7 @@ struct ConversationHeader: View { label: failed ? "More for \(agent.name), a routine's latest run failed" : "More for \(agent.name)", items: [ .init(title: "Computer", systemImage: "desktopcomputer", action: openComputer), + .init(title: "Threads", systemImage: "bubble.left.and.bubble.right", action: openThreads), .init(title: "Routines", systemImage: "arrow.triangle.2.circlepath", action: openRoutines), ] ) diff --git a/apps/ios/Sugabots/Conversation/ConversationScreen.swift b/apps/ios/Sugabots/Conversation/ConversationScreen.swift index 913f88947..e2f0e2bbd 100644 --- a/apps/ios/Sugabots/Conversation/ConversationScreen.swift +++ b/apps/ios/Sugabots/Conversation/ConversationScreen.swift @@ -130,6 +130,9 @@ private struct ConversationContent: View { openComputer: { showingComputer = true }, openRoutines: { if let pod, let agent = kind.agent { openPage(.routines(pod, agent: agent)) } + }, + openThreads: { + if let pod, let agent = kind.agent { openPage(.threads(pod, agent: agent)) } } ) } diff --git a/apps/ios/Sugabots/Conversation/Times.swift b/apps/ios/Sugabots/Conversation/Times.swift index 9844e4855..4f5d64beb 100644 --- a/apps/ios/Sugabots/Conversation/Times.swift +++ b/apps/ios/Sugabots/Conversation/Times.swift @@ -62,6 +62,38 @@ enum Times { return date.formatted(sameYear ? style : style.year()) } + /// How long ago `date` was, as `formatDistanceToNowStrict` with `addSuffix` + /// writes it: one unit, the largest under its next, rounded to the nearest + /// whole one ("4 minutes ago", "18 days ago", "6 months ago"). Days run to + /// 30 and months to 12, with no weeks; a time after `now` is "in 1 second". + static func ago(_ date: Date, now: Date = .now) -> String { + let seconds = now.timeIntervalSince(date) + let words = distance(abs(seconds)) + return seconds < 0 ? "in \(words)" : "\(words) ago" + } + + private static let secondsInMinute = 60.0 + private static let secondsInHour = 60 * secondsInMinute + private static let secondsInDay = 24 * secondsInHour + private static let secondsInMonth = 30 * secondsInDay + private static let secondsInYear = 365 * secondsInDay + + private static func distance(_ seconds: TimeInterval) -> String { + func count(_ amount: Double, _ unit: String) -> String { + let whole = Int(amount.rounded()) + return whole == 1 ? "1 \(unit)" : "\(whole) \(unit)s" + } + if seconds < secondsInMinute { return count(seconds, "second") } + if seconds < secondsInHour { return count(seconds / secondsInMinute, "minute") } + if seconds < secondsInDay { return count(seconds / secondsInHour, "hour") } + if seconds < secondsInMonth { return count(seconds / secondsInDay, "day") } + if seconds < secondsInYear { + let months = (seconds / secondsInMonth).rounded() + return months == Double(monthsInYear) ? "1 year" : count(months, "month") + } + return count(seconds / secondsInYear, "year") + } + /// How many days before `now`'s day `date`'s day is: 0 today, 1 yesterday, negative in the future. static func daysAgo(_ date: Date, now: Date = .now, calendar: Calendar = .current) -> Int { calendar.dateComponents([.day], from: calendar.startOfDay(for: date), to: calendar.startOfDay(for: now)).day ?? 0 diff --git a/apps/ios/Sugabots/Home/ConversationList.swift b/apps/ios/Sugabots/Home/ConversationList.swift index 86b3825ec..b4efdfe85 100644 --- a/apps/ios/Sugabots/Home/ConversationList.swift +++ b/apps/ios/Sugabots/Home/ConversationList.swift @@ -17,8 +17,8 @@ struct ConversationList: View { var body: some View { let list = store.chatLists[pod.id] let bots = store.bots(in: pod) - // Done threads leave the list. - let threads = (list?.threads ?? []).filter { $0.conversation.doneAt == nil } + // Done threads are kept for the counts of what is open; the tree under each leaves them out. + let threads = list?.threads ?? [] let chats = list?.chats ?? [] let byChat = Self.threadsByChat(chats, threads) let groups = Self.groupByBot( @@ -32,7 +32,7 @@ struct ConversationList: View { SectionHeading( label: "Channels", open: chatsOpen, - news: .of(chats.map { ($0.unreadMessages, false) } + byChat.values.flatMap { $0 }.map { ($0.unreadMessages, $0.needsYou) }), + news: .of(chats.map { ($0.unreadMessages, false) } + byChat.values.flatMap(Self.open).map { ($0.unreadMessages, $0.needsYou) }), toggle: { toggle("chats") }, actionLabel: "New channel in \(pod.name)", action: { namingChannel = true } @@ -64,7 +64,7 @@ struct ConversationList: View { label: "Bots", open: botsOpen, news: .of(groups.flatMap { group in - group.threads.map { ($0.unreadMessages, $0.needsYou) } + Self.open(group.threads).map { ($0.unreadMessages, $0.needsYou) } + (group.channel.map { [($0.unreadMessages, $0.needsYou)] } ?? []) }), toggle: { toggle("bots") }, @@ -144,6 +144,11 @@ struct ConversationList: View { store.preferences.toggleFolded(section, in: pod.id) } + /// The threads in `rows` not yet marked done. + static func open(_ rows: [ChatListItem]) -> [ChatListItem] { + rows.filter { $0.conversation.doneAt == nil } + } + /// The threads between people started from each of `chats`, newest first, by the chat's id; only chats with one. private static func threadsByChat(_ chats: [ChatList.Chat], _ threads: [ChatListItem]) -> [String: [ChatListItem]] { let chatIds = Set(chats.map(\.conversation.id)) @@ -168,7 +173,14 @@ struct ConversationList: View { for bot in bots { groups[bot.id] = BotGroup(agent: bot) } for channel in channels { groups[channel.agent.id, default: BotGroup(agent: channel.agent)].channel = channel } for row in threads { groups[key(row.agent), default: BotGroup(agent: row.agent)].threads.append(row) } - return groups.values.sorted { a, b in + // A group that isn't one of the pod's bots and has no channel opens + // nothing, so it's listed only while one of its threads is open, as it + // would otherwise be a row with nothing under it. + let podBots = Set(bots.map(\.id)) + let listed = groups.values.filter { group in + group.agent.map { podBots.contains($0.id) } == true || group.channel != nil || !open(group.threads).isEmpty + } + return listed.sorted { a, b in guard let first = a.agent else { return false } guard let second = b.agent else { return true } return first.name.localizedCompare(second.name) == .orderedAscending @@ -176,8 +188,8 @@ struct ConversationList: View { } } -/// A bot with its channel, once somebody opened it, and its open threads, -/// newest first; or the threads between people, when `agent` is nil. +/// A bot with its channel, once somebody opened it, and its threads, done ones +/// included, newest first; or the threads between people, when `agent` is nil. struct BotGroup: Identifiable { static let peopleKey = "people" @@ -335,9 +347,7 @@ private struct BotItem: View { .contextMenu { if let place { NotificationMenu(place: place) } } - if !group.threads.isEmpty { - ThreadTree(pod: pod, threads: group.threads) - } + ThreadTree(pod: pod, threads: group.threads, allThreadsOf: group.agent) } } @@ -357,55 +367,57 @@ private struct BotItem: View { } } -/// Threads hanging under a bot or a channel: the first few, then how many more. +/// Threads hanging under a bot or a channel that aren't done. Under a bot, +/// given as `allThreadsOf`, only the newest few show, then All threads, which +/// leads to the rest, done ones included. Nothing while none is open: a bot's +/// done threads are then reached from its channel's ⋯ and its Details. @MainActor private struct ThreadTree: View { let pod: Pod - /// Newest first. + /// Newest first, done ones included. let threads: [ChatListItem] - @State private var unclipped = false - - /// How many threads show before Show more, as the web's `THREADS_SHOWN`. - private static let threadsBeforeShowMore = Limits.threadsShown + var allThreadsOf: Agent? var body: some View { - let shown = unclipped ? threads : Array(threads.prefix(Self.threadsBeforeShowMore)) - let hidden = threads.count - shown.count - VStack(alignment: .leading, spacing: 1) { - ForEach(shown) { row in - NavigationLink(value: Route.conversation(threadId: row.conversation.id, title: row.conversation.title)) { - threadRow(lit: row.unreadMessages > 0 || row.needsYou) { - // In a Personal pod a conversation is with the bot, so goes by its name. - Text(pod.kind == .personal ? row.agent?.name ?? row.conversation.title : row.conversation.title) - .lineLimit(1) - Spacer(minLength: 0) - UnreadMarker(unreadMessages: row.unreadMessages, needsYou: row.needsYou).frame(width: 22) + let open = ConversationList.open(threads) + let shown = allThreadsOf == nil ? open : Array(open.prefix(Limits.threadsShown)) + if !shown.isEmpty { + VStack(alignment: .leading, spacing: 1) { + ForEach(shown) { row in + NavigationLink(value: Route.conversation(threadId: row.conversation.id, title: row.conversation.title)) { + threadRow(lit: row.unreadMessages > 0 || row.needsYou) { + // In a Personal pod a conversation is with the bot, so goes by its name. + Text(pod.kind == .personal ? row.agent?.name ?? row.conversation.title : row.conversation.title) + .lineLimit(1) + Spacer(minLength: 0) + UnreadMarker(unreadMessages: row.unreadMessages, needsYou: row.needsYou).frame(width: 22) + } } + .buttonStyle(PressableRowStyle(cornerRadius: 6)) } - .buttonStyle(PressableRowStyle(cornerRadius: 6)) - } - if hidden > 0 { - Button { unclipped = true } label: { - Text("Show \(hidden) more") - .font(Typeface.rubik(12)) - .foregroundStyle(Palette.subtleForeground) - .padding(.horizontal, 8) - .frame(maxWidth: .infinity, minHeight: 28, alignment: .leading) - .contentShape(Rectangle()) + if let agent = allThreadsOf { + NavigationLink(value: Route.threads(pod, agent: agent)) { + threadRow(lit: false, quiet: true) { + Text("All threads").lineLimit(1) + Spacer(minLength: 0) + Icon(.chevronRight, size: 14, strokeWidth: 2).frame(width: 22) + } + } + .buttonStyle(PressableRowStyle(cornerRadius: 6)) } - .buttonStyle(.plain) } + .padding(.leading, ConversationList.nestedIndent) + .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 1) } + .padding(.leading, 17) + .padding(.top, 1) } - .padding(.leading, ConversationList.nestedIndent) - .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 1) } - .padding(.leading, 17) - .padding(.top, 1) } - private func threadRow(lit: Bool, @ViewBuilder content: () -> some View) -> some View { + /// `lit` while it has something new; `quiet`, greyer still, for the way to all of a bot's threads. + private func threadRow(lit: Bool, quiet: Bool = false, @ViewBuilder content: () -> some View) -> some View { HStack(spacing: 8) { content() } .font(Typeface.rubik(15, lit ? .semibold : .regular)) - .foregroundStyle(lit ? Palette.foreground : Palette.mutedForeground) + .foregroundStyle(lit ? Palette.foreground : quiet ? Palette.subtleForeground : Palette.mutedForeground) .padding(.leading, 8) .padding(.trailing, 6) .frame(height: 40) diff --git a/apps/ios/Sugabots/Home/ThreadsScreen.swift b/apps/ios/Sugabots/Home/ThreadsScreen.swift new file mode 100644 index 000000000..8d89a2eeb --- /dev/null +++ b/apps/ios/Sugabots/Home/ThreadsScreen.swift @@ -0,0 +1,150 @@ +import SwiftUI + +/// A bot's threads, as the web's `ThreadsStage` on a phone: those still going, +/// or those done, newest first, each with when it last moved and its latest +/// message. Each opens its thread, and Back returns here for the next. +@MainActor +struct ThreadsScreen: View { + let pod: Pod + let agent: Agent + @Environment(WorkspaceStore.self) private var store + @State private var tab: Tab = .open + + enum Tab: Hashable { + case open + case done + } + + var body: some View { + let list = store.chatLists[pod.id] + let all = (list?.threads ?? []).filter { $0.agent?.id == agent.id } + let going = all.filter { $0.conversation.doneAt == nil } + let done = all.filter { $0.conversation.doneAt != nil } + let shown = tab == .done ? done : going + VStack(alignment: .leading, spacing: 0) { + PodPageHeader(title: "\(agent.name)'s threads") {} + SegmentedChoice( + label: "Which threads", + options: [(.open, "Open · \(going.count)"), (.done, "Done · \(done.count)")], + value: tab, + fill: true, + size: .large + ) { tab = $0 } + // Filling the row, its choices would also grow as tall as the page offers. + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 16) + .padding(.bottom, 8) + if list != nil, shown.isEmpty { + EmptyState( + title: tab == .done ? "No done threads" : "No open threads", + text: tab == .done + ? "Threads with \(agent.name) you mark done show here." + : "Start one with the + beside \(agent.name) on Home." + ) + .padding(.bottom, 60) + } else { + ScrollView { + LazyVStack(spacing: 1) { + ForEach(shown) { row in + ThreadListRow(row: row) + } + } + .padding(.horizontal, 8) + .padding(.bottom, 8) + } + } + } + .background(Palette.background.ignoresSafeArea()) + .task { await store.refreshChatList(pod) } + } +} + +/// A thread in the list: its title, ticked when done, and when it last moved; +/// under it, the faces of who is in it and its latest message. Bright while it +/// has unread messages and isn't done. +@MainActor +private struct ThreadListRow: View { + let row: ChatListItem + + var body: some View { + let done = row.conversation.doneAt != nil + let lit = !done && row.unreadMessages > 0 + NavigationLink(value: Route.conversation(threadId: row.conversation.id, title: row.conversation.title)) { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 8) { + if done { + Icon(.check, size: 12, strokeWidth: 2.25).foregroundStyle(Palette.subtleForeground) + } + Text(row.conversation.title) + .font(Typeface.rubik(15, lit ? .semibold : .regular)) + .foregroundStyle(lit ? Palette.foreground : Palette.softForeground) + .lineLimit(1) + Spacer(minLength: 0) + if let last = row.lastMessage { + Text(Times.ago(last.at)) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + } + } + if !row.participants.isEmpty || row.lastMessage != nil { + HStack(spacing: 8) { + ParticipantFaces(participants: row.participants, size: 16) + if let last = row.lastMessage { + Text(last.preview) + .font(Typeface.rubik(12)) + .foregroundStyle(Palette.subtleForeground) + .lineLimit(1) + } + } + } + } + .padding(.horizontal, 10) + .padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(PressableRowStyle(cornerRadius: 8)) + } +} + +/// The faces of who is in a thread, overlapping in a row, as the web's +/// `ParticipantFaces`: people first, then bots, each in the order given, the +/// first `shown` of them and then how many more. Each is ringed in `surface`, +/// the colour of what the row is on, so it reads apart from the one under it. +/// For decoration only: whatever holds it names who is in the thread. +struct ParticipantFaces: View { + let participants: [ThreadParticipant] + var shown = 4 + var size: CGFloat = 20 + var surface: Color = Palette.background + + /// How far each face sits over the one before it, as a share of its size. + private static let overlap: CGFloat = 0.3 + private static let ringWidth: CGFloat = 2 + + var body: some View { + let people = participants.filter { if case .person = $0 { true } else { false } } + let bots = participants.filter { if case .agent = $0 { true } else { false } } + let faces = Array((people + bots).prefix(shown)) + let hidden = people.count + bots.count - faces.count + HStack(spacing: -(size * Self.overlap).rounded()) { + ForEach(Array(faces.enumerated()), id: \.offset) { _, participant in + ringed(ParticipantFace(participant: participant, size: size)) + } + if hidden > 0 { + ringed( + Text("+\(hidden)") + .font(Typeface.rubik(max(9, (size * 0.45).rounded()), .semibold)) + .foregroundStyle(Palette.mutedForeground) + .frame(width: size, height: size) + .background(Palette.chip, in: Circle()) + ) + } + } + .accessibilityHidden(true) + } + + private func ringed(_ face: some View) -> some View { + face.background(Circle().fill(surface).padding(-Self.ringWidth)) + } +} diff --git a/apps/ios/Sugabots/Settings/SettingsControls.swift b/apps/ios/Sugabots/Settings/SettingsControls.swift index aa5e40bfd..c3f49a2cc 100644 --- a/apps/ios/Sugabots/Settings/SettingsControls.swift +++ b/apps/ios/Sugabots/Settings/SettingsControls.swift @@ -9,16 +9,28 @@ struct SegmentedChoice: View { let value: Value? /// Stretches the choices across the row, as on a phone's narrow rows. var fill = false + var size = Size.regular let choose: (Value) -> Void @Environment(\.isEnabled) private var isEnabled + enum Size { + /// The web's, beside a setting's label. + case regular + /// Across the top of a page, where the choice is what the page shows, as a phone's tabs are. + case large + + var fontSize: CGFloat { self == .large ? 15 : 12.5 } + var minHeight: CGFloat { self == .large ? 38 : 28 } + var cornerRadius: CGFloat { self == .large ? 10 : 8 } + } + var body: some View { HStack(spacing: 0) { ForEach(options, id: \.value) { option in let chosen = option.value == value Button { choose(option.value) } label: { Text(option.label) - .font(Typeface.rubik(12.5, .medium)) + .font(Typeface.rubik(size.fontSize, .medium)) // Stretched across a row, a long choice wraps rather than being cut short, as on the web. .lineLimit(fill ? 2 : 1) .multilineTextAlignment(.center) @@ -26,8 +38,8 @@ struct SegmentedChoice: View { .padding(.horizontal, 11) .padding(.vertical, 5) // The web's 5px either side of a line of `text-sm`. - .frame(maxWidth: fill ? .infinity : nil, minHeight: 28, maxHeight: fill ? .infinity : nil) - .background(chosen ? Palette.personAvatar : .clear, in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + .frame(maxWidth: fill ? .infinity : nil, minHeight: size.minHeight, maxHeight: fill ? .infinity : nil) + .background(chosen ? Palette.personAvatar : .clear, in: RoundedRectangle(cornerRadius: size.cornerRadius, style: .continuous)) .contentShape(Rectangle()) } .buttonStyle(.plain) @@ -35,7 +47,7 @@ struct SegmentedChoice: View { } } .padding(2) - .background(Palette.chip, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .background(Palette.chip, in: RoundedRectangle(cornerRadius: size.cornerRadius + 2, style: .continuous)) // Beside a label, the choices keep their width, as the web's `shrink-0`. .fixedSize(horizontal: !fill, vertical: false) .opacity(isEnabled ? 1 : 0.5)