Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions mobile/plugins/shortcuts/ChatShortcuts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,118 @@ internal import BotkinsActivity
internal import Expo
import React
import UIKit
import UniformTypeIdentifiers

private let maxShortcutAttachments = 10
private let maxShortcutAttachmentBytes = 25 * 1024 * 1024

private struct StagedShortcutAttachment: Encodable {
let name: String
let uri: String
}

@available(iOS 17.0, *)
private func safeShortcutFilename(for file: IntentFile, index: Int) -> String {
let raw = (file.filename as NSString).lastPathComponent
.trimmingCharacters(in: .whitespacesAndNewlines)
.replacingOccurrences(of: "/", with: "-")
.replacingOccurrences(of: ":", with: "-")
var name = (raw.isEmpty || raw == "." || raw == "..") ? "attachment-\(index + 1)" : raw
if (name as NSString).pathExtension.isEmpty,
let ext = file.type?.preferredFilenameExtension,
!ext.isEmpty {
name += ".\(ext)"
}
return name
}

private func uniqueShortcutFilename(_ name: String, used: inout Set<String>) -> String {
let lower = name.lowercased()
if !used.contains(lower) {
used.insert(lower)
return name
}
let ext = (name as NSString).pathExtension
let base = ext.isEmpty ? name : (name as NSString).deletingPathExtension
var counter = 2
while true {
let candidate = ext.isEmpty ? "\(base)-\(counter)" : "\(base)-\(counter).\(ext)"
if !used.contains(candidate.lowercased()) {
used.insert(candidate.lowercased())
return candidate
}
counter += 1
}
}

@available(iOS 17.0, *)
private func writeShortcutAttachment(_ file: IntentFile, named name: String, to destURL: URL) throws {
let fm = FileManager.default
if let sourceURL = file.fileURL {
let scoped = sourceURL.startAccessingSecurityScopedResource()
defer { if scoped { sourceURL.stopAccessingSecurityScopedResource() } }
if let size = try? sourceURL.resourceValues(forKeys: [.fileSizeKey]).fileSize {
if size == 0 {
throw ShortcutError.message("\"\(name)\" is empty.")
}
if size > maxShortcutAttachmentBytes {
throw ShortcutError.message("\"\(name)\" is too large. Files can be up to 25 MB.")
}
}
do {
try fm.copyItem(at: sourceURL, to: destURL)
let copiedSize = (try? fm.attributesOfItem(atPath: destURL.path)[.size] as? NSNumber)?.intValue ?? 0
if copiedSize == 0 {
throw ShortcutError.message("\"\(name)\" is empty.")
}
if copiedSize > maxShortcutAttachmentBytes {
throw ShortcutError.message("\"\(name)\" is too large. Files can be up to 25 MB.")
}
return
} catch let error as ShortcutError {
throw error
} catch {
try? fm.removeItem(at: destURL)
}
}
let data = file.data
if data.isEmpty {
throw ShortcutError.message("\"\(name)\" is empty.")
}
if data.count > maxShortcutAttachmentBytes {
throw ShortcutError.message("\"\(name)\" is too large. Files can be up to 25 MB.")
}
try data.write(to: destURL, options: .atomic)
}

@available(iOS 17.0, *)
private func stageShortcutAttachments(_ files: [IntentFile]) throws -> (dir: URL, json: String) {
guard files.count <= maxShortcutAttachments else {
throw ShortcutError.message("Attach up to 10 files at a time.")
}
let fm = FileManager.default
let dir = fm.temporaryDirectory.appendingPathComponent("botkins-shortcut-\(UUID().uuidString)", isDirectory: true)
try fm.createDirectory(at: dir, withIntermediateDirectories: true)
do {
var used: Set<String> = []
var staged: [StagedShortcutAttachment] = []
for (index, file) in files.enumerated() {
let baseName = safeShortcutFilename(for: file, index: index)
let name = uniqueShortcutFilename(baseName, used: &used)
let destURL = dir.appendingPathComponent(name, isDirectory: false)
try writeShortcutAttachment(file, named: name, to: destURL)
staged.append(StagedShortcutAttachment(name: name, uri: destURL.absoluteString))
}
let encoded = try JSONEncoder().encode(staged)
guard let json = String(data: encoded, encoding: .utf8) else {
throw ShortcutError.message("The shortcut attachments could not be prepared.")
}
return (dir, json)
} catch {
try? fm.removeItem(at: dir)
throw error
}
}

enum ShortcutError: LocalizedError {
case message(String)
Expand Down Expand Up @@ -35,6 +147,8 @@ struct SendBotkinsChat: AppIntent {
@Parameter(title: "Prompt", requestValueDialog: "What would you like to send?", inputConnectionBehavior: .connectToPreviousIntentResult)
var prompt: String
@Parameter(title: "Agent") var agent: ShortcutAgent
@Parameter(title: "Attachments", description: "Photos, videos, or files to send with the prompt.", supportedContentTypes: [.item])
var attachments: [IntentFile]?
@Parameter(title: "Model", description: "Leave empty to use the bot’s model.")
var model: ShortcutModel?
@Parameter(title: "Thinking Level", optionsProvider: ThinkingLevels()) var effort: String?
Expand All @@ -43,6 +157,7 @@ struct SendBotkinsChat: AppIntent {

static var parameterSummary: some ParameterSummary {
Summary("Send \(\.$prompt) to \(\.$agent)") {
\.$attachments
\.$model
\.$effort
\.$wait
Expand All @@ -59,6 +174,15 @@ struct SendBotkinsChat: AppIntent {
fields["modelHost"] = model.host
fields["model"] = model.key
}
var stagedDir: URL?
defer {
if let dir = stagedDir { try? FileManager.default.removeItem(at: dir) }
}
if let files = attachments, !files.isEmpty {
let staged = try stageShortcutAttachments(files)
stagedDir = staged.dir
fields["attachments"] = staged.json
}
fields["action"] = "send"
fields["prompt"] = prompt
fields["effort"] = effort
Expand Down Expand Up @@ -135,12 +259,50 @@ struct ChatWithYourBotkin: AppIntent {
}
}

@available(iOS 17.0, *)
struct RunBotkinsWorkflow: AppIntent {
static let title: LocalizedStringResource = "Run a Workflow"
static let description = IntentDescription("Run a Botkins workflow on your computer. Turn on Wait for Result to pass the run result to the next action.", resultValueName: "Result")
static var authenticationPolicy: IntentAuthenticationPolicy { .requiresAuthentication }

@Parameter(title: "Computer") var computer: ShortcutHost
@Parameter(title: "Workflow") var workflow: ShortcutWorkflow
@Parameter(title: "Inputs", description: "Optional JSON object of input values for the workflow’s manual trigger.")
var inputs: String?
@Parameter(title: "Wait for Result", default: true) var wait: Bool

static var parameterSummary: some ParameterSummary {
Summary("Run \(\.$workflow)") {
\.$computer
\.$inputs
\.$wait
}
}

func perform() async throws -> some IntentResult & ReturnsValue<String> {
if computer.id != ShortcutHost.current.id, computer.id != workflow.host {
throw ShortcutError.message("Choose a workflow from the selected computer.")
}
var fields: [String: String] = [
"action": "workflow",
"host": workflow.host,
"workflow": workflow.workflowId,
"wait": wait ? "yes" : "no",
]
if let inputs, !inputs.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
fields["inputs"] = inputs
}
return .result(value: try await runShortcut(fields))
}
}

@available(iOS 17.0, *)
struct BotkinsShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(intent: OpenBotkins(), phrases: ["Open \(.applicationName)"], shortTitle: "Open Botkins", systemImageName: "bubble.left.and.bubble.right")
AppShortcut(intent: ChatWithYourBotkin(), phrases: ["Chat with my Botkin in \(.applicationName)"], shortTitle: "Chat with your Botkin", systemImageName: "person.bubble")
AppShortcut(intent: SendBotkinsChat(), phrases: ["Send a chat with \(.applicationName)"], shortTitle: "Send a Botkins Chat", systemImageName: "paperplane")
AppShortcut(intent: StartBotkinsVoiceChat(), phrases: ["Start a voice chat with \(.applicationName)"], shortTitle: "Start a Voice Chat", systemImageName: "waveform")
AppShortcut(intent: RunBotkinsWorkflow(), phrases: ["Run a workflow in \(.applicationName)"], shortTitle: "Run a Workflow", systemImageName: "arrow.triangle.branch")
}
}
71 changes: 71 additions & 0 deletions mobile/plugins/shortcuts/ShortcutPickers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ private struct Catalog: Decodable {
}
}

private struct WorkflowCatalog: Decodable {
struct Item: Decodable {
let id, name: String
let description: String?
let enabled: Bool
}
let host, name: String
let workflows: [Item]

static func load(host: String? = nil) async throws -> Self {
var fields = ["action": "workflows"]
fields["host"] = host
let json = try await runShortcut(fields)
return try JSONDecoder().decode(Self.self, from: Data(json.utf8))
}
}

private func hosts(in identifiers: [String]) -> Set<String> {
Set(identifiers.compactMap { id in id.firstIndex(of: "|").map { String(id[..<$0]) } })
}
Expand Down Expand Up @@ -183,6 +200,60 @@ struct ShortcutModel: AppEntity {
}
}

@available(iOS 17.0, *)
struct ShortcutWorkflow: AppEntity {
static let typeDisplayRepresentation: TypeDisplayRepresentation = "Workflow"
static let defaultQuery = WorkflowQuery()
let host: String
let workflowId: String
let name: String
let summary: String?
let computer: String?
var id: String { host + "|" + workflowId }
var displayRepresentation: DisplayRepresentation {
let trimmed = summary?.trimmingCharacters(in: .whitespacesAndNewlines)
let subtitle = (trimmed?.isEmpty == false ? trimmed : nil) ?? computer
return DisplayRepresentation(
title: "\(name)",
subtitle: subtitle.map { "\($0)" },
image: .init(systemName: "arrow.triangle.branch")
)
}

struct WorkflowQuery: EntityQuery {
@IntentParameterDependency<RunBotkinsWorkflow>(\.$computer) var intent
private func host() -> String? {
guard let id = intent?.computer.id, id != ShortcutHost.current.id else { return nil }
return id
}
private func workflows(on host: String?) async throws -> [ShortcutWorkflow] {
let catalog = try await WorkflowCatalog.load(host: host)
return catalog.workflows.map {
ShortcutWorkflow(
host: catalog.host,
workflowId: $0.id,
name: $0.name,
summary: $0.description,
computer: catalog.name
)
}
}
func suggestedEntities() async throws -> [ShortcutWorkflow] {
try await workflows(on: host())
}
func entities(for identifiers: [String]) async throws -> [ShortcutWorkflow] {
var options: [ShortcutWorkflow] = []
for host in hosts(in: identifiers) { options += try await workflows(on: host) }
return try identifiers.map { id in
guard let workflow = options.first(where: { $0.id == id }) else {
throw ShortcutError.message("Choose a workflow that is still available on the selected computer.")
}
return workflow
}
}
}
}

@available(iOS 17.0, *)
struct ThinkingLevels: DynamicOptionsProvider {
@IntentParameterDependency<SendBotkinsChat>(\.$agent, \.$model) var intent
Expand Down
34 changes: 34 additions & 0 deletions mobile/src/features/chat/uploads.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Files a person attaches to a message: picked on the phone, sent to the computer in parts of at
// most 3 MB with `link.upload`, then named in `send`'s attachments.
import { File, FileMode } from "expo-file-system";
import type { LinkClient } from "@/link/client";
import type { UploadedFile } from "@/link/types";
import { api, holdBackgroundLink } from "@/state/link";

Expand Down Expand Up @@ -61,6 +62,39 @@ export function sizeOf(uri: string): number {
}
}

type UploadLink = Pick<LinkClient, "call">;

/** Sends a file over a specific LinkClient in parts without mutating foreground app state. */
export async function uploadWithLink(
link: UploadLink,
uri: string,
name: string,
signal?: AbortSignal,
onProgress?: (fraction: number) => void,
): Promise<UploadedFile> {
signal?.throwIfAborted();
const handle = new File(uri).open(FileMode.ReadOnly);
try {
const total = handle.size ?? 0;
if (total > MAX_BYTES) throw new Error(`"${name}" is too large. Files can be up to 25 MB.`);
let sent = 0;
let id: string | undefined;
for (;;) {
const bytes = await handle.readBytes(PART);
const last = bytes.length < PART || (total > 0 && sent + bytes.length >= total);
signal?.throwIfAborted();
if (sent + bytes.length > MAX_BYTES) throw new Error(`"${name}" is too large. Files can be up to 25 MB.`);
const result = await link.call<UploadedFile>("link.upload", { ...(id ? { id } : {}), name, data: toBase64(bytes), last });
id = result.id;
sent += bytes.length;
onProgress?.(total ? Math.min(1, sent / total) : 1);
if (last) return result;
}
} finally {
handle.close();
}
}

// One file at a time, so several big files never sit in memory together.
let queue: Promise<unknown> = Promise.resolve();

Expand Down
Loading
Loading