From af176849fabf029751aa9c07538c422c32b5882d Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:21:02 -0600 Subject: [PATCH] Add attachments to Send a Botkins Chat and add Run a Workflow shortcut Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- mobile/plugins/shortcuts/ChatShortcuts.swift | 162 +++++++++++ .../plugins/shortcuts/ShortcutPickers.swift | 71 +++++ mobile/src/features/chat/uploads.ts | 34 +++ mobile/src/features/shortcuts/bridge.ts | 48 +++- mobile/src/features/shortcuts/chat.ts | 45 +++- mobile/src/features/shortcuts/workflow.ts | 149 +++++++++++ mobile/src/link/types.ts | 2 + mobile/tests/shortcuts.test.ts | 251 ++++++++++++++++++ 8 files changed, 756 insertions(+), 6 deletions(-) create mode 100644 mobile/src/features/shortcuts/workflow.ts diff --git a/mobile/plugins/shortcuts/ChatShortcuts.swift b/mobile/plugins/shortcuts/ChatShortcuts.swift index 62d39859..1b09b6ec 100644 --- a/mobile/plugins/shortcuts/ChatShortcuts.swift +++ b/mobile/plugins/shortcuts/ChatShortcuts.swift @@ -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 { + 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 = [] + 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) @@ -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? @@ -43,6 +157,7 @@ struct SendBotkinsChat: AppIntent { static var parameterSummary: some ParameterSummary { Summary("Send \(\.$prompt) to \(\.$agent)") { + \.$attachments \.$model \.$effort \.$wait @@ -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 @@ -135,6 +259,43 @@ 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 { + 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] { @@ -142,5 +303,6 @@ struct BotkinsShortcuts: AppShortcutsProvider { 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") } } diff --git a/mobile/plugins/shortcuts/ShortcutPickers.swift b/mobile/plugins/shortcuts/ShortcutPickers.swift index d8239c7d..14e7004d 100644 --- a/mobile/plugins/shortcuts/ShortcutPickers.swift +++ b/mobile/plugins/shortcuts/ShortcutPickers.swift @@ -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 { Set(identifiers.compactMap { id in id.firstIndex(of: "|").map { String(id[..<$0]) } }) } @@ -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(\.$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(\.$agent, \.$model) var intent diff --git a/mobile/src/features/chat/uploads.ts b/mobile/src/features/chat/uploads.ts index d2742d93..b9997c14 100644 --- a/mobile/src/features/chat/uploads.ts +++ b/mobile/src/features/chat/uploads.ts @@ -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"; @@ -61,6 +62,39 @@ export function sizeOf(uri: string): number { } } +type UploadLink = Pick; + +/** 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 { + 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("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 = Promise.resolve(); diff --git a/mobile/src/features/shortcuts/bridge.ts b/mobile/src/features/shortcuts/bridge.ts index 101cbbb4..5b1e4e6f 100644 --- a/mobile/src/features/shortcuts/bridge.ts +++ b/mobile/src/features/shortcuts/bridge.ts @@ -1,9 +1,10 @@ import { requireOptionalNativeModule, type EventSubscription } from "expo-modules-core"; import { AppState } from "react-native"; +import type { ShortcutAttachment } from "./chat"; type Fields = { id: string; - action: "hosts" | "catalog" | "send" | "voice" | "open"; + action: "hosts" | "catalog" | "send" | "voice" | "open" | "workflows" | "workflow"; host?: string; bot?: string; botHost?: string; @@ -12,6 +13,9 @@ type Fields = { model?: string; effort?: string; prompt?: string; + attachments?: string; + workflow?: string; + inputs?: string; wait?: string; notify?: string; models?: string; @@ -24,6 +28,26 @@ type Native = { }; const native = requireOptionalNativeModule("BotkinsShortcuts"); +function parseAttachments(raw?: string): ShortcutAttachment[] { + if (!raw?.trim()) return []; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new Error("The shortcut attachments could not be read."); + } + if (!Array.isArray(parsed)) throw new Error("The shortcut attachments could not be read."); + const items: ShortcutAttachment[] = []; + for (const entry of parsed) { + if (!entry || typeof entry !== "object") continue; + const { name, uri } = entry as Record; + if (typeof uri === "string" && uri.trim()) { + items.push({ name: typeof name === "string" && name.trim() ? name.trim() : "attachment", uri }); + } + } + return items; +} + async function run(fields: Fields, signal: AbortSignal): Promise { if (fields.action === "hosts") { const { shortcutHosts } = await import("@/state/link"); @@ -40,13 +64,31 @@ async function run(fields: Fields, signal: AbortSignal): Promise { return ""; } const { shortcutLink } = await import("@/state/link"); - const { sendShortcut, shortcutCatalog } = await import("./chat"); const { host, name, link } = await shortcutLink(fields.host); try { signal.throwIfAborted(); + if (fields.action === "workflows") { + const { shortcutWorkflows } = await import("./workflow"); + return JSON.stringify({ host, name, ...(await shortcutWorkflows(link)) }); + } + if (fields.action === "workflow") { + const { runWorkflowShortcut } = await import("./workflow"); + return await runWorkflowShortcut(link, { workflow: fields.workflow ?? "", inputs: fields.inputs, wait: fields.wait === "yes" }, signal); + } + const { sendShortcut, shortcutCatalog } = await import("./chat"); if (fields.action === "catalog") return JSON.stringify({ host, name, ...(await shortcutCatalog(link, fields.models === "yes")) }); if (fields.modelHost && fields.modelHost !== host) throw new Error("Choose a model from the agent’s computer."); - return await sendShortcut(link, { ...fields, prompt: fields.prompt ?? "", wait: fields.wait === "yes", notify: fields.notify !== "no" }, signal); + return await sendShortcut( + link, + { + ...fields, + prompt: fields.prompt ?? "", + attachments: parseAttachments(fields.attachments), + wait: fields.wait === "yes", + notify: fields.notify !== "no", + }, + signal, + ); } finally { link.stop(); } diff --git a/mobile/src/features/shortcuts/chat.ts b/mobile/src/features/shortcuts/chat.ts index 2291f95b..09bbe024 100644 --- a/mobile/src/features/shortcuts/chat.ts +++ b/mobile/src/features/shortcuts/chat.ts @@ -8,7 +8,21 @@ type Link = Pick; type News = { epoch: string; v: Record | null; parts: Record }; type Context = { bots?: Bot[]; settings?: Preferences; meta?: Meta }; -export type ShortcutSend = { bot?: string; prompt: string; model?: string; effort?: string; wait: boolean; notify: boolean }; +export const MAX_SHORTCUT_ATTACHMENTS = 10; +export type ShortcutAttachment = { name: string; uri: string }; +export type ShortcutUploadedAttachment = { name: string; path: string }; +export type ShortcutUploader = (link: Link, item: ShortcutAttachment, signal: AbortSignal) => Promise; + +export type ShortcutSend = { + bot?: string; + prompt: string; + model?: string; + effort?: string; + wait: boolean; + notify: boolean; + attachments?: ShortcutAttachment[]; + upload?: ShortcutUploader; +}; const sync = (link: Link, options = {}) => link.call("link.sync", { steps: "light", appends: {}, ...options }); function selectedBot(bots: Bot[] = [], id?: string) { @@ -46,12 +60,18 @@ export function shortcutReply(detail: ChatDetail, runId: string): string | undef } export async function sendShortcut(link: Link, input: ShortcutSend, signal: AbortSignal): Promise { - if (!input.prompt.trim()) throw new Error("Enter a prompt for the bot."); + const attachments = input.attachments ?? []; + if (attachments.length > MAX_SHORTCUT_ATTACHMENTS) throw new Error("Attach up to 10 files at a time."); + const trimmed = input.prompt.trim(); + if (!trimmed && !attachments.length) throw new Error("Enter a prompt for the bot."); if (input.prompt.length > 32_000) throw new Error("Use a prompt of up to 32,000 characters."); + // The computer requires non-empty text with a message, so attachments alone get a plain line. + const prompt = trimmed || (attachments.length === 1 ? "See the attached file." : "See the attached files."); const initial = await sync(link); const { bots, settings, meta } = initial.parts as Context; const bot = selectedBot(bots, input.bot); if (!input.notify && !meta?.capabilities.includes("quiet-replies-v1")) throw new Error("Update Botkins on your computer to send without a reply notification."); + if (attachments.length && meta && !meta.capabilities.includes("uploads-v1")) throw new Error("Update Botkins on your computer to send attachments."); let choice; if (input.model || input.effort) { const { models, defaultProvider } = await modelOptions(link); @@ -60,12 +80,31 @@ export async function sendShortcut(link: Link, input: ShortcutSend, signal: Abor if (input.effort && !model.efforts.includes(input.effort)) throw new Error("Choose a thinking level this model supports."); choice = chooseModel(model, input.effort); } + const uploaded: ShortcutUploadedAttachment[] = []; + if (attachments.length) { + const uploader: ShortcutUploader = + input.upload ?? + (async (uploadLink, item, uploadSignal) => { + const { uploadWithLink } = await import("@/features/chat/uploads"); + const file = await uploadWithLink(uploadLink, item.uri, item.name, uploadSignal); + return { name: file.name, path: file.path }; + }); + for (const item of attachments) { + signal.throwIfAborted(); + const file = await uploader(link, item, signal); + uploaded.push({ name: file.name || item.name, path: file.path }); + } + } signal.throwIfAborted(); const chat = await link.call("createChat", bot.id); signal.throwIfAborted(); if (choice) await link.call("setModel", "chat", chat, choice); signal.throwIfAborted(); - await link.call("send", chat, input.prompt, input.notify ? {} : { notify: false }); + const sendOptions = { + ...(uploaded.length ? { attachments: uploaded } : {}), + ...(!input.notify ? { notify: false as const } : {}), + }; + await link.call("send", chat, prompt, sendOptions); if (!input.wait) return ""; // The first user message identifies this turn even if another device starts the next one. diff --git a/mobile/src/features/shortcuts/workflow.ts b/mobile/src/features/shortcuts/workflow.ts new file mode 100644 index 00000000..f756ef20 --- /dev/null +++ b/mobile/src/features/shortcuts/workflow.ts @@ -0,0 +1,149 @@ +// A workflow shortcut owns its link for the duration of the call, never touching foreground UI state. +import type { LinkClient } from "@/link/client"; +import type { Workflow, WorkflowRun, WorkflowStepRun } from "@/link/types"; + +type Link = Pick; +type News = { epoch: string; v: Record | null; parts: Record }; + +export type ShortcutWorkflowRun = { + workflow: string; + inputs?: string; + wait: boolean; +}; + +const sync = (link: Link, options = {}) => link.call("link.sync", { steps: "light", appends: {}, ...options }); + +export function parseWorkflowInputs(raw?: string): Record | undefined { + if (raw === undefined || !raw.trim()) return undefined; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + throw new Error('Inputs must be a JSON object, like {"topic": "news"}.'); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error('Inputs must be a JSON object, like {"topic": "news"}.'); + } + return parsed as Record; +} + +/** Workflow list for the iOS Shortcuts picker. */ +export async function shortcutWorkflows(link: Link) { + const response = await link.call<{ workflows?: Workflow[]; runs?: WorkflowRun[] }>("workflowsList"); + const workflows = Array.isArray(response?.workflows) ? response.workflows : []; + return { + workflows: workflows.map((workflow) => ({ + id: workflow.id, + name: workflow.name, + description: workflow.description ?? "", + enabled: workflow.enabled !== false, + })), + }; +} + +function formatOutputs(outputs: Record | undefined): string { + if (!outputs || typeof outputs !== "object") return ""; + const entries = Object.entries(outputs).filter(([, value]) => value !== undefined && value !== null && (typeof value !== "string" || value.trim().length > 0)); + if (!entries.length) return ""; + if (entries.length === 1) { + const [, value] = entries[0]; + return typeof value === "string" ? value.trim() : JSON.stringify(value); + } + return JSON.stringify(Object.fromEntries(entries)); +} + +function completedStepsNewestFirst(run: WorkflowRun): WorkflowStepRun[] { + const indexed = Object.values(run.steps ?? {}) + .filter((step) => step.status === "completed" && step.kind !== "trigger") + .map((step, index) => ({ step, index })); + indexed.sort((a, b) => { + const timeDiff = (b.step.finishedAt ?? b.step.startedAt ?? 0) - (a.step.finishedAt ?? a.step.startedAt ?? 0); + return timeDiff !== 0 ? timeDiff : b.index - a.index; + }); + return indexed.map((entry) => entry.step); +} + +/** Extracts the most useful human-readable output from a completed workflow run. */ +export function extractWorkflowOutput(run: WorkflowRun): string { + const completed = completedStepsNewestFirst(run); + const generative = completed.filter((step) => step.kind === "agent" || step.kind === "model"); + for (const step of generative) { + const text = formatOutputs(step.outputs); + if (text) return text; + } + for (const step of generative) { + const summary = step.summary?.trim(); + if (summary) return summary; + } + const outputs = completed.filter((step) => step.kind === "output"); + for (const step of outputs) { + const text = formatOutputs(step.outputs) || step.summary?.trim(); + if (text) return text; + } + for (const step of completed) { + const text = formatOutputs(step.outputs) || step.summary?.trim(); + if (text) return text; + } + if (run.context && typeof run.context === "object") { + const triggerKeys = new Set([ + "run_time", + "triggered_by", + ...Object.keys((run.triggerNodeId ? run.steps?.[run.triggerNodeId]?.outputs : undefined) ?? {}), + ]); + const extra = Object.fromEntries(Object.entries(run.context).filter(([key]) => !triggerKeys.has(key))); + const text = formatOutputs(extra); + if (text) return text; + } + return "Workflow completed."; +} + +export function workflowRunOutcome(run: WorkflowRun): string | undefined { + if (run.status === "running") return undefined; + if (run.status === "completed") return extractWorkflowOutput(run); + if (run.status === "waiting_approval") throw new Error("This workflow is waiting for your approval in Botkins."); + if (run.status === "cancelled") throw new Error(run.error || "The workflow run was cancelled."); + throw new Error(run.error || "The workflow run failed."); +} + +export async function runWorkflowShortcut(link: Link, input: ShortcutWorkflowRun, signal: AbortSignal): Promise { + const workflowId = input.workflow.trim(); + if (!workflowId) throw new Error("Choose a workflow to run."); + const parsedInputs = parseWorkflowInputs(input.inputs); + + let epoch: string | undefined; + let have: Record | null | undefined; + if (input.wait) { + signal.throwIfAborted(); + const initial = await sync(link); + epoch = initial.epoch; + have = initial.v; + } + + signal.throwIfAborted(); + const started = await link.call("workflowRun", workflowId, parsedInputs ? { inputs: parsedInputs } : {}); + if (!input.wait) return "Started workflow."; + + const immediate = workflowRunOutcome(started); + if (immediate !== undefined) return immediate; + + while (!signal.aborted) { + const news = await sync(link, { ...(epoch ? { epoch } : {}), ...(have ? { have } : {}), wait: 15_000 }); + epoch = news.epoch; + if (news.v) have = news.v; + + let current: WorkflowRun | undefined; + const syncedRuns = news.parts.workflowRuns as WorkflowRun[] | undefined; + if (Array.isArray(syncedRuns)) { + current = syncedRuns.find((item) => item.id === started.id); + } else { + signal.throwIfAborted(); + const listed = await link.call<{ workflows?: Workflow[]; runs?: WorkflowRun[] }>("workflowsList"); + current = listed?.runs?.find((item) => item.id === started.id); + } + if (current) { + const outcome = workflowRunOutcome(current); + if (outcome !== undefined) return outcome; + } + } + throw new Error("The shortcut stopped waiting. Check the workflow in Botkins."); +} diff --git a/mobile/src/link/types.ts b/mobile/src/link/types.ts index 7460ad1e..14ed1a3c 100644 --- a/mobile/src/link/types.ts +++ b/mobile/src/link/types.ts @@ -1971,6 +1971,7 @@ export type WorkflowStepRun = { startedAt?: number | null; finishedAt?: number | null; summary?: string; + outputs?: Record; error?: string; errorCode?: string | null; githubUncertain?: WorkflowGithubUncertainInfo | null; @@ -1990,6 +1991,7 @@ export type WorkflowRun = { error?: string | null; errorCode?: string | null; githubUncertain?: WorkflowGithubUncertainInfo | null; + context?: Record; steps: Record; pendingApproval?: { nodeId: string; label: string; message: string; noteField?: string | null } | null; }; diff --git a/mobile/tests/shortcuts.test.ts b/mobile/tests/shortcuts.test.ts index e038a889..42d01b17 100644 --- a/mobile/tests/shortcuts.test.ts +++ b/mobile/tests/shortcuts.test.ts @@ -6,7 +6,9 @@ import { test } from "node:test"; import { LinkHost } from "../link-host/index.mjs"; import { MockBackend } from "../link-host/mock-backend.mjs"; import { LinkClient, pair, type FetchLike } from "../src/link/client"; +import type { Workflow, WorkflowRun } from "../src/link/types"; import { sendShortcut, shortcutReply } from "../src/features/shortcuts/chat"; +import { extractWorkflowOutput, runWorkflowShortcut, shortcutWorkflows } from "../src/features/shortcuts/workflow"; test("a shortcut sends over the paired link, returns its final reply, and can also send quietly without waiting", async (t) => { const dir = mkdtempSync(join(tmpdir(), "botkins-shortcut-")); @@ -81,3 +83,252 @@ test("Push.kindOf suppresses channel chat reply pushes unless the connection's n assert.equal(host.push.kindOf(scheduledRun, quietChat), "routines"); assert.equal(host.push.kindOf(run, normalChat), "replies"); }); + +test("sendShortcut uploads attachments, allows empty prompt with attachments, and enforces the 10-file limit", async () => { + const calls: { method: string; args: unknown[] }[] = []; + const uploadedItems: { name: string; uri: string }[] = []; + const fakeLink = { + async call(method: string, ...args: unknown[]): Promise { + calls.push({ method, args }); + if (method === "link.sync") { + return { + epoch: "e1", + v: { bots: 1 }, + parts: { + bots: [{ id: "bot-1", name: "Alfie" }], + meta: { capabilities: ["quiet-replies-v1", "uploads-v1"] }, + settings: {}, + }, + } as T; + } + if (method === "createChat") return "chat-att" as T; + if (method === "send") return undefined as T; + throw new Error("Unexpected call: " + method); + }, + }; + const upload = async (_link: unknown, item: { name: string; uri: string }) => { + uploadedItems.push(item); + return { name: item.name, path: "/uploads/" + item.name }; + }; + + // Single attachment with prompt + await sendShortcut( + fakeLink, + { + prompt: "Summarize this screenshot", + wait: false, + notify: true, + attachments: [{ name: "screen.png", uri: "file:///tmp/screen.png" }], + upload, + }, + new AbortController().signal, + ); + assert.deepEqual(uploadedItems, [{ name: "screen.png", uri: "file:///tmp/screen.png" }]); + const firstSend = calls.filter((c) => c.method === "send")[0]; + assert.deepEqual(firstSend.args, [ + "chat-att", + "Summarize this screenshot", + { attachments: [{ name: "screen.png", path: "/uploads/screen.png" }] }, + ]); + + // Multiple attachments with empty prompt + quiet notify + uploadedItems.length = 0; + await sendShortcut( + fakeLink, + { + prompt: " ", + wait: false, + notify: false, + attachments: [ + { name: "a.jpg", uri: "file:///tmp/a.jpg" }, + { name: "b.pdf", uri: "file:///tmp/b.pdf" }, + ], + upload, + }, + new AbortController().signal, + ); + assert.equal(uploadedItems.length, 2); + const secondSend = calls.filter((c) => c.method === "send")[1]; + assert.deepEqual(secondSend.args, [ + "chat-att", + "See the attached files.", + { + attachments: [ + { name: "a.jpg", path: "/uploads/a.jpg" }, + { name: "b.pdf", path: "/uploads/b.pdf" }, + ], + notify: false, + }, + ]); + + // Single attachment with empty prompt + await sendShortcut( + fakeLink, + { + prompt: "", + wait: false, + notify: true, + attachments: [{ name: "only.txt", uri: "file:///tmp/only.txt" }], + upload, + }, + new AbortController().signal, + ); + const thirdSend = calls.filter((c) => c.method === "send")[2]; + assert.equal(thirdSend.args[1], "See the attached file."); + + // Over-limit (>10 attachments) rejects before touching the link + const beforeCalls = calls.length; + const tooMany = Array.from({ length: 11 }, (_, i) => ({ name: `f${i}.txt`, uri: `file:///tmp/f${i}.txt` })); + await assert.rejects( + sendShortcut(fakeLink, { prompt: "hi", wait: false, notify: true, attachments: tooMany, upload }, new AbortController().signal), + /up to 10 files/i, + ); + await assert.rejects( + sendShortcut(fakeLink, { prompt: " ", wait: false, notify: true, attachments: [], upload }, new AbortController().signal), + /prompt/i, + ); + assert.equal(calls.length, beforeCalls); +}); + +test("shortcutWorkflows returns workflow metadata for the picker", async () => { + const workflows: Workflow[] = [ + { id: "wf-1", name: "Morning Brief", description: "Daily digest", enabled: true, nodes: [], edges: [], createdAt: 1, updatedAt: 2 }, + { id: "wf-2", name: "Release Check", enabled: false, nodes: [], edges: [], createdAt: 1, updatedAt: 2 }, + ]; + const fakeLink = { + async call(method: string): Promise { + assert.equal(method, "workflowsList"); + return { workflows, runs: [] } as T; + }, + }; + const catalog = await shortcutWorkflows(fakeLink); + assert.deepEqual(catalog, { + workflows: [ + { id: "wf-1", name: "Morning Brief", description: "Daily digest", enabled: true }, + { id: "wf-2", name: "Release Check", description: "", enabled: false }, + ], + }); +}); + +test("runWorkflowShortcut handles no-wait, completion, failure, approval, and invalid JSON inputs", async () => { + const makeRun = (overrides: Partial): WorkflowRun => ({ + id: "wfr-1", + workflowId: "wf-1", + workflowName: "Morning Brief", + status: "running", + triggerNodeId: "t1", + startedAt: 100, + steps: { + t1: { nodeId: "t1", kind: "trigger", label: "Manual", status: "completed", startedAt: 100, finishedAt: 100, outputs: { topic: "ai" } }, + }, + ...overrides, + }); + + // Invalid JSON inputs fail fast without calling the link + let called = false; + const untouched = { + async call(): Promise { + called = true; + throw new Error("should not call"); + }, + }; + await assert.rejects(runWorkflowShortcut(untouched, { workflow: "wf-1", inputs: "{bad", wait: false }, new AbortController().signal), /JSON object/i); + await assert.rejects(runWorkflowShortcut(untouched, { workflow: "wf-1", inputs: "[1, 2]", wait: false }, new AbortController().signal), /JSON object/i); + await assert.rejects(runWorkflowShortcut(untouched, { workflow: "wf-1", inputs: '"str"', wait: false }, new AbortController().signal), /JSON object/i); + assert.equal(called, false); + + // No-wait passes parsed inputs and returns confirmation + const runCalls: unknown[][] = []; + const noWaitLink = { + async call(method: string, ...args: unknown[]): Promise { + runCalls.push([method, ...args]); + return makeRun({ status: "running" }) as T; + }, + }; + assert.equal( + await runWorkflowShortcut(noWaitLink, { workflow: "wf-1", inputs: '{"topic":"news"}', wait: false }, new AbortController().signal), + "Started workflow.", + ); + assert.deepEqual(runCalls, [["workflowRun", "wf-1", { inputs: { topic: "news" } }]]); + + // Wait for completion via link.sync and extract agent reply + let syncCount = 0; + const waitSuccessLink = { + async call(method: string): Promise { + if (method === "workflowRun") return makeRun({ status: "running" }) as T; + if (method === "link.sync") { + syncCount++; + if (syncCount === 1) return { epoch: "e1", v: { workflowRuns: 1 }, parts: { workflowRuns: [] } } as T; + if (syncCount === 2) return { epoch: "e1", v: { workflowRuns: 2 }, parts: { workflowRuns: [makeRun({ status: "running" })] } } as T; + return { + epoch: "e1", + v: { workflowRuns: 3 }, + parts: { + workflowRuns: [ + makeRun({ + status: "completed", + finishedAt: 300, + steps: { + t1: { nodeId: "t1", kind: "trigger", label: "Manual", status: "completed", startedAt: 100, finishedAt: 100, outputs: { topic: "news" } }, + a1: { nodeId: "a1", kind: "agent", label: "Research", status: "completed", startedAt: 110, finishedAt: 250, outputs: { agent_reply: "Top 3 stories today." }, summary: "Top 3 stories today." }, + o1: { nodeId: "o1", kind: "output", label: "Post", status: "completed", startedAt: 260, finishedAt: 300, summary: "Posted to Main" }, + }, + }), + ], + }, + } as T; + } + throw new Error("Unexpected: " + method); + }, + }; + assert.equal( + await runWorkflowShortcut(waitSuccessLink, { workflow: "wf-1", wait: true }, new AbortController().signal), + "Top 3 stories today.", + ); + + // Wait for failure surfaces error + const waitFailLink = { + async call(method: string): Promise { + if (method === "workflowRun") return makeRun({ status: "running" }) as T; + if (method === "link.sync") { + return { epoch: "e1", v: { workflowRuns: 2 }, parts: { workflowRuns: [makeRun({ status: "failed", error: "Research: Model offline" })] } } as T; + } + throw new Error("Unexpected: " + method); + }, + }; + await assert.rejects( + runWorkflowShortcut(waitFailLink, { workflow: "wf-1", wait: true }, new AbortController().signal), + /Research: Model offline/, + ); + + // Wait for approval surfaces approval message + const waitApprovalLink = { + async call(method: string): Promise { + if (method === "workflowRun") return makeRun({ status: "waiting_approval" }) as T; + if (method === "link.sync") return { epoch: "e1", v: {}, parts: {} } as T; + throw new Error("Unexpected: " + method); + }, + }; + await assert.rejects( + runWorkflowShortcut(waitApprovalLink, { workflow: "wf-1", wait: true }, new AbortController().signal), + /waiting for your approval/i, + ); + + // Output extraction fallback checks + assert.equal( + extractWorkflowOutput(makeRun({ status: "completed" })), + "Workflow completed.", + ); + assert.equal( + extractWorkflowOutput( + makeRun({ + status: "completed", + steps: { + t1: { nodeId: "t1", kind: "trigger", label: "Manual", status: "completed", startedAt: 100, finishedAt: 100 }, + o1: { nodeId: "o1", kind: "output", label: "Notify", status: "completed", startedAt: 110, finishedAt: 120, summary: "Sent notification: Ready" }, + }, + }), + ), + "Sent notification: Ready", + ); +});