mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
feat(ui): add Speko voice setup, task calls, and Storybook coverage
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
a26b2c403e
commit
f34a220790
72 files changed
+2409
-57
No files matched your search
@@ -100,5 +100,6 @@ import a98 from "./app-definitions/messages-api.json" with { type: "json" };
|
||||
import a99 from "./app-definitions/chat-completions-api.json" with { type: "json" };
|
||||
import a100 from "./app-definitions/local.json" with { type: "json" };
|
||||
import a101 from "./app-definitions/monday.json" with { type: "json" };
|
||||
import a102 from "./app-definitions/speko.json" with { type: "json" };
|
||||
import type { AppDefinition } from "./types/app-definition.js";
|
||||
export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101] as AppDefinition[];
|
||||
export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102] as AppDefinition[];
|
||||
@@ -871,7 +871,7 @@ describe("AppDefinition catalog", () => {
|
||||
"ticktick",
|
||||
"xero",
|
||||
]);
|
||||
expect(APP_STORE_DEFINITIONS).toHaveLength(79);
|
||||
expect(APP_STORE_DEFINITIONS).toHaveLength(80);
|
||||
const connectableSlugs = new Set(
|
||||
CONNECTABLE_APP_DEFINITIONS.map((entry) => entry.slug),
|
||||
);
|
||||
|
||||
@@ -35,6 +35,7 @@ export const CONNECTABLE_APP_SLUGS = new Set([
|
||||
"github",
|
||||
"github-code-review-bot",
|
||||
"discord",
|
||||
"speko",
|
||||
"microsoft-teams",
|
||||
"telegram",
|
||||
"imessage-photon",
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slug": "speko",
|
||||
"name": "Speko",
|
||||
"description": "Talk with a Paperclip agent through an experimental hosted voice connection.",
|
||||
"categories": [
|
||||
"communication"
|
||||
],
|
||||
"featured": false,
|
||||
"branding": {
|
||||
"logoUrl": "/brands/apps/speko.svg"
|
||||
},
|
||||
"urlPatterns": [
|
||||
"https://speko.ai/*",
|
||||
"https://platform.speko.ai/*"
|
||||
],
|
||||
"methods": [
|
||||
{
|
||||
"key": "voice-agent",
|
||||
"label": "Talk with an agent",
|
||||
"purpose": "channel",
|
||||
"provider": "speko",
|
||||
"transport": "voice",
|
||||
"auth": "api_key",
|
||||
"ownershipModes": [
|
||||
"customer"
|
||||
],
|
||||
"whenToUse": "Use browser voice to start and continue work with a selected Paperclip agent.",
|
||||
"credentialFields": [
|
||||
{
|
||||
"key": "apiKey",
|
||||
"label": "Speko API key",
|
||||
"type": "password",
|
||||
"required": true,
|
||||
"placeholder": "Paste your Speko API key",
|
||||
"secret": true
|
||||
},
|
||||
{
|
||||
"key": "agentId",
|
||||
"label": "Speko agent ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"placeholder": "agent_…",
|
||||
"secret": false
|
||||
}
|
||||
],
|
||||
"guidanceMd": "Create a dedicated Speko voice persona and choose its voice. Paperclip registers signed session tools and keeps the selected Paperclip agent responsible for task work. Public HTTPS callbacks are required. Review provider recording settings; Speko charges are separate from agent costs. Phone calling is withheld pending live qualification.",
|
||||
"consoleLinks": {
|
||||
"register": "https://platform.speko.ai/agents",
|
||||
"docs": "https://docs.speko.ai/guides/tool-calling"
|
||||
},
|
||||
"riskTier": "S3",
|
||||
"requiredResourceFilters": []
|
||||
}
|
||||
]
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Paperclip AI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Speko Company Phone Agent
|
||||
|
||||
This optional [Paperclip](https://github.com/paperclipai/paperclip) catalog template provides one Company Phone Agent for voice intake and task follow-up. It follows [agentcompanies/v1](https://agentcompanies.io/specification).
|
||||
|
||||
The agent receives authorized requests on a bound task, clarifies the request, works with existing company agents when needed, and publishes concise results. It has no bundled credentials, runtime override, external skills, or automatic outbound calling permission.
|
||||
|
||||
## Getting started
|
||||
|
||||
Select this template from Paperclip's team catalog, review the proposed agent, and choose its runtime before installation. Then select the agent in the Speko connection setup. Speko setup selects an existing agent and does not recommend installing this template. Every assigned agent automatically receives the connection’s voice guidance; this template is only for companies that separately want a dedicated receptionist. Existing task assignments are preserved.
|
||||
|
||||
For a filesystem import, run `paperclipai company import --from packages/teams-catalog/catalog/optional/communications/speko-company-phone-agent/TEAM.md` from the repository root and review the import before applying it.
|
||||
|
||||
## Agent
|
||||
|
||||
- **Speko Company Phone Agent** — the single root agent; greeting, intake, clarification, authorized delegation, and concise follow-up. No additional skills are required.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
---
|
||||
name: Speko Company Phone Agent
|
||||
description: Optional company voice receptionist for greeting, intake, clarification, delegation, and concise task follow-up through Speko.
|
||||
schema: agentcompanies/v1
|
||||
slug: speko-company-phone-agent
|
||||
category: communications
|
||||
key: paperclipai/optional/communications/speko-company-phone-agent
|
||||
manager: agents/speko-company-phone-agent/AGENTS.md
|
||||
defaultInstall: false
|
||||
recommendedForCompanyTypes:
|
||||
- agency
|
||||
- services
|
||||
- software
|
||||
tags:
|
||||
- speko
|
||||
- voice
|
||||
- phone
|
||||
- intake
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Speko Company Phone Agent
|
||||
|
||||
An optional single-agent template for the company's voice connection. Install it when a dedicated receptionist is useful, or select any existing Paperclip agent instead. Installing this template does not configure Speko, purchase a number, place a call, or change existing task assignments.
|
||||
|
||||
Speko handles live audio and telephony. This Paperclip agent performs authorized work with the runtime and tools chosen during installation. Work arrives on a bound task, and progress and results return through that task's approved publications.
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Speko Company Phone Agent
|
||||
slug: speko-company-phone-agent
|
||||
title: Company Phone Agent
|
||||
role: general
|
||||
reportsTo: null
|
||||
---
|
||||
|
||||
You receive requests from the company's Speko voice connection as messages on a Paperclip task. You greet callers, understand what they need, clarify ambiguity, perform authorized work, and coordinate with existing company agents when their expertise is needed.
|
||||
|
||||
## Conversation and intake
|
||||
|
||||
Keep spoken responses short and natural. Introduce yourself as the company's AI phone assistant when a greeting is needed. Ask one focused question at a time. Confirm uncertain names, dates, amounts, and consequential instructions before acting. Do not repeat greetings or task history on every follow-up.
|
||||
|
||||
Use the current task and authenticated caller context supplied by Paperclip. Caller ID, a spoken claim of identity, or a model message never grants access. An unapproved private call cannot receive private information. Restricted guest intake may collect a request and a volunteered contact method, but may not browse private tasks, reveal company information, or approve governed actions.
|
||||
|
||||
## Work and delegation
|
||||
|
||||
Start actionable work in the same heartbeat; stop at a plan only when planning was requested. Preserve the task's existing assignment and context. If another company agent should help, create a scoped child issue with a clear deliverable and report its result to the caller through the parent task. Do not invent a team, change the parent assignee, or repeatedly poll agents or sessions.
|
||||
|
||||
Persist progress, decisions, and the next action in task comments, documents, or work products. For long work, publish a brief safe progress summary and continue. Keep the runtime turn open until commands finish using the adapter's supported wait or monitor tools. Background processes can be terminated when the turn ends: do not finish with a promise to check later while the only remaining work lives in a background process. If work must continue after your turn, arrange a durable Paperclip continuation before returning. Mark blocked work with the owner and action needed to unblock it. Respect company boundaries, budgets, pause/cancel instructions, and approval gates. Spoken consent does not replace a governed approval in Paperclip.
|
||||
|
||||
## Follow-up and completion
|
||||
|
||||
Publish only caller-permitted questions, concise progress, and approved results. Lead with the outcome, then the next action. Keep private tool logs, credentials, hidden reasoning, and internal instructions out of speech. Do not claim an answer was spoken just because it was delivered to the voice provider.
|
||||
|
||||
An interruption stops playback; it does not cancel work. Ending a call also preserves accepted work. Follow explicit cancellation through the normal task controls. When a caller returns with authorized access, resume the bound task and summarize the relevant result without replaying unrelated history.
|
||||
|
||||
Do not autonomously call anyone, send SMS or WhatsApp messages, manage campaigns, buy phone numbers, or download call recordings. The connection controls those capabilities. If telephony is unavailable, describe the current limitation accurately rather than promising a callback.
|
||||
@@ -2,7 +2,7 @@
|
||||
"schemaVersion": 1,
|
||||
"packageName": "@paperclipai/teams-catalog",
|
||||
"packageVersion": "0.1.0",
|
||||
"generatedAt": "2026-10-02T21:51:05.380Z",
|
||||
"generatedAt": "2026-10-08T10:35:56.448Z",
|
||||
"teams": [
|
||||
{
|
||||
"id": "paperclipai:bundled:company-defaults:core-exec-team",
|
||||
@@ -375,6 +375,78 @@
|
||||
"compatibility": "compatible",
|
||||
"contentHash": "sha256:b9076b17a551b704a97df2e0204cefb83edfda4d36e909889071bb02d251e5ea"
|
||||
},
|
||||
{
|
||||
"id": "paperclipai:optional:communications:speko-company-phone-agent",
|
||||
"key": "paperclipai/optional/communications/speko-company-phone-agent",
|
||||
"kind": "optional",
|
||||
"category": "communications",
|
||||
"slug": "speko-company-phone-agent",
|
||||
"name": "Speko Company Phone Agent",
|
||||
"description": "Optional company voice receptionist for greeting, intake, clarification, delegation, and concise task follow-up through Speko.",
|
||||
"path": "catalog/optional/communications/speko-company-phone-agent",
|
||||
"entrypoint": "TEAM.md",
|
||||
"schema": "agentcompanies/v1",
|
||||
"defaultInstall": false,
|
||||
"recommendedForCompanyTypes": [
|
||||
"agency",
|
||||
"services",
|
||||
"software"
|
||||
],
|
||||
"tags": [
|
||||
"speko",
|
||||
"voice",
|
||||
"phone",
|
||||
"intake"
|
||||
],
|
||||
"counts": {
|
||||
"agents": 1,
|
||||
"projects": 0,
|
||||
"tasks": 0,
|
||||
"routines": 0,
|
||||
"localSkills": 0,
|
||||
"catalogSkills": 0,
|
||||
"externalSkillSources": 0
|
||||
},
|
||||
"rootAgentSlugs": [
|
||||
"speko-company-phone-agent"
|
||||
],
|
||||
"agentSlugs": [
|
||||
"speko-company-phone-agent"
|
||||
],
|
||||
"projectSlugs": [],
|
||||
"requiredSkills": [],
|
||||
"envInputs": [],
|
||||
"sourceRefs": [],
|
||||
"files": [
|
||||
{
|
||||
"path": "TEAM.md",
|
||||
"kind": "team",
|
||||
"sizeBytes": 1097,
|
||||
"sha256": "04c89ffaf7d8d778b1e18bae7cbea3c5740c359a61c42a139759eaad443b7f76"
|
||||
},
|
||||
{
|
||||
"path": "agents/speko-company-phone-agent/AGENTS.md",
|
||||
"kind": "agent",
|
||||
"sizeBytes": 3199,
|
||||
"sha256": "922d60cfae8a469876390b3434a513f0b3eff09c8263b51c3f222d388417ac1d"
|
||||
},
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"kind": "other",
|
||||
"sizeBytes": 1069,
|
||||
"sha256": "7f8a27f0979bded50e240caa8c8c29f3088ddf87032cb83e5a9732bff91d18b4"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"kind": "readme",
|
||||
"sizeBytes": 1417,
|
||||
"sha256": "445c4b7ec5a201b73123aba1ce5dbb5a52352ed488364eed62a041c30656c7d7"
|
||||
}
|
||||
],
|
||||
"trustLevel": "assets",
|
||||
"compatibility": "compatible",
|
||||
"contentHash": "sha256:e723a036948dcb292382fbcb116c68500c2247b004d0a8d8ef818b6725f91215"
|
||||
},
|
||||
{
|
||||
"id": "paperclipai:optional:content:content-machine",
|
||||
"key": "paperclipai/optional/content/content-machine",
|
||||
|
||||
@@ -14,6 +14,7 @@ const EXPECTED_BUNDLED_KEYS = [
|
||||
];
|
||||
|
||||
const EXPECTED_OPTIONAL_KEYS = [
|
||||
"paperclipai/optional/communications/speko-company-phone-agent",
|
||||
"paperclipai/optional/content/content-machine",
|
||||
];
|
||||
|
||||
@@ -99,6 +100,7 @@ describe("shipped teams catalog", () => {
|
||||
"product-engineering/qa": { role: "qa", reportsTo: "cto", skills: ["qa-acceptance"] },
|
||||
"product-engineering/senior-coder": { role: "engineer", reportsTo: "cto", skills: ["github-pr-workflow", "doc-maintenance"] },
|
||||
"product-design/ux-designer": { role: "designer", reportsTo: null, skills: ["wireframe", "design-critique", "task-planning"] },
|
||||
"speko-company-phone-agent/speko-company-phone-agent": { role: "general", reportsTo: null, skills: undefined },
|
||||
"content-machine/content-lead": { role: "content-strategist", reportsTo: null, skills: ["content-calendar"] },
|
||||
};
|
||||
const observed: Record<string, unknown> = {};
|
||||
|
||||
@@ -2057,6 +2057,62 @@ const validateApp = (app) => {
|
||||
);
|
||||
}
|
||||
};
|
||||
apps.push({
|
||||
"schemaVersion": 1,
|
||||
"slug": "speko",
|
||||
"name": "Speko",
|
||||
"description": "Talk with a Paperclip agent through an experimental hosted voice connection.",
|
||||
"categories": [
|
||||
"communication"
|
||||
],
|
||||
"featured": false,
|
||||
"branding": {
|
||||
"logoUrl": "/brands/apps/speko.svg"
|
||||
},
|
||||
"urlPatterns": [
|
||||
"https://speko.ai/*",
|
||||
"https://platform.speko.ai/*"
|
||||
],
|
||||
"methods": [
|
||||
{
|
||||
"key": "voice-agent",
|
||||
"label": "Talk with an agent",
|
||||
"purpose": "channel",
|
||||
"provider": "speko",
|
||||
"transport": "voice",
|
||||
"auth": "api_key",
|
||||
"ownershipModes": [
|
||||
"customer"
|
||||
],
|
||||
"whenToUse": "Use browser voice to start and continue work with a selected Paperclip agent.",
|
||||
"credentialFields": [
|
||||
{
|
||||
"key": "apiKey",
|
||||
"label": "Speko API key",
|
||||
"type": "password",
|
||||
"required": true,
|
||||
"placeholder": "Paste your Speko API key",
|
||||
"secret": true
|
||||
},
|
||||
{
|
||||
"key": "agentId",
|
||||
"label": "Speko agent ID",
|
||||
"type": "text",
|
||||
"required": true,
|
||||
"placeholder": "agent_\u2026",
|
||||
"secret": false
|
||||
}
|
||||
],
|
||||
"guidanceMd": "Create a dedicated Speko voice persona and choose its voice. Paperclip registers signed session tools and keeps the selected Paperclip agent responsible for task work. Public HTTPS callbacks are required. Review provider recording settings; Speko charges are separate from agent costs. Phone calling is withheld pending live qualification.",
|
||||
"consoleLinks": {
|
||||
"register": "https://platform.speko.ai/agents",
|
||||
"docs": "https://docs.speko.ai/guides/tool-calling"
|
||||
},
|
||||
"riskTier": "S3",
|
||||
"requiredResourceFilters": []
|
||||
}
|
||||
]
|
||||
});
|
||||
const captureFiles = definitionsOnly ? [] : fs
|
||||
.readdirSync(corpus)
|
||||
.filter((fileName) => fileName.endsWith(".md") && fileName !== "INDEX.md")
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
"@paperclipai/hermes-paperclip-adapter": "workspace:*",
|
||||
"@paperclipai/shared": "workspace:*",
|
||||
"@radix-ui/react-slot": "^1.3.3",
|
||||
"@spekoai/client": "0.0.13",
|
||||
"@tailwindcss/typography": "^0.5.20",
|
||||
"@tanstack/react-query": "^5.102.8",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
|
||||
@@ -598,6 +598,12 @@
|
||||
"catalogVisible": true,
|
||||
"localAsset": "/brands/apps/api-key-generic.svg"
|
||||
},
|
||||
{
|
||||
"slug": "speko",
|
||||
"provider": "Speko",
|
||||
"catalogVisible": true,
|
||||
"localAsset": "/brands/apps/speko.svg"
|
||||
},
|
||||
{
|
||||
"slug": "calendly",
|
||||
"provider": "Calendly",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48">
|
||||
<rect width="48" height="48" rx="12" fill="#2f6ad1"/>
|
||||
<rect x="14" y="7" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="21" y="7" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="28" y="7" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="35" y="7" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="7" y="14" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="14" y="21" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="21" y="21" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="28" y="21" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="35" y="28" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="7" y="35" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="14" y="35" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="21" y="35" width="6" height="6" fill="#ffffff"/>
|
||||
<rect x="28" y="35" width="6" height="6" fill="#ffffff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 921 B |
@@ -21,7 +21,7 @@ export type {
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
export type ChatProvider =
|
||||
"slack" | "github" | "discord" | "microsoft-teams" | "telegram" | "agentmail" | "imessage-photon";
|
||||
"slack" | "github" | "discord" | "microsoft-teams" | "telegram" | "agentmail" | "imessage-photon" | "speko";
|
||||
export type ChatEndpointStatus =
|
||||
| "draft"
|
||||
| "verifying"
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { VoiceCallbackPreference } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
const path = (companyId: string, endpointId: string) => `/companies/${encodeURIComponent(companyId)}/voice-callbacks/${encodeURIComponent(endpointId)}`;
|
||||
export const voiceCallbacksApi = {
|
||||
get: (companyId: string, endpointId: string) => api.get<VoiceCallbackPreference | null>(path(companyId, endpointId), { cache: "no-store" }),
|
||||
save: (companyId: string, endpointId: string, preference: VoiceCallbackPreference) => api.put<VoiceCallbackPreference>(path(companyId, endpointId), preference),
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { VoiceCallHistoryEntry } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
export const voiceHistoryApi = {
|
||||
list: (companyId: string, endpointId: string) => api.get<VoiceCallHistoryEntry[]>(`/companies/${encodeURIComponent(companyId)}/voice-history/${encodeURIComponent(endpointId)}`, { cache: "no-store" }),
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { VoicePhoneConfiguration, VoiceInboundCall, VoiceUnapprovedCallHistoryEntry } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
const path = (companyId: string, endpointId: string) => `/companies/${encodeURIComponent(companyId)}/voice-phone/${encodeURIComponent(endpointId)}`;
|
||||
export const voicePhoneApi = {
|
||||
configuration: (companyId: string, endpointId: string) => api.get<VoicePhoneConfiguration>(path(companyId, endpointId), {cache: "no-store"}),
|
||||
save: (companyId: string, endpointId: string, input: {numberId: string; enabled: boolean; guestIntake?: boolean; lowTrustEnvironmentId?: string | null}) => api.put<VoicePhoneConfiguration>(path(companyId, endpointId), input),
|
||||
incoming: (companyId: string, endpointId: string) => api.get<VoiceInboundCall[]>(`${path(companyId, endpointId)}/incoming`, {cache: "no-store"}),
|
||||
history: (companyId: string, endpointId: string) => api.get<VoiceUnapprovedCallHistoryEntry[]>(`${path(companyId, endpointId)}/history`, {cache: "no-store"}),
|
||||
decide: (companyId: string, endpointId: string, callId: string, input: {approve: boolean; approvalCode: string; issueId?: string}) => api.post<VoiceInboundCall>(`${path(companyId, endpointId)}/incoming/${encodeURIComponent(callId)}`, input),
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { VoiceSession, VoiceSessionMedia, VoiceSessionNotification } from "@paperclipai/shared";
|
||||
import { api } from "./client";
|
||||
|
||||
const base = (companyId: string) => `/companies/${encodeURIComponent(companyId)}/voice-sessions`;
|
||||
export const voiceSessionsApi = {
|
||||
start(companyId: string, input: { endpointId: string; issueId?: string; newConversation?: boolean; idempotencyKey: string; maxDurationSeconds?: number }) {
|
||||
return api.post<{ session: VoiceSession; media?: VoiceSessionMedia }>(base(companyId), input);
|
||||
},
|
||||
get(companyId: string, sessionId: string) {
|
||||
return api.get<VoiceSession>(`${base(companyId)}/${encodeURIComponent(sessionId)}`, { cache: "no-store" });
|
||||
},
|
||||
end(companyId: string, sessionId: string) {
|
||||
return api.post<VoiceSession>(`${base(companyId)}/${encodeURIComponent(sessionId)}/end`, {});
|
||||
},
|
||||
notification(companyId: string, sessionId: string) {
|
||||
return api.get<VoiceSessionNotification | null>(`${base(companyId)}/${encodeURIComponent(sessionId)}/notification`, { cache: "no-store" });
|
||||
},
|
||||
};
|
||||
@@ -27,12 +27,13 @@ function sentenceCaseStatus(status: string): string {
|
||||
*/
|
||||
// design-allow(pill-pattern): DECISION-SHEET.md C8 - status badges keep the bespoke WCAG-tuned
|
||||
// .status-chip color-mix mechanic and do not wrap the Badge primitive.
|
||||
export function StatusBadge({ status, label }: { status: string; label?: string }) {
|
||||
export function StatusBadge({ status, label, className }: { status: string; label?: string; className?: string }) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",
|
||||
statusBadge[status] ?? statusBadgeDefault
|
||||
statusBadge[status] ?? statusBadgeDefault,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{label ?? status.replace(/[_-]/g, " ")}
|
||||
|
||||
@@ -2,12 +2,13 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { ExternalLink, MessageSquarePlus } from "lucide-react";
|
||||
import { chatEndpointsApi, type ChatProvider } from "@/api/chatEndpoints";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { StatusBadge } from "@/components/StatusBadge";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { Link } from "@/lib/router";
|
||||
import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";
|
||||
|
||||
const providerNames: Record<ChatProvider, string> = {
|
||||
speko: "Speko",
|
||||
slack: "Slack",
|
||||
github: "GitHub Code Review Bot",
|
||||
discord: "Discord",
|
||||
@@ -79,7 +80,7 @@ export function AgentChannelsPanel({
|
||||
"Provider identity"}
|
||||
</p>
|
||||
</div>
|
||||
<StatusBadge status={endpoint.status} />
|
||||
<Badge variant="outline">{endpoint.status.replace(/[_-]/g, " ")}</Badge>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link to={`/apps/chat/${endpoint.id}/settings`}>
|
||||
Open connection <ExternalLink />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ExternalLink, Paperclip, Radio } from "lucide-react";
|
||||
@@ -32,6 +33,7 @@ import {
|
||||
} from "./board-send-draft";
|
||||
|
||||
const providerNames: Record<ChatProvider, string> = {
|
||||
speko: "Speko",
|
||||
slack: "Slack",
|
||||
github: "GitHub",
|
||||
discord: "Discord",
|
||||
@@ -127,23 +129,19 @@ type ConnectedTaskProps = {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
issueCacheRefs?: string[];
|
||||
assigneeAgentId?: string | null;
|
||||
};
|
||||
|
||||
export function ExternallyConnectedTaskBanner(props: ConnectedTaskProps) {
|
||||
const { binding } = useIssueChatBinding(props.companyId, props.issueId);
|
||||
if (!binding || binding.provider === "agentmail") return null;
|
||||
return (
|
||||
<ConnectedTaskComposer
|
||||
key={boardSendDraftKey(
|
||||
props.companyId,
|
||||
props.issueId,
|
||||
binding.endpointId,
|
||||
binding.conversationId,
|
||||
)}
|
||||
return <>
|
||||
{binding && binding.provider !== "speko" && binding.provider !== "agentmail" && <ConnectedTaskComposer
|
||||
key={boardSendDraftKey(props.companyId, props.issueId, binding.endpointId, binding.conversationId)}
|
||||
{...props}
|
||||
binding={binding}
|
||||
/>
|
||||
);
|
||||
/>}
|
||||
<TaskVoiceLauncher companyId={props.companyId} issueId={props.issueId} agentId={props.assigneeAgentId} boundEndpointId={binding?.provider === "speko" ? binding.endpointId : undefined} />
|
||||
</>;
|
||||
}
|
||||
|
||||
function ConnectedTaskComposer({
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { voiceSessionsApi } from "@/api/voiceSessions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { VoiceCallContext } from "./VoiceCallContext";
|
||||
import { Link } from "react-router-dom";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { connectSpekoVoiceMedia } from "@/lib/speko-voice-media";
|
||||
import { createVoiceCallAttempt, type VoiceCallJournal } from "@/lib/voice-call-attempt";
|
||||
import { VoiceConversationPanel } from "./VoiceConversationPanel";
|
||||
|
||||
export interface NativeVoiceConversationProps {
|
||||
companyId: string;
|
||||
endpointId: string;
|
||||
issueId?: string;
|
||||
managed?: boolean;
|
||||
autoStart?: boolean;
|
||||
newConversation?: boolean;
|
||||
onEndedChange?: (ended: boolean) => void;
|
||||
journal?: VoiceCallJournal;
|
||||
agentName: string;
|
||||
/** Story fixtures replace the external client and media, never the component. */
|
||||
client?: typeof voiceSessionsApi;
|
||||
connect?: typeof connectSpekoVoiceMedia;
|
||||
}
|
||||
|
||||
export function NativeVoiceConversation(props: NativeVoiceConversationProps) {
|
||||
const host = useContext(VoiceCallContext);
|
||||
const [newConversation, setNewConversation] = useState(false);
|
||||
if (host && !props.managed) return <div className="flex flex-col gap-2">
|
||||
{!props.issueId && <ConversationChoice value={newConversation} disabled={host.active} onChange={setNewConversation} />}
|
||||
<Button size="sm" variant="outline" disabled={host.active} onClick={() => host.open({ ...props, newConversation })}>{host.active ? "Voice panel open" : "Start voice"}</Button>
|
||||
</div>;
|
||||
return <VoiceSessionView {...props} />;
|
||||
}
|
||||
|
||||
function ConversationChoice({ value, disabled, onChange }: { value: boolean; disabled: boolean; onChange(value: boolean): void }) {
|
||||
return <label className="flex flex-col gap-2 text-sm">Conversation
|
||||
<select disabled={disabled} aria-label="Conversation" className="rounded-md border border-input bg-background p-2 text-sm" value={value ? "new" : "continue"} onChange={event => onChange(event.target.value === "new")}><option value="continue">Continue conversation</option><option value="new">New conversation</option></select>
|
||||
</label>;
|
||||
}
|
||||
|
||||
export function VoiceSessionView({ companyId, endpointId, issueId, agentName, autoStart, newConversation: initialNewConversation = false, onEndedChange, journal, client = voiceSessionsApi, connect = connectSpekoVoiceMedia }: NativeVoiceConversationProps) {
|
||||
const [sessionId, setSessionId] = useState<string>();
|
||||
const [boundIssueId, setBoundIssueId] = useState(issueId);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const [accessLost, setAccessLost] = useState(false);
|
||||
const [newConversation, setNewConversation] = useState(initialNewConversation);
|
||||
const intent = useRef(newConversation);
|
||||
intent.current = newConversation;
|
||||
const dependencies = useMemo(() => {
|
||||
const attempt = createVoiceCallAttempt(companyId, client, journal);
|
||||
return {
|
||||
async mint() {
|
||||
setAccessLost(false); setStarting(true);
|
||||
try {
|
||||
const result = await attempt.start({ endpointId, issueId, ...(intent.current ? { newConversation: true } : {}) });
|
||||
setSessionId(result.session.id); setBoundIssueId(result.session.issueId);
|
||||
return result.media;
|
||||
} finally { setStarting(false); }
|
||||
},
|
||||
async end(id: string) {
|
||||
await attempt.end(id);
|
||||
setSessionId(undefined); setNewConversation(false);
|
||||
},
|
||||
connect,
|
||||
};
|
||||
}, [companyId, endpointId, issueId, client, connect, journal]);
|
||||
const notification = useQuery({
|
||||
queryKey: ["voice-notification", companyId, sessionId],
|
||||
queryFn: () => client.notification(companyId, sessionId!),
|
||||
enabled: Boolean(sessionId),
|
||||
refetchInterval: 1000,
|
||||
refetchIntervalInBackground: true,
|
||||
retry: false,
|
||||
});
|
||||
const rejected = notification.error instanceof ApiError && [401, 403, 404].includes(notification.error.status);
|
||||
useEffect(() => { if (rejected) setAccessLost(true); }, [rejected]);
|
||||
const accessRevoked = rejected || accessLost;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
{!issueId && !sessionId && !autoStart && <ConversationChoice value={newConversation} disabled={starting} onChange={setNewConversation} />}
|
||||
{boundIssueId && <Link className="text-sm text-primary underline" to={`/issues/${encodeURIComponent(boundIssueId)}`}>View conversation task</Link>}
|
||||
<VoiceConversationPanel agentName={agentName} autoStart={autoStart} accessRevoked={accessRevoked} onEndedChange={onEndedChange} dependencies={dependencies} notification={notification.data ?? undefined} />
|
||||
{(notification.isError || accessLost) && <p role="alert" className="text-sm text-destructive">{accessRevoked ? "Access to this call is no longer available. The call is being closed." : "Task updates are temporarily unavailable. The connection will retry; end the call if the problem continues."}</p>}
|
||||
<p className="text-xs text-muted-foreground">Speko handles the audio and may retain recordings according to your workspace settings. Paperclip keeps task history. Speko usage is billed separately from agent work. Calls are limited to ten minutes.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useQuery, useMutation } from "@tanstack/react-query";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import type { VoiceCallHistoryEntry, VoiceCallReport, VoiceUnapprovedCallHistoryEntry } from "@paperclipai/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { voiceSessionsApi } from "@/api/voiceSessions";
|
||||
import { voicePhoneApi } from "@/api/voicePhone";
|
||||
import { voiceHistoryApi } from "@/api/voiceHistory";
|
||||
|
||||
function charge(amount: string | null) {
|
||||
if (amount === null) return "Not yet reported";
|
||||
const value = BigInt(amount);
|
||||
const whole = value / 1_000_000n, fraction = (value % 1_000_000n).toString().padStart(6, "0");
|
||||
return `$${whole}.${fraction} USD`;
|
||||
}
|
||||
export function SpekoCallReport({ report }: { report: VoiceCallReport }) {
|
||||
return <div className="space-y-3">
|
||||
<dl className="flex flex-wrap gap-4 text-sm"><div><dt className="text-muted-foreground">Speko charge</dt><dd>{charge(report.costMicroUsd)}</dd></div>{report.durationSeconds !== null && <div><dt className="text-muted-foreground">Duration</dt><dd>{report.durationSeconds} seconds</dd></div>}</dl>
|
||||
<p className="text-xs text-muted-foreground">Agent costs are separate. Recordings remain in Speko.</p>
|
||||
{report.transcript.length ? <ol aria-label="Call transcript" className="space-y-3">{report.transcript.map(turn => <li key={turn.id} className="min-w-0"><p className="text-xs font-medium text-muted-foreground">{turn.speaker === "caller" ? "You" : "Agent"}{turn.interrupted ? " · interrupted" : ""}</p><p className="whitespace-pre-wrap break-words text-sm">{turn.text}</p></li>)}</ol>
|
||||
: <p className="text-sm text-muted-foreground">{report.status === "unavailable" ? "The transcript is unavailable. Paperclip will retry while Speko finishes the report." : report.status === "pending" ? "The transcript will appear after Speko finishes the call report." : "Speko did not provide a transcript for this call."}</p>}
|
||||
</div>;
|
||||
}
|
||||
const modeNames = { browser: "Browser voice", inbound_phone: "Incoming call", outbound_phone: "Outgoing call" } as const;
|
||||
const stateNames = { reserved: "Preparing", creating: "Connecting", creation_unknown: "Checking connection", connecting: "Connecting", active: "In progress", awaiting_approval: "Awaiting approval", ending: "Ending", ended: "Completed", failed: "Failed", expired: "Expired" } as const;
|
||||
export function SpekoCallActivityItem({ entry: { session, report }, onEnd, ending, presentation = "history" }: { entry: VoiceCallHistoryEntry; onEnd?(sessionId: string): void; ending?: boolean; presentation?: "history" | "activity" }) {
|
||||
const summary = useRef<HTMLElement | null>(null);
|
||||
const restoreFocus = useRef(false);
|
||||
useEffect(() => {
|
||||
if (restoreFocus.current && ["ended", "failed", "expired"].includes(session.state)) { summary.current?.focus(); restoreFocus.current = false; }
|
||||
}, [session.state]);
|
||||
return <details data-activity-kind="call" className={presentation === "activity" ? "px-2 py-3 transition-colors hover:bg-accent/50" : "rounded-md border border-border p-3"}>
|
||||
<summary ref={summary} className="cursor-pointer break-words text-sm font-medium">{modeNames[session.mode]} · {stateNames[session.state]}<span className="ml-2 text-xs font-normal text-muted-foreground">{new Date(session.createdAt).toLocaleString()}</span></summary>
|
||||
<div className="mt-3 space-y-3"><Link className="text-sm text-primary underline" to={`/issues/${encodeURIComponent(session.issueId)}`}>Conversation task</Link>
|
||||
{session.errorCode && <p className="text-sm text-muted-foreground">{session.errorCode === "cleanup_pending" ? "Confirming call cleanup with Speko." : "This call encountered a connection problem. Check your Speko connection before trying again."}</p>}
|
||||
{!session.endedAt && !["ended", "failed", "expired"].includes(session.state) && session.callerAuthority !== "guest_intake" && onEnd && <Button size="sm" variant="outline" disabled={ending} onClick={() => { restoreFocus.current = true; onEnd(session.id); }}>{ending ? "Ending…" : "End call"}</Button>}
|
||||
<SpekoCallReport report={report} />
|
||||
</div>
|
||||
</details>;
|
||||
}
|
||||
export function SpekoUnapprovedCallActivityItem({ call, presentation = "history" }: { call: VoiceUnapprovedCallHistoryEntry; presentation?: "history" | "activity" }) {
|
||||
return <div data-activity-kind="unapproved_call" className={presentation === "activity" ? "px-2 py-3 text-sm" : "rounded-md border border-border p-3 text-sm"}><p>{call.state === "denied" ? "Call denied" : call.state === "expired" ? "Approval expired" : "Missed call"} · {new Date(call.createdAt).toLocaleString()}</p><p className="text-xs text-muted-foreground">No private task was connected.</p></div>;
|
||||
}
|
||||
export interface SpekoCallHistoryViewProps { entries?: VoiceCallHistoryEntry[]; unapprovedCalls?: VoiceUnapprovedCallHistoryEntry[]; loading?: boolean; error?: string; onRetry(): void; onEnd?(sessionId: string): void; endingSessionId?: string }
|
||||
export function SpekoCallHistoryView({ entries = [], unapprovedCalls = [], loading, error, onRetry, onEnd, endingSessionId }: SpekoCallHistoryViewProps) {
|
||||
return <section className="max-w-xl space-y-3" aria-label="Your calls">
|
||||
<div className="flex items-center justify-between gap-3"><h2 className="text-lg font-semibold">Your calls</h2><Button size="sm" variant="ghost" onClick={onRetry} disabled={loading}>Refresh</Button></div>
|
||||
{loading && <p role="status" className="text-sm text-muted-foreground">Loading calls…</p>}
|
||||
{error && <div className="space-y-2"><p role="alert" className="text-sm text-destructive">{error}</p><Button size="sm" variant="outline" onClick={onRetry}>Try again</Button></div>}
|
||||
{!loading && !error && !entries.length && !unapprovedCalls.length && <p className="text-sm text-muted-foreground">Your browser conversations and phone calls will appear here.</p>}
|
||||
{!error && entries.map(entry => <SpekoCallActivityItem key={entry.session.id} entry={entry} onEnd={onEnd} ending={endingSessionId === entry.session.id} />)}
|
||||
{!error && unapprovedCalls.length > 0 && <div className="space-y-2"><h3 className="text-sm font-medium">Unapproved incoming calls</h3><ul className="space-y-2">{unapprovedCalls.map(call => <li key={call.id}><SpekoUnapprovedCallActivityItem call={call} /></li>)}</ul></div>}
|
||||
</section>;
|
||||
}
|
||||
export function useSpekoCallHistory(companyId: string, endpointId: string, enabled = true) {
|
||||
const query = useQuery({ queryKey: ["speko-history", companyId, endpointId], queryFn: () => voiceHistoryApi.list(companyId, endpointId), enabled, retry: false, refetchInterval: enabled ? 30_000 : false });
|
||||
const incoming = useQuery({queryKey: ["speko-unapproved-history", companyId, endpointId], queryFn: () => voicePhoneApi.history(companyId, endpointId), retry: false, enabled: enabled && query.isSuccess, refetchInterval: enabled ? 30_000 : false});
|
||||
const ending = useMutation({mutationFn: (sessionId: string) => voiceSessionsApi.end(companyId, sessionId), onSuccess: () => query.refetch()});
|
||||
return { entries: query.data ?? [], unapprovedCalls: incoming.data ?? [], loading: query.isLoading || incoming.isLoading, error: (ending.error ?? query.error ?? incoming.error)?.message, endingSessionId: ending.isPending ? ending.variables : undefined,
|
||||
onEnd: (sessionId: string) => ending.mutate(sessionId), onRetry: () => { ending.reset(); void query.refetch(); void incoming.refetch(); } };
|
||||
}
|
||||
export function SpekoCallHistory({ companyId, endpointId }: { companyId: string; endpointId: string }) {
|
||||
return <SpekoCallHistoryView {...useSpekoCallHistory(companyId, endpointId)} />;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type { VoiceInboundCall } from "@paperclipai/shared";
|
||||
import { voicePhoneApi } from "@/api/voicePhone";
|
||||
import { issuesApi } from "@/api/issues";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
export interface SpekoIncomingCallCardProps { call: VoiceInboundCall; tasks?: {id: string; label: string}[]; busy?: boolean; error?: string; onDecide(input: {approve: boolean; approvalCode: string; issueId?: string}): void }
|
||||
export function SpekoIncomingCallCard({call, tasks = [], busy, error, onDecide}: SpekoIncomingCallCardProps) {
|
||||
const [code, setCode] = useState(""), [issueId, setIssueId] = useState(""), [invalid, setInvalid] = useState(false);
|
||||
const heading = useRef<HTMLHeadingElement>(null);
|
||||
const pending = ["guest_intake", "awaiting_approval", "approving"].includes(call.state);
|
||||
useEffect(() => { if (!pending) heading.current?.focus(); }, [pending]);
|
||||
if (call.state === "guest_intake") return <section className="max-w-xl space-y-3 rounded-md border border-border p-3" aria-label="Incoming conversation">
|
||||
<h3 className="text-sm font-semibold">Incoming conversation</h3>
|
||||
{call.intakeIssueId && <Link className="text-sm text-primary underline" to={`/issues/${call.intakeIssueId}`}>Open conversation task</Link>}
|
||||
<p className="text-sm text-muted-foreground">This caller is talking to the agent in a new low-trust task.</p>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<Button variant="outline" disabled={busy} onClick={() => onDecide({approve: false, approvalCode: call.approvalCode})}>End call</Button>
|
||||
</section>;
|
||||
return <section className="max-w-xl space-y-3 rounded-md border border-border p-3" aria-label="Incoming call approval">
|
||||
<h3 ref={heading} tabIndex={-1} className="text-sm font-semibold">{call.state === "approved" ? "Call approved" : call.state === "denied" ? "Call denied" : call.state === "expired" ? "Call expired" : call.state === "ended" ? "Caller hung up" : "Incoming call awaiting approval"}</h3>
|
||||
{call.intakeIssueId && <Link className="text-sm text-primary underline" to={`/issues/${encodeURIComponent(call.intakeIssueId)}`}>Review phone intake</Link>}
|
||||
{pending ? <form className="space-y-3" onSubmit={event => {event.preventDefault(); if (code !== call.approvalCode) {setInvalid(true); return;} setInvalid(false); onDecide({approve: true, approvalCode: code, ...(issueId ? {issueId} : {})});}}>
|
||||
<p className="text-sm text-muted-foreground">Approve only the call you are currently on. Enter the six-digit code spoken on the phone. Approval gives this call your access to the selected task.</p>
|
||||
<label className="grid gap-2 text-sm font-medium">Code spoken on your call<Input inputMode="numeric" autoComplete="off" maxLength={6} value={code} disabled={busy} aria-invalid={invalid} onChange={event => {setCode(event.target.value); setInvalid(false);}} /></label>
|
||||
<label className="grid min-w-0 gap-2 text-sm font-medium">Conversation task<select aria-label="Conversation task" className="w-full min-w-0 rounded-md border border-input bg-background p-2 text-sm" disabled={busy} value={issueId} onChange={event => setIssueId(event.target.value)}><option value="">Continue your conversation, or create one</option>{tasks.map(task => <option key={task.id} value={task.id}>{task.label}</option>)}</select></label>
|
||||
{invalid && <p role="alert" className="text-sm text-destructive">That code does not match this live call. Ask the phone agent to repeat it.</p>}
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<div className="flex items-center justify-between gap-3"><Button type="button" variant="ghost" disabled={busy} onClick={() => onDecide({approve: false, approvalCode: call.approvalCode})}>Deny call</Button><Button type="submit" disabled={busy}>{busy ? "Confirming…" : "Approve live call"}</Button></div>
|
||||
</form> : <p className="text-sm text-muted-foreground">{call.state === "approved" ? "You can now give instructions on the phone. Earlier instructions were discarded." : "This call cannot access your private tasks."}</p>}
|
||||
</section>;
|
||||
}
|
||||
export function SpekoIncomingCalls({companyId, endpointId, agentId}: {companyId: string; endpointId: string; agentId: string}) {
|
||||
const [decision, setDecision] = useState<VoiceInboundCall>();
|
||||
useEffect(() => { setDecision(undefined); }, [companyId, endpointId]);
|
||||
const query = useQuery({queryKey: ["speko-incoming", companyId, endpointId], queryFn: () => voicePhoneApi.incoming(companyId, endpointId), refetchInterval: 2000, retry: false});
|
||||
const tasks = useQuery({queryKey: ["speko-approval-tasks", companyId, agentId], queryFn: () => issuesApi.list(companyId, {assigneeAgentId: agentId}), enabled: Boolean(query.data?.length), retry: false});
|
||||
const mutation = useMutation({mutationFn: ({id, ...input}: {id: string; approve: boolean; approvalCode: string; issueId?: string}) => voicePhoneApi.decide(companyId, endpointId, id, input), onSuccess: result => { setDecision(result); return query.refetch(); }});
|
||||
return <div className="space-y-3">{query.error && <p role="alert" className="text-sm text-destructive">Incoming call approval is unavailable. {query.error.message}</p>}{!query.error && [...(query.data ?? []).filter(call => call.id !== decision?.id), ...(decision ? [decision] : [])].map(call => <SpekoIncomingCallCard key={call.id} call={call} tasks={tasks.error ? [] : tasks.data?.filter(task => !["done", "cancelled"].includes(task.status)).map(task => ({id: task.id, label: `${task.identifier ?? "Task"} · ${task.title}`}))} busy={mutation.isPending && mutation.variables?.id === call.id} error={mutation.variables?.id === call.id ? mutation.error?.message : undefined} onDecide={input => mutation.mutate({id: call.id, ...input})} />)}</div>;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { voiceCallbacksApi } from "@/api/voiceCallbacks";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import type { VoiceCallbackPreference } from "@paperclipai/shared";
|
||||
export interface SpekoPhoneCallbackFormProps {
|
||||
preference?: VoiceCallbackPreference | null;
|
||||
loading?: boolean; saving?: boolean; error?: string; saved?: boolean;
|
||||
onSave(preference: VoiceCallbackPreference): void;
|
||||
}
|
||||
export function SpekoPhoneCallbackForm({ preference, loading, saving, error, saved, onSave }: SpekoPhoneCallbackFormProps) {
|
||||
const [phoneNumber, setPhoneNumber] = useState(preference?.phoneNumber ?? "");
|
||||
const [enabled, setEnabled] = useState(preference?.enabled ?? false);
|
||||
const [invalid, setInvalid] = useState(false);
|
||||
useEffect(() => { setPhoneNumber(preference?.phoneNumber ?? ""); setEnabled(preference?.enabled ?? false); }, [preference]);
|
||||
return <section className="max-w-xl space-y-3">
|
||||
<h2 className="text-lg font-semibold">Call my phone</h2>
|
||||
<form className="space-y-3" onSubmit={event => { event.preventDefault(); if (!/^\+[1-9]\d{6,14}$/.test(phoneNumber)) { setInvalid(true); return; } setInvalid(false); onSave({ phoneNumber, enabled }); }}>
|
||||
<label className="grid gap-2 text-sm font-medium">Your callback number<Input type="tel" autoComplete="tel" placeholder="+12015551234" value={phoneNumber} disabled={loading || saving} aria-invalid={invalid} aria-describedby={invalid ? "speko-phone-error" : undefined} onChange={event => { setPhoneNumber(event.target.value); setInvalid(false); }} /></label>
|
||||
<label className="flex items-center gap-2 text-sm"><Checkbox checked={enabled} disabled={loading || saving} onCheckedChange={value => setEnabled(value === true)} />Allow this agent to call me about my tasks</label>
|
||||
{invalid && <p id="speko-phone-error" role="alert" className="text-sm text-destructive">Use an international number beginning with + and the country code.</p>}
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<div className="flex items-center justify-between gap-3"><p role="status" className="text-sm text-muted-foreground">{loading ? "Loading your callback setting…" : saved ? "Callback setting saved" : ""}</p><Button type="submit" disabled={loading || saving}>{saving ? "Saving…" : "Save phone setting"}</Button></div>
|
||||
</form>
|
||||
</section>;
|
||||
}
|
||||
export function SpekoPhoneCallback({ companyId, endpointId }: { companyId: string; endpointId: string }) {
|
||||
const key = ["speko-callback", companyId, endpointId];
|
||||
const query = useQuery({ queryKey: key, queryFn: () => voiceCallbacksApi.get(companyId, endpointId), retry: false });
|
||||
const mutation = useMutation({ mutationFn: (preference: VoiceCallbackPreference) => voiceCallbacksApi.save(companyId, endpointId, preference), onSuccess: () => query.refetch() });
|
||||
return <SpekoPhoneCallbackForm preference={query.data} loading={query.isLoading} saving={mutation.isPending} saved={mutation.isSuccess} error={(query.error ?? mutation.error)?.message} onSave={preference => mutation.mutate(preference)} />;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { VoicePhoneConfiguration } from "@paperclipai/shared";
|
||||
import { voicePhoneApi } from "@/api/voicePhone";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
export interface SpekoPhoneLineFormProps { configuration?: VoicePhoneConfiguration; loading?: boolean; saving?: boolean; saved?: boolean; error?: string; onRefresh(): void; onSave(input: {numberId: string; enabled: boolean; guestIntake?: boolean; lowTrustEnvironmentId?: string | null}): void }
|
||||
export function SpekoPhoneLineForm({configuration, loading, saving, saved, error, onRefresh, onSave}: SpekoPhoneLineFormProps) {
|
||||
const [numberId, setNumberId] = useState(configuration?.number?.id ?? ""), [enabled, setEnabled] = useState(configuration?.number?.enabled ?? false), [guestIntake, setGuestIntake] = useState(configuration?.number?.guestIntake ?? false), [invalid, setInvalid] = useState(false), [environmentId, setEnvironmentId] = useState(configuration?.number?.lowTrustEnvironmentId ?? "");
|
||||
useEffect(() => {setNumberId(configuration?.number?.id ?? ""); setEnabled(configuration?.number?.enabled ?? false); setGuestIntake(configuration?.number?.guestIntake ?? false); setEnvironmentId(configuration?.number?.lowTrustEnvironmentId ?? "");}, [configuration]);
|
||||
const selected = configuration?.inventory.find(n => n.id === numberId);
|
||||
return <section className="max-w-xl space-y-3">
|
||||
<div className="flex items-center justify-between gap-3"><h2 className="text-lg font-semibold">Incoming calls</h2><Button size="sm" variant="ghost" disabled={loading || saving} onClick={onRefresh}>Refresh numbers</Button></div>
|
||||
<p className="text-sm text-muted-foreground">Let callers start a conversation in a new task, or require approval to discuss an existing task.</p>
|
||||
{loading && <p role="status" className="text-sm text-muted-foreground">Loading Speko numbers…</p>}
|
||||
{!loading && !configuration?.inventory.length && <p className="text-sm text-muted-foreground">No numbers are available. <a className="text-primary underline" href="https://platform.speko.ai" target="_blank" rel="noreferrer">Buy or import a number in Speko</a>, complete verification and add credits, then refresh.</p>}
|
||||
<form className="space-y-3" onSubmit={event => {event.preventDefault(); if (!numberId || !selected?.available) {setInvalid(true); return;} setInvalid(false); onSave({numberId, enabled, guestIntake, lowTrustEnvironmentId: environmentId || null});}}>
|
||||
<label className="grid min-w-0 gap-2 text-sm font-medium">Company phone number<select aria-label="Company phone number" disabled={loading || saving} className="min-w-0 w-full rounded-md border border-input bg-background p-2 text-sm" value={numberId} onChange={event => {setNumberId(event.target.value); setInvalid(false);}}><option value="">Select a number</option>{configuration?.inventory.map(n => <option key={n.id} value={n.id} disabled={!n.available}>{n.phoneNumber}{n.label ? ` · ${n.label}` : ""}{!n.available ? " · unavailable" : ""}</option>)}</select></label>
|
||||
{selected && !selected.inboundReady && <p className="text-sm text-muted-foreground">Complete number setup in Speko before enabling incoming calls.{selected.issues.length ? ` ${selected.issues.join(". ")}` : ""}</p>}
|
||||
<label className="flex items-center gap-2 text-sm"><Checkbox checked={enabled} disabled={loading || saving} onCheckedChange={value => setEnabled(value === true)} />Enable incoming calls on this number</label>
|
||||
<label className="flex items-center gap-2 text-sm"><Checkbox checked={guestIntake} disabled={loading || saving} onCheckedChange={value => setGuestIntake(value === true)} />Let callers start new low-trust tasks without sign-in</label>
|
||||
{guestIntake && <p className="text-sm text-muted-foreground">Each call gets its own task. The assigned agent can discuss that conversation under a low-trust policy, without access to existing private tasks or private tools.</p>}
|
||||
{guestIntake && <label className="grid min-w-0 gap-2 text-sm font-medium">Execution sandbox<select aria-label="Execution sandbox" disabled={loading || saving} className="min-w-0 w-full rounded-md border border-input bg-background p-2 text-sm" value={environmentId} onChange={event => setEnvironmentId(event.target.value)}><option value="">Use this agent's sandbox</option>{configuration?.sandboxEnvironments?.map(e => <option key={e.id} value={e.id}>{e.name}</option>)}</select><span className="text-sm font-normal text-muted-foreground">Only new incoming tasks use this setting. Low-trust work requires an active sandbox and isolated workspaces.</span></label>}
|
||||
{invalid && <p role="alert" className="text-sm text-destructive">Choose an available company phone number.</p>}
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<div className="flex items-center justify-between gap-3"><p role="status" className="text-sm text-muted-foreground">{saved ? "Incoming call setting saved" : ""}</p><Button type="submit" disabled={loading || saving}>{saving ? "Saving…" : "Save incoming call setting"}</Button></div>
|
||||
</form>
|
||||
</section>;
|
||||
}
|
||||
export function SpekoPhoneLine({companyId, endpointId}: {companyId: string; endpointId: string}) {
|
||||
const queryClient = useQueryClient(), key = ["speko-phone-line", companyId, endpointId];
|
||||
const query = useQuery({queryKey: key, queryFn: () => voicePhoneApi.configuration(companyId, endpointId), retry: false});
|
||||
const mutation = useMutation({mutationFn: (input: {numberId: string; enabled: boolean; guestIntake?: boolean; lowTrustEnvironmentId?: string | null}) => voicePhoneApi.save(companyId, endpointId, input), onSuccess: data => queryClient.setQueryData(key, data)});
|
||||
return <SpekoPhoneLineForm configuration={query.data} loading={query.isLoading} saving={mutation.isPending} saved={mutation.isSuccess} error={(mutation.error ?? query.error)?.message} onRefresh={() => void query.refetch()} onSave={input => mutation.mutate(input)} />;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
export interface SpekoProviderSetupProps {
|
||||
agentName: string;
|
||||
credentials: Record<string, string>;
|
||||
onChange(values: Record<string, string>): void;
|
||||
onConnect(values: Record<string, string>): void;
|
||||
callbackUrl?: string | null;
|
||||
pending?: boolean;
|
||||
repairing?: boolean;
|
||||
}
|
||||
export function SpekoProviderSetup({ agentName, credentials, onChange, onConnect, callbackUrl, pending = false, repairing = false }: SpekoProviderSetupProps) {
|
||||
const ready = repairing || Boolean(credentials.apiKey?.trim() && credentials.agentId?.trim());
|
||||
const reachable = callbackUrl?.startsWith("https://") === true;
|
||||
function connect() {
|
||||
if (!ready || !reachable || pending) return;
|
||||
const values = Object.fromEntries(Object.entries(credentials).filter(([, value]) => value.trim()));
|
||||
if (!repairing && !values.signingSecret) {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
||||
values.signingSecret = `whsec_${btoa(String.fromCharCode(...bytes))}`;
|
||||
onChange(values);
|
||||
}
|
||||
onConnect(values);
|
||||
}
|
||||
return <div className="space-y-5">
|
||||
<div>
|
||||
<h1 className="text-xl font-bold">Connect {agentName} to Speko</h1>
|
||||
<p className="mt-1 text-sm text-muted-foreground">Choose a dedicated Speko voice persona. Paperclip uses its voice while {agentName} keeps its existing runtime, tools, and task context.</p>
|
||||
</div>
|
||||
<ol className="list-decimal space-y-2 pl-5 text-sm">
|
||||
<li>Create a dedicated agent in Speko and choose its voice. Keep only Speko’s default tools; Paperclip adds the task connection.</li>
|
||||
<li>Copy its agent ID and a Speko API key below.</li>
|
||||
<li>Review recording and retention settings in your Speko workspace before testing.</li>
|
||||
</ol>
|
||||
<Button asChild variant="outline"><a href="https://platform.speko.ai/agents" target="_blank" rel="noreferrer">Open Speko agents</a></Button>
|
||||
<label className="grid gap-2 text-sm font-medium">Speko agent ID<Input autoComplete="off" value={credentials.agentId ?? ""} placeholder={repairing ? "Leave blank to keep the current persona" : "agent_…"} onChange={(event) => onChange({ ...credentials, agentId: event.target.value })} /></label>
|
||||
<label className="grid gap-2 text-sm font-medium">Speko API key<Input type="password" autoComplete="new-password" value={credentials.apiKey ?? ""} placeholder={repairing ? "Leave blank to keep the saved key" : "Paste your Speko API key"} onChange={(event) => onChange({ ...credentials, apiKey: event.target.value })} /></label>
|
||||
{!reachable && <p role="alert" className="text-sm text-destructive">Configure a public HTTPS callback origin for Paperclip first. Local instances need an explicitly configured tunnel or reverse proxy.</p>}
|
||||
{reachable && <p className="break-all text-xs text-muted-foreground">Callback: {callbackUrl}</p>}
|
||||
<p className="text-sm text-muted-foreground">Credentials and a generated callback signing secret are saved in the company vault. Speko charges for voice usage separately from agent work. Outgoing calls are experimental. After connecting, save your callback number to let this agent call you about your tasks.</p>
|
||||
<Button disabled={!ready || !reachable || pending} onClick={connect}>{pending ? "Verifying Speko…" : repairing ? "Reconnect Speko" : "Connect Speko"}</Button>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { chatEndpointsApi } from "@/api/chatEndpoints";
|
||||
import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { NativeVoiceConversation } from "./NativeVoiceConversation";
|
||||
|
||||
export function TaskVoiceLauncher({ companyId, issueId, agentId, boundEndpointId }: { companyId: string; issueId: string; agentId?: string | null; boundEndpointId?: string }) {
|
||||
const { enabled } = useChatConnectorsEnabled();
|
||||
const [open, setOpen] = useState(false), [selected, setSelected] = useState("");
|
||||
const connections = useQuery({ queryKey: ["task-voice-endpoints", companyId], queryFn: () => chatEndpointsApi.list(companyId), enabled: enabled && Boolean(agentId || boundEndpointId) });
|
||||
if (!enabled) return null;
|
||||
const candidates = (connections.data ?? []).filter((endpoint) => endpoint.provider === "speko" && endpoint.status === "active" && (boundEndpointId ? endpoint.id === boundEndpointId : endpoint.assignedAgentId === agentId));
|
||||
const endpoint = candidates.find((entry) => entry.id === selected) ?? candidates[0];
|
||||
if (!endpoint) return boundEndpointId ? <p className="text-sm text-muted-foreground">{connections.isPending ? "Loading voice connection…" : "Voice is unavailable. Check the Speko connection in Apps."}</p> : null;
|
||||
return <section aria-label="Task voice conversation" className="space-y-3 rounded-lg border border-border p-4">
|
||||
{!open ? <div className="flex flex-wrap items-center gap-3">
|
||||
{candidates.length > 1 && <label className="flex min-w-0 max-w-full flex-col gap-2 text-sm">Voice persona<select aria-label="Voice persona" className="w-full min-w-0 max-w-full rounded-md border border-input bg-background p-2 text-sm" value={endpoint.id} onChange={(event) => setSelected(event.target.value)}>{candidates.map((entry) => <option key={entry.id} value={entry.id}>{entry.botLabel ?? entry.assignedAgentName}</option>)}</select></label>}
|
||||
<Button variant="outline" onClick={() => setOpen(true)}>Talk to {endpoint.assignedAgentName}</Button>
|
||||
</div> : <NativeVoiceConversation key={`${companyId}:${issueId}:${endpoint.id}`} companyId={companyId} endpointId={endpoint.id} issueId={issueId} agentName={endpoint.assignedAgentName} />}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createContext } from "react";
|
||||
import type { NativeVoiceConversationProps } from "./NativeVoiceConversation";
|
||||
export const VoiceCallContext = createContext<{
|
||||
active: boolean;
|
||||
open(props: NativeVoiceConversationProps): void;
|
||||
} | null>(null);
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { NativeVoiceConversation, type NativeVoiceConversationProps } from "./NativeVoiceConversation";
|
||||
import { voiceCallJournal } from "@/lib/voice-call-attempt";
|
||||
import { VoiceCallContext } from "./VoiceCallContext";
|
||||
|
||||
/** Owns media above routes. Scope changes unmount the call and clean up media. */
|
||||
export function VoiceCallProvider({ children, companyId, userId }: {
|
||||
children: ReactNode; companyId: string | null; userId: string | null;
|
||||
}) {
|
||||
const [call, setCall] = useState<{ props: NativeVoiceConversationProps; userId: string | null; id: string } | null>(null);
|
||||
const returnFocus = useRef<HTMLElement | null>(null);
|
||||
const [ended, setEnded] = useState(false);
|
||||
const current = call?.props.companyId === companyId && call.userId === userId ? call : null;
|
||||
useEffect(() => { if (call && !current) setCall(null); }, [call, current]);
|
||||
const open = useCallback((props: NativeVoiceConversationProps) => {
|
||||
if (props.companyId !== companyId || current) return;
|
||||
returnFocus.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
setEnded(false); setCall({ props: { ...props, journal: props.journal ?? (props.client ? undefined : voiceCallJournal(sessionStorage, props.companyId, userId ?? "unresolved")) }, userId, id: crypto.randomUUID() });
|
||||
}, [companyId, userId, current]);
|
||||
const value = useMemo(() => ({ active: Boolean(current), open }), [current, open]);
|
||||
return <VoiceCallContext.Provider value={value}>
|
||||
{children}
|
||||
{current && <aside aria-label="Current voice call" className="fixed inset-x-4 bottom-4 z-50 max-h-(--sz-calc-18) overflow-y-auto rounded-lg border border-border bg-background p-4 shadow-lg sm:left-auto sm:w-96">
|
||||
<NativeVoiceConversation {...current.props} key={current.id} managed autoStart onEndedChange={setEnded} />
|
||||
{ended && <Button variant="ghost" size="sm" onClick={() => { setCall(null); requestAnimationFrame(() => { if (returnFocus.current?.isConnected) returnFocus.current.focus(); }); }}>Close voice panel</Button>}
|
||||
</aside>}
|
||||
</VoiceCallContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Mic, MicOff, Phone, PhoneOff, RotateCcw, Volume2 } from "lucide-react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const VOICE_CONTROL_STATES = ["idle", "connecting", "listening", "speaking", "working", "interrupted", "reconnecting", "ending", "ended", "failed", "cleanup_failed"] as const;
|
||||
export type VoiceControlState = typeof VOICE_CONTROL_STATES[number];
|
||||
const labels: Record<VoiceControlState, string> = {
|
||||
idle: "Ready to talk", connecting: "Connecting…", listening: "Listening", speaking: "Speaking",
|
||||
working: "Working on your task", interrupted: "Listening to your follow-up", reconnecting: "Reconnecting…",
|
||||
ending: "Ending call…", ended: "Call ended", failed: "Voice connection unavailable", cleanup_failed: "Call closure unconfirmed",
|
||||
};
|
||||
export interface VoiceControlsProps {
|
||||
state: VoiceControlState;
|
||||
agentName: string;
|
||||
muted?: boolean;
|
||||
busy?: boolean;
|
||||
playbackBlocked?: boolean;
|
||||
canRepeat?: boolean;
|
||||
onRepeat?: () => void;
|
||||
error?: string;
|
||||
announcement?: string;
|
||||
onStart: () => void;
|
||||
onMute: () => void;
|
||||
onEnd: () => void;
|
||||
onResumeAudio: () => void;
|
||||
className?: string;
|
||||
}
|
||||
export function VoiceControls({ state, agentName, muted = false, busy = false, playbackBlocked = false, canRepeat = false, onRepeat, error, announcement, onStart, onMute, onEnd, onResumeAudio, className }: VoiceControlsProps) {
|
||||
const inactive = state === "idle" || state === "ended" || state === "failed";
|
||||
const connecting = state === "connecting" || state === "reconnecting";
|
||||
const startButton = useRef<HTMLButtonElement>(null);
|
||||
const restoreFocus = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!inactive || !restoreFocus.current) return;
|
||||
restoreFocus.current = false;
|
||||
if (document.activeElement === document.body) startButton.current?.focus();
|
||||
}, [inactive]);
|
||||
return (
|
||||
<section aria-label={`Voice conversation with ${agentName}`} className={cn("flex min-w-0 flex-col gap-3", className)}>
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<h3 className="break-words text-sm font-medium">Talk to {agentName}</h3>
|
||||
<p role="status" className="text-sm text-muted-foreground">{labels[state]}{muted && !inactive ? " · Microphone muted" : ""}</p>
|
||||
</div>
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{inactive ? (
|
||||
<Button ref={startButton} size="sm" disabled={busy} onClick={onStart}><Phone aria-hidden="true" />{state === "failed" ? "Try again" : "Start voice"}</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button size="sm" variant="outline" aria-pressed={muted} disabled={busy || connecting || state === "ending" || state === "cleanup_failed"} onClick={onMute}>
|
||||
{muted ? <MicOff aria-hidden="true" /> : <Mic aria-hidden="true" />}{muted ? "Unmute" : "Mute"}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" disabled={state === "ending"} onClick={() => { restoreFocus.current = true; onEnd(); }}><PhoneOff aria-hidden="true" />{state === "cleanup_failed" ? "Retry ending call" : "End call"}</Button>
|
||||
</>
|
||||
)}
|
||||
{canRepeat && onRepeat && !inactive && <Button size="sm" variant="outline" disabled={busy || connecting || state === "ending" || state === "cleanup_failed"} onClick={onRepeat}><RotateCcw aria-hidden="true" />Repeat answer</Button>}
|
||||
{playbackBlocked && !inactive && <Button size="sm" variant="outline" onClick={onResumeAudio}><Volume2 aria-hidden="true" />Enable audio</Button>}
|
||||
</div>
|
||||
{!inactive && <p className="text-xs text-muted-foreground">Ending the call keeps your task running. Speko voice charges are separate from agent costs.</p>}
|
||||
<span className="sr-only" aria-live="polite" aria-atomic="true">{announcement}</span>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
|
||||
import { createVoiceSessionController, type VoiceSessionDependencies } from "@/lib/voice-session-controller";
|
||||
import { VoiceControls } from "./VoiceControls";
|
||||
import { VoiceTranscript } from "./VoiceTranscript";
|
||||
|
||||
export interface VoiceConversationPanelProps {
|
||||
agentName: string;
|
||||
autoStart?: boolean;
|
||||
accessRevoked?: boolean;
|
||||
onEndedChange?: (ended: boolean) => void;
|
||||
/** Keep this object stable for the lifetime of a task's voice panel. */
|
||||
dependencies: VoiceSessionDependencies;
|
||||
notification?: { sessionId: string; generation: number; publicationId: string; attempt?: number };
|
||||
}
|
||||
|
||||
export function VoiceConversationPanel({ agentName, dependencies, notification, autoStart = false, onEndedChange, accessRevoked = false }: VoiceConversationPanelProps) {
|
||||
const controller = useMemo(() => createVoiceSessionController(dependencies), [dependencies]);
|
||||
const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
|
||||
const started = useRef(false);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// StrictMode's initial cleanup runs before this microtask. Never open media
|
||||
// for an already unmounted panel, or restart when call data changes.
|
||||
queueMicrotask(() => { if (!cancelled && autoStart && !started.current) { started.current = true; void controller.start(); } });
|
||||
return () => { cancelled = true; };
|
||||
}, [controller, autoStart]);
|
||||
useEffect(() => { onEndedChange?.(snapshot.state === "ended" || snapshot.state === "failed"); }, [snapshot.state, onEndedChange]);
|
||||
useEffect(() => () => { if (controller.getSnapshot().state !== "idle") void controller.stop(); }, [controller]);
|
||||
useEffect(() => { if (accessRevoked) void controller.stop(); }, [controller, accessRevoked]);
|
||||
useEffect(() => { if (notification) void controller.notify(notification); else controller.clearPendingNotifications(); }, [controller, notification?.sessionId, notification?.generation, notification?.publicationId, notification?.attempt]);
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-4">
|
||||
<VoiceControls {...snapshot} agentName={agentName} onStart={() => { void controller.start(); }} onMute={() => { void controller.mute(); }} onEnd={() => { void controller.stop(); }} onResumeAudio={() => { void controller.resumeAudio(); }} onRepeat={() => { void controller.repeat(); }} />
|
||||
<div className="max-h-64 overflow-y-auto" role="region" aria-label="Voice transcript history" tabIndex={snapshot.transcript.length ? 0 : undefined}><VoiceTranscript entries={snapshot.transcript} agentName={agentName} /></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { VoiceTranscriptEntry } from "@/lib/voice-transcript";
|
||||
|
||||
export interface VoiceTranscriptProps {
|
||||
entries: readonly VoiceTranscriptEntry[];
|
||||
agentName: string;
|
||||
unavailable?: boolean;
|
||||
}
|
||||
|
||||
/** Announcements belong to the session controller, once per final segment. */
|
||||
export function VoiceTranscript({ entries, agentName, unavailable = false }: VoiceTranscriptProps) {
|
||||
if (unavailable) return <p className="text-sm text-muted-foreground">The transcript is unavailable. Your task history is still available.</p>;
|
||||
if (!entries.length) return <p className="text-sm text-muted-foreground">Your conversation will appear here.</p>;
|
||||
return (
|
||||
<ol aria-label="Conversation transcript" aria-live="off" className="flex min-w-0 flex-col gap-4">
|
||||
{entries.map((entry) => (
|
||||
<li key={entry.id} className="flex min-w-0 flex-col gap-1">
|
||||
<span className="text-xs font-medium text-muted-foreground break-words">
|
||||
{entry.source === "user" ? "You" : entry.source === "application" ? "Paperclip" : agentName}
|
||||
{!entry.final && <span> · Speaking</span>}
|
||||
{entry.interrupted && <span> · Interrupted</span>}
|
||||
</span>
|
||||
<p className="whitespace-pre-wrap break-words text-sm">{entry.text}</p>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
@@ -1027,7 +1027,7 @@ function StandardConnectionSetupFlow({
|
||||
const visibleGalleryApps = useMemo(
|
||||
() => (galleryQuery.data?.apps ?? []).filter((app) => memoryConnectorsEnabled || !isMemoryConnectorId(app.slug)).filter((app) =>
|
||||
app.slug === "agentmail" || chatConnectorsEnabled ||
|
||||
!app.methods.some((method) => method.transport === "chat_sdk") ||
|
||||
!app.methods.some((method) => method.purpose === "channel") ||
|
||||
appSupportsToolCatalogSetup(app),
|
||||
),
|
||||
[galleryQuery.data, chatConnectorsEnabled, memoryConnectorsEnabled],
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { VoiceMediaCallbacks, VoiceMediaCredentials } from "./voice-session-controller";
|
||||
|
||||
/** Load media after the server authorizes a user-initiated session. */
|
||||
export async function connectSpekoVoiceMedia(credentials: VoiceMediaCredentials, callbacks: VoiceMediaCallbacks) {
|
||||
const { VoiceConversation } = await import("@spekoai/client");
|
||||
const conversation = await VoiceConversation.create({
|
||||
transportToken: credentials.transportToken,
|
||||
transportUrl: credentials.transportUrl,
|
||||
onModeChange: callbacks.onModeChange,
|
||||
onDisconnect: callbacks.onDisconnect,
|
||||
onAudioPlaybackBlocked: callbacks.onAudioPlaybackBlocked,
|
||||
onMessage: (message) => callbacks.onMessage({ source: message.source, text: message.text, isFinal: message.isFinal, segmentId: message.segmentId }),
|
||||
});
|
||||
return {
|
||||
endSession: () => conversation.endSession(),
|
||||
setMicMuted: (muted: boolean) => conversation.setMicMuted(muted),
|
||||
sendChatMessage: (text: string) => conversation.sendChatMessage(text),
|
||||
async startAudioPlayback() {
|
||||
await conversation.startAudioPlayback();
|
||||
if (!conversation.canPlaybackAudio) throw new Error("Audio playback remains blocked");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { VoiceSession, VoiceSessionMedia } from "@paperclipai/shared";
|
||||
import { createVoiceCallAttempt, voiceCallJournal } from "./voice-call-attempt";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { VoiceSessionStartError } from "./voice-session-controller";
|
||||
|
||||
function fixture() {
|
||||
const rows = new Map<string, string>();
|
||||
const storage = { getItem: (key: string) => rows.get(key) ?? null, setItem: (key: string, value: string) => { rows.set(key, value); }, removeItem: (key: string) => { rows.delete(key); } };
|
||||
const session = { id: "session", state: "active" } as VoiceSession;
|
||||
const media = { sessionId: "session", generation: 1, transportToken: "must-never-be-saved", transportUrl: "wss://test.invalid" } satisfies VoiceSessionMedia;
|
||||
const client = { start: vi.fn(async () => ({ session, media })), end: vi.fn(async () => ({ ...session, state: "ended" as const })), get: vi.fn(async () => session), notification: vi.fn(async () => null) };
|
||||
const journal = voiceCallJournal(storage, "company", "operator");
|
||||
return { rows, storage, client, journal };
|
||||
}
|
||||
describe("voice reload recovery", () => {
|
||||
it("retains exact cleanup identity and a safe credit reason after a rejected creation", async () => {
|
||||
const f=fixture();f.client.start.mockRejectedValue(new ApiError("private provider detail",409,{details:{code:"voice_credits_required",sessionId:"failed-call"}}));
|
||||
const attempt=createVoiceCallAttempt("company",f.client,f.journal);
|
||||
await expect(attempt.start({endpointId:"endpoint"})).rejects.toMatchObject({sessionId:"failed-call",reason:"credits_required"});
|
||||
expect(f.client.start).toHaveBeenCalledOnce();expect(f.journal.read()?.sessionId).toBe("failed-call");
|
||||
await attempt.end("failed-call");expect(f.journal.read()).toBeUndefined();
|
||||
});
|
||||
it("closes the saved call on reload without minting or reissuing media", async () => {
|
||||
const f = fixture();
|
||||
const original = createVoiceCallAttempt("company", f.client, f.journal);
|
||||
await original.start({ endpointId: "endpoint", issueId: "task" });
|
||||
expect([...f.rows.values()].join()).not.toContain("must-never-be-saved");
|
||||
const reloaded = createVoiceCallAttempt("company", f.client, f.journal);
|
||||
await expect(reloaded.start({ endpointId: "different-endpoint" })).rejects.toMatchObject({ sessionId: "session" });
|
||||
expect(f.client.start).toHaveBeenCalledOnce();
|
||||
await reloaded.end("session"); expect(f.journal.read()).toBeUndefined();
|
||||
await reloaded.start({ endpointId: "different-endpoint" }); expect(f.client.start).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("recovers a lost creation response using the original key and exact task intent", async () => {
|
||||
const f = fixture(); f.client.start.mockRejectedValueOnce(new Error("Lost response"));
|
||||
await expect(createVoiceCallAttempt("company", f.client, f.journal).start({ endpointId: "endpoint", newConversation: true })).rejects.toThrow("Lost response");
|
||||
const reloaded = createVoiceCallAttempt("company", f.client, f.journal);
|
||||
await expect(reloaded.start({ endpointId: "different", issueId: "other-task" })).rejects.toBeInstanceOf(VoiceSessionStartError);
|
||||
expect(f.client.start.mock.calls[0]).toEqual(f.client.start.mock.calls[1]);
|
||||
await reloaded.end("session");
|
||||
});
|
||||
it("preserves recovery across an uncertain hangup and isolates company/user scopes", async () => {
|
||||
const f = fixture(); const attempt = createVoiceCallAttempt("company", f.client, f.journal);
|
||||
await attempt.start({ endpointId: "endpoint" });
|
||||
f.client.end.mockRejectedValueOnce(new Error("Unconfirmed"));
|
||||
await expect(attempt.end("session")).rejects.toThrow("Unconfirmed");
|
||||
expect(f.journal.read()?.sessionId).toBe("session");
|
||||
expect(voiceCallJournal(f.storage, "other-company", "operator").read()).toBeUndefined();
|
||||
expect(voiceCallJournal(f.storage, "company", "another-user").read()).toBeUndefined();
|
||||
await attempt.end("session"); expect(f.journal.read()).toBeUndefined();
|
||||
});
|
||||
it("does not open a provider call if recovery identity cannot be persisted", async () => {
|
||||
const f = fixture(); const journal = { ...f.journal, write() { throw new Error("Storage unavailable"); } };
|
||||
await expect(createVoiceCallAttempt("company", f.client, journal).start({ endpointId: "endpoint" })).rejects.toThrow("Storage unavailable");
|
||||
expect(f.client.start).not.toHaveBeenCalled();
|
||||
});
|
||||
it("still identifies the exact call for cleanup if storage fails after creation", async () => {
|
||||
const f = fixture(); let writes = 0;
|
||||
const journal = { ...f.journal, write: (value: Parameters<typeof f.journal.write>[0]) => { if (++writes > 1) throw new Error("Storage full"); f.journal.write(value); } };
|
||||
await expect(createVoiceCallAttempt("company", f.client, journal).start({ endpointId: "endpoint" })).rejects.toMatchObject({ sessionId: "session" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { voiceSessionsApi } from "@/api/voiceSessions";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { VoiceSessionStartError } from "./voice-session-controller";
|
||||
|
||||
type StartInput = Parameters<typeof voiceSessionsApi.start>[1];
|
||||
export interface VoiceCallAttempt { request: StartInput; sessionId?: string }
|
||||
export interface VoiceCallJournal {
|
||||
read(): VoiceCallAttempt | undefined;
|
||||
write(attempt: VoiceCallAttempt): void;
|
||||
clear(): void;
|
||||
}
|
||||
|
||||
/** Tab-scoped recovery identity only. Never persist media tokens or transcripts. */
|
||||
export function voiceCallJournal(storage: Pick<Storage, "getItem" | "setItem" | "removeItem">, companyId: string, callerId: string): VoiceCallJournal {
|
||||
const key = `paperclip:voice-attempt:${encodeURIComponent(companyId)}:${encodeURIComponent(callerId)}`;
|
||||
return {
|
||||
read() {
|
||||
const raw = storage.getItem(key);
|
||||
if (!raw) return undefined;
|
||||
if (raw.length > 4096) throw new Error("Invalid voice recovery identity");
|
||||
const value = JSON.parse(raw) as VoiceCallAttempt;
|
||||
if (!value || typeof value.request?.endpointId !== "string" || typeof value.request.idempotencyKey !== "string"
|
||||
|| value.sessionId !== undefined && typeof value.sessionId !== "string") throw new Error("Invalid voice recovery identity");
|
||||
return value;
|
||||
},
|
||||
write({ request, sessionId }) {
|
||||
storage.setItem(key, JSON.stringify({ request: { endpointId: request.endpointId, issueId: request.issueId,
|
||||
newConversation: request.newConversation, idempotencyKey: request.idempotencyKey, maxDurationSeconds: request.maxDurationSeconds }, sessionId }));
|
||||
},
|
||||
clear() { storage.removeItem(key); },
|
||||
};
|
||||
}
|
||||
|
||||
/** Recover an uncertain request with the SAME input/key, then close its exact call. */
|
||||
export function createVoiceCallAttempt(companyId: string, client: typeof voiceSessionsApi, journal?: VoiceCallJournal) {
|
||||
let attempt: VoiceCallAttempt | undefined;
|
||||
let recovering = false;
|
||||
return {
|
||||
async start(input: Omit<StartInput, "idempotencyKey">) {
|
||||
if (!attempt) {
|
||||
attempt = journal?.read();
|
||||
recovering = Boolean(attempt);
|
||||
attempt ??= { request: { ...input, idempotencyKey: crypto.randomUUID() } };
|
||||
}
|
||||
// A storage failure must occur before the provider can open a call.
|
||||
journal?.write(attempt);
|
||||
if (attempt.sessionId) throw new VoiceSessionStartError(attempt.sessionId);
|
||||
let result: Awaited<ReturnType<typeof client.start>>;
|
||||
try { result = await client.start(companyId, attempt.request); }
|
||||
catch (error) {
|
||||
const body = error instanceof ApiError ? error.body as { details?: { sessionId?: string; code?: string } } | null : null;
|
||||
if (body?.details?.sessionId) {
|
||||
attempt.sessionId = body.details.sessionId;
|
||||
try { journal?.write(attempt); } catch { /* Exact identity still reaches cleanup. */ }
|
||||
throw new VoiceSessionStartError(attempt.sessionId, body.details.code === "voice_credits_required" ? "credits_required" : undefined);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
attempt.sessionId = result.session.id;
|
||||
// If persisting the identity fails after creation, the controller still
|
||||
// receives the exact call to close; never lose a live provider resource.
|
||||
try { journal?.write(attempt); }
|
||||
catch { throw new VoiceSessionStartError(attempt.sessionId); }
|
||||
if (recovering || !result.media) throw new VoiceSessionStartError(attempt.sessionId);
|
||||
return { ...result, media: result.media };
|
||||
},
|
||||
async end(sessionId: string) {
|
||||
const result = await client.end(companyId, sessionId);
|
||||
if (!["ended", "failed", "expired"].includes(result.state)) throw new Error("Speko has not confirmed hangup yet");
|
||||
const saved = journal?.read();
|
||||
if (!saved || saved.sessionId === sessionId || saved.request.idempotencyKey === attempt?.request.idempotencyKey) journal?.clear();
|
||||
attempt = undefined; recovering = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createVoiceSessionController, VOICE_REPEAT_NOTIFICATION, VoiceSessionStartError, type VoiceMediaCallbacks, type VoiceMediaCredentials } from "./voice-session-controller";
|
||||
const credentials: VoiceMediaCredentials = { sessionId: "session-a", generation: 2, transportToken: "short-lived-test-token", transportUrl: "wss://media.example.test" };
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
function setup() {
|
||||
let callbacks!: VoiceMediaCallbacks;
|
||||
const media = { endSession: vi.fn(async () => {}), setMicMuted: vi.fn(async (_muted: boolean) => {}), sendChatMessage: vi.fn(async (_text: string) => {}), startAudioPlayback: vi.fn(async () => {}) };
|
||||
const dependencies = { mint: vi.fn(async () => credentials), end: vi.fn(async (_id: string) => {}), connect: vi.fn(async (_credentials: VoiceMediaCredentials, cb: VoiceMediaCallbacks) => { callbacks = cb; return media; }) };
|
||||
return { controller: createVoiceSessionController(dependencies), dependencies, media, callbacks: () => callbacks };
|
||||
}
|
||||
afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
|
||||
describe("voice media session lifecycle", () => {
|
||||
it("closes a definitively rejected call and explains credits without automatic retry or media", async () => {
|
||||
const x=setup();x.dependencies.mint.mockRejectedValue(new VoiceSessionStartError("failed-call","credits_required"));
|
||||
await x.controller.start();expect(x.dependencies.connect).not.toHaveBeenCalled();expect(x.dependencies.end).toHaveBeenCalledWith("failed-call");
|
||||
expect(x.dependencies.mint).toHaveBeenCalledOnce();expect(x.controller.getSnapshot()).toMatchObject({state:"failed",error:"Speko needs credits before starting a call. Add credits in Speko, then try again."});
|
||||
});
|
||||
it("closes a session minted after the caller ended without connecting media", async () => {
|
||||
const x = setup(); const mint = deferred<VoiceMediaCredentials>(); x.dependencies.mint.mockReturnValue(mint.promise);
|
||||
const starting = x.controller.start(); const stopping = x.controller.stop(); expect(x.controller.getSnapshot().state).toBe("ending"); mint.resolve(credentials); await Promise.all([starting, stopping]);
|
||||
expect(x.dependencies.connect).not.toHaveBeenCalled(); expect(x.dependencies.end).toHaveBeenCalledExactlyOnceWith("session-a");
|
||||
expect(x.controller.getSnapshot().state).toBe("ended");
|
||||
});
|
||||
it("closes late-connected media and ignores its obsolete callbacks", async () => {
|
||||
const x = setup(); const connecting = deferred<typeof x.media>(); let callbacks!: VoiceMediaCallbacks;
|
||||
x.dependencies.connect.mockImplementation(async (_credentials, cb) => { callbacks = cb; return connecting.promise; });
|
||||
const starting = x.controller.start(); await Promise.resolve(); const stopping = x.controller.stop(); connecting.resolve(x.media); await Promise.all([starting, stopping]);
|
||||
callbacks.onModeChange("speaking"); callbacks.onMessage({ source: "agent", text: "stale", segmentId: "x", isFinal: true });
|
||||
expect(x.media.endSession).toHaveBeenCalledOnce(); expect(x.controller.getSnapshot()).toMatchObject({ state: "ended", transcript: [] });
|
||||
});
|
||||
it("fences notifications to the session generation and reserves concurrent duplicates", async () => {
|
||||
const x = setup(); await x.controller.start(); const delivery = deferred<void>(); x.media.sendChatMessage.mockReturnValue(delivery.promise);
|
||||
const notification = { sessionId: "session-a", generation: 2, publicationId: "result-a" };
|
||||
expect(await x.controller.notify({ ...notification, generation: 1 })).toBe(false);
|
||||
expect(await x.controller.notify({ ...notification, sessionId: "another-company-session" })).toBe(false);
|
||||
const first = x.controller.notify(notification); expect(await x.controller.notify(notification)).toBe(false); delivery.resolve(); expect(await first).toBe(true);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce(); expect(x.controller.getSnapshot().transcript[0]?.source).toBe("application");
|
||||
});
|
||||
it("does not replay ambiguous delivery failure or expose private provider errors", async () => {
|
||||
const x = setup(); await x.controller.start(); x.media.sendChatMessage.mockRejectedValue(new Error("private provider response"));
|
||||
const notification = { sessionId: "session-a", generation: 2, publicationId: "result-a" };
|
||||
await x.controller.notify(notification); await x.controller.notify(notification);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce(); expect(JSON.stringify(x.controller.getSnapshot())).not.toContain("private provider response");
|
||||
});
|
||||
it("allows a server-authorized later hint after an interruption without duplicating transcript rows", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
const notification = { sessionId: "session-a", generation: 2, publicationId: "result-a", attempt: 0 };
|
||||
expect(await x.controller.notify(notification)).toBe(true);
|
||||
expect(await x.controller.notify(notification)).toBe(false);
|
||||
x.callbacks().onModeChange("speaking");
|
||||
x.callbacks().onModeChange("listening");
|
||||
expect(await x.controller.notify({ ...notification, attempt: 1 })).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledTimes(2);
|
||||
expect(x.controller.getSnapshot().transcript).toHaveLength(1);
|
||||
});
|
||||
it("waits for an acknowledgment to finish before announcing a fast task result", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
x.callbacks().onModeChange("speaking");
|
||||
await x.controller.notify({ sessionId: "session-a", generation: 2, publicationId: "fast-result" });
|
||||
expect(x.media.sendChatMessage).not.toHaveBeenCalled();
|
||||
x.callbacks().onModeChange("listening");
|
||||
await vi.advanceTimersByTimeAsync(1_500);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("coalesces queued result hints and never sends them concurrently", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
x.callbacks().onModeChange("speaking");
|
||||
for (const publicationId of ["one", "two", "three"]) await x.controller.notify({ ...credentials, publicationId });
|
||||
const sent = deferred<void>(); x.media.sendChatMessage.mockReturnValue(sent.promise);
|
||||
x.callbacks().onModeChange("listening");
|
||||
await vi.advanceTimersByTimeAsync(1_500);
|
||||
await x.controller.notify({ ...credentials, publicationId: "four" });
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
sent.resolve(); await Promise.resolve();
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("does not mistake pauses between words for a safe result boundary", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
await x.controller.notify({ ...credentials, publicationId: "first" });
|
||||
x.callbacks().onModeChange("speaking");
|
||||
await x.controller.notify({ ...credentials, publicationId: "amended" });
|
||||
// The live SDK oscillates even while the first result is being read.
|
||||
for (let i = 0; i < 15; i++) {
|
||||
x.callbacks().onModeChange("listening");
|
||||
await vi.advanceTimersByTimeAsync(800);
|
||||
x.callbacks().onMessage({ source: "agent", text: `Result word ${i}`, segmentId: "answer", isFinal: false });
|
||||
await vi.advanceTimersByTimeAsync(400);
|
||||
x.callbacks().onModeChange("speaking");
|
||||
}
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
x.callbacks().onModeChange("listening");
|
||||
await vi.advanceTimersByTimeAsync(1_499);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
x.callbacks().onMessage({ source: "agent", text: "The complete result", segmentId: "answer", isFinal: true });
|
||||
await vi.advanceTimersByTimeAsync(1_500);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledTimes(2);
|
||||
expect(x.controller.getSnapshot().state).toBe("listening");
|
||||
});
|
||||
it("allows a caller interruption to retire unfinished speech before a later result", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
x.callbacks().onMessage({ source: "agent", text: "An interrupted answer", segmentId: "old-answer", isFinal: false });
|
||||
await x.controller.notify({ ...credentials, publicationId: "next" });
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(x.media.sendChatMessage).not.toHaveBeenCalled();
|
||||
x.callbacks().onMessage({ source: "user", text: "Please include the other instruction", segmentId: "followup", isFinal: true });
|
||||
// A delayed native transcript for the interrupted turn must not reopen
|
||||
// its gate after the caller has already moved on.
|
||||
x.callbacks().onMessage({ source: "agent", text: "An interrupted answer, delayed fragment", segmentId: "old-answer", isFinal: false });
|
||||
await vi.advanceTimersByTimeAsync(1_500);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
expect(x.controller.getSnapshot().transcript[0]?.final).toBe(false);
|
||||
});
|
||||
it("clears queued hints when a call ends during the quiet period", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
x.callbacks().onModeChange("speaking");
|
||||
await x.controller.notify({ ...credentials, publicationId: "pending" });
|
||||
x.callbacks().onModeChange("listening");
|
||||
await x.controller.stop();
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(x.media.sendChatMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
it("discards an obsolete queued hint when the server reports no undelivered result", async () => {
|
||||
vi.useFakeTimers();
|
||||
const x = setup(); await x.controller.start();
|
||||
await x.controller.notify({ ...credentials, publicationId: "result" });
|
||||
await x.controller.notify({ ...credentials, publicationId: "result", attempt: 1 });
|
||||
x.controller.clearPendingNotifications();
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("repeats only on caller action without creating another session or task request", async () => {
|
||||
const x = setup();
|
||||
await x.controller.repeat(); expect(x.media.sendChatMessage).not.toHaveBeenCalled();
|
||||
await x.controller.start();
|
||||
await x.controller.notify({ ...credentials, publicationId: "result" });
|
||||
x.callbacks().onModeChange("speaking");
|
||||
const sent = deferred<void>(); x.media.sendChatMessage.mockReturnValueOnce(sent.promise);
|
||||
const repeating = x.controller.repeat(); await x.controller.repeat();
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledTimes(2);
|
||||
expect(x.media.sendChatMessage).toHaveBeenLastCalledWith(VOICE_REPEAT_NOTIFICATION);
|
||||
sent.resolve(); await repeating;
|
||||
expect(x.dependencies.mint).toHaveBeenCalledOnce();
|
||||
await x.controller.stop(); await x.controller.repeat();
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("changes mute state after media succeeds, rejecting double clicks", async () => {
|
||||
const x = setup(); await x.controller.start(); const muting = deferred<void>(); x.media.setMicMuted.mockReturnValue(muting.promise);
|
||||
const first = x.controller.mute(); await x.controller.mute(); expect(x.controller.getSnapshot().muted).toBe(false);
|
||||
muting.resolve(); await first; expect(x.controller.getSnapshot().muted).toBe(true); expect(x.media.setMicMuted).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("announces committed speech, not each partial or repeated final", async () => {
|
||||
const x = setup(); await x.controller.start();
|
||||
x.callbacks().onMessage({ source: "agent", segmentId: "a", text: "One", isFinal: false }); expect(x.controller.getSnapshot().announcement).toBe("");
|
||||
x.callbacks().onMessage({ source: "agent", segmentId: "a", text: "One result", isFinal: true }); const announcement = x.controller.getSnapshot().announcement;
|
||||
x.callbacks().onMessage({ source: "agent", segmentId: "a", text: "One result", isFinal: true });
|
||||
expect(x.controller.getSnapshot().announcement).toBe(announcement); expect(x.controller.getSnapshot().transcript).toHaveLength(1);
|
||||
});
|
||||
it("joins simultaneous stops and blocks a new start until cleanup completes", async () => {
|
||||
const x = setup(); await x.controller.start(); const closing = deferred<void>(); x.dependencies.end.mockReturnValue(closing.promise);
|
||||
const first = x.controller.stop(); const second = x.controller.stop(); await x.controller.start();
|
||||
expect(first).toBe(second); expect(x.dependencies.mint).toHaveBeenCalledOnce(); expect(x.controller.getSnapshot().state).toBe("ending");
|
||||
closing.resolve(); await first; expect(x.dependencies.end).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("retries failed remote cleanup without closing media twice or starting another call", async () => {
|
||||
const x = setup(); await x.controller.start(); x.dependencies.end.mockRejectedValueOnce(new Error("provider unavailable"));
|
||||
await x.controller.stop(); expect(x.controller.getSnapshot().state).toBe("cleanup_failed"); await x.controller.start(); expect(x.dependencies.mint).toHaveBeenCalledOnce();
|
||||
await x.controller.stop(); expect(x.controller.getSnapshot().state).toBe("ended"); expect(x.media.endSession).toHaveBeenCalledOnce(); expect(x.dependencies.end).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("preserves an early speaking callback during connection", async () => {
|
||||
const x = setup(); x.dependencies.connect.mockImplementation(async (_credentials, cb) => { cb.onModeChange("speaking"); return x.media; });
|
||||
await x.controller.start(); expect(x.controller.getSnapshot().state).toBe("speaking");
|
||||
});
|
||||
it("reconciles unsegmented partials and announces their final", async () => {
|
||||
const x = setup(); await x.controller.start();
|
||||
x.callbacks().onMessage({ source: "agent", text: "A", isFinal: false });
|
||||
x.callbacks().onMessage({ source: "agent", text: "A result", isFinal: true });
|
||||
x.callbacks().onMessage({ source: "agent", text: "A result", isFinal: true });
|
||||
expect(x.controller.getSnapshot().transcript).toHaveLength(1); expect(x.controller.getSnapshot().announcement).toBe("Agent: A result");
|
||||
});
|
||||
it("ends media and provider once without cancelling execution", async () => {
|
||||
const x = setup(); await x.controller.start(); await x.controller.stop(); await x.controller.stop();
|
||||
expect(x.media.endSession).toHaveBeenCalledOnce(); expect(x.dependencies.end).toHaveBeenCalledExactlyOnceWith("session-a");
|
||||
});
|
||||
it("queues a result notification received while media is still connecting", async () => {
|
||||
const x = setup(), connecting = deferred<typeof x.media>();
|
||||
x.dependencies.connect.mockReturnValue(connecting.promise);
|
||||
const start = x.controller.start();
|
||||
await Promise.resolve();
|
||||
await x.controller.notify({ sessionId: credentials.sessionId, generation: credentials.generation, publicationId: "early-result" });
|
||||
expect(x.media.sendChatMessage).not.toHaveBeenCalled();
|
||||
connecting.resolve(x.media);
|
||||
await start;
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("retains a call identity for cleanup when creation returned no media token", async () => {
|
||||
const x = setup();
|
||||
x.dependencies.mint.mockRejectedValue(new VoiceSessionStartError("uncertain-session"));
|
||||
x.dependencies.end.mockRejectedValueOnce(new Error("Still ending"));
|
||||
await x.controller.start();
|
||||
expect(x.dependencies.connect).not.toHaveBeenCalled();
|
||||
expect(x.controller.getSnapshot().state).toBe("cleanup_failed");
|
||||
await x.controller.start();
|
||||
expect(x.dependencies.mint).toHaveBeenCalledOnce();
|
||||
await x.controller.stop();
|
||||
expect(x.dependencies.end).toHaveBeenLastCalledWith("uncertain-session");
|
||||
expect(x.controller.getSnapshot().state).toBe("ended");
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import { VOICE_RESULT_NOTIFICATION, VOICE_REPEAT_NOTIFICATION } from "@paperclipai/shared";
|
||||
export { VOICE_RESULT_NOTIFICATION, VOICE_REPEAT_NOTIFICATION } from "@paperclipai/shared";
|
||||
import type { VoiceControlState } from "../components/voice/VoiceControls";
|
||||
import { updateVoiceTranscript, type VoiceTranscriptEntry, type VoiceTranscriptUpdate } from "./voice-transcript";
|
||||
|
||||
export class VoiceSessionStartError extends Error {
|
||||
constructor(readonly sessionId: string, readonly reason?: "credits_required") { super("The call needs cleanup before reconnecting"); }
|
||||
}
|
||||
|
||||
export interface VoiceMediaCredentials {
|
||||
sessionId: string;
|
||||
generation: number;
|
||||
transportToken: string;
|
||||
transportUrl: string;
|
||||
}
|
||||
export interface VoiceMedia {
|
||||
endSession(): Promise<void>;
|
||||
setMicMuted(muted: boolean): Promise<void>;
|
||||
sendChatMessage(text: string): Promise<void>;
|
||||
startAudioPlayback(): Promise<void>;
|
||||
}
|
||||
export interface VoiceMediaCallbacks {
|
||||
onMessage(update: VoiceTranscriptUpdate): void;
|
||||
onModeChange(mode: "listening" | "speaking"): void;
|
||||
onDisconnect(): void;
|
||||
onAudioPlaybackBlocked(): void;
|
||||
}
|
||||
export interface VoiceSessionSnapshot {
|
||||
state: VoiceControlState;
|
||||
muted: boolean;
|
||||
busy: boolean;
|
||||
playbackBlocked: boolean;
|
||||
canRepeat?: boolean;
|
||||
transcript: readonly VoiceTranscriptEntry[];
|
||||
announcement: string;
|
||||
error?: string;
|
||||
}
|
||||
export interface VoiceSessionDependencies {
|
||||
/** Server authorizes endpoint, company, task and actor before minting. */
|
||||
mint(): Promise<VoiceMediaCredentials>;
|
||||
end(sessionId: string): Promise<void>;
|
||||
connect(credentials: VoiceMediaCredentials, callbacks: VoiceMediaCallbacks): Promise<VoiceMedia>;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/** Media lifecycle only. Ending a call never invokes task cancellation. */
|
||||
export function createVoiceSessionController(dependencies: VoiceSessionDependencies) {
|
||||
let snapshot: VoiceSessionSnapshot = { state: "idle", muted: false, busy: false, playbackBlocked: false, transcript: [], announcement: "" };
|
||||
const listeners = new Set<() => void>();
|
||||
let epoch = 0, media: VoiceMedia | undefined, credentials: VoiceMediaCredentials | undefined;
|
||||
let cleanupSessionId: string | undefined;
|
||||
let startup: Promise<void> | undefined, stopping: Promise<void> | undefined;
|
||||
const notifications = new Set<string>();
|
||||
const queuedNotifications = new Map<string, { sessionId: string; generation: number; publicationId: string; attempt?: number }>();
|
||||
const unfinishedAgentSegments = new Set<string>();
|
||||
const interruptedAgentSegments = new Set<string>();
|
||||
const fallbackSegments = new Map<string, { id: string; final: boolean; text: string }>();
|
||||
let sequence = 0, hintSending = false, hintSentAt = Number.NEGATIVE_INFINITY;
|
||||
let quietAfter = 0;
|
||||
let notificationTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
function clearNotificationTimer() { clearTimeout(notificationTimer); notificationTimer = undefined; }
|
||||
function noteActivity() {
|
||||
// SDK mode is LiveKit's active-speaker amplitude, not a completed turn.
|
||||
// Word pauses must not authorize a new typed turn that interrupts playback.
|
||||
quietAfter = Date.now() + 1_500;
|
||||
scheduleNotifications();
|
||||
}
|
||||
function scheduleNotifications() {
|
||||
clearNotificationTimer();
|
||||
if (!queuedNotifications.size || !media || stopping || hintSending || snapshot.state === "speaking" || unfinishedAgentSegments.size || snapshot.playbackBlocked) return;
|
||||
const delay = Math.max(0, quietAfter - Date.now(), hintSentAt + 10_000 - Date.now());
|
||||
notificationTimer = setTimeout(() => { notificationTimer = undefined; flushNotifications(); }, delay);
|
||||
}
|
||||
const change = (patch: Partial<VoiceSessionSnapshot>) => { snapshot = { ...snapshot, ...patch }; listeners.forEach((listener) => listener()); };
|
||||
async function cleanup() {
|
||||
const ownedMedia = media, ownedCredentials = credentials, ownedSessionId = credentials?.sessionId ?? cleanupSessionId;
|
||||
const results = await Promise.allSettled([
|
||||
Promise.resolve().then(async () => { if (ownedMedia) { await ownedMedia.endSession(); if (media === ownedMedia) media = undefined; } }),
|
||||
Promise.resolve().then(async () => { if (ownedSessionId) { await dependencies.end(ownedSessionId); if (credentials === ownedCredentials) credentials = undefined; if (cleanupSessionId === ownedSessionId) cleanupSessionId = undefined; } }),
|
||||
]);
|
||||
return results.every((result) => result.status === "fulfilled");
|
||||
}
|
||||
function stop() {
|
||||
if (stopping) return stopping;
|
||||
if (snapshot.state === "ended" && !startup && !media && !credentials && !cleanupSessionId) return Promise.resolve();
|
||||
epoch++;
|
||||
clearNotificationTimer(); queuedNotifications.clear();
|
||||
change({ state: "ending", busy: true, error: undefined });
|
||||
// Join creation before declaring the call ended: a late token or media
|
||||
// connection still belongs to this call and must be closed too.
|
||||
const operation = (async () => {
|
||||
await startup;
|
||||
const closed = await cleanup();
|
||||
change({ state: closed ? "ended" : "cleanup_failed", busy: false, playbackBlocked: false, muted: false,
|
||||
error: closed ? undefined : "The call could not be fully closed. Retry ending it before starting another call." });
|
||||
})();
|
||||
stopping = operation.finally(() => { stopping = undefined; });
|
||||
return stopping;
|
||||
}
|
||||
async function start() {
|
||||
if (!["idle", "ended", "failed"].includes(snapshot.state) || startup || stopping || media || credentials || cleanupSessionId) return;
|
||||
const ownedEpoch = ++epoch;
|
||||
notifications.clear(); queuedNotifications.clear(); unfinishedAgentSegments.clear(); interruptedAgentSegments.clear(); fallbackSegments.clear(); sequence = 0; hintSentAt = Number.NEGATIVE_INFINITY; hintSending = false; quietAfter = 0; clearNotificationTimer();
|
||||
change({ state: "connecting", busy: true, muted: false, canRepeat: false, error: undefined, playbackBlocked: false, transcript: [], announcement: "" });
|
||||
let failed = false, recovering = false, creditsRequired = false;
|
||||
const operation = (async () => {
|
||||
try {
|
||||
credentials = await dependencies.mint();
|
||||
if (epoch !== ownedEpoch) return;
|
||||
media = await dependencies.connect(credentials, {
|
||||
onModeChange(mode) { if (epoch === ownedEpoch) { change({ state: mode }); noteActivity(); } },
|
||||
onDisconnect() { if (epoch === ownedEpoch) void stop(); },
|
||||
onAudioPlaybackBlocked() { if (epoch === ownedEpoch) change({ playbackBlocked: true }); },
|
||||
onMessage(update) {
|
||||
if (epoch !== ownedEpoch || update.source === "user" && [VOICE_RESULT_NOTIFICATION, VOICE_REPEAT_NOTIFICATION].includes(update.text) || !update.text.trim()) return;
|
||||
let segmentId = update.segmentId;
|
||||
if (!segmentId) {
|
||||
let fallback = fallbackSegments.get(update.source);
|
||||
if (!fallback || fallback.final && fallback.text !== update.text) fallback = { id: `unsegmented-${++sequence}`, final: false, text: "" };
|
||||
segmentId = fallback.id;
|
||||
fallbackSegments.set(update.source, { id: segmentId, final: fallback.final || update.isFinal, text: update.text });
|
||||
}
|
||||
const transcript = updateVoiceTranscript(snapshot.transcript, { ...update, segmentId }, segmentId);
|
||||
const entry = transcript.find((item) => item.id === `${update.source}:${segmentId}`);
|
||||
const previous = snapshot.transcript.find((item) => item.id === entry?.id);
|
||||
// Active-speaker silence can occur in the middle of a streamed
|
||||
// sentence. Wait for its final transcript before admitting another
|
||||
// background typed turn. A real caller interruption retires the old
|
||||
// pending speech; it does not mean that speech was fully heard.
|
||||
if (update.source === "user") {
|
||||
for (const id of unfinishedAgentSegments) interruptedAgentSegments.add(id);
|
||||
unfinishedAgentSegments.clear();
|
||||
} else if (entry?.final || interruptedAgentSegments.has(segmentId)) unfinishedAgentSegments.delete(segmentId);
|
||||
else unfinishedAgentSegments.add(segmentId);
|
||||
noteActivity();
|
||||
change({ transcript, ...(update.isFinal && entry && (!previous?.final || previous.text !== entry.text) ? { announcement: `${update.source === "user" ? "You" : "Agent"}: ${update.text}` } : {}) });
|
||||
},
|
||||
});
|
||||
if (epoch === ownedEpoch) {
|
||||
change({ state: snapshot.state === "connecting" ? "listening" : snapshot.state, busy: false, canRepeat: true });
|
||||
flushNotifications();
|
||||
}
|
||||
} catch (error) { if (error instanceof VoiceSessionStartError) { cleanupSessionId = error.sessionId; recovering = true; creditsRequired = error.reason === "credits_required"; } failed = true; }
|
||||
})();
|
||||
startup = operation;
|
||||
await operation;
|
||||
if (startup === operation) startup = undefined;
|
||||
if (failed && epoch === ownedEpoch) {
|
||||
// Stop also retires callbacks from media that failed during creation.
|
||||
await stop();
|
||||
if (snapshot.state === "ended") change({ state: "failed", error: creditsRequired ? "Speko needs credits before starting a call. Add credits in Speko, then try again." : recovering ? "The previous call was closed. Start voice again to reconnect; your task is preserved." : "Voice could not connect. Check microphone permissions and your connection, then try again." });
|
||||
}
|
||||
}
|
||||
async function mute() {
|
||||
if (!media || snapshot.busy || stopping) return;
|
||||
const owned = media, ownedEpoch = epoch, target = !snapshot.muted;
|
||||
change({ busy: true });
|
||||
try { await owned.setMicMuted(target); if (epoch === ownedEpoch) change({ muted: target, error: undefined }); }
|
||||
catch { if (epoch === ownedEpoch) change({ error: "Microphone state could not be changed. Try again or end the call." }); }
|
||||
finally { if (epoch === ownedEpoch) change({ busy: false }); }
|
||||
}
|
||||
function flushNotifications() {
|
||||
if (!media || stopping) return;
|
||||
// Hints carry no result text. One hint is enough to request the next
|
||||
// durable answer; a burst of hints would interrupt the voice persona.
|
||||
const pending = [...queuedNotifications.values()].at(-1); queuedNotifications.clear();
|
||||
if (pending) void notify(pending);
|
||||
}
|
||||
async function notify(input: { sessionId: string; generation: number; publicationId: string; attempt?: number }) {
|
||||
const notificationKey = `${input.publicationId}:${input.attempt ?? 0}`;
|
||||
if (!credentials || stopping || input.sessionId !== credentials.sessionId || input.generation !== credentials.generation || notifications.has(notificationKey)) return false;
|
||||
if (!media || snapshot.state === "speaking" || unfinishedAgentSegments.size || snapshot.playbackBlocked || hintSending || Date.now() < quietAfter || Date.now() - hintSentAt < 10_000) { queuedNotifications.clear(); queuedNotifications.set(input.publicationId, input); scheduleNotifications(); return false; }
|
||||
const ownedEpoch = epoch;
|
||||
// Reserve before awaiting delivery. An ambiguous transport failure is not
|
||||
// permission to replay the same attempt. Only a fresh server check that
|
||||
// the publication remains unclaimed can authorize a later hint.
|
||||
notifications.add(notificationKey);
|
||||
hintSending = true; hintSentAt = Date.now();
|
||||
try {
|
||||
await media.sendChatMessage(VOICE_RESULT_NOTIFICATION);
|
||||
if (epoch !== ownedEpoch) return false;
|
||||
change({ canRepeat: true });
|
||||
if (!snapshot.transcript.some((entry) => entry.id === `publication:${input.publicationId}`)) change({ transcript: [...snapshot.transcript, { id: `publication:${input.publicationId}`, source: "application", text: "A task update is available.", final: true }] });
|
||||
return true;
|
||||
} catch { if (epoch === ownedEpoch) change({ error: "A task update could not be delivered to voice. Open the task to read it." }); return false; }
|
||||
finally { if (epoch === ownedEpoch) { hintSending = false; scheduleNotifications(); } }
|
||||
}
|
||||
function clearPendingNotifications() { queuedNotifications.clear(); clearNotificationTimer(); }
|
||||
async function repeat() {
|
||||
if (!media || stopping || snapshot.busy || hintSending || !snapshot.canRepeat) return;
|
||||
const ownedEpoch = epoch;
|
||||
// A caller-initiated repeat may interrupt speech; background results may not.
|
||||
change({ busy: true });
|
||||
hintSentAt = Date.now(); hintSending = true;
|
||||
try { await media.sendChatMessage(VOICE_REPEAT_NOTIFICATION); }
|
||||
catch { if (epoch === ownedEpoch) change({ error: "The answer could not be repeated. Open the task to read it." }); }
|
||||
finally { if (epoch === ownedEpoch) { hintSending = false; change({ busy: false }); scheduleNotifications(); } }
|
||||
}
|
||||
async function resumeAudio() {
|
||||
if (!media || stopping) return;
|
||||
const ownedEpoch = epoch;
|
||||
try { await media.startAudioPlayback(); if (epoch === ownedEpoch) { change({ playbackBlocked: false }); scheduleNotifications(); } }
|
||||
catch { if (epoch === ownedEpoch) change({ error: "Audio playback is blocked. Check this browser’s sound settings." }); }
|
||||
}
|
||||
return { start, stop, mute, notify, repeat, clearPendingNotifications, resumeAudio, getSnapshot: () => snapshot,
|
||||
subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; } };
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { updateVoiceTranscript } from "./voice-transcript";
|
||||
|
||||
describe("voice transcript reconciliation", () => {
|
||||
it("keeps a delayed reply separate from an earlier acknowledgment by the same speaker", () => {
|
||||
const first = updateVoiceTranscript([], { source: "agent", segmentId: "ack", text: "Working on it.", isFinal: true }, "unused");
|
||||
const result = updateVoiceTranscript(first, { source: "agent", segmentId: "answer", text: "The result is ready.", isFinal: true }, "unused");
|
||||
expect(result.map((e) => e.text)).toEqual(["Working on it.", "The result is ready."]);
|
||||
});
|
||||
it("replaces partials, ignores stale partials after final, and deduplicates repeated final reports", () => {
|
||||
let entries = updateVoiceTranscript([], { source: "user", segmentId: "a", text: "Add", isFinal: false }, "unused");
|
||||
for (const update of [{ text: "Add a follow-up", isFinal: true }, { text: "Add a", isFinal: false }, { text: "Add a follow-up", isFinal: true }]) {
|
||||
entries = updateVoiceTranscript(entries, { source: "user", segmentId: "a", ...update }, "unused");
|
||||
}
|
||||
expect(entries).toEqual([{ id: "user:a", source: "user", text: "Add a follow-up", final: true }]);
|
||||
});
|
||||
it("does not overwrite overlapping speakers sharing a segment identifier", () => {
|
||||
const first = updateVoiceTranscript([], { source: "agent", segmentId: "a", text: "Working", isFinal: false }, "unused");
|
||||
expect(updateVoiceTranscript(first, { source: "user", segmentId: "a", text: "Wait", isFinal: true }, "unused")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/** One entry per transport segment. Never merge distinct turns by speaker. */
|
||||
export interface VoiceTranscriptEntry {
|
||||
id: string;
|
||||
source: "user" | "agent" | "application";
|
||||
text: string;
|
||||
final: boolean;
|
||||
interrupted?: boolean;
|
||||
}
|
||||
export interface VoiceTranscriptUpdate {
|
||||
segmentId?: string;
|
||||
source: "user" | "agent";
|
||||
text: string;
|
||||
isFinal: boolean;
|
||||
}
|
||||
export function updateVoiceTranscript(
|
||||
entries: readonly VoiceTranscriptEntry[],
|
||||
update: VoiceTranscriptUpdate,
|
||||
fallbackId: string,
|
||||
): VoiceTranscriptEntry[] {
|
||||
if (!update.text.trim()) return [...entries];
|
||||
const id = `${update.source}:${update.segmentId ?? fallbackId}`;
|
||||
const index = entries.findIndex((entry) => entry.id === id);
|
||||
const previous = entries[index];
|
||||
// A late recognizer partial must not replace a committed final transcript.
|
||||
if (previous?.final && !update.isFinal) return [...entries];
|
||||
const next = { id, source: update.source, text: update.text, final: update.isFinal, ...(previous?.interrupted ? { interrupted: true } : {}) };
|
||||
if (index < 0) return [...entries, next];
|
||||
return entries.map((entry, i) => i === index ? next : entry);
|
||||
}
|
||||
+9
-1
@@ -1,3 +1,5 @@
|
||||
import { VoiceCallProvider } from "./components/voice/VoiceCallProvider";
|
||||
import { useAccountIdentity } from "./api/companies-query";
|
||||
import * as React from "react";
|
||||
import { StrictMode } from "react";
|
||||
import * as ReactDOM from "react-dom";
|
||||
@@ -58,6 +60,12 @@ function CompanyAwareBreadcrumbProvider({ children }: { children: React.ReactNod
|
||||
return <BreadcrumbProvider companyName={selectedCompany?.name ?? null}>{children}</BreadcrumbProvider>;
|
||||
}
|
||||
|
||||
function CompanyVoiceCalls({ children }: { children: React.ReactNode }) {
|
||||
const { selectedCompanyId } = useCompany();
|
||||
const { userId } = useAccountIdentity();
|
||||
return <VoiceCallProvider companyId={selectedCompanyId} userId={userId}>{children}</VoiceCallProvider>;
|
||||
}
|
||||
|
||||
const rootElement = document.getElementById("root");
|
||||
if (!rootElement) throw new Error("Paperclip root element is missing");
|
||||
|
||||
@@ -79,7 +87,7 @@ getOrCreatePaperclipReactRoot(window, rootElement).render(
|
||||
<PanelProvider>
|
||||
<PluginLauncherProvider>
|
||||
<DialogProvider>
|
||||
<App />
|
||||
<CompanyVoiceCalls><App /></CompanyVoiceCalls>
|
||||
</DialogProvider>
|
||||
</PluginLauncherProvider>
|
||||
</PanelProvider>
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import { SpekoPhoneLineForm } from "@/components/voice/SpekoPhoneLine";
|
||||
import { SpekoIncomingCallCard } from "@/components/voice/SpekoIncomingCalls";
|
||||
import { SpekoCallHistoryView, SpekoCallActivityItem, SpekoUnapprovedCallActivityItem } from "@/components/voice/SpekoCallHistory";
|
||||
import { SpekoPhoneCallbackForm } from "@/components/voice/SpekoPhoneCallback";
|
||||
import { SpekoProviderSetup } from "@/components/voice/SpekoProviderSetup";
|
||||
import { VoiceControls } from "@/components/voice/VoiceControls";
|
||||
import { VoiceTranscript } from "@/components/voice/VoiceTranscript";
|
||||
import { AnimatedDialogContent } from "@/components/AnimatedDialogContent";
|
||||
import { ExternalAgentPresetPicker, DotConnectionChecks } from "@/components/new-agent/ExternalAgentInviteContent";
|
||||
import { AgentMailApiKeyField } from "@/features/connections/AgentMailApiKeyField";
|
||||
@@ -2304,6 +2311,29 @@ export function DesignGuide() {
|
||||
<SavedProviderKeySelect options={[]} value="" onChange={() => {}} loading={false} error />
|
||||
</Section>
|
||||
|
||||
<Section title="Voice conversations">
|
||||
<div className="flex flex-col gap-6">
|
||||
<VoiceControls state="working" agentName="Company Phone Agent" onStart={() => {}} onMute={() => {}} onEnd={() => {}} onResumeAudio={() => {}} />
|
||||
<VoiceControls state="failed" agentName="Company Phone Agent" error="Microphone access was denied. Allow access in your browser, then try again." onStart={() => {}} onMute={() => {}} onEnd={() => {}} onResumeAudio={() => {}} />
|
||||
<VoiceTranscript agentName="Company Phone Agent" entries={[
|
||||
{ id: "ack", source: "agent", text: "I’m checking that now.", final: true },
|
||||
{ id: "followup", source: "user", text: "Include the revised delivery address too.", final: true },
|
||||
]} />
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Speko provider setup">
|
||||
<SpekoPhoneCallbackForm onSave={() => {}} />
|
||||
<SpekoCallHistoryView onRetry={() => {}} />
|
||||
<div className="divide-y divide-border border-y border-border">
|
||||
<SpekoCallActivityItem presentation="activity" entry={{session: {id: "demo-call", companyId: "demo", endpointId: "demo", issueId: "demo-task", assignedAgentId: "demo-agent", state: "ended", mode: "browser", generation: 1, callerAuthority: "member", replyCursor: 0, createdAt: "2026-10-07T17:00:00Z", expiresAt: "2026-10-07T17:10:00Z", endedAt: "2026-10-07T17:02:00Z", errorCode: null}, report: {status: "pending", costMicroUsd: null, durationSeconds: null, updatedAt: null, transcript: []}}} />
|
||||
<SpekoUnapprovedCallActivityItem presentation="activity" call={{id: "demo-missed", state: "expired", createdAt: "2026-10-07T17:00:00Z", updatedAt: "2026-10-07T17:02:00Z"}} />
|
||||
</div>
|
||||
<SpekoPhoneLineForm onRefresh={() => {}} onSave={() => {}} />
|
||||
<SpekoIncomingCallCard call={{id: "demo", state: "awaiting_approval", approvalCode: "123456", createdAt: "2026-10-07T17:00:00Z", expiresAt: "2026-10-07T17:02:00Z", sessionId: null}} onDecide={() => {}} />
|
||||
<SpekoProviderSetup agentName="Company Phone Agent" callbackUrl="https://paperclip.example/api/voice-webhooks/example/tools" credentials={{}} onChange={() => {}} onConnect={() => {}} />
|
||||
</Section>
|
||||
|
||||
<Section title="External agent invitation">
|
||||
<p className="text-sm text-muted-foreground">Match the harness picker with provider cards. Connection checks reflect confirmed server evidence. AnimatedDialogContent resizes to its content using motion tokens and respects reduced motion.</p>
|
||||
<ExternalAgentPresetPicker onSelect={() => {}} />
|
||||
|
||||
@@ -7598,6 +7598,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
|
||||
|
||||
<ExternallyConnectedTaskBanner
|
||||
key={issue.id}
|
||||
assigneeAgentId={issue.assigneeAgentId}
|
||||
attachments={attachments ?? []}
|
||||
companyId={issue.companyId}
|
||||
issueId={issue.id}
|
||||
|
||||
@@ -1062,20 +1062,24 @@ export function useInstallTeamCatalogEntry({
|
||||
};
|
||||
}
|
||||
|
||||
function TeamInstallerDialog({
|
||||
export function TeamInstallerDialog({
|
||||
team,
|
||||
companyId,
|
||||
agents,
|
||||
open,
|
||||
onClose,
|
||||
onInstalled,
|
||||
onReturnFocus,
|
||||
defaultCollisionStrategy = "rename",
|
||||
}: {
|
||||
team: CatalogTeam;
|
||||
companyId: string;
|
||||
agents: Agent[];
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onInstalled: () => void;
|
||||
onReturnFocus?: () => void;
|
||||
defaultCollisionStrategy?: CompanyPortabilityCollisionStrategy;
|
||||
onInstalled: (result: CatalogTeamInstallResult) => void;
|
||||
}) {
|
||||
const steps = useMemo(() => computeSteps(team), [team]);
|
||||
const [stepIndex, setStepIndex] = useState(0);
|
||||
@@ -1098,7 +1102,7 @@ function TeamInstallerDialog({
|
||||
const [allowLocalPathSources, setAllowLocalPathSources] = useState(false);
|
||||
|
||||
// Step 4 — preview controls
|
||||
const [collisionStrategy, setCollisionStrategy] = useState<CompanyPortabilityCollisionStrategy>("rename");
|
||||
const [collisionStrategy, setCollisionStrategy] = useState<CompanyPortabilityCollisionStrategy>(defaultCollisionStrategy);
|
||||
const [nameOverrides, setNameOverrides] = useState<Record<string, string>>({});
|
||||
// slug -> adapterType override (the install schema accepts adapterOverrides).
|
||||
const [adapterOverrides, setAdapterOverrides] = useState<Record<string, string>>({});
|
||||
@@ -1121,7 +1125,7 @@ function TeamInstallerDialog({
|
||||
setAllowExternalSources(false);
|
||||
setAllowUnpinnedOptionalSources(false);
|
||||
setAllowLocalPathSources(false);
|
||||
setCollisionStrategy("rename");
|
||||
setCollisionStrategy(defaultCollisionStrategy);
|
||||
setNameOverrides({});
|
||||
setAdapterOverrides({});
|
||||
setSecretValues({});
|
||||
@@ -1132,7 +1136,7 @@ function TeamInstallerDialog({
|
||||
setApplyError(null);
|
||||
setInstallResult(null);
|
||||
}
|
||||
}, [open]);
|
||||
}, [open, defaultCollisionStrategy]);
|
||||
|
||||
const currentStep = steps[stepIndex];
|
||||
|
||||
@@ -1208,7 +1212,7 @@ function TeamInstallerDialog({
|
||||
onSuccess: (result) => {
|
||||
setInstallResult(result);
|
||||
setPhase("done");
|
||||
onInstalled();
|
||||
onInstalled(result);
|
||||
},
|
||||
onError: (error) => {
|
||||
setPhase("error");
|
||||
@@ -1432,7 +1436,7 @@ function TeamInstallerDialog({
|
||||
if (isMobileSheet) {
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={(next) => { if (!next && dismissable) onClose(); }}>
|
||||
<SheetContent side="bottom" className="flex h-(--sz-100dvh) flex-col gap-0 p-0">
|
||||
<SheetContent onCloseAutoFocus={onReturnFocus ? (event) => { event.preventDefault(); onReturnFocus(); } : undefined} side="bottom" className="flex h-(--sz-100dvh) flex-col gap-0 p-0">
|
||||
<SheetHeader className="border-b border-border">
|
||||
<SheetTitle>{headerTitle}</SheetTitle>
|
||||
{headerDescription && <SheetDescription>{headerDescription}</SheetDescription>}
|
||||
@@ -1446,7 +1450,7 @@ function TeamInstallerDialog({
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => { if (!next && dismissable) onClose(); }}>
|
||||
<DialogContent className="max-w-3xl">
|
||||
<DialogContent onCloseAutoFocus={onReturnFocus ? (event) => { event.preventDefault(); onReturnFocus(); } : undefined} className="max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{headerTitle}</DialogTitle>
|
||||
{headerDescription && <DialogDescription>{headerDescription}</DialogDescription>}
|
||||
@@ -1492,7 +1496,7 @@ export function StepTargetManager({
|
||||
<li key={slug} className="flex items-center gap-2 border-b border-border/60 px-3 py-2 text-sm last:border-b-0">
|
||||
<Crown className="h-3.5 w-3.5 text-amber-500" />
|
||||
<span className="font-medium">{titleCase(slug)}</span>
|
||||
<Badge variant="ghost" className="ml-auto bg-amber-500/15 text-(length:--text-micro) text-amber-600 dark:text-amber-300">
|
||||
<Badge variant="ghost" className="ml-auto bg-accent text-(length:--text-micro) text-accent-foreground">
|
||||
→ ?
|
||||
</Badge>
|
||||
</li>
|
||||
@@ -1503,7 +1507,7 @@ export function StepTargetManager({
|
||||
{!fullCompany && (
|
||||
<div className="space-y-1.5" aria-describedby="target-manager-help">
|
||||
<SectionHeader>Target manager</SectionHeader>
|
||||
<Command className="rounded-md border border-border">
|
||||
{agents.length === 0 ? <p role="status" className="rounded-md border border-border p-3 text-sm text-muted-foreground">No agents are available to manage this team. Create an agent in your company, then try again.</p> : <Command className="rounded-md border border-border">
|
||||
<CommandInput placeholder="Search agents…" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No agents found.</CommandEmpty>
|
||||
@@ -1517,14 +1521,14 @@ export function StepTargetManager({
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Users2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="font-medium">{agent.name}</span>
|
||||
<span className="text-xs text-muted-foreground capitalize">{agent.role}</span>
|
||||
<span className="text-xs capitalize">{agent.role}</span>
|
||||
{targetManagerAgentId === agent.id && <Check className="ml-auto h-4 w-4 text-emerald-500" />}
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</Command>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1079,6 +1079,7 @@ describe("Connectors landing page", () => {
|
||||
"microsoft-teams",
|
||||
"notion",
|
||||
"slack",
|
||||
"speko",
|
||||
"telegram",
|
||||
"custom-mcp",
|
||||
]);
|
||||
|
||||
@@ -568,6 +568,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
|
||||
});
|
||||
}
|
||||
const nativeChatApps = [
|
||||
{ slug: "speko", name: "Speko", description: "Talk with an agent using experimental browser voice." },
|
||||
{ slug: "agentmail", name: "AgentMail", description: "Give agents email inboxes and handle each conversation as a task." },
|
||||
{ slug: "imessage-photon", name: "iMessage Photon", description: "Message agents and share photos from Apple Messages with a dedicated Photon number." },
|
||||
{
|
||||
@@ -704,6 +705,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
|
||||
);
|
||||
if (!target) {
|
||||
const names = {
|
||||
speko: "Speko",
|
||||
slack: "Slack",
|
||||
github: "GitHub",
|
||||
discord: "Discord",
|
||||
|
||||
@@ -107,7 +107,7 @@ describe("app connect policy", () => {
|
||||
it("retains GitHub tools but denies chat-only deep links while chat connectors are disabled", () => {
|
||||
expect(canEnterAppsConnect(new URLSearchParams("source=github"))).toBe(true);
|
||||
expect(canEnterAppsConnect(new URLSearchParams("source=agentmail"))).toBe(true);
|
||||
for (const source of ["discord", "telegram", "microsoft-teams"]) {
|
||||
for (const source of ["discord", "telegram", "microsoft-teams", "speko"]) {
|
||||
expect(canEnterAppsConnect(new URLSearchParams({ source })), source).toBe(false);
|
||||
expect(canEnterAppsConnect(new URLSearchParams({ source, reconnect: "connection-1" })), source).toBe(false);
|
||||
}
|
||||
|
||||
@@ -76,7 +76,8 @@ export function canEnterAppsConnect(
|
||||
const entry = getAppStoreDefinition(source);
|
||||
if (
|
||||
!chatConnectorsEnabled &&
|
||||
entry?.methods.some((method) => method.transport === "chat_sdk") &&
|
||||
source !== "agentmail" &&
|
||||
entry?.methods.some((method) => method.purpose === "channel") &&
|
||||
!entry.methods.some((method) => (method.purpose ?? "tool") !== "channel" && method.transport !== "chat_sdk")
|
||||
) return false;
|
||||
// A retained connection may belong to a provider hidden from fresh catalog
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import { SpekoPhoneLine } from "@/components/voice/SpekoPhoneLine";
|
||||
import { SpekoIncomingCalls } from "@/components/voice/SpekoIncomingCalls";
|
||||
import { SpekoCallActivityItem, SpekoUnapprovedCallActivityItem, useSpekoCallHistory } from "@/components/voice/SpekoCallHistory";
|
||||
import { SpekoPhoneCallback } from "@/components/voice/SpekoPhoneCallback";
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { Identity } from "@/components/Identity";
|
||||
import { SlackSetupAdvanced } from "./SlackAppDetails";
|
||||
@@ -67,6 +71,7 @@ const tabItems = tabs.map((value) => ({
|
||||
label: value[0].toUpperCase() + value.slice(1),
|
||||
}));
|
||||
const providerNames: Record<ChatProvider, string> = {
|
||||
speko: "Speko",
|
||||
agentmail: "AgentMail",
|
||||
slack: "Slack",
|
||||
github: "GitHub",
|
||||
@@ -80,6 +85,10 @@ const providerLifecycleGuidance: Record<
|
||||
ChatProvider,
|
||||
{ reconnect: string; remove: string }
|
||||
> = {
|
||||
speko: {
|
||||
reconnect: "Reverify this voice persona and update its signed session tools. Existing task assignments stay attached to their history.",
|
||||
remove: "Stop this connection from accepting voice requests. Accepted work and task history remain in Paperclip.",
|
||||
},
|
||||
agentmail: { reconnect: "Reconnect the same email inbox.", remove: "Disconnect email and retain task history." },
|
||||
slack: {
|
||||
reconnect:
|
||||
@@ -307,8 +316,9 @@ export function ChatEndpointDetail() {
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<AgentAvatar agent={agentQuery.data ?? { id: endpoint.assignedAgentId, name: endpoint.assignedAgentName }} size={48} />
|
||||
<div>
|
||||
<h1 className="text-xl font-bold">
|
||||
{endpoint.assignedAgentName}
|
||||
<h1 className={endpoint.provider === "speko" ? "flex items-center gap-3 text-xl font-bold" : "text-xl font-bold"}>
|
||||
{endpoint.provider === "speko" && <AppLogo name="Speko" brandKey="speko" size={36} />}
|
||||
{endpoint.assignedAgentName}{endpoint.provider === "speko" ? " in Speko" : ""}
|
||||
</h1>
|
||||
<p className="mt-1 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<AppLogo name={providerNames[endpoint.provider]} brandKey={endpoint.provider} size={16} compact />
|
||||
@@ -327,6 +337,7 @@ export function ChatEndpointDetail() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{endpoint.provider === "speko" && <a href="https://platform.speko.ai/agents" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-sm text-primary underline">Open Speko<ExternalLink className="size-3.5" aria-hidden="true" /></a>}
|
||||
{slackUrl && <Button asChild variant="outline"><a href={slackUrl} target="_blank" rel="noopener noreferrer">Open Slack <ExternalLink className="size-4" /></a></Button>}
|
||||
{setupIncomplete ? (
|
||||
<Button
|
||||
@@ -340,19 +351,27 @@ export function ChatEndpointDetail() {
|
||||
Continue setup
|
||||
</Button>
|
||||
) : null}
|
||||
{["paused", "attention", "revoked"].includes(endpoint.status) && <StatusBadge status={endpoint.status} />}
|
||||
{endpoint.status !== "active" && <StatusBadge status={endpoint.status} className={endpoint.provider === "speko" ? "text-foreground" : undefined} />}
|
||||
</div>
|
||||
</header>
|
||||
{activeTab === "settings" && endpoint.provider === "speko" && endpoint.status === "active" && <div className="space-y-6"><SpekoPhoneCallback companyId={endpoint.companyId} endpointId={endpoint.id} /><SpekoPhoneLine companyId={endpoint.companyId} endpointId={endpoint.id} /><SpekoIncomingCalls companyId={endpoint.companyId} endpointId={endpoint.id} agentId={endpoint.assignedAgentId} /></div>}
|
||||
{activeTab === "settings" && (
|
||||
<>
|
||||
{endpoint.provider === "github" && <GitHubBotManagement endpoint={endpoint} view="settings" />}
|
||||
{endpoint.provider !== "github" && <Settings endpointId={endpoint.id} endpoint={endpoint} />}
|
||||
</>
|
||||
)}
|
||||
{activeTab === "access" && endpoint.provider === "speko" && (
|
||||
<section className="max-w-3xl space-y-3">
|
||||
<h2 className="text-lg font-semibold">Private voice access</h2>
|
||||
<p className="text-sm text-muted-foreground">Browser calls use the signed-in Paperclip user’s current company access. Each call stays bound to its selected agent and task.</p>
|
||||
<p className="text-sm text-muted-foreground">Outgoing calls use your saved callback number and opt-in. For a private incoming call, enter the code spoken on the phone in signed-in Paperclip and select a task to approve that live call. Incoming calls can start a new conversation task without sign-in, under a task-scoped low-trust policy. Private mode is optional and requires approval before accessing existing tasks.</p>
|
||||
</section>
|
||||
)}
|
||||
{activeTab === "reviews" && endpoint.provider === "github" && <GitHubReviews endpointId={endpoint.id} />}
|
||||
{activeTab === "access" && endpoint.provider === "github" && <GitHubBotManagement endpoint={endpoint} view="access" />}
|
||||
{activeTab === "access" && endpoint.provider === "agentmail" && <EmailAccess endpoint={endpoint} />}
|
||||
{activeTab === "access" && endpoint.provider !== "github" && endpoint.provider !== "agentmail" && (
|
||||
{activeTab === "access" && endpoint.provider !== "speko" && endpoint.provider !== "github" && endpoint.provider !== "agentmail" && (
|
||||
<Access
|
||||
endpointId={endpoint.id}
|
||||
allowUnlinked={endpoint.allowUnlinkedPeople}
|
||||
@@ -414,6 +433,7 @@ function Settings({
|
||||
const resourcesQuery = useQuery({
|
||||
queryKey: queryKeys.chatEndpoints.resources(endpointId),
|
||||
queryFn: () => chatEndpointsApi.listResources(endpointId),
|
||||
enabled: endpoint.provider !== "speko",
|
||||
...(endpoint.provider === "slack" ? liveChatQueryOptions : {}),
|
||||
});
|
||||
const saveResources = useMutation({
|
||||
@@ -445,6 +465,7 @@ function Settings({
|
||||
tone: "error",
|
||||
}),
|
||||
});
|
||||
if (endpoint.provider === "speko") return null;
|
||||
const resources = resourcesQuery.data ?? [];
|
||||
const destinationResources = resources.filter((resource) =>
|
||||
isIndividuallyToggleableResource(endpoint.provider, resource.type),
|
||||
@@ -816,7 +837,7 @@ function Conversations({
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">
|
||||
{provider === "agentmail"
|
||||
{provider === "speko" ? "No conversations yet. Open an assigned task and choose Talk to agent." : provider === "agentmail"
|
||||
? "No email conversations yet. Send an email to this agent’s address to start one."
|
||||
: "No conversations yet. Message the agent to start one."}
|
||||
</p>
|
||||
@@ -865,6 +886,7 @@ function Activity({
|
||||
...liveChatQueryOptions,
|
||||
refetchInterval: cursor ? false : liveChatQueryOptions.refetchInterval,
|
||||
});
|
||||
const calls = useSpekoCallHistory(endpoint.companyId, endpointId, endpoint.provider === "speko" && !cursor);
|
||||
const replay = useMutation({
|
||||
mutationFn: (item: ChatActivityItem) =>
|
||||
item.kind === "publication"
|
||||
@@ -978,6 +1000,14 @@ function Activity({
|
||||
}),
|
||||
});
|
||||
const rows = query.data?.items ?? [];
|
||||
// Calls use their own caller-authorized API and appear once in recent activity.
|
||||
// Older connection-event pages retain the existing cursor contract.
|
||||
const activityEntries = [
|
||||
...(!query.isError ? rows.map(item => ({ kind: "connection" as const, id: `connection:${item.id}`, createdAt: item.createdAt, item })) : []),
|
||||
...(!cursor && !calls.error ? calls.entries.map(entry => ({ kind: "call" as const, id: `call:${entry.session.id}`, createdAt: entry.session.createdAt, entry })) : []),
|
||||
...(!cursor && !calls.error ? calls.unapprovedCalls.map(call => ({ kind: "unapproved_call" as const, id: `unapproved:${call.id}`, createdAt: call.createdAt, call })) : []),
|
||||
].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id));
|
||||
|
||||
const { status } = endpoint;
|
||||
const health = connectionHealthPresentation(endpoint);
|
||||
const lifecycleAction = lifecycle.variables;
|
||||
@@ -989,7 +1019,7 @@ function Activity({
|
||||
] as const)
|
||||
: [];
|
||||
return (
|
||||
<section className="space-y-5">
|
||||
<section className="space-y-5" aria-label="Connection activity">
|
||||
<h2 className="text-lg font-semibold">Connection activity</h2>
|
||||
{((status !== "active" && health.message) || health.error) && (
|
||||
<div
|
||||
@@ -1140,9 +1170,10 @@ function Activity({
|
||||
</div>
|
||||
</details>
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-semibold">
|
||||
Recent activity
|
||||
</h3>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h3 className="text-sm font-semibold">Recent activity</h3>
|
||||
{endpoint.provider === "speko" && !cursor && <Button size="sm" variant="ghost" onClick={() => { void query.refetch(); calls.onRetry(); }} disabled={query.isFetching || calls.loading}>Refresh</Button>}
|
||||
</div>
|
||||
{endpoint.provider === "agentmail" && rows.some((item) => item.kind === "publication" && item.status === "delivery_unknown") && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Review unconfirmed email delivery in the{" "}
|
||||
@@ -1150,7 +1181,7 @@ function Activity({
|
||||
</p>
|
||||
)}
|
||||
<div className="divide-y divide-border border-y border-border">
|
||||
{query.isLoading && (
|
||||
{(query.isLoading || calls.loading) && (
|
||||
<div className="flex items-center gap-2 py-5 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Loading activity…
|
||||
@@ -1170,11 +1201,15 @@ function Activity({
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{!query.isLoading &&
|
||||
!query.isError &&
|
||||
rows.map((item) => (
|
||||
{calls.error && endpoint.provider === "speko" && !cursor && <div className="flex flex-wrap items-center justify-between gap-3 py-4"><p role="alert" className="text-sm text-destructive">Call activity could not be loaded. {calls.error}</p><Button size="sm" variant="outline" onClick={calls.onRetry}>Retry calls</Button></div>}
|
||||
{activityEntries.map(entry => {
|
||||
if (entry.kind === "call") return <SpekoCallActivityItem key={entry.id} entry={entry.entry} presentation="activity" onEnd={calls.onEnd} ending={calls.endingSessionId === entry.entry.session.id} />;
|
||||
if (entry.kind === "unapproved_call") return <SpekoUnapprovedCallActivityItem key={entry.id} call={entry.call} presentation="activity" />;
|
||||
const item = entry.item;
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
key={entry.id}
|
||||
data-activity-kind="connection"
|
||||
className="flex items-start gap-3 px-2 py-3 transition-colors hover:bg-accent/50"
|
||||
>
|
||||
<span className="mt-0.5 text-muted-foreground" aria-hidden="true">
|
||||
@@ -1230,8 +1265,9 @@ function Activity({
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!query.isLoading && !query.isError && rows.length === 0 && (
|
||||
);
|
||||
})}
|
||||
{!query.isLoading && !query.isError && !calls.loading && !calls.error && activityEntries.length === 0 && (
|
||||
<p className="py-5 text-sm text-muted-foreground">
|
||||
No connection activity yet.
|
||||
</p>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { SpekoProviderSetup } from "@/components/voice/SpekoProviderSetup";
|
||||
import { NativeVoiceConversation } from "@/components/voice/NativeVoiceConversation";
|
||||
import { buildSlackAppManifest, defaultSlackAppConfiguration } from "@paperclipai/shared";
|
||||
import { SlackAppDetails, SlackSetupAdvanced } from "./SlackAppDetails";
|
||||
import { SlackAutomaticSetup } from "./SlackAutomaticSetup";
|
||||
@@ -51,6 +53,7 @@ import {
|
||||
} from "./github-private-key-file";
|
||||
|
||||
const providerNames: Record<ChatProvider, string> = {
|
||||
speko: "Speko",
|
||||
agentmail: "AgentMail",
|
||||
slack: "Slack",
|
||||
github: "GitHub",
|
||||
@@ -296,7 +299,7 @@ function ChatSdkEndpointSetup() {
|
||||
onSuccess: (next) => {
|
||||
setViewedStep(null);
|
||||
syncEndpointSnapshot(next);
|
||||
if (next.provider === "imessage-photon" || next.provider === "slack") {
|
||||
if (next.provider === "imessage-photon" || next.provider === "slack" || next.provider === "speko") {
|
||||
const resumed = new URLSearchParams(params);
|
||||
resumed.set("resume", next.id);
|
||||
setParams(resumed, { replace: true });
|
||||
@@ -505,7 +508,7 @@ function ChatSdkEndpointSetup() {
|
||||
</p>
|
||||
);
|
||||
|
||||
if (purpose === "choice") {
|
||||
if (purpose === "choice" && provider !== "speko") {
|
||||
return <ChatConnectionPurpose provider={provider} onChat={() => setPurpose("chat")} onTools={() => navigate(toolHref)} />;
|
||||
}
|
||||
|
||||
@@ -614,7 +617,15 @@ function ChatSdkEndpointSetup() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{endpoint && step === tryStep && (!automaticSlack || automaticSlackComplete) && (
|
||||
{endpoint && step === tryStep && provider === "speko" && (
|
||||
<div className="space-y-5">
|
||||
<h1 className="text-xl font-bold">Test your Speko voice connection</h1>
|
||||
<p className="text-sm text-muted-foreground">Ask the agent to do some work, add a spoken follow-up, and listen for its result. Accepted work stays in Paperclip when you end the call.</p>
|
||||
<NativeVoiceConversation companyId={endpoint.companyId} endpointId={endpoint.id} agentName={selectedAgent?.name ?? endpoint.assignedAgentName} />
|
||||
<SetupWizardFooter onSaveExit={() => navigate("/apps")}><Button disabled={testConnection.isPending} onClick={() => testConnection.mutate()}>Verify test conversation</Button></SetupWizardFooter>
|
||||
</div>
|
||||
)}
|
||||
{endpoint && step === tryStep && provider !== "speko" && (!automaticSlack || automaticSlackComplete) && (
|
||||
automaticSlack ? <div className="flex flex-col items-center gap-6 py-8 text-center">
|
||||
<AgentCharacter
|
||||
agent={selectedAgent ?? { id: endpoint.assignedAgentId, name: endpoint.assignedAgentName }}
|
||||
@@ -659,7 +670,7 @@ function ChatSdkEndpointSetup() {
|
||||
onSaveExit={() => navigate("/apps")}
|
||||
/>
|
||||
)}
|
||||
{step !== 0 && !isSlack && <div className="flex justify-start">
|
||||
{step !== 0 && !isSlack && !(provider === "speko" && step === tryStep) && <div className="flex justify-start">
|
||||
<Button className="text-muted-foreground" variant="ghost" onClick={() => navigate("/apps")}>
|
||||
Save & exit
|
||||
</Button>
|
||||
@@ -887,6 +898,7 @@ function ProviderConnectStep({
|
||||
null,
|
||||
2,
|
||||
);
|
||||
if (provider === "speko") return <SpekoProviderSetup agentName={agentName} credentials={credentials} onChange={setCredentials} onConnect={(values) => onAction(repairing ? "reconnect" : "configure", values)} callbackUrl={endpoint.setup?.webhookUrl} pending={pending} repairing={repairing} />;
|
||||
if (provider === "imessage-photon") return <PhotonConnectStep endpoint={endpoint} agentName={agentName} repairing={repairing} pending={pending} onAction={onAction} />;
|
||||
if (provider === "discord") {
|
||||
const applicationId = credentials.applicationId?.trim() ?? "";
|
||||
|
||||
@@ -9,6 +9,7 @@ import { queryKeys } from "@/lib/queryKeys";
|
||||
import { Navigate, useSearchParams } from "@/lib/router";
|
||||
|
||||
const providerNames: Record<ChatProvider, string> = {
|
||||
speko: "Speko",
|
||||
slack: "Slack",
|
||||
github: "GitHub",
|
||||
discord: "Discord",
|
||||
|
||||
@@ -122,7 +122,10 @@ describe("chat connector UI contract", () => {
|
||||
expect(detail).not.toContain("Change agent");
|
||||
for (const label of ["Pause", "Resume", "Reconnect", "Remove connection"]) {
|
||||
expect(activity).toContain(label);
|
||||
expect(settings).not.toContain(label);
|
||||
// Guidance may name an action that lives on Activity; only controls
|
||||
// must stay out of the Settings surface.
|
||||
const settingsButtons = settings.match(/<Button\b[\s\S]*?<\/Button>/g) ?? [];
|
||||
expect(settingsButtons.join("\n")).not.toContain(label);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { VoiceCallHistoryEntry } from "@paperclipai/shared";
|
||||
export const callHistoryFixture: VoiceCallHistoryEntry = {
|
||||
session: { id: "call-1", companyId: "company", endpointId: "endpoint", issueId: "task", assignedAgentId: "agent", state: "ended", mode: "outbound_phone", generation: 1, callerAuthority: "member", replyCursor: 1, createdAt: "2026-10-07T17:00:00Z", expiresAt: "2026-10-07T17:10:00Z", endedAt: "2026-10-07T17:02:00Z", errorCode: null },
|
||||
report: { status: "available", costMicroUsd: "152340", durationSeconds: 120, updatedAt: "2026-10-07T17:02:05Z", transcript: [
|
||||
{ id: "u1", index: 0, speaker: "caller", text: "Check the release checklist and tell me what still needs attention.", startedAt: "2026-10-07T17:00:01Z", endedAt: "2026-10-07T17:00:05Z", interrupted: false },
|
||||
{ id: "a1", index: 1, speaker: "agent", text: "The build passed. Two checks still need review.", startedAt: "2026-10-07T17:01:00Z", endedAt: "2026-10-07T17:01:06Z", interrupted: false },
|
||||
] },
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { ChatEndpoint } from "@/api/chatEndpoints";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { storybookAgents } from "./paperclipData";
|
||||
|
||||
export const spekoCompanyId = "company-storybook";
|
||||
export const spekoAgent = { ...storybookAgents[0]!, name: "Company Phone Agent" };
|
||||
export const spekoEndpoint: ChatEndpoint = {
|
||||
id: "voice-endpoint-fixture", companyId: spekoCompanyId, provider: "speko", status: "active",
|
||||
assignedAgentId: spekoAgent.id, assignedAgentName: spekoAgent.name,
|
||||
botLabel: "Company reception", providerAccountLabel: "Speko workspace", allowUnlinkedPeople: false,
|
||||
setup: { step: "complete", webhookUrl: "https://paperclip.example/api/voice-webhooks/fixture/tools" },
|
||||
conversations: [], activity: [], resources: [], identityLinks: [],
|
||||
};
|
||||
export function SpekoQueryFixture({ children, endpoints = [spekoEndpoint], enabled = true }: { children: ReactNode; endpoints?: ChatEndpoint[]; enabled?: boolean }) {
|
||||
const [client] = useState(() => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false, refetchOnMount: false, refetchOnWindowFocus: false } } });
|
||||
client.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: enabled });
|
||||
client.setQueryData(queryKeys.chatEndpoints.list(spekoCompanyId), endpoints);
|
||||
client.setQueryData(["task-voice-endpoints", spekoCompanyId], endpoints);
|
||||
for (const endpoint of endpoints) client.setQueryData(queryKeys.chatEndpoints.detail(endpoint.id), endpoint);
|
||||
return client;
|
||||
});
|
||||
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { addons } from "storybook/preview-api";
|
||||
|
||||
/** Allows the browser suite to await and inspect Storybook interaction results. */
|
||||
export const voiceStoryLifecycle = {
|
||||
beforeEach() {
|
||||
delete document.body.dataset.spekoStoryReady;
|
||||
delete document.body.dataset.spekoStoryError;
|
||||
const channel = addons.getChannel();
|
||||
const report = (error: unknown) => { document.body.dataset.spekoStoryError = JSON.stringify(error); };
|
||||
channel.on("playFunctionThrewException", report);
|
||||
channel.on("unhandledErrorsWhilePlaying", report);
|
||||
return () => {
|
||||
channel.off("playFunctionThrewException", report);
|
||||
channel.off("unhandledErrorsWhilePlaying", report);
|
||||
};
|
||||
},
|
||||
afterEach({ id }: { id: string }) { document.body.dataset.spekoStoryReady = id; },
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { DesignGuide } from "@/pages/DesignGuide";
|
||||
const meta = { title: "Design system/Design guide", component: DesignGuide, parameters: { layout: "fullscreen" } } satisfies Meta<typeof DesignGuide>;
|
||||
export default meta;
|
||||
export const Showcase: StoryObj<typeof meta> = {};
|
||||
@@ -0,0 +1,105 @@
|
||||
import { StrictMode, useMemo, useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
import type { VoiceSession } from "@paperclipai/shared";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { VoiceCallProvider } from "@/components/voice/VoiceCallProvider";
|
||||
import { NativeVoiceConversation } from "@/components/voice/NativeVoiceConversation";
|
||||
import type { voiceSessionsApi } from "@/api/voiceSessions";
|
||||
import type { connectSpekoVoiceMedia } from "@/lib/speko-voice-media";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
|
||||
function Fixture({ longConversation = false }: { longConversation?: boolean }) {
|
||||
const [companyId, setCompany] = useState("company-storybook");
|
||||
const [userId, setUser] = useState<string | null>("operator");
|
||||
const [page, setPage] = useState("agent");
|
||||
const [started, setStarted] = useState(0), [closed, setClosed] = useState(0);
|
||||
const [intent, setIntent] = useState("none");
|
||||
const fixture = useMemo(() => {
|
||||
const session: VoiceSession = { id: "fixture-call", companyId: "company-storybook", endpointId: "fixture-endpoint", issueId: "fixture-task", assignedAgentId: "agent-codex", state: "active", mode: "browser", generation: 1, callerAuthority: "member", replyCursor: 0, createdAt: "2026-10-07T12:00:00Z", expiresAt: "2026-10-07T12:10:00Z", endedAt: null, errorCode: null };
|
||||
const client: typeof voiceSessionsApi = {
|
||||
async start(_company, input) { setStarted(n => n + 1); setIntent(input.newConversation ? "new" : "continue"); return { session, media: { sessionId: session.id, generation: 1, transportToken: "fixture-only", transportUrl: "wss://fixture.invalid" } }; },
|
||||
async get() { return session; }, async end() { return { ...session, state: "ended" }; }, async notification() { return null; },
|
||||
};
|
||||
const connect: typeof connectSpekoVoiceMedia = async (_credentials, callbacks) => {
|
||||
callbacks.onModeChange("listening");
|
||||
if (longConversation) for (let i = 0; i < 30; i++) callbacks.onMessage({ source: i % 2 ? "agent" : "user", segmentId: `segment-${i}`, text: `Turn ${i + 1}. Please include the additional context for the project, and keep the same task open while we discuss the result.`, isFinal: true });
|
||||
return { async endSession() { setClosed(n => n + 1); }, async setMicMuted() {}, async startAudioPlayback() {}, async sendChatMessage() {} };
|
||||
};
|
||||
return { client, connect };
|
||||
}, [longConversation]);
|
||||
return <StrictMode><VoiceCallProvider companyId={companyId} userId={userId}>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap gap-2"><Button onClick={() => setPage(p => p === "agent" ? "tasks" : "agent")}>Navigate</Button><Button onClick={() => setCompany("another-company")}>Switch company</Button><Button onClick={() => setUser(null)}>Sign out</Button></div>
|
||||
<p data-testid="page">{page === "agent" ? "Agent page" : "Tasks page"}</p>
|
||||
<p data-testid="calls">Started: {started}; media closed: {closed}; intent: {intent}</p>
|
||||
{page === "agent" && <NativeVoiceConversation companyId={companyId} endpointId="fixture-endpoint" agentName="Company Phone Agent" {...fixture} />}
|
||||
</div>
|
||||
</VoiceCallProvider></StrictMode>;
|
||||
}
|
||||
const meta: Meta<typeof VoiceCallProvider> = { ...voiceStoryLifecycle, title: "Connections/Speko/Call provider", component: VoiceCallProvider, render: () => <Fixture />, parameters: { layout: "padded" } };
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
const start: NonNullable<Story["play"]> = async ({ canvasElement }) => {
|
||||
const c = within(canvasElement);
|
||||
await userEvent.click(c.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(c.getByRole("button", { name: "Mute" })).toBeEnabled());
|
||||
await expect(c.getByTestId("calls")).toHaveTextContent("Started: 1; media closed: 0");
|
||||
};
|
||||
export const Initial: Story = {};
|
||||
export const Active: Story = { play: start };
|
||||
export const Navigation: Story = { play: async context => {
|
||||
await start(context); const c = within(context.canvasElement);
|
||||
await userEvent.click(c.getByRole("button", { name: "Navigate" }));
|
||||
await expect(c.getByTestId("page")).toHaveTextContent("Tasks page");
|
||||
await expect(c.getByRole("button", { name: "Mute" })).toBeEnabled();
|
||||
await expect(c.getByTestId("calls")).toHaveTextContent("Started: 1; media closed: 0");
|
||||
} };
|
||||
export const NewConversation: Story = { play: async context => {
|
||||
const c = within(context.canvasElement);
|
||||
await userEvent.selectOptions(c.getByRole("combobox", { name: "Conversation" }), "new");
|
||||
await start(context); await expect(c.getByTestId("calls")).toHaveTextContent("intent: new");
|
||||
} };
|
||||
export const CompanyChange: Story = { play: async context => {
|
||||
await start(context); const c = within(context.canvasElement);
|
||||
await userEvent.click(c.getByRole("button", { name: "Switch company" }));
|
||||
await waitFor(() => expect(c.getByTestId("calls")).toHaveTextContent("media closed: 1"));
|
||||
await expect(c.queryByRole("complementary", { name: "Current voice call" })).not.toBeInTheDocument();
|
||||
} };
|
||||
export const SignOut: Story = { play: async context => {
|
||||
await start(context); const c = within(context.canvasElement);
|
||||
await userEvent.click(c.getByRole("button", { name: "Sign out" }));
|
||||
await waitFor(() => expect(c.getByTestId("calls")).toHaveTextContent("media closed: 1"));
|
||||
} };
|
||||
export const EndAndRestart: Story = { play: async context => {
|
||||
await start(context); const c = within(context.canvasElement);
|
||||
await userEvent.click(c.getByRole("button", { name: "End call" }));
|
||||
await waitFor(() => expect(c.getByTestId("calls")).toHaveTextContent("media closed: 1"));
|
||||
await expect(c.getByRole("button", { name: "Voice panel open" })).toBeDisabled();
|
||||
await userEvent.click(c.getByRole("button", { name: "Close voice panel" }));
|
||||
await waitFor(() => expect(c.getByRole("button", { name: "Start voice" })).toHaveFocus());
|
||||
await userEvent.keyboard("{Enter}");
|
||||
await waitFor(() => expect(c.getByTestId("calls")).toHaveTextContent("Started: 2; media closed: 1"));
|
||||
await expect(c.getByRole("button", { name: "Mute" })).toBeEnabled();
|
||||
} };
|
||||
|
||||
export const LongConversation: Story = { render: () => <Fixture longConversation />, play: async context => {
|
||||
await start(context); const c = within(context.canvasElement);
|
||||
const panel = c.getByRole("complementary", { name: "Current voice call" });
|
||||
const bounds = panel.getBoundingClientRect();
|
||||
await expect(bounds.top).toBeGreaterThanOrEqual(0);
|
||||
await expect(bounds.bottom).toBeLessThanOrEqual(window.innerHeight);
|
||||
const transcript = c.getByRole("region", { name: "Voice transcript history" });
|
||||
transcript.focus(); await expect(transcript).toHaveFocus();
|
||||
await expect(c.getByRole("button", { name: "End call" })).toBeVisible();
|
||||
} };
|
||||
|
||||
export const RestartInPanel: Story = { play: async context => {
|
||||
await start(context); const c = within(context.canvasElement);
|
||||
await userEvent.click(c.getByRole("button", { name: "End call" }));
|
||||
await waitFor(() => expect(c.getByRole("button", { name: "Close voice panel" })).toBeVisible());
|
||||
await userEvent.click(c.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(c.getByTestId("calls")).toHaveTextContent("Started: 2; media closed: 1"));
|
||||
await expect(c.getByRole("button", { name: "Mute" })).toBeEnabled();
|
||||
await expect(c.queryByRole("button", { name: "Close voice panel" })).not.toBeInTheDocument();
|
||||
} };
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { StatusBadge } from "@/components/StatusBadge";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
const meta: Meta<typeof StatusBadge> = { ...voiceStoryLifecycle, title: "Connections/Speko/Connection status", component: StatusBadge, args: { className: "text-foreground" }, parameters: { layout: "padded" } };
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Attention: Story = { args: { status: "attention" } };
|
||||
export const Revoked: Story = { args: { status: "revoked" } };
|
||||
export const Removed: Story = { args: { status: "archived" } };
|
||||
export const Paused: Story = { args: { status: "paused" } };
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
import type { VoiceSession } from "@paperclipai/shared";
|
||||
import { voiceCallJournal } from "@/lib/voice-call-attempt";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { NativeVoiceConversation } from "@/components/voice/NativeVoiceConversation";
|
||||
import type { voiceSessionsApi } from "@/api/voiceSessions";
|
||||
import type { connectSpekoVoiceMedia } from "@/lib/speko-voice-media";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
const session: VoiceSession = { id: "fixture-session", companyId: "company-storybook", endpointId: "fixture-endpoint", issueId: "fixture-task", assignedAgentId: "agent-codex", state: "active", mode: "browser", generation: 1, callerAuthority: "member", replyCursor: 0, createdAt: "2026-09-12T12:00:00Z", expiresAt: "2026-09-12T12:10:00Z", endedAt: null, errorCode: null };
|
||||
function Fixture({ creditsRequired = false, notificationsFail = false, accessRevoked = false, unknownCreation = false, cleanupPending = false, interruptedHint = false, agentEntry = false, recovered = false, partialReply = false }: { creditsRequired?: boolean; notificationsFail?: boolean; accessRevoked?: boolean; unknownCreation?: boolean; cleanupPending?: boolean; interruptedHint?: boolean; agentEntry?: boolean; recovered?: boolean; partialReply?: boolean }) {
|
||||
const [hintCount, setHintCount] = useState(0);
|
||||
const fixture = useMemo(() => {
|
||||
let endCount = 0, hints = 0, notifications = 0;
|
||||
const client: typeof voiceSessionsApi = {
|
||||
async start() { if (creditsRequired) throw new ApiError("Speko needs credits", 409, {details: {code: "voice_credits_required", sessionId: session.id}}); return { session, ...(unknownCreation ? {} : { media: { sessionId: session.id, generation: 1, transportToken: "fixture-only", transportUrl: "wss://fixture.invalid" } }) }; },
|
||||
async get() { return session; },
|
||||
async end() { return { ...session, state: cleanupPending && endCount++ === 0 ? "ending" : "ended" }; },
|
||||
async notification() { if (accessRevoked) throw new ApiError("Access revoked", 403, null); if (notificationsFail) throw new Error("Synthetic outage"); return { sessionId: session.id, generation: 1, publicationId: "fixture-result", attempt: interruptedHint ? notifications++ : 0 }; },
|
||||
};
|
||||
let finish = () => {};
|
||||
const connect: typeof connectSpekoVoiceMedia = async (_credentials, callbacks) => {
|
||||
callbacks.onMessage({ source: "agent", segmentId: "ack", text: "I’ll compare those options.", isFinal: !partialReply });
|
||||
finish = () => callbacks.onMessage({ source: "agent", segmentId: "ack", text: "I’ll compare those options.", isFinal: true });
|
||||
return { async endSession() {}, async setMicMuted() {}, async startAudioPlayback() {}, async sendChatMessage() { setHintCount(n => n + 1); if (interruptedHint && hints++ === 0) { callbacks.onModeChange("speaking"); callbacks.onModeChange("listening"); return; } callbacks.onMessage({ source: "agent", segmentId: "result", text: "The comparison is ready. The second option arrives on Friday.", isFinal: true }); } };
|
||||
};
|
||||
const values = new Map<string, string>();
|
||||
const journal = voiceCallJournal({ getItem: key => values.get(key) ?? null, setItem: (key, value) => { values.set(key, value); }, removeItem: key => { values.delete(key); } }, "company-storybook", "operator");
|
||||
if (recovered) journal.write({ request: { endpointId: "fixture-endpoint", idempotencyKey: "saved-attempt" }, sessionId: session.id });
|
||||
return { client, connect, finish: () => finish(), ...(recovered ? { journal } : {}) };
|
||||
}, [creditsRequired, notificationsFail, accessRevoked, unknownCreation, cleanupPending, interruptedHint, recovered, partialReply]);
|
||||
return <><NativeVoiceConversation companyId="company-storybook" endpointId="fixture-endpoint" issueId={agentEntry ? undefined : "fixture-task"} agentName="Company Phone Agent" {...fixture} />{partialReply && <><Button onClick={fixture.finish}>Finish spoken answer</Button><p data-testid="hint-count">Hints: {hintCount}</p></>}</>;
|
||||
}
|
||||
const meta: Meta<typeof NativeVoiceConversation> = { ...voiceStoryLifecycle, title: "Connections/Speko/Native conversation", component: NativeVoiceConversation, parameters: { layout: "padded" } };
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
const start: NonNullable<Story["play"]> = async ({ canvasElement }) => { const canvas = within(canvasElement); await userEvent.click(canvas.getByRole("button", { name: "Start voice" })); await waitFor(() => expect(canvas.getByRole("button", { name: "Mute" })).toBeEnabled()); };
|
||||
export const Idle: Story = { render: () => <Fixture /> };
|
||||
export const DelayedResult: Story = { render: () => <Fixture />, play: async (context) => { await start(context); await waitFor(() => expect(within(context.canvasElement).getByRole("list", { name: "Conversation transcript" })).toHaveTextContent("comparison is ready"), { timeout: 15_000 }); } };
|
||||
export const NotificationUnavailable: Story = { render: () => <Fixture notificationsFail />, play: async (context) => { await start(context); await waitFor(() => expect(within(context.canvasElement).getByRole("alert")).toHaveTextContent("Task updates are temporarily unavailable")); } };
|
||||
export const Muted: Story = { render: () => <Fixture />, play: async (context) => { await start(context); const canvas = within(context.canvasElement); await userEvent.click(canvas.getByRole("button", { name: "Mute" })); await waitFor(() => expect(canvas.getByRole("button", { name: "Unmute" })).toBeEnabled()); } };
|
||||
export const Ended: Story = { render: () => <Fixture />, play: async (context) => { await start(context); const canvas = within(context.canvasElement); await userEvent.click(canvas.getByRole("button", { name: "End call" })); await waitFor(() => expect(canvas.getByRole("status")).toHaveTextContent("Call ended")); } };
|
||||
export const CreationRecovery: Story = { render: () => <Fixture unknownCreation />, play: async ({ canvasElement }) => { const canvas = within(canvasElement); await userEvent.click(canvas.getByRole("button", { name: "Start voice" })); await waitFor(() => expect(canvas.getByRole("button", { name: "Try again" })).toBeEnabled()); } };
|
||||
export const PendingHangup: Story = { render: () => <Fixture cleanupPending />, play: async (context) => { await start(context); const canvas = within(context.canvasElement); await userEvent.click(canvas.getByRole("button", { name: "End call" })); await waitFor(() => expect(canvas.getByRole("button", { name: "Retry ending call" })).toBeEnabled()); } };
|
||||
|
||||
export const InterruptedHintRecovery: Story = { render: () => <Fixture interruptedHint />, play: DelayedResult.play };
|
||||
|
||||
export const ContinueConversation: Story = { render: () => <Fixture agentEntry />, play: async (context) => {
|
||||
const canvas = within(context.canvasElement);
|
||||
await expect(canvas.getByRole("combobox", { name: "Conversation" })).toHaveValue("continue");
|
||||
await start(context);
|
||||
await expect(canvas.getByRole("link", { name: "View conversation task" })).toHaveAttribute("href", "/issues/fixture-task");
|
||||
} };
|
||||
export const NewConversation: Story = { render: () => <Fixture agentEntry />, play: async (context) => {
|
||||
const canvas = within(context.canvasElement);
|
||||
await userEvent.selectOptions(canvas.getByRole("combobox", { name: "Conversation" }), "new");
|
||||
await start(context);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "End call" }));
|
||||
await waitFor(() => expect(canvas.getByRole("combobox", { name: "Conversation" })).toHaveValue("continue"));
|
||||
} };
|
||||
|
||||
export const AccessRevoked: Story = { render: () => <Fixture accessRevoked />, play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(canvas.getByRole("status")).toHaveTextContent("Call ended"));
|
||||
await expect(canvas.getByRole("alert")).toHaveTextContent("Access to this call is no longer available");
|
||||
} };
|
||||
|
||||
export const ReloadRecovery: Story = { render: () => <Fixture recovered />, play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(canvas.getByRole("alert")).toHaveTextContent("previous call was closed"));
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Try again" }));
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: "Mute" })).toBeEnabled());
|
||||
} };
|
||||
|
||||
export const PauseWithinSpokenAnswer: Story = { render: () => <Fixture partialReply />, play: async context => {
|
||||
await start(context); const canvas = within(context.canvasElement);
|
||||
await expect(canvas.getByTestId("hint-count")).toHaveTextContent("Hints: 0");
|
||||
await expect(canvas.getByRole("list", { name: "Conversation transcript" })).toHaveTextContent("Speaking");
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Finish spoken answer" }));
|
||||
await waitFor(() => expect(canvas.getByTestId("hint-count")).toHaveTextContent("Hints: 1"), { timeout: 15_000 });
|
||||
await expect(canvas.getByRole("list", { name: "Conversation transcript" })).toHaveTextContent("comparison is ready");
|
||||
} };
|
||||
|
||||
export const CreditsRequired: Story = { render: () => <Fixture creditsRequired />, play: async ({canvasElement}) => { const c=within(canvasElement); await userEvent.click(c.getByRole("button", {name: "Start voice"})); await waitFor(() => expect(c.getByRole("alert")).toHaveTextContent("Add credits in Speko")); await expect(c.queryByRole("button", {name: "Mute"})).not.toBeInTheDocument(); } };
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
import { Routes, Route, useNavigate, useLocation } from "react-router-dom";
|
||||
import { CONNECTABLE_APP_DEFINITIONS } from "@paperclipai/shared";
|
||||
import { Browse } from "@/pages/apps/Browse";
|
||||
import { ChatEndpointSetup } from "@/pages/apps/chat/ChatEndpointSetup";
|
||||
import { ChatEndpointDetail } from "@/pages/apps/chat/ChatEndpointDetail";
|
||||
import { ChatIdentityConfirm } from "@/pages/apps/chat/ChatIdentityConfirm";
|
||||
import type { ChatEndpoint } from "@/api/chatEndpoints";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { spekoAgent, spekoCompanyId, spekoEndpoint } from "../fixtures/spekoNative";
|
||||
import { callHistoryFixture } from "../fixtures/spekoCallHistory";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
|
||||
type State = { status?: ChatEndpoint["status"]; step?: "provider_setup" | "test" | "complete"; failure?: boolean; conversations?: boolean; incoming?: "awaiting_approval" | "guest_intake"; history?: boolean; activity?: boolean; historyFailure?: boolean; unapprovedHistory?: boolean; agentName?: string };
|
||||
const token = "storybook-identity-token-not-a-credential";
|
||||
function PageFixture({ path, agents = [spekoAgent] }: { path: string; agents?: (typeof spekoAgent)[] }) {
|
||||
const navigate = useNavigate(), location = useLocation();
|
||||
const [opened, setOpened] = useState(false);
|
||||
const [client] = useState(() => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false, refetchOnWindowFocus: false } } });
|
||||
client.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: true });
|
||||
client.setQueryData(["chat-endpoint-setup-agents", spekoCompanyId], agents);
|
||||
client.setQueryData(queryKeys.apps.gallery(spekoCompanyId), { apps: CONNECTABLE_APP_DEFINITIONS.filter((app) => app.slug === "speko") });
|
||||
client.setQueryData(queryKeys.tools.applications(spekoCompanyId), []);
|
||||
client.setQueryData(queryKeys.tools.connections(spekoCompanyId), []);
|
||||
return client;
|
||||
});
|
||||
useEffect(() => { navigate(path, { replace: true }); setOpened(true); }, [navigate, path]);
|
||||
if (!opened) return <p>Opening fixture…</p>;
|
||||
return <QueryClientProvider client={client}><div className="p-4" data-fixture-location={location.pathname + location.search}>
|
||||
<Routes>
|
||||
<Route path="/PAP/apps" element={<Browse />} />
|
||||
<Route path="/PAP/apps/chat/connect" element={<ChatEndpointSetup />} />
|
||||
<Route path="/PAP/apps/chat/:endpointId/:tab" element={<ChatEndpointDetail />} />
|
||||
<Route path="/identity" element={<ChatIdentityConfirm />} />
|
||||
</Routes>
|
||||
</div></QueryClientProvider>;
|
||||
}
|
||||
const meta: Meta = {
|
||||
...voiceStoryLifecycle, title: "Connections/Speko/Pages", parameters: { layout: "fullscreen" },
|
||||
beforeEach(context) {
|
||||
const cleanup = voiceStoryLifecycle.beforeEach(), original = window.fetch;
|
||||
const state = (context.parameters.speko ?? {}) as State;
|
||||
const endpoint = { ...spekoEndpoint, assignedAgentName: state.agentName ?? spekoEndpoint.assignedAgentName, status: state.status ?? "active", setup: { ...spekoEndpoint.setup, step: state.step ?? "complete" } };
|
||||
window.fetch = async (input, init) => {
|
||||
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin);
|
||||
if (url.pathname === "/api/health") return Response.json({ status: "ok", deploymentMode: "local_trusted", authReady: true, bootstrapStatus: "ready" });
|
||||
if (/\/voice-phone\/[^/]+\/incoming$/.test(url.pathname)) return Response.json(state.incoming ? [{id: "incoming-fixture", state: state.incoming, approvalCode: "482159", createdAt: "2026-10-07T17:00:00Z", expiresAt: "2026-10-07T17:10:00Z", sessionId: null, intakeIssueId: state.incoming === "guest_intake" ? "intake-fixture" : null}] : []);
|
||||
if (/\/voice-phone\/[^/]+\/history$/.test(url.pathname)) return Response.json(state.unapprovedHistory ? [{id: "missed-call", state: "denied", createdAt: "2026-10-07T17:04:00Z", updatedAt: "2026-10-07T17:04:01Z"}] : []);
|
||||
if (url.pathname.includes("/voice-phone/")) return Response.json({number: null, inventory: []});
|
||||
if (url.pathname.includes("/voice-history/")) return state.historyFailure ? Response.json({error: "Your access to this connection has changed."}, {status: 403}) : Response.json(state.history ? [callHistoryFixture] : []);
|
||||
if (url.pathname.endsWith("/issues")) return Response.json([]);
|
||||
if (url.pathname.includes("/voice-callbacks/")) return Response.json(null);
|
||||
if (url.pathname.startsWith("/api/voice-") || url.hostname.includes("speko.")) throw new Error("Stories must not start real calls");
|
||||
if (url.pathname.includes("/chat-endpoints")) {
|
||||
if (state.failure) return Response.json({ error: "Synthetic provider verification failed. Reconnect and try again." }, { status: 503 });
|
||||
if (url.pathname.endsWith("/conversations")) return Response.json(state.conversations ? [{ id: "conversation-fixture", externalLabel: "Browser voice", issueId: "task-fixture", issueIdentifier: "PAP-42", issueTitle: "Compare delivery options", state: "active", updatedAt: "2026-06-24T11:55:00Z", lastPublicationStatus: "published" }] : []);
|
||||
if (url.pathname.endsWith("/activity")) return Response.json({items: state.activity ? [
|
||||
{id: "newer-event", kind: "action", status: "completed", summary: "Speko connection verified", createdAt: "2026-10-07T17:03:00Z"},
|
||||
{id: "older-event", kind: "action", status: "completed", summary: "Speko credentials saved", createdAt: "2026-10-07T16:59:00Z"},
|
||||
] : [], nextCursor: null});
|
||||
if (/\/(resources|principals)$/.test(url.pathname)) return Response.json([]);
|
||||
if (url.pathname.endsWith("/chat-endpoints")) return Response.json(init?.method === "POST" ? endpoint : [endpoint]);
|
||||
return Response.json(endpoint);
|
||||
}
|
||||
if (url.pathname === "/api/chat-identity-links/preview") return Response.json({ companyId: spekoCompanyId, companyName: "Example company", companyPrefix: "PAP", endpointId: endpoint.id, provider: "speko", externalLabel: "Voice session identity", botLabel: endpoint.botLabel, expiresAt: "2026-09-12T13:00:00Z" });
|
||||
return original(input, init);
|
||||
};
|
||||
return () => { window.fetch = original; cleanup(); };
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj;
|
||||
function page(path: string, expected: string, state: State = {}): Story {
|
||||
return { parameters: { speko: state }, render: () => <PageFixture path={path} />, play: async ({ canvasElement }) => {
|
||||
await waitFor(() => expect(within(canvasElement).getAllByText(expected, { exact: false })[0]).toBeVisible());
|
||||
await Promise.all([...canvasElement.querySelectorAll("img")].map((image) => image.decode()));
|
||||
} };
|
||||
}
|
||||
const detail = (tab: string) => `/PAP/apps/chat/${spekoEndpoint.id}/${tab}`;
|
||||
export const Catalog = page("/PAP/apps", "Speko");
|
||||
export const ChooseAgent: Story = {
|
||||
...page("/PAP/apps/chat/connect?provider=speko&purpose=chat", "Which agent do you want to chat with?"),
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const picker = await canvas.findByRole("button", { name: "Choose an active agent" });
|
||||
await expect(canvas.queryByRole("button", { name: "Review recommended agent" })).not.toBeInTheDocument();
|
||||
await expect(canvas.getByRole("button", { name: "Continue" })).toBeDisabled();
|
||||
picker.focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
const agent = await within(document.body).findByRole("button", { name: `Select ${spekoAgent.name}` });
|
||||
agent.focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
await expect(canvas.getByRole("button", { name: "Continue" })).toBeEnabled();
|
||||
},
|
||||
};
|
||||
export const ChooseAgentLongName: Story = {
|
||||
...ChooseAgent,
|
||||
render: () => <PageFixture path="/PAP/apps/chat/connect?provider=speko&purpose=chat" agents={[{ ...spekoAgent, name: "Head of International Customer Support and Technical Escalations" }]} />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(await canvas.findByRole("button", { name: "Choose an active agent" }));
|
||||
await userEvent.click(await within(document.body).findByRole("button", { name: "Select Head of International Customer Support and Technical Escalations" }));
|
||||
await expect(canvas.getByRole("button", { name: "Continue" })).toBeEnabled();
|
||||
},
|
||||
};
|
||||
export const ChooseAgentEmpty: Story = {
|
||||
render: () => <PageFixture path="/PAP/apps/chat/connect?provider=speko&purpose=chat" agents={[]} />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(await canvas.findByRole("button", { name: "Choose an active agent" }));
|
||||
await expect(await within(document.body).findByText("No active agents are available.")).toBeVisible();
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await expect(canvas.getByRole("button", { name: "Choose an active agent" })).toHaveFocus();
|
||||
await expect(canvas.getByRole("button", { name: "Continue" })).toBeDisabled();
|
||||
},
|
||||
};
|
||||
export const ConfigureProvider = page(`/PAP/apps/chat/connect?provider=speko&resume=${spekoEndpoint.id}`, "Speko API key", { status: "draft", step: "provider_setup" });
|
||||
export const TestConversation = page(`/PAP/apps/chat/connect?provider=speko&resume=${spekoEndpoint.id}`, "Test your Speko voice connection", { status: "verifying", step: "test" });
|
||||
export const Active = page(detail("settings"), "Company Phone Agent in Speko");
|
||||
export const Paused = page(detail("settings"), "Company Phone Agent in Speko", { status: "paused" });
|
||||
export const Attention = page(detail("settings"), "Company Phone Agent in Speko", { status: "attention" });
|
||||
export const Revoked = page(detail("settings"), "Company Phone Agent in Speko", { status: "revoked" });
|
||||
export const Removed = page(detail("settings"), "Company Phone Agent in Speko", { status: "archived" });
|
||||
export const LoadingFailure = page(detail("settings"), "This chat connection could not be loaded", { failure: true });
|
||||
export const PrivateAccess = page(detail("access"), "Private voice access");
|
||||
export const Conversations = page(detail("conversations"), "Compare delivery options", { conversations: true });
|
||||
export const ConversationsEmpty = page(detail("conversations"), "No conversations yet");
|
||||
export const ActivityEmpty = page(detail("activity"), "Connection activity");
|
||||
export const IdentityProviderLabel = page(`/identity?token=${token}`, "Voice session identity");
|
||||
|
||||
export const SetupKeepsResumeLink: Story = {
|
||||
parameters: { speko: { status: "draft", step: "provider_setup" } },
|
||||
render: () => <PageFixture path={`/PAP/apps/chat/connect?provider=speko&purpose=chat&agentId=${spekoAgent.id}`} />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(await canvas.findByRole("button", { name: /^Continue$/ }));
|
||||
await waitFor(() => expect(canvasElement.querySelector("[data-fixture-location]")?.getAttribute("data-fixture-location")).toContain(`resume=${spekoEndpoint.id}`));
|
||||
await expect(await canvas.findByLabelText("Speko API key", { exact: true })).toHaveAttribute("type", "password");
|
||||
},
|
||||
};
|
||||
|
||||
export const PendingIncoming = page(detail("settings"), "Incoming call awaiting approval", {incoming: "awaiting_approval"});
|
||||
export const GuestIntake = page(detail("settings"), "Incoming conversation", {incoming: "guest_intake"});
|
||||
export const WithCallHistory = page(detail("activity"), "Outgoing call · Completed", {history: true});
|
||||
export const SettingsWithoutCallHistory: Story = {
|
||||
...page(detail("settings"), "Company Phone Agent in Speko", {history: true}),
|
||||
play: async ({canvasElement}) => {
|
||||
const c = within(canvasElement);
|
||||
await expect(await c.findByText("Company Phone Agent in Speko")).toBeVisible();
|
||||
await expect(c.queryByRole("heading", {name: "Your calls"})).not.toBeInTheDocument();
|
||||
await expect(c.queryByRole("button", {name: "Start voice"})).not.toBeInTheDocument();
|
||||
await expect(c.queryByRole("combobox", {name: "Conversation"})).not.toBeInTheDocument();
|
||||
await expect(c.queryByText(/Let this agent call your saved number/)).not.toBeInTheDocument();
|
||||
await expect(c.getByRole("link", {name: "Open Speko"})).toHaveAttribute("href", "https://platform.speko.ai/agents");
|
||||
await waitFor(() => expect(canvasElement.querySelector('header img[src="/brands/apps/speko.svg"]')).toBeInTheDocument());
|
||||
await expect(c.queryByText("Outgoing call · Completed", {exact: false})).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
export const ActivityWithMixedEntries: Story = {
|
||||
...page(detail("activity"), "Outgoing call · Completed", {history: true, activity: true}),
|
||||
play: async ({canvasElement}) => {
|
||||
const c = within(canvasElement);
|
||||
await expect(await c.findByText("Speko credentials saved")).toBeVisible();
|
||||
await waitFor(() => expect([...canvasElement.querySelectorAll("[data-activity-kind]")].map(row => row.getAttribute("data-activity-kind"))).toEqual(["connection", "call", "connection"]));
|
||||
await userEvent.click(await c.findByText("Outgoing call · Completed", {exact: false}));
|
||||
await expect(c.getByRole("list", {name: "Call transcript"})).toBeVisible();
|
||||
await expect(c.getByRole("link", {name: "Conversation task"})).toHaveAttribute("href", expect.stringContaining("/issues/task"));
|
||||
await expect(c.getByText("$0.152340 USD")).toBeVisible();
|
||||
},
|
||||
};
|
||||
export const ActivityUnapprovedCall = page(detail("activity"), "Call denied", {unapprovedHistory: true});
|
||||
export const ActivityCallHistoryFailure = page(detail("activity"), "Call activity could not be loaded", {historyFailure: true, activity: true});
|
||||
export const PausedCallHistory = page(detail("activity"), "Outgoing call · Completed", {history: true, status: "paused"});
|
||||
|
||||
export const LongAgentHeader = page(detail("settings"), "Head of International Customer Support and Technical Escalations", {agentName: "Head of International Customer Support and Technical Escalations"});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { SpekoPhoneCallbackForm } from "@/components/voice/SpekoPhoneCallback";
|
||||
import type { VoiceCallbackPreference } from "@paperclipai/shared";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
const meta = { ...voiceStoryLifecycle, title: "Connections/Speko/Phone callback", component: SpekoPhoneCallbackForm, args: { onSave: () => {} }, parameters: { layout: "padded" } } satisfies Meta<typeof SpekoPhoneCallbackForm>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Initial: Story = {};
|
||||
export const Loading: Story = { args: { loading: true } };
|
||||
export const Enabled: Story = { args: { preference: { phoneNumber: "+12015551234", enabled: true } } };
|
||||
export const Disabled: Story = { args: { preference: { phoneNumber: "+12015551234", enabled: false } } };
|
||||
export const Saving: Story = { args: { saving: true } };
|
||||
export const Saved: Story = { args: { saved: true } };
|
||||
export const ProviderFailure: Story = { args: { error: "Speko calling is unavailable. Check your phone configuration in Speko and try again." } };
|
||||
function Interactive() {
|
||||
const [preference, setPreference] = useState<VoiceCallbackPreference | null>(null);
|
||||
return <SpekoPhoneCallbackForm preference={preference} saved={Boolean(preference)} onSave={setPreference} />;
|
||||
}
|
||||
export const ValidationAndKeyboardSave: Story = { render: () => <Interactive />, play: async ({ canvasElement }) => {
|
||||
const c = within(canvasElement); const number = c.getByRole("textbox", { name: "Your callback number" });
|
||||
number.focus(); await userEvent.type(number, "555"); await userEvent.keyboard("{Enter}");
|
||||
await expect(c.getByRole("alert")).toHaveTextContent("international"); await expect(number).toHaveAttribute("aria-invalid", "true");
|
||||
await userEvent.clear(number); await userEvent.type(number, "+12015551234"); await userEvent.tab();
|
||||
await expect(c.getByRole("checkbox")).toHaveFocus(); await userEvent.keyboard(" "); await userEvent.tab();
|
||||
await expect(c.getByRole("button", { name: "Save phone setting" })).toHaveFocus(); await userEvent.keyboard("{Enter}");
|
||||
await expect(c.getByRole("status")).toHaveTextContent("Callback setting saved");
|
||||
await expect(c.getByRole("checkbox")).toBeChecked();
|
||||
} };
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { SpekoProviderSetup, type SpekoProviderSetupProps } from "@/components/voice/SpekoProviderSetup";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
function Fixture(props: Partial<SpekoProviderSetupProps>) {
|
||||
const [credentials, setCredentials] = useState(props.credentials ?? {});
|
||||
const [connected, setConnected] = useState(false);
|
||||
return connected ? <p role="status">Credentials saved. Continue to the test conversation.</p> : <SpekoProviderSetup agentName="Company Phone Agent" callbackUrl="https://paperclip.example/api/voice-webhooks/endpoint/tools" {...props} credentials={credentials} onChange={setCredentials} onConnect={(values) => { if (!props.repairing && !values.signingSecret?.startsWith("whsec_")) throw new Error("Missing signing secret"); setConnected(true); }} />;
|
||||
}
|
||||
const meta: Meta<typeof SpekoProviderSetup> = { ...voiceStoryLifecycle, title: "Connections/Speko/Provider setup", component: SpekoProviderSetup, parameters: { layout: "padded" } };
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Initial: Story = { render: () => <Fixture /> };
|
||||
export const CredentialsEntered: Story = { render: () => <Fixture credentials={{ apiKey: "synthetic-not-a-key", agentId: "agent_fixture" }} /> };
|
||||
export const MissingHttps: Story = { render: () => <Fixture callbackUrl="http://localhost:3100/callback" /> };
|
||||
export const VerificationLoading: Story = { render: () => <Fixture pending credentials={{ apiKey: "synthetic-not-a-key", agentId: "agent_fixture" }} /> };
|
||||
export const ResumableSetup: Story = { render: () => <Fixture repairing /> };
|
||||
export const LongAgentName: Story = { render: () => <Fixture agentName="Company Phone Agent for International Customer Support and Technical Escalations" /> };
|
||||
export const KeyboardValidationAndConnect: Story = {
|
||||
render: () => <Fixture />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole("button", { name: "Connect Speko" })).toBeDisabled();
|
||||
await userEvent.click(canvas.getByRole("textbox", { name: "Speko agent ID" }));
|
||||
await userEvent.type(canvas.getByRole("textbox", { name: "Speko agent ID" }), "agent_fixture");
|
||||
await userEvent.tab();
|
||||
const key = canvas.getByLabelText("Speko API key");
|
||||
await expect(key).toHaveFocus();
|
||||
await expect(key).toHaveAttribute("type", "password");
|
||||
await userEvent.type(key, "synthetic-not-a-key");
|
||||
await userEvent.tab();
|
||||
await expect(canvas.getByRole("button", { name: "Connect Speko" })).toHaveFocus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
await expect(canvas.getByRole("status")).toHaveTextContent("Credentials saved");
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
|
||||
import { AgentChannelsPanel } from "@/components/chat/AgentChannelsPanel";
|
||||
import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import { SpekoQueryFixture, spekoAgent, spekoCompanyId, spekoEndpoint } from "../fixtures/spekoNative";
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
const props = { companyId: spekoCompanyId, issueId: "task-fixture", agentId: spekoAgent.id };
|
||||
const meta: Meta<typeof TaskVoiceLauncher> = { ...voiceStoryLifecycle, title: "Connections/Speko/Task launcher", component: TaskVoiceLauncher, parameters: { layout: "padded" } };
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const ExistingAgent: Story = { render: () => <SpekoQueryFixture><TaskVoiceLauncher {...props} /></SpekoQueryFixture> };
|
||||
export const MultiplePersonas: Story = { render: () => <SpekoQueryFixture endpoints={[spekoEndpoint, { ...spekoEndpoint, id: "second", botLabel: "International customer reception and technical escalation" }]}><TaskVoiceLauncher {...props} /></SpekoQueryFixture> };
|
||||
export const UnavailableAgent: Story = { render: () => <SpekoQueryFixture endpoints={[]}><TaskVoiceLauncher {...props} boundEndpointId={spekoEndpoint.id} /></SpekoQueryFixture> };
|
||||
export const AgentChannels: Story = { render: () => <SpekoQueryFixture><AgentChannelsPanel companyId={spekoCompanyId} agentId={spekoAgent.id} /></SpekoQueryFixture> };
|
||||
export const ConnectionLifecycle: Story = { render: () => <SpekoQueryFixture endpoints={["active", "paused", "attention", "verifying", "revoked"].map((status) => ({ ...spekoEndpoint, id: status, status: status as typeof spekoEndpoint.status, botLabel: `Company reception · ${status}` }))}><AgentChannelsPanel companyId={spekoCompanyId} agentId={spekoAgent.id} /></SpekoQueryFixture> };
|
||||
function BoundTask() {
|
||||
const client = useQueryClient();
|
||||
useState(() => client.setQueryData(["issue-chat-binding", spekoCompanyId, props.issueId], { endpointId: spekoEndpoint.id, provider: "speko", externalLabel: "Voice conversation", conversationId: "conversation", assignedAgentLocked: true }));
|
||||
return <ExternallyConnectedTaskBanner companyId={spekoCompanyId} issueId={props.issueId} assigneeAgentId={spekoAgent.id} />;
|
||||
}
|
||||
export const BoundTaskBanner: Story = { render: () => <SpekoQueryFixture><BoundTask /></SpekoQueryFixture> };
|
||||
export const KeyboardOpen: Story = {
|
||||
...ExistingAgent,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
canvas.getByRole("button", { name: `Talk to ${spekoAgent.name}` }).focus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
await expect(canvas.getByRole("button", { name: "Start voice" })).toBeVisible();
|
||||
await expect(canvas.getByText("Ready to talk")).toBeVisible();
|
||||
// Opening controls must not acquire a microphone or create a session.
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within, fn } from "storybook/test";
|
||||
import { SpekoCallHistoryView, SpekoCallReport, SpekoCallActivityItem, SpekoUnapprovedCallActivityItem } from "@/components/voice/SpekoCallHistory";
|
||||
import { callHistoryFixture } from "../../fixtures/spekoCallHistory";
|
||||
import { voiceStoryLifecycle } from "../../fixtures/voiceStoryLifecycle";
|
||||
const entry = callHistoryFixture;
|
||||
const meta = { ...voiceStoryLifecycle, title: "Connections/Speko/Call history", component: SpekoCallHistoryView, args: { onRetry: fn() }, parameters: { layout: "padded" } } satisfies Meta<typeof SpekoCallHistoryView>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Empty: Story = {};
|
||||
export const Loading: Story = { args: { loading: true } };
|
||||
export const Failure: Story = { args: { error: "Call history could not be loaded. Check your connection and try again." }, play: async ({canvasElement, args}) => { await userEvent.click(within(canvasElement).getByRole("button", {name: "Try again"})); await expect(args.onRetry).toHaveBeenCalled(); } };
|
||||
export const Completed: Story = { args: { entries: [entry] } };
|
||||
export const Active: Story = { args: { entries: [{ ...entry, session: { ...entry.session, state: "active", mode: "browser", endedAt: null }, report: { ...entry.report, status: "pending", transcript: [], costMicroUsd: null } }] } };
|
||||
export const Failed: Story = { args: { entries: [{ ...entry, session: { ...entry.session, state: "failed", errorCode: "provider_unavailable" } }] } };
|
||||
export const Missed: Story = { args: { entries: [{ ...entry, session: { ...entry.session, mode: "inbound_phone" }, report: { ...entry.report, transcript: [], durationSeconds: 0 } }] } };
|
||||
export const TranscriptUnavailable: Story = { render: () => <SpekoCallReport report={{...entry.report, status: "unavailable", transcript: []}} /> };
|
||||
export const PartialCost: Story = { render: () => <SpekoCallReport report={{...entry.report, costMicroUsd: null, durationSeconds: null}} /> };
|
||||
export const InterruptedAnswer: Story = { render: () => <SpekoCallReport report={{...entry.report, transcript: entry.report.transcript.map(t => ({...t, interrupted: t.speaker === "agent"}))}} /> };
|
||||
export const LongConversation: Story = { render: () => <SpekoCallReport report={{...entry.report, transcript: Array.from({length: 30}, (_,index) => ({...entry.report.transcript[index % 2]!, id: `turn-${index}`, index, text: entry.report.transcript[index % 2]!.text.repeat(8)}))}} /> };
|
||||
export const KeyboardDisclosure: Story = { args: { entries: [entry] }, play: async ({canvasElement}) => { const c=within(canvasElement); const summary=canvasElement.querySelector("summary")!; (summary as HTMLElement).focus(); await userEvent.click(summary); await expect(c.getByRole("link", {name: "Conversation task"})).toBeVisible(); await expect(c.getByRole("list", {name: "Call transcript"})).toBeVisible(); await userEvent.click(summary); await expect(c.getByRole("link", {name: "Conversation task", hidden: true})).not.toBeVisible(); } };
|
||||
|
||||
export const EndCallFocus: Story = { render: function FocusFixture() {
|
||||
const [ended, setEnded] = useState(false);
|
||||
return <SpekoCallHistoryView onRetry={fn()} onEnd={() => setEnded(true)} entries={[{...entry, session: {...entry.session, state: ended ? "ended" : "active", endedAt: ended ? entry.session.endedAt : null}}]} />;
|
||||
}, play: async ({canvasElement}) => { const c = within(canvasElement); const summary = canvasElement.querySelector("summary")!; await userEvent.click(summary); await userEvent.click(c.getByRole("button", {name: "End call"})); await expect(summary).toHaveFocus(); await expect(summary).toHaveTextContent("Completed"); } };
|
||||
|
||||
export const UnapprovedIncoming: Story = {args: {unapprovedCalls: ["ended", "denied", "expired"].map((state, index) => ({id: `missed-${index}`, state: state as "ended" | "denied" | "expired", createdAt: "2026-10-07T17:00:00Z", updatedAt: "2026-10-07T17:02:00Z"}))}};
|
||||
export const RevokedHistory: Story = {args: {entries: [entry], error: "Your access to this connection has changed."}, play: async ({canvasElement}) => { await expect(within(canvasElement).queryByText("Outgoing call · Completed", {exact: false})).toBeNull(); }};
|
||||
|
||||
export const ActivityEntry: Story = { render: () => <SpekoCallActivityItem entry={entry} presentation="activity" /> };
|
||||
export const ActivityUnapprovedEntry: Story = { render: () => <SpekoUnapprovedCallActivityItem presentation="activity" call={{id: "missed-call", state: "expired", createdAt: "2026-10-07T17:00:00Z", updatedAt: "2026-10-07T17:02:00Z"}} /> };
|
||||
export const ActivityEndCallFocus: Story = { render: function ActivityFocusFixture() {
|
||||
const [ended, setEnded] = useState(false);
|
||||
return <SpekoCallActivityItem presentation="activity" onEnd={() => setEnded(true)} entry={{...entry, session: {...entry.session, state: ended ? "ended" : "active", endedAt: ended ? entry.session.endedAt : null}}} />;
|
||||
}, play: EndCallFocus.play };
|
||||
@@ -0,0 +1,25 @@
|
||||
import type {Meta, StoryObj} from "@storybook/react-vite";
|
||||
import {useState} from "react";
|
||||
import {expect, userEvent, within} from "storybook/test";
|
||||
import {SpekoIncomingCallCard} from "@/components/voice/SpekoIncomingCalls";
|
||||
import type {VoiceInboundCall} from "@paperclipai/shared";
|
||||
import {voiceStoryLifecycle} from "../../fixtures/voiceStoryLifecycle";
|
||||
const call: VoiceInboundCall = {id: "incoming", state: "awaiting_approval", approvalCode: "123456", createdAt: "2026-10-07T17:00:00Z", expiresAt: "2026-10-07T17:02:00Z", sessionId: null};
|
||||
const meta = {...voiceStoryLifecycle, title: "Connections/Speko/Live phone approval", component: SpekoIncomingCallCard, args: {call, onDecide: () => {}}, parameters: {layout: "padded"}} satisfies Meta<typeof SpekoIncomingCallCard>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const AwaitingApproval: Story = {};
|
||||
export const ExistingTask: Story = {args: {tasks: [{id: "task", label: "PAP-42 · Review the upcoming release and summarize the remaining verification work"}]}};
|
||||
export const Confirming: Story = {args: {busy: true}};
|
||||
export const Approved: Story = {args: {call: {...call, state: "approved"}}};
|
||||
export const Denied: Story = {args: {call: {...call, state: "denied"}}};
|
||||
export const Expired: Story = {args: {call: {...call, state: "expired"}}};
|
||||
export const HungUp: Story = {args: {call: {...call, state: "ended"}}};
|
||||
export const Failure: Story = {args: {error: "The call ended before approval. Start a new call."}};
|
||||
function Interactive() {const [value,setValue] = useState(call); return <SpekoIncomingCallCard call={value} onDecide={input => setValue({...value,state: input.approve ? "approved" : "denied"})} />;}
|
||||
export const KeyboardApprovalAndFocus: Story = {render: () => <Interactive />, play: async ({canvasElement}) => {const c=within(canvasElement), code=c.getByRole("textbox", {name: "Code spoken on your call"}); code.focus(); await userEvent.type(code, "000000"); await userEvent.keyboard("{Enter}"); await expect(c.getByRole("alert")).toHaveTextContent("does not match"); await userEvent.clear(code); await userEvent.type(code, "123456"); await userEvent.keyboard("{Enter}"); await expect(c.getByRole("heading", {name: "Call approved"})).toHaveFocus();}};
|
||||
|
||||
export const GuestIntake: Story = {args: {call: {...call, state: "guest_intake", intakeIssueId: "intake-task"}}, play: async ({canvasElement}) => {const c=within(canvasElement); await expect(c.getByRole("heading", {name: "Incoming conversation"})).toBeVisible(); await expect(c.queryByRole("textbox", {name: "Code spoken on your call"})).not.toBeInTheDocument(); await expect(c.getByRole("link", {name: "Open conversation task"})).toHaveAttribute("href", "/issues/intake-task"); await expect(c.getByRole("button", {name: "End call"})).toBeEnabled();}};
|
||||
|
||||
function PublicInteractive() {const [value,setValue] = useState<VoiceInboundCall>({...call, state: "guest_intake", intakeIssueId: "intake-task"}); return <SpekoIncomingCallCard call={value} onDecide={() => setValue({...value,state: "ended"})} />;}
|
||||
export const PublicKeyboardEnd: Story = {render: () => <PublicInteractive />, play: async ({canvasElement}) => {const c=within(canvasElement); c.getByRole("button", {name: "End call"}).focus(); await userEvent.keyboard("{Enter}"); await expect(c.getByRole("heading", {name: "Caller hung up"})).toHaveFocus();}};
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { useState } from "react";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { SpekoPhoneLineForm } from "@/components/voice/SpekoPhoneLine";
|
||||
import type { VoicePhoneConfiguration } from "@paperclipai/shared";
|
||||
import { voiceStoryLifecycle } from "../../fixtures/voiceStoryLifecycle";
|
||||
const configuration: VoicePhoneConfiguration = { number: null, inventory: [{id: "number", phoneNumber: "+12015550123", label: "Company front desk", available: true, inboundReady: true, outboundReady: true, issues: []}] };
|
||||
const meta = {...voiceStoryLifecycle, title: "Connections/Speko/Incoming phone line", component: SpekoPhoneLineForm, args: {onRefresh: () => {}, onSave: () => {}}, parameters: {layout: "padded"}} satisfies Meta<typeof SpekoPhoneLineForm>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Initial: Story = {args: {configuration}};
|
||||
export const Loading: Story = {args: {loading: true}};
|
||||
export const EmptyInventory: Story = {args: {configuration: {number: null, inventory: []}}};
|
||||
export const Selected: Story = {args: {configuration: {...configuration, number: {id: "number", phoneNumber: "+12015550123", enabled: true}}}};
|
||||
export const VerificationRequired: Story = {args: {configuration: {...configuration, number: {id: "number", phoneNumber: "+12015550123", enabled: false}, inventory: configuration.inventory.map(n => ({...n, inboundReady: false, issues: ["Business verification required"]}))}}};
|
||||
export const InsufficientCredits: Story = {args: {configuration: {...configuration, inventory: configuration.inventory.map(n => ({...n, available: false, inboundReady: false, issues: ["Insufficient credits"]}))}, error: "Add credits to your Speko workspace before enabling this number."}};
|
||||
export const ProviderFailure: Story = {args: {error: "Speko is unavailable. Refresh numbers after the connection recovers."}};
|
||||
export const LongLabels: Story = {args: {configuration: {...configuration, inventory: configuration.inventory.map(n => ({...n, label: "Customer support, sales and operations company phone line with an unusually long descriptive name"}))}}};
|
||||
function Interactive() { const [value, setValue] = useState(configuration), [saved, setSaved] = useState(false); return <SpekoPhoneLineForm configuration={value} saved={saved} onRefresh={() => {}} onSave={input => {setValue({...value, number: {id: input.numberId, phoneNumber: "+12015550123", enabled: input.enabled, guestIntake: input.guestIntake}}); setSaved(true);}} />; }
|
||||
export const KeyboardSave: Story = {render: () => <Interactive />, play: async ({canvasElement}) => {const c = within(canvasElement); await userEvent.click(c.getByRole("button", {name: "Save incoming call setting"})); await expect(c.getByRole("alert")).toHaveTextContent("Choose an available"); const select = c.getByRole("combobox", {name: "Company phone number"}); await userEvent.selectOptions(select, "number"); select.focus(); await userEvent.tab(); await expect(c.getByRole("checkbox", {name: "Enable incoming calls on this number"})).toHaveFocus(); await userEvent.keyboard(" "); await userEvent.tab(); await userEvent.tab(); await userEvent.keyboard("{Enter}"); await expect(c.getAllByRole("status").at(-1)!).toHaveTextContent("Incoming call setting saved");}};
|
||||
|
||||
export const GuestIntake: Story = {args: {configuration: {...configuration, number: {id: "number", phoneNumber: "+12015550123", enabled: true, guestIntake: true}}}};
|
||||
|
||||
export const PrivateTaskApproval: Story = {args: {configuration: {...configuration, number: {id: "number", phoneNumber: "+12015550123", enabled: true, guestIntake: false}}}};
|
||||
|
||||
export const SelectedSandbox: Story = {args: {configuration: {...configuration, number: {id: "number", phoneNumber: "+12015550123", enabled: true, guestIntake: true, lowTrustEnvironmentId: "sandbox"}, sandboxEnvironments: [{id: "sandbox", name: "Company phone Daytona sandbox"}]}}, play: async ({canvasElement}) => {await expect(within(canvasElement).getByRole("combobox", {name: "Execution sandbox"})).toHaveValue("sandbox");}};
|
||||
@@ -66,7 +66,7 @@ function makeAgent(id: string, name: string, role: string): Agent {
|
||||
};
|
||||
}
|
||||
|
||||
function makePreview(errors: string[] = []): CatalogTeamImportPreviewResult {
|
||||
export function makePreview(errors: string[] = []): CatalogTeamImportPreviewResult {
|
||||
return {
|
||||
team: baseTeam,
|
||||
portabilityPreview: {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
import { useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, within } from "storybook/test";
|
||||
import { VoiceControls, VOICE_CONTROL_STATES, type VoiceControlState } from "@/components/voice/VoiceControls";
|
||||
|
||||
const noop = () => {};
|
||||
const meta = { ...voiceStoryLifecycle,
|
||||
title: "Connections/Speko/Voice controls",
|
||||
component: VoiceControls,
|
||||
args: { state: "idle", agentName: "Speko Company Phone Agent", onStart: noop, onMute: noop, onEnd: noop, onResumeAudio: noop },
|
||||
parameters: { layout: "padded" },
|
||||
} satisfies Meta<typeof VoiceControls>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Idle: Story = {};
|
||||
export const Connecting: Story = { args: { state: "connecting" } };
|
||||
export const Listening: Story = { args: { state: "listening" } };
|
||||
export const Speaking: Story = { args: { state: "speaking" } };
|
||||
export const Muted: Story = { args: { state: "listening", muted: true } };
|
||||
export const Working: Story = { args: { state: "working" } };
|
||||
export const Interrupted: Story = { args: { state: "interrupted" } };
|
||||
export const Reconnecting: Story = { args: { state: "reconnecting" } };
|
||||
export const Ending: Story = { args: { state: "ending" } };
|
||||
export const CleanupFailed: Story = { args: { state: "cleanup_failed", error: "The call could not be fully closed. Retry ending it before starting another call." } };
|
||||
export const Ended: Story = { args: { state: "ended" } };
|
||||
export const Failed: Story = { args: { state: "failed", error: "Speko could not connect. Check your connection and try again." } };
|
||||
export const MicrophoneDenied: Story = { args: { state: "failed", error: "Microphone access was denied. Allow microphone access in your browser, then try again." } };
|
||||
export const PlaybackBlocked: Story = { args: { state: "listening", playbackBlocked: true } };
|
||||
export const LongName: Story = { args: { state: "working", agentName: "Company phone agent for international customer support and implementation scheduling" } };
|
||||
export const StateMatrix: Story = { render: (args) => <div className="flex flex-col gap-8">{VOICE_CONTROL_STATES.map((state) => <VoiceControls key={state} {...args} state={state} />)}</div> };
|
||||
function Interactive() {
|
||||
const [state, setState] = useState<VoiceControlState>("idle");
|
||||
const [muted, setMuted] = useState(false);
|
||||
return <VoiceControls state={state} muted={muted} agentName="Company Phone Agent" onStart={() => setState("listening")} onMute={() => setMuted((value) => !value)} onEnd={() => setState("ended")} onResumeAudio={noop} />;
|
||||
}
|
||||
export const KeyboardMuteAndEnd: Story = {
|
||||
render: () => <Interactive />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const start = canvas.getByRole("button", { name: "Start voice" });
|
||||
start.focus(); await userEvent.keyboard("{Enter}");
|
||||
const mute = canvas.getByRole("button", { name: "Mute" });
|
||||
mute.focus(); await userEvent.keyboard(" ");
|
||||
await expect(canvas.getByRole("button", { name: "Unmute" })).toHaveAttribute("aria-pressed", "true");
|
||||
await userEvent.tab();
|
||||
await expect(canvas.getByRole("button", { name: "End call" })).toHaveFocus();
|
||||
await userEvent.keyboard("{Enter}");
|
||||
await expect(canvas.getByRole("status")).toHaveTextContent("Call ended");
|
||||
await expect(canvas.getByRole("button", { name: "Start voice" })).toHaveFocus();
|
||||
},
|
||||
};
|
||||
|
||||
function RepeatFixture() {
|
||||
const [announcement, setAnnouncement] = useState("");
|
||||
return <VoiceControls state="speaking" agentName="Company Phone Agent" canRepeat announcement={announcement}
|
||||
onStart={noop} onMute={noop} onEnd={noop} onResumeAudio={noop} onRepeat={() => setAnnouncement("Repeat requested")} />;
|
||||
}
|
||||
export const RepeatAnswer: Story = { render: () => <RepeatFixture />, play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement); canvas.getByRole("button", { name: "Repeat answer" }).focus();
|
||||
await userEvent.keyboard("{Enter}"); await expect(canvas.getByText("Repeat requested")).toBeInTheDocument();
|
||||
} };
|
||||
export const RepeatUnavailableWhileEnding: Story = { args: { state: "ending", canRepeat: true, onRepeat: noop } };
|
||||
@@ -0,0 +1,59 @@
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
import { useMemo } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { expect, userEvent, waitFor, within } from "storybook/test";
|
||||
import { VoiceConversationPanel } from "@/components/voice/VoiceConversationPanel";
|
||||
import type { VoiceSessionDependencies } from "@/lib/voice-session-controller";
|
||||
|
||||
function Fixture({ failConnection = false, failCleanup = false }: { failConnection?: boolean; failCleanup?: boolean }) {
|
||||
const dependencies = useMemo<VoiceSessionDependencies>(() => {
|
||||
let attempts = 0, endings = 0;
|
||||
return {
|
||||
async mint() { if (failConnection && attempts++ === 0) throw new Error("Synthetic connection failure"); return { sessionId: "storybook-session", generation: 1, transportToken: "fixture-only", transportUrl: "wss://example.invalid" }; },
|
||||
async end() { if (failCleanup && endings++ === 0) throw new Error("Synthetic hangup failure"); },
|
||||
async connect(_credentials, callbacks) {
|
||||
callbacks.onMessage({ source: "agent", segmentId: "ack", text: "I’ll work on that.", isFinal: true });
|
||||
return { async endSession() {}, async setMicMuted() {}, async startAudioPlayback() {}, async sendChatMessage() {} };
|
||||
},
|
||||
};
|
||||
}, [failConnection, failCleanup]);
|
||||
return <VoiceConversationPanel agentName="Company Phone Agent" dependencies={dependencies} />;
|
||||
}
|
||||
const meta: Meta<typeof VoiceConversationPanel> = { ...voiceStoryLifecycle, title: "Connections/Speko/Conversation", component: VoiceConversationPanel, parameters: { layout: "padded" } };
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Idle: Story = { render: () => <Fixture /> };
|
||||
export const Connected: Story = {
|
||||
render: () => <Fixture />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: "Mute" })).toBeEnabled());
|
||||
await expect(canvas.getByRole("list", { name: "Conversation transcript" })).toHaveTextContent("I’ll work on that.");
|
||||
},
|
||||
};
|
||||
export const ConnectionRecovery: Story = {
|
||||
render: () => <Fixture failConnection />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(canvas.getByRole("alert")).toHaveTextContent("Voice could not connect"));
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Try again" }));
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: "Mute" })).toBeEnabled());
|
||||
await expect(canvas.queryByRole("alert")).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
export const CleanupRecovery: Story = {
|
||||
render: () => <Fixture failCleanup />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Start voice" }));
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: "Mute" })).toBeEnabled());
|
||||
await userEvent.click(canvas.getByRole("button", { name: "End call" }));
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: "Retry ending call" })).toBeEnabled());
|
||||
await expect(canvas.queryByRole("button", { name: "Start voice" })).not.toBeInTheDocument();
|
||||
await userEvent.click(canvas.getByRole("button", { name: "Retry ending call" }));
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: "Start voice" })).toHaveFocus());
|
||||
await expect(canvas.getByRole("status")).toHaveTextContent("Call ended");
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { VoiceTranscript } from "@/components/voice/VoiceTranscript";
|
||||
|
||||
const meta = { ...voiceStoryLifecycle,
|
||||
title: "Connections/Speko/Transcript", component: VoiceTranscript,
|
||||
args: { agentName: "Company Phone Agent", entries: [] }, parameters: { layout: "padded" },
|
||||
} satisfies Meta<typeof VoiceTranscript>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
export const Empty: Story = {};
|
||||
export const Unavailable: Story = { args: { unavailable: true } };
|
||||
export const PartialSpeech: Story = { args: { entries: [{ id: "a", source: "user", text: "Could you check the next", final: false }] } };
|
||||
export const FinalSpeech: Story = { args: { entries: [{ id: "a", source: "user", text: "Could you check the next delivery date?", final: true }] } };
|
||||
export const OverlappingUpdates: Story = { args: { entries: [
|
||||
{ id: "a", source: "agent", text: "The order is scheduled for", final: false, interrupted: true },
|
||||
{ id: "b", source: "user", text: "Please check the revised address too.", final: true },
|
||||
] } };
|
||||
export const DelayedResult: Story = { args: { entries: [
|
||||
{ id: "a", source: "agent", text: "I’m checking that now.", final: true },
|
||||
{ id: "notification", source: "application", text: "A task update is available.", final: true },
|
||||
{ id: "b", source: "agent", text: "The next delivery date is September 18.", final: true },
|
||||
] } };
|
||||
export const TaskReference: Story = { args: { entries: [{ id: "a", source: "agent", text: "The changes are recorded in task PAP-42. Open the task to review and approve them.", final: true }] } };
|
||||
export const LongConversation: Story = { args: { agentName: "Company agent for customer support across international regions", entries: Array.from({ length: 30 }, (_, index) => ({ id: String(index), source: index % 2 ? "agent" as const : "user" as const, text: index % 2 ? "The task is still running. I have added your clarification to the same task and will share its approved answer here." : "Please include the details we discussed earlier and preserve the existing task context.", final: true })) } };
|
||||
Reference in new issue
Block a user