-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathApp.tsx
More file actions
5210 lines (5032 loc) · 183 KB
/
Copy pathApp.tsx
File metadata and controls
5210 lines (5032 loc) · 183 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type WheelEvent,
} from "react";
import {
ArrowLeft,
Check,
Copy,
CornerDownRight,
Loader2,
} from "lucide-react";
import { motion } from "motion/react";
import {
addSessionCapability,
clearMessageFeedbackCache,
createSession,
DEFAULT_STUDIO_ACCESS,
DEFAULT_SITE_BRANDING,
deleteRuntime,
deleteMedia,
deleteSessionMedia,
deleteSession,
downloadArtifact,
previewArtifact,
getAgentInfo,
getAutomaticEvaluationStatuses,
getSessionTrace,
getSessionCapabilities,
getSession,
getStudioAccess,
getRuntimes,
listApps,
listSessionBuiltinTools,
listSessions,
removeSessionCapability,
runSSE,
refreshAgentFeedbackCases,
submitIssueFeedback,
submitMessageFeedback,
upsertCachedAgentFeedbackCase,
uploadMedia,
getUiConfig,
type AdkEvent,
type AgentInfo,
type AgentNode,
type AgentTarget,
type AgentFeedbackCase,
type AdkSession,
type AddSessionCapability,
type Attachment,
type FrontendInvocation,
type CloudRuntime,
type MessageFeedbackRating,
type SiteBranding,
type SessionCapabilities,
type StudioAccess,
type UiFeatures,
} from "./adk/client";
import {
issueFeedbackToolCalls,
traceForInvocation,
type IssueFeedbackIssue,
type IssueFeedbackModule,
} from "./adk/issueFeedback";
import { requiresSessionCapabilityRunner } from "./adk/sessionCapabilities";
import {
applyEvent,
emptyAcc,
eventsToTurns,
type Block,
type Turn,
type TurnActivityDetail,
} from "./blocks";
import { Sidebar, type SidebarPage } from "./ui/Sidebar";
import { AgentInfoPanel } from "./ui/AgentTopology";
import { SkillCenterView } from "./ui/SkillCenter";
import { AddAgentKitView } from "./ui/AddAgentKit";
import { AgentWorkspace } from "./ui/AgentWorkspace";
import {
MyAgents,
invalidateRuntimeAgentCache,
type MyAgentCardData,
} from "./ui/MyAgents";
import { Applications, type ApplicationId } from "./ui/Applications";
import { GitHubIntegration } from "./ui/GitHubIntegration";
import { FeishuBotIntegration } from "./automations/feishu/FeishuBotIntegration";
import { CodingAgentsIntegration } from "./automations/coding-agents/CodingAgentsIntegration";
import { SearchView } from "./ui/Search";
import {
buildAgentEntries,
connectRuntime,
loadConnections,
registerConnections,
removeRuntimeConnection,
remoteAppId,
type AgentEntry,
type RemoteConnection,
} from "./adk/connections";
import { Blocks, ThinkingPlaceholder } from "./ui/Blocks";
import { Composer } from "./ui/Composer";
import { InvocationChips } from "./ui/InvocationChips";
import { MediaGroup } from "./ui/Media";
import { QuickCreate, type QuickCreateKind } from "./ui/QuickCreate";
import { StackCards } from "./ui/AddAgentMenu";
import { IntelligentCreate } from "./create/IntelligentCreate";
import { CustomCreate } from "./create/CustomCreate";
import { TemplateCreate } from "./create/TemplateCreate";
import { WorkflowCreate } from "./create/WorkflowCreate";
import { CodePackageCreate } from "./create/CodePackageCreate";
import type { AgentDraft } from "./create/types";
import {
loadWorkspaceDrafts,
workspaceDraftsKey,
writeWorkspaceDrafts,
type WorkspaceAgentDraft,
} from "./create/agentDraftStorage";
import type { DeployResult, DeploymentTaskUpdate } from "./ui/ProjectPreview";
import { createSkillJob, deleteSkillJob } from "./ui/skill-create/api";
import { SkillCreateWorkspace } from "./ui/skill-create/SkillCreateWorkspace";
import { SKILL_MODELS, type SkillCreationJob } from "./ui/skill-create/types";
import type { NewChatMode, NewChatTask } from "./ui/new-chat-modes/types";
import { NewChatFeatureCarousel } from "./ui/new-chat-modes/NewChatFeatureCarousel";
import { NewChatFeatureNotice } from "./ui/new-chat-modes/NewChatFeatureNotice";
import {
NEW_CHAT_TASK_OPTIONAL_TOOLS,
NEW_CHAT_TASK_TOOLS,
} from "./ui/new-chat-modes/taskTools";
import {
sandboxClient,
type SandboxApproval,
type SandboxApprovalDecision,
type SandboxAgentResource,
type SandboxAgentKind,
type SandboxAgentWorkspace as SandboxAgentWorkspaceData,
type SandboxLaunchCapabilities,
type SandboxPermissions,
type SandboxRetentionMode,
type SandboxSession as SandboxSessionInfo,
type SandboxSkill,
type SandboxToolLaunch,
} from "./adk/sandbox";
import {
getSandboxCapability,
getSkillCreatorCapability,
} from "./adk/newChatCapabilities";
import {
SandboxLaunchDialog,
type SandboxLaunchState,
} from "./ui/SandboxLaunchDialog";
import {
SandboxActivityRecord,
SandboxSessionWarning,
SandboxTokenUsageRow,
} from "./ui/SandboxSession";
import {
SandboxApprovalDialog,
SandboxPermissionsDialog,
SandboxThreadsDialog,
SandboxToolDialog,
SandboxWorkspaceDialog,
} from "./ui/SandboxControls";
import { SandboxAgentDetails } from "./ui/SandboxAgentDetails";
import { SandboxAgentWorkspace } from "./ui/SandboxAgentWorkspace";
import { SandboxComposer } from "./ui/SandboxComposer";
import { sandboxSnapshotTurns } from "./ui/sandboxCommands";
import { useSandboxCodexCommands } from "./ui/useSandboxCodexCommands";
import defaultSiteLogo from "./assets/logo.svg";
import {
FeedbackDownIcon,
FeedbackUpIcon,
IssueFeedbackIcon,
} from "./ui/icons/FeedbackIcons";
interface IssueFeedbackTarget {
turn: Turn;
input: string;
}
function issueFeedbackModuleForPage(page: string): IssueFeedbackModule {
if (page === "agents") return "agents";
if (page === "applications") return "applications";
if (page === "search") return "search";
if (["conversation", "new-chat", "sandbox"].includes(page)) {
return "conversation";
}
return "other";
}
interface NewChatCapabilitiesState {
agentId?: string;
ready?: boolean;
harnessEnabled?: boolean;
builtinTools?: string[];
temporaryEnabled?: boolean;
skillCreateEnabled?: boolean;
}
async function probeNewChatCapabilities(
agentId: string,
): Promise<NewChatCapabilitiesState> {
const [sandboxResult, skillResult, harnessResult] = await Promise.allSettled([
getSandboxCapability(),
getSkillCreatorCapability(),
listSessionBuiltinTools(agentId),
]);
return {
agentId,
ready: true,
harnessEnabled: harnessResult.status === "fulfilled",
builtinTools: harnessResult.status === "fulfilled" ? harnessResult.value : [],
temporaryEnabled:
sandboxResult.status === "fulfilled" && sandboxResult.value.enabled,
skillCreateEnabled:
skillResult.status === "fulfilled" && skillResult.value.enabled,
};
}
type CreateMode = QuickCreateKind | "package";
type CreateView = "menu" | CreateMode | null;
// Persist the last view so a page refresh restores where the user was.
const LS = { app: "veadk.appName", view: "veadk.view", session: "veadk.sessionId" } as const;
const DRAFT_AUTOSAVE_DELAY_MS = 600;
const AUTO_EVALUATION_RUNNING_POLL_MS = 1_000;
const AUTO_EVALUATION_RETRY_POLL_MS = 5_000;
const AUTO_EVALUATION_MIN_PENDING_POLL_MS = 500;
const EMPTY_STRING_SET: Set<string> = new Set<string>();
const EMPTY_STRING_ARR: string[] = [];
function emptyInvocation(): FrontendInvocation {
return { skills: [] };
}
function activeWorkspaceDraftKey(userId: string): string {
return `${workspaceDraftsKey(userId)}.active`;
}
function workspaceAgentOrderKey(userId: string): string {
return `veadk.agentOrder.${encodeURIComponent(userId)}`;
}
function loadWorkspaceAgentOrder(userId: string): string[] {
if (!userId) return [];
try {
const value = JSON.parse(localStorage.getItem(workspaceAgentOrderKey(userId)) || "[]");
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
} catch {
return [];
}
}
function findAgentNode(node: AgentNode, name: string): AgentNode | undefined {
if (node.name === name || node.id === name) return node;
for (const child of node.children) {
const found = findAgentNode(child, name);
if (found) return found;
}
return undefined;
}
function mentionableDescendants(node: AgentNode): AgentTarget[] {
const targets: AgentTarget[] = [];
for (const child of node.children) {
if (!child.mentionable) continue;
targets.push({
name: child.name,
description: child.description,
type: child.type,
path: child.path,
});
targets.push(...mentionableDescendants(child));
}
return targets;
}
function loadView(): CreateView {
const v = typeof localStorage !== "undefined" ? localStorage.getItem(LS.view) : null;
return v === "menu" || v === "intelligent" || v === "custom" || v === "template" || v === "workflow"
? v
: null;
}
import { TraceDrawer } from "./ui/TraceDrawer";
import { LoginPage } from "./ui/LoginPage";
import { AuthExpiredDialog } from "./ui/AuthExpiredDialog";
import { IssueFeedbackDialog } from "./ui/IssueFeedbackDialog";
import { PlatformFeedback } from "./ui/PlatformFeedback";
import { Markdown } from "./ui/Markdown";
import {
clearLocalUser,
logout,
openLoginWindow,
resolveIdentity,
setLocalUser,
type AuthStatus,
} from "./adk/identity";
import {
AUTHENTICATION_REQUIRED_EVENT,
authenticationRestored,
isAuthenticationPending,
} from "./adk/authSession";
import {
identifyStudioTelemetryUser,
initStudioTelemetry,
} from "./adk/telemetry";
import {
trackSandboxCreateFailed,
trackSandboxCreateSucceeded,
trackStudioLoaded,
} from "./adk/telemetryEvents";
import type { A2uiAction, A2uiComponent } from "./a2ui/types";
import { buildSurfaces } from "./a2ui/Surface";
/** Hand-drawn "from zero" mark: a blank Agent canvas ready to create. */
function ScratchIcon({ className }: { className?: string }) {
return (
<svg
className={className}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.45"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<rect x="3.75" y="3.75" width="16.5" height="16.5" rx="3.25" />
<path d="M12 8.5v7M8.5 12h7" />
<path d="M6.75 6.75h1M16.25 17.25h1" opacity="0.6" />
</svg>
);
}
/** Hand-drawn code package mark: an archive with source inside. */
function PackageIcon({ className }: { className?: string }) {
return (
<svg
className={className}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.45"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<rect x="3.5" y="5" width="17" height="14.75" rx="2.25" />
<path d="M3.5 9h17M9.25 12.25 7.1 14.4l2.15 2.15M14.75 12.25l2.15 2.15-2.15 2.15M12.8 11.85l-1.6 5.1" />
</svg>
);
}
/** Hand-drawn migration mark: an existing project moving into a new runtime. */
function MigrationIcon({ className }: { className?: string }) {
return (
<svg
className={className}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.45"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<rect x="2.75" y="5" width="6.5" height="14" rx="1.6" />
<path d="M5.25 8.5h1.5M5.25 11.5h1.5" />
<rect x="14.75" y="5" width="6.5" height="14" rx="1.6" />
<path d="M17.25 15.5h1.5M17.25 12.5h1.5M8.75 12h6.5m-2.5-2.5 2.5 2.5-2.5 2.5" />
</svg>
);
}
/** Hand-drawn "tracing / observability" icon (stacked spans). */
function TraceIcon() {
return (
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden>
<rect x="3" y="4" width="14" height="3.2" rx="1.2" fill="currentColor" stroke="none" />
<rect x="6" y="10.4" width="13" height="3.2" rx="1.2" fill="currentColor" stroke="none" opacity="0.7" />
<rect x="9" y="16.8" width="9" height="3.2" rx="1.2" fill="currentColor" stroke="none" opacity="0.45" />
</svg>
);
}
/** Format an epoch-seconds timestamp as Beijing (Asia/Shanghai) time. */
function fmtTime(ts?: number): string {
if (!ts) return "";
return new Date(ts * 1000).toLocaleString("zh-CN", {
timeZone: "Asia/Shanghai",
hour12: false,
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
function fmtMeta(meta?: { tokens?: number; ts?: number }): string {
if (!meta) return "";
const parts: string[] = [];
if (meta.ts) parts.push(fmtTime(meta.ts));
if (meta.tokens != null) parts.push(`${meta.tokens.toLocaleString()} tokens`);
return parts.join(" · ");
}
/** Plain-text content of a turn (answer text only), for copying. */
function turnText(turn: Turn): string {
return turn.blocks
.map((b) => (b.kind === "text" ? b.text : ""))
.join("")
.trim();
}
function previousUserTurnText(turns: Turn[], turnIndex: number): string {
for (let index = turnIndex - 1; index >= 0; index -= 1) {
if (turns[index].role === "user") return turnText(turns[index]);
}
return "";
}
const A2UI_TOOL_NAME = "send_a2ui_json_to_client";
/** Whether a finalized assistant turn has anything visible to render — non-empty
* text, media, a renderable A2UI surface, or a non-A2UI tool. Thinking, the hidden
* (done) A2UI tool, and empty A2UI surfaces don't count, so a reply that was
* ONLY thinking + an empty surface returns false (→ we show a fallback). */
function turnHasVisibleContent(turn: Turn): boolean {
return turn.blocks.some((b) => {
if (b.kind === "text") return b.text.trim().length > 0;
if (b.kind === "attachment") return b.files.length > 0;
if (b.kind === "artifact") return b.files.length > 0;
if (b.kind === "tool") return !(b.name === A2UI_TOOL_NAME && b.done);
if (b.kind === "agent-transfer") return false;
if (b.kind === "a2ui") return buildSurfaces(b.messages).some((s) => s.components[s.rootId]);
if (b.kind === "auth") return true; // the OAuth card counts as content
return false; // thinking is not an answer
});
}
/** True while a turn is paused on an unresolved OAuth card — like streaming, we
* hide the actions/timestamp row until authorization completes. */
function turnAwaitingAuth(turn: Turn): boolean {
return turn.blocks.some((b) => b.kind === "auth" && !b.done);
}
/** Open the OAuth authorize URL in a popup and resolve with the full callback
* URL. Auto-captures when the provider redirects back to our origin (poll +
* postMessage); if the popup closes without capture (cross-origin redirect),
* falls back to asking the user to paste the callback URL. */
function runOAuthPopup(authUri: string): Promise<string> {
return new Promise((resolve, reject) => {
let protocol = "";
try {
protocol = new URL(authUri, window.location.href).protocol;
} catch {
// Invalid URLs are rejected with unsupported schemes below.
}
if (protocol !== "http:" && protocol !== "https:") {
reject(new Error("授权链接不是 http/https 地址,已阻止打开。"));
return;
}
const popup = window.open(authUri, "veadk_oauth", "width=520,height=720");
if (!popup) {
reject(new Error("弹窗被拦截,请允许弹窗后重试。"));
return;
}
let done = false;
const cleanup = () => {
clearInterval(timer);
window.removeEventListener("message", onMsg);
};
const finish = (url: string) => {
if (done) return;
done = true;
cleanup();
try {
popup.close();
} catch {
/* ignore */
}
resolve(url);
};
const onMsg = (e: MessageEvent) => {
if (e.origin !== window.location.origin) return;
const d = e.data as { veadkOAuth?: boolean; url?: string } | null;
if (d && d.veadkOAuth && typeof d.url === "string") finish(d.url);
};
window.addEventListener("message", onMsg);
const timer = setInterval(() => {
if (done) return;
if (popup.closed) {
cleanup();
const pasted = window.prompt(
"授权完成后,请粘贴回调页面(浏览器地址栏)的完整 URL:",
);
if (pasted && pasted.trim()) {
done = true;
resolve(pasted.trim());
} else {
reject(new Error("授权已取消。"));
}
return;
}
try {
const href = popup.location.href; // throws while cross-origin
if (
href &&
href !== "about:blank" &&
new URL(href).origin === window.location.origin &&
/[?&](code|state|error)=/.test(href)
) {
finish(href);
}
} catch {
/* still on the provider's origin — keep polling */
}
}, 500);
});
}
/** Clone an ADK AuthConfig and set the OAuth2 callback URL, so ADK can exchange
* the code for a token when we send it back as the credential response. */
function withAuthResponseUri(authConfig: unknown, callbackUrl: string): unknown {
const cfg = JSON.parse(JSON.stringify(authConfig ?? {})) as Record<string, any>;
const cred = cfg.exchangedAuthCredential ?? cfg.exchanged_auth_credential ?? {};
const o = cred.oauth2 ?? {};
o.authResponseUri = callbackUrl;
o.auth_response_uri = callbackUrl;
cred.oauth2 = o;
cfg.exchangedAuthCredential = cred;
return cfg;
}
function CopyButton({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
return (
<button
className="icon-btn"
title={copied ? "已复制" : "复制"}
disabled={!text}
onClick={async () => {
if (!text) return;
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
/* clipboard unavailable */
}
}}
>
{copied ? <Check className="icon" /> : <Copy className="icon" />}
</button>
);
}
// Side-effect import: registers all A2UI components under a2ui/components/*.
import "./a2ui/components";
const GREETINGS = [
"今天想做点什么?",
"有什么可以帮你的?",
"需要我帮你查点什么吗?",
"有问题尽管问我",
"嗨,我们开始吧",
"开始一段新对话吧",
"今天想先解决哪件事?",
"把你的想法告诉我吧",
"我们从哪里开始?",
"有什么任务交给我?",
"准备好一起推进了吗?",
"说说你现在最关心的问题",
"今天也一起把事情做好",
"我在,随时可以开始",
];
const pickGreeting = () => GREETINGS[Math.floor(Math.random() * GREETINGS.length)];
function releaseAttachmentPreviews(items: Attachment[]) {
for (const item of items) {
if (item.previewUrl?.startsWith("blob:")) URL.revokeObjectURL(item.previewUrl);
}
}
function attachmentDraftId() {
return `draft-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
function browserMimeType(file: File) {
if (file.type) return file.type;
const extension = file.name.split(".").pop()?.toLowerCase();
if (extension === "md" || extension === "markdown") return "text/markdown";
if (extension === "txt") return "text/plain";
return "application/octet-stream";
}
const SANDBOX_MODE_LABELS: Record<SandboxPermissions["sandboxMode"], string> = {
"read-only": "只读",
"workspace-write": "工作区写入",
"danger-full-access": "完全访问",
};
const SANDBOX_APPROVAL_POLICY_LABELS: Record<
SandboxPermissions["approvalPolicy"],
string
> = {
untrusted: "仅不可信命令",
"on-request": "按需审批",
never: "不审批",
};
const SANDBOX_REVIEWER_LABELS: Record<
SandboxPermissions["approvalsReviewer"],
string
> = {
user: "由我审批",
auto_review: "自动审查",
};
function approvalActivityTitle(
approval: SandboxApproval,
decision: SandboxApprovalDecision,
): string {
const subject = approval.kind === "file" ? "文件修改" : "命令执行";
if (decision === "accept") return `已允许本次${subject}`;
if (decision === "acceptForSession") return `已在本会话中允许${subject}`;
if (decision === "decline") return `已拒绝${subject}`;
return `已取消${subject}审批`;
}
function approvalActivityDetails(
approval: SandboxApproval,
): TurnActivityDetail[] {
const details: TurnActivityDetail[] = [];
if (approval.command?.trim()) {
details.push({ label: "命令", value: approval.command.trim(), code: true });
}
if (approval.grantRoot?.trim()) {
details.push({
label: "授权路径",
value: approval.grantRoot.trim(),
code: true,
});
}
if (approval.cwd?.trim()) {
details.push({ label: "执行目录", value: approval.cwd.trim(), code: true });
}
return details;
}
function remoteSelectionIds(connections: RemoteConnection[]) {
return connections.flatMap((connection) =>
connection.apps.map((app) => remoteAppId(connection.id, app)),
);
}
function runtimeIdForSelection(
connections: RemoteConnection[],
selectedAppName: string,
) {
return connections.find(
(connection) =>
connection.runtimeId &&
connection.apps.some(
(app) => remoteAppId(connection.id, app) === selectedAppName,
),
)?.runtimeId ?? "";
}
interface AutomaticEvaluationTarget {
runtimeId: string;
region: string;
appName: string;
}
function automaticEvaluationTargetForSelection(
connections: RemoteConnection[],
selectedAppName: string,
): AutomaticEvaluationTarget | null {
for (const connection of connections) {
const runtimeApp = connection.apps.find(
(app) => remoteAppId(connection.id, app) === selectedAppName,
);
if (runtimeApp && connection.runtimeId) {
return {
runtimeId: connection.runtimeId,
region: connection.region ?? "cn-beijing",
appName: runtimeApp,
};
}
}
return null;
}
export default function App() {
const [apps, setApps] = useState<string[]>([]);
const [appName, setAppName] = useState("");
const [sessions, setSessions] = useState<AdkSession[]>([]);
const [sessionId, setSessionId] = useState("");
const creatingSessionRef = useRef<Promise<string> | null>(null);
const [initializingSession, setInitializingSession] = useState(false);
const [pendingTurns, setPendingTurns] = useState<Turn[]>([]);
const [sandboxSession, setSandboxSession] =
useState<SandboxSessionInfo | null>(null);
const [sandboxTurns, setSandboxTurns] = useState<Turn[]>([]);
const [sandboxBusy, setSandboxBusy] = useState(false);
const [sandboxSettingsBusy, setSandboxSettingsBusy] = useState(false);
const [sandboxSettingsError, setSandboxSettingsError] = useState("");
const [sandboxPermissionsOpen, setSandboxPermissionsOpen] = useState(false);
const [sandboxWorkspaceOpen, setSandboxWorkspaceOpen] = useState(false);
const [sandboxToolKind, setSandboxToolKind] =
useState<"terminal" | "browser" | null>(null);
const [sandboxToolLaunch, setSandboxToolLaunch] =
useState<SandboxToolLaunch | null>(null);
const [sandboxToolLoading, setSandboxToolLoading] = useState(false);
const [sandboxToolError, setSandboxToolError] = useState("");
const [sandboxApproval, setSandboxApproval] =
useState<SandboxApproval | null>(null);
const [sandboxApprovalBusy, setSandboxApprovalBusy] = useState(false);
const [sandboxApprovalError, setSandboxApprovalError] = useState("");
const [sandboxUploadBusy, setSandboxUploadBusy] = useState(false);
const [sandboxLaunchOpen, setSandboxLaunchOpen] = useState(false);
const [sandboxLaunchState, setSandboxLaunchState] =
useState<SandboxLaunchState>("confirm");
const [sandboxLaunchError, setSandboxLaunchError] = useState("");
const [sandboxLaunchCapabilities, setSandboxLaunchCapabilities] =
useState<SandboxLaunchCapabilities | null>(null);
const [sandboxLaunchCapabilitiesLoading, setSandboxLaunchCapabilitiesLoading] =
useState(false);
const [sandboxLaunchCapabilitiesError, setSandboxLaunchCapabilitiesError] =
useState("");
const [sandboxLaunchKind, setSandboxLaunchKind] =
useState<"codex" | SandboxAgentKind>("codex");
const [sandboxLaunchFromAgents, setSandboxLaunchFromAgents] = useState(false);
const [sandboxAgentRefreshKey, setSandboxAgentRefreshKey] = useState(0);
const [sandboxAgentDetailTarget, setSandboxAgentDetailTarget] =
useState<SandboxAgentResource | null>(null);
const [sandboxAgentWorkspace, setSandboxAgentWorkspace] =
useState<SandboxAgentWorkspaceData | null>(null);
const sandboxLaunchAbortRef = useRef<AbortController | null>(null);
const sandboxLaunchCapabilitiesAbortRef =
useRef<AbortController | null>(null);
const sandboxMessageAbortRef = useRef<AbortController | null>(null);
const sandboxSessionIdRef = useRef(sandboxSession?.id ?? "");
const sandboxActiveAssistantTurnIdRef = useRef("");
const sandboxUploadRunRef = useRef(0);
const sandboxPreviewUrlsRef = useRef<Set<string>>(new Set());
sandboxSessionIdRef.current = sandboxSession?.id ?? "";
useEffect(() => () => {
for (const previewUrl of sandboxPreviewUrlsRef.current) {
URL.revokeObjectURL(previewUrl);
}
sandboxPreviewUrlsRef.current.clear();
}, []);
function createSandboxPreviewUrl(file: File) {
const previewUrl = URL.createObjectURL(file);
sandboxPreviewUrlsRef.current.add(previewUrl);
return previewUrl;
}
function releaseSandboxPreviewUrl(previewUrl?: string) {
if (!previewUrl || !sandboxPreviewUrlsRef.current.delete(previewUrl)) return;
URL.revokeObjectURL(previewUrl);
}
function releaseAllSandboxPreviews() {
for (const previewUrl of sandboxPreviewUrlsRef.current) {
URL.revokeObjectURL(previewUrl);
}
sandboxPreviewUrlsRef.current.clear();
}
// Turns are stored PER SESSION, so a background stream can keep updating its
// own session's transcript while you view another one — no cross-session
// leak, no data loss, and no re-fetch when you switch back (its entry is
// already live). The view shows the active session's entry.
const [turnsBySession, setTurnsBySession] = useState<Record<string, Turn[]>>(
{},
);
const persistentTurns = sessionId
? turnsBySession[sessionId] ?? []
: pendingTurns;
const turns = sandboxSession ? sandboxTurns : persistentTurns;
const setTurnsFor = (
sid: string,
updater: Turn[] | ((prev: Turn[]) => Turn[]),
) =>
setTurnsBySession((m) => ({
...m,
[sid]: typeof updater === "function" ? updater(m[sid] ?? []) : updater,
}));
function appendSandboxActivity(
activeSessionId: string,
title: string,
details: TurnActivityDetail[] = [],
beforeTurnId = "",
) {
if (sandboxSessionIdRef.current !== activeSessionId) return;
const activityId = crypto.randomUUID();
const activityTurn: Turn = {
role: "system",
blocks: [],
activity: {
id: activityId,
title,
...(details.length > 0 ? { details } : {}),
},
meta: { localId: activityId, ts: Date.now() / 1000 },
};
setSandboxTurns((current) => {
if (!beforeTurnId) return [...current, activityTurn];
const beforeIndex = current.findIndex(
(turn) => turn.meta?.localId === beforeTurnId,
);
if (beforeIndex < 0) return [...current, activityTurn];
return [
...current.slice(0, beforeIndex),
activityTurn,
...current.slice(beforeIndex),
];
});
}
const [input, setInput] = useState("");
const [newChatMode, setNewChatMode] = useState<NewChatMode>("agent");
const [newChatTask, setNewChatTask] = useState<NewChatTask | null>(null);
const [newChatCapabilities, setNewChatCapabilities] =
useState<NewChatCapabilitiesState>({});
const newChatCapabilitiesCacheRef = useRef(
new Map<string, NewChatCapabilitiesState>(),
);
const newChatCapabilitiesReady =
!appName ||
(newChatCapabilities.ready === true && newChatCapabilities.agentId === appName);
const [skillJob, setSkillJob] = useState<SkillCreationJob | null>(null);
const [skillCreating, setSkillCreating] = useState(false);
const skillCreationRunRef = useRef(0);
const [attachments, setAttachments] = useState<Attachment[]>([]);
const [invocation, setInvocation] = useState<FrontendInvocation>(emptyInvocation);
const [agentInfo, setAgentInfo] = useState<AgentInfo | null>(null);
const [agentInfoRefreshKey, setAgentInfoRefreshKey] = useState(0);
const [capabilitiesLoading, setCapabilitiesLoading] = useState(false);
const [sessionCapabilities, setSessionCapabilities] =
useState<SessionCapabilities | null>(null);
const [sessionCapabilitiesLoading, setSessionCapabilitiesLoading] =
useState(false);
const [sessionBuiltinTools, setSessionBuiltinTools] = useState<string[]>([]);
const [sessionCapabilityMutating, setSessionCapabilityMutating] =
useState(false);
const removedAttachmentIdsRef = useRef<Set<string>>(new Set());
// Streaming state is PER SESSION so multiple sessions can stream at once
// (each /run_sse is an independent request). `streamingSids` = which sessions
// are currently streaming; the AbortControllers let unmount / delete cancel
// a specific session's stream. A normal switch does NOT abort — the stream
// keeps running and persisting.
const [streamingSids, setStreamingSids] = useState<Set<string>>(
() => new Set(),
);
const [streamPresentationSids, setStreamPresentationSids] = useState<Set<string>>(
() => new Set(),
);
const [evaluatingSids, setEvaluatingSids] = useState<Set<string>>(
() => new Set(),
);
const streamAbortsRef = useRef<Map<string, AbortController>>(new Map());
const streamPresentationTimersRef = useRef<Map<string, number>>(new Map());
const automaticEvaluationStatusTimerRef = useRef<number | undefined>(undefined);
const automaticEvaluationStatusRefreshRef = useRef<() => void>(() => {});
const setStreaming = (sid: string, on: boolean) =>
setStreamingSids((s) => {
const n = new Set(s);
if (on) n.add(sid);
else n.delete(sid);
return n;
});
const startStreamPresentation = (sid: string) => {
const timer = streamPresentationTimersRef.current.get(sid);
if (timer !== undefined) window.clearTimeout(timer);
streamPresentationTimersRef.current.delete(sid);
setStreamPresentationSids((current) => new Set(current).add(sid));
};
const finishStreamPresentation = (sid: string) => {
const previousTimer = streamPresentationTimersRef.current.get(sid);
if (previousTimer !== undefined) window.clearTimeout(previousTimer);
const timer = window.setTimeout(() => {
streamPresentationTimersRef.current.delete(sid);
setStreamPresentationSids((current) => {
const next = new Set(current);
next.delete(sid);
return next;
});
}, 2400);
streamPresentationTimersRef.current.set(sid, timer);
};
const setEvaluating = (sid: string, on: boolean) => {
setEvaluatingSids((current) => {
if (current.has(sid) === on) return current;
const next = new Set(current);
if (on) next.add(sid);
else next.delete(sid);
return next;
});
};
// The session currently on screen — used to gate the single global error
// banner (per-session transcripts/topology don't need it).
const viewSidRef = useRef("");
const [error, setError] = useState("");
const [draftStorageError, setDraftStorageError] = useState("");
const [feedbackPendingIds, setFeedbackPendingIds] = useState<Set<string>>(
() => new Set(),
);
const [issueFeedbackTarget, setIssueFeedbackTarget] =
useState<IssueFeedbackTarget | null>(null);
const [platformFeedbackOrigin, setPlatformFeedbackOrigin] =
useState<string | null>(null);
const [traceOpen, setTraceOpen] = useState(false);
const [traceEndTimeMs, setTraceEndTimeMs] = useState<number>();
const [greeting, setGreeting] = useState(pickGreeting);
const [authStatus, setAuthStatus] = useState<AuthStatus | null>(null);
const [authExpired, setAuthExpired] = useState(false);
const [authRecoveryChecking, setAuthRecoveryChecking] = useState(false);
const [authRecoveryError, setAuthRecoveryError] = useState("");
const authRecoveryActiveRef = useRef(false);
const [authError, setAuthError] = useState<string | null>(null);
const [userId, setUserId] = useState("");
const [userInfo, setUserInfo] = useState<Record<string, unknown> | undefined>();
// Null while the server-derived role is unresolved. Privileged UI remains
// hidden until this has loaded; failures fall back to the ordinary user.
const [access, setAccess] = useState<StudioAccess | null>(null);
const grantedRuntimeScope = access?.capabilities.runtimeScope ?? "mine";
// Per-module feature gates (studio mode disables chat-centric modules).
// Defaults to all-enabled until /web/ui-config resolves.
const [features, setFeatures] = useState<UiFeatures>({
newChat: true,
search: true,
skillCenter: true,
history: true,
addAgent: true,
manageAgents: true,
addAgentkit: true,
});
const [agentsSource, setAgentsSource] = useState<"local" | "cloud">("cloud");
const [siteBranding, setSiteBranding] = useState<SiteBranding>(DEFAULT_SITE_BRANDING);
const [version, setVersion] = useState("");
const [uiConfigLoaded, setUiConfigLoaded] = useState(false);
const [localMode, setLocalMode] = useState(false);
const [loadingSession, setLoadingSession] = useState(false);
// The executing sub-agent (ADK event.author) and everyone who emitted this
// turn — PER SESSION, so each session's topology highlights its own stream.
const [activeAgentBySession, setActiveAgentBySession] = useState<
Record<string, string>
>({});
const [seenAgentsBySession, setSeenAgentsBySession] = useState<
Record<string, Set<string>>
>({});
// The current delegation chain (root → … → executing agent) per session,
// built from event.actions.transfer_to_agent / end_of_agent.
const [execPathBySession, setExecPathBySession] = useState<
Record<string, string[]>
>({});
// Everything the view needs for the ACTIVE session, derived from the
// per-session maps above.
const busy = streamingSids.has(sessionId);
const presentingStream = streamPresentationSids.has(sessionId);
const conversationBusy = busy || initializingSession;
const sessionConfigurationBusy = !!sessionId && sessionCapabilitiesLoading;
const activeConversationBusy = sandboxSession
? sandboxBusy
: conversationBusy;
const activeConversationPresenting =
activeConversationBusy || (!sandboxSession && presentingStream);
const sandboxCommands = useSandboxCodexCommands({
session: sandboxSession,
conversationBusy: sandboxBusy,
onInputChange: setInput,
onSessionPatch: (patch) => {
const activeSessionId = sandboxSessionIdRef.current;
setSandboxSession((current) =>
current?.id === activeSessionId ? { ...current, ...patch } : current
);
},
onSnapshot: (snapshot) => {
const activeSessionId = sandboxSessionIdRef.current;
releaseAllSandboxPreviews();
setSandboxTurns(sandboxSnapshotTurns(snapshot));
setSandboxSession((current) =>
current?.id === activeSessionId
? {
...current,
threadId: snapshot.threadId,
cwd: snapshot.cwd ?? current.cwd,