diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml new file mode 100644 index 00000000..f5c27010 --- /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 00000000..5c254bba --- /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 95569a6b..a8e34463 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 00000000..40e514a2 --- /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 00000000..a2728eb7 --- /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 00000000..eaaca872 --- /dev/null +++ b/apps/ios/Sugabots.xcodeproj/project.pbxproj @@ -0,0 +1,854 @@ +// !$*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 */; }; + 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 */; }; + 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 = ""; }; + 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 = ""; }; + 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 */, + BFB2EB1B6BE7E724046B1C4F /* ThreadsScreen.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 */, + EA70591BD79AAE1750A8CD02 /* ThreadsScreen.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 00000000..18d98100 --- /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 00000000..0daf83f4 --- /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 00000000..44c92029 --- /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 00000000..0ab16911 --- /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 00000000..6f58677f --- /dev/null +++ b/apps/ios/Sugabots/App/DebugLaunch.swift @@ -0,0 +1,187 @@ +#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) + /// `threads/Pod/Bot`: the bot's threads. + case threads(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 .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, _): + 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 ("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) + 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 .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) })) + 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 00000000..a2f9d82d --- /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 00000000..c92c699a --- /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 00000000..b1e7d850 --- /dev/null +++ b/apps/ios/Sugabots/App/Route.swift @@ -0,0 +1,35 @@ +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 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. + 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 00000000..09397f80 --- /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 00000000..934aad8d --- /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 00000000..0feca46a --- /dev/null +++ b/apps/ios/Sugabots/App/SugabotsApp.swift @@ -0,0 +1,363 @@ +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 .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) + 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 00000000..fddbd2c1 --- /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 00000000..7302ca9f --- /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 00000000..53b223fd --- /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 00000000..3074c9df --- /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 00000000..f83e6e1a --- /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 00000000..cef800e1 --- /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 00000000..7ae3a5e1 --- /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 00000000..7ae88c15 --- /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 00000000..bcc17eff --- /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 00000000..d38b74c6 --- /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 00000000..faa97a6a Binary files /dev/null and b/apps/ios/Sugabots/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ 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 00000000..317fcc7f --- /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 00000000..d458f1c5 --- /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 00000000..3e30c0d2 --- /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 00000000..103da27f Binary files /dev/null and b/apps/ios/Sugabots/Assets.xcassets/Mark.imageset/Mark.png differ diff --git a/apps/ios/Sugabots/Attention/ApprovalsScreen.swift b/apps/ios/Sugabots/Attention/ApprovalsScreen.swift new file mode 100644 index 00000000..da60a18f --- /dev/null +++ b/apps/ios/Sugabots/Attention/ApprovalsScreen.swift @@ -0,0 +1,253 @@ +import SwiftUI + +/// Approvals, as the web's `Approvals` on a phone: what waits on the person, +/// each a card with the request folded and Deny and Allow, then what was +/// resolved, newest first. +@MainActor +struct ApprovalsScreen: View { + @Environment(WorkspaceStore.self) private var store + @State private var showAll = false + + /// How many resolved requests show before Show older. + private static let answeredShown = 10 + + var body: some View { + let waiting = store.approvals.waiting.map(ApprovalEntry.init) + let answered = store.approvals.answered.map(ApprovalEntry.init) + let shown = showAll ? answered : Array(answered.prefix(Self.answeredShown)) + VStack(spacing: 0) { + TabPageHeader(title: "Approvals") { EmptyView() } + ScrollView { + VStack(alignment: .leading, spacing: 12) { + if store.approvalsFailed { + Text("Approvals could not be loaded.").font(Typeface.rubik(15)).foregroundStyle(Palette.mutedForeground).padding(.horizontal, 4) + } + if store.approvalsLoaded { + if waiting.isEmpty { + NothingWaiting().padding(.bottom, 12) + } else { + SectionLabel(text: "Waiting on you") + VStack(spacing: 8) { + ForEach(waiting) { WaitingCard(request: $0) } + } + .padding(.bottom, 20) + } + if !answered.isEmpty { + SectionLabel(text: "Resolved") + VStack(spacing: 0) { + ForEach(shown) { ResolvedRow(request: $0) } + } + if answered.count > 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 00000000..ae13a656 --- /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 00000000..1d95c511 --- /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 00000000..6fbf0cbe --- /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 00000000..626c6a4c --- /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 00000000..2d5b08e7 --- /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 00000000..29a23e5e --- /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 00000000..f52258cb --- /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 00000000..77399709 --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationDetails.swift @@ -0,0 +1,361 @@ +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.threads(pod, agent: agent)) { + RoundActionLabel(icon: .messagesSquare, label: "Threads") + } + .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 00000000..7d94173f --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationHeader.swift @@ -0,0 +1,373 @@ +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 + let openThreads: () -> 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: "Threads", systemImage: "bubble.left.and.bubble.right", action: openThreads), + .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 00000000..bb798d21 --- /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 00000000..e2f0e2bb --- /dev/null +++ b/apps/ios/Sugabots/Conversation/ConversationScreen.swift @@ -0,0 +1,669 @@ +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)) } + }, + openThreads: { + if let pod, let agent = kind.agent { openPage(.threads(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 00000000..df46efe8 --- /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 00000000..c3606b30 --- /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 00000000..bf77999a --- /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 00000000..ebd8f4a8 --- /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 00000000..6bd2a24c --- /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 00000000..4c3ca586 --- /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 00000000..d9c38f7b --- /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/Times.swift b/apps/ios/Sugabots/Conversation/Times.swift index 9844e485..4f5d64be 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/Conversation/ToolLine.swift b/apps/ios/Sugabots/Conversation/ToolLine.swift new file mode 100644 index 00000000..110c24e0 --- /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 00000000..c187d9ad --- /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 00000000..aa9d448b --- /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 00000000..881fc797 --- /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 00000000..980c60be --- /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 00000000..aa23bddc --- /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 00000000..39d98e55 --- /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 00000000..a7c3a64e --- /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 00000000..aac90c49 --- /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 00000000..bc6c6e27 --- /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 00000000..9858751f --- /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 00000000..9b50c3cc --- /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 00000000..1d28c4f2 --- /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 00000000..b59ed8ea --- /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 00000000..cd5102a4 Binary files /dev/null and b/apps/ios/Sugabots/Fonts/JetBrainsMono.woff2 differ diff --git a/apps/ios/Sugabots/Fonts/OFL-JetBrainsMono.txt b/apps/ios/Sugabots/Fonts/OFL-JetBrainsMono.txt new file mode 100644 index 00000000..8f7ed671 --- /dev/null +++ b/apps/ios/Sugabots/Fonts/OFL-JetBrainsMono.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) JetBrainsMono-Italic[wght].ttf: Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/ios/Sugabots/Fonts/OFL-Rubik.txt b/apps/ios/Sugabots/Fonts/OFL-Rubik.txt new file mode 100644 index 00000000..03af63b5 --- /dev/null +++ b/apps/ios/Sugabots/Fonts/OFL-Rubik.txt @@ -0,0 +1,93 @@ +Copyright 2015 The Rubik Project Authors (https://github.com/googlefonts/rubik) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/ios/Sugabots/Fonts/Rubik.ttf b/apps/ios/Sugabots/Fonts/Rubik.ttf new file mode 100644 index 00000000..a59aeb63 Binary files /dev/null and b/apps/ios/Sugabots/Fonts/Rubik.ttf differ diff --git a/apps/ios/Sugabots/Home/ChannelScreens.swift b/apps/ios/Sugabots/Home/ChannelScreens.swift new file mode 100644 index 00000000..896f9578 --- /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 00000000..b4efdfe8 --- /dev/null +++ b/apps/ios/Sugabots/Home/ConversationList.swift @@ -0,0 +1,452 @@ +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 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( + 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(Self.open).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 + Self.open(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 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)) + 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) } + // 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 + } + } +} + +/// 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" + + 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) } + } + ThreadTree(pod: pod, threads: group.threads, allThreadsOf: group.agent) + } + + } + + /// 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 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, done ones included. + let threads: [ChatListItem] + var allThreadsOf: Agent? + + var body: some View { + 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)) + } + 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)) + } + } + .padding(.leading, ConversationList.nestedIndent) + .overlay(alignment: .leading) { Rectangle().fill(Palette.border).frame(width: 1) } + .padding(.leading, 17) + .padding(.top, 1) + } + } + + /// `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 : quiet ? Palette.subtleForeground : 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 00000000..cb2d98e1 --- /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 00000000..91bdbd0f --- /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/Home/ThreadsScreen.swift b/apps/ios/Sugabots/Home/ThreadsScreen.swift new file mode 100644 index 00000000..8d89a2ee --- /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/Info.plist b/apps/ios/Sugabots/Info.plist new file mode 100644 index 00000000..0bf7bac7 --- /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 00000000..626ba8be --- /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 00000000..eb0b3044 --- /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 00000000..a33510ba --- /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 00000000..82b8e0b0 --- /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 00000000..e62cc4d5 --- /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 00000000..23f55c70 --- /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 00000000..88f6073e --- /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 00000000..6e0d24bf --- /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 00000000..ab553711 --- /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 00000000..a165c8b5 --- /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 00000000..c8d83c80 --- /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 00000000..9dfb2e84 --- /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 00000000..cbd5ef0f --- /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 00000000..71bceb63 --- /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 00000000..3b009209 --- /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 00000000..12a2d60f --- /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 00000000..838d140f --- /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 00000000..9569e706 --- /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 00000000..885b4903 --- /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 00000000..4184c616 --- /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 00000000..d8200c89 --- /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 00000000..c3f49a2c --- /dev/null +++ b/apps/ios/Sugabots/Settings/SettingsControls.swift @@ -0,0 +1,512 @@ +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 + 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(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) + .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: size.minHeight, maxHeight: fill ? .infinity : nil) + .background(chosen ? Palette.personAvatar : .clear, in: RoundedRectangle(cornerRadius: size.cornerRadius, style: .continuous)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(chosen ? .isSelected : []) + } + } + .padding(2) + .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) + .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 00000000..4e357473 --- /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 00000000..7c25be58 --- /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 00000000..a61eef8e --- /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 00000000..555a6a25 --- /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 00000000..eefc34bb --- /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) + } +}