-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtypes.ts
More file actions
1346 lines (1183 loc) · 49.9 KB
/
types.ts
File metadata and controls
1346 lines (1183 loc) · 49.9 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
// Types shared between main and renderer processes
// Core types are re-exported from @kata/core
// Import and re-export core types
import type {
Message as CoreMessage,
MessageRole as CoreMessageRole,
TypedError,
TokenUsage as CoreTokenUsage,
Workspace as CoreWorkspace,
SessionMetadata as CoreSessionMetadata,
StoredAttachment as CoreStoredAttachment,
ContentBadge,
ToolDisplayMeta,
} from '@kata/core/types';
// Import mode types from dedicated subpath export (avoids pulling in SDK)
import type { PermissionMode } from '@kata/shared/agent/modes';
export type { PermissionMode };
export { PERMISSION_MODE_CONFIG } from '@kata/shared/agent/modes';
// Import thinking level types
import type { ThinkingLevel } from '@kata/shared/agent/thinking-levels';
export type { ThinkingLevel };
export { THINKING_LEVELS, DEFAULT_THINKING_LEVEL } from '@kata/shared/agent/thinking-levels';
export type {
CoreMessage as Message,
CoreMessageRole as MessageRole,
TypedError,
CoreTokenUsage as TokenUsage,
CoreWorkspace as Workspace,
CoreSessionMetadata as SessionMetadata,
CoreStoredAttachment as StoredAttachment,
ContentBadge,
ToolDisplayMeta,
};
// Import and re-export auth types for onboarding
// Use types-only subpaths to avoid pulling in Node.js dependencies
import type { AuthState, SetupNeeds } from '@kata/shared/auth/types';
import type { AuthType } from '@kata/shared/config/types';
export type { AuthState, SetupNeeds, AuthType };
// Import source types for session source selection
import type { LoadedSource, FolderSourceConfig, SourceConnectionStatus } from '@kata/shared/sources/types';
export type { LoadedSource, FolderSourceConfig, SourceConnectionStatus };
// Import skill types
import type { LoadedSkill, SkillMetadata } from '@kata/shared/skills/types';
export type { LoadedSkill, SkillMetadata };
// Import git types
import type { GitState, PrInfo } from '@kata/shared/git';
export type { GitState, PrInfo };
/** Manager-level daemon state (matches DaemonManager.state in main process) */
export type DaemonManagerState = 'stopped' | 'starting' | 'running' | 'stopping' | 'error' | 'paused';
/**
* File/directory entry in a skill folder
*/
export interface SkillFile {
name: string
type: 'file' | 'directory'
size?: number
children?: SkillFile[]
}
/**
* File/directory entry in a session folder
* Supports recursive tree structure with children for directories
*/
export interface SessionFile {
name: string
path: string
type: 'file' | 'directory'
size?: number
children?: SessionFile[] // Recursive children for directories
}
/**
* File search result for @ mention file selection.
* Returned by FS_SEARCH IPC handler when user types @filename in input.
*/
export interface FileSearchResult {
name: string
path: string
type: 'file' | 'directory'
relativePath: string // Path relative to search base
}
// Import auth request types for unified auth flow
import type { AuthRequest as SharedAuthRequest, CredentialInputMode as SharedCredentialInputMode, CredentialAuthRequest as SharedCredentialAuthRequest } from '@kata/shared/agent';
export type { SharedAuthRequest as AuthRequest };
export type { SharedCredentialInputMode as CredentialInputMode };
// CredentialRequest is used by UI components for displaying credential input
export type CredentialRequest = SharedCredentialAuthRequest;
export { generateMessageId } from '@kata/core/types';
/**
* OAuth result from main process
*/
export interface OAuthResult {
success: boolean
error?: string
}
/**
* MCP connection validation result
*/
export interface McpValidationResult {
success: boolean
error?: string
tools?: string[]
}
/**
* MCP tool with safe mode permission status
*/
export interface McpToolWithPermission {
name: string
description?: string
allowed: boolean // true if allowed in safe mode, false if requires permission
}
/**
* Result of fetching MCP tools with permission status
*/
export interface McpToolsResult {
success: boolean
error?: string
tools?: McpToolWithPermission[]
}
/**
* Result of sharing or revoking a session
*/
export interface ShareResult {
success: boolean
url?: string
error?: string
}
/**
* Result of refreshing/regenerating a session title
*/
export interface RefreshTitleResult {
success: boolean
title?: string
error?: string
}
// Re-export permission types from core, extended with sessionId for multi-session context
export type { PermissionRequest as BasePermissionRequest } from '@kata/core/types';
import type { PermissionRequest as BasePermissionRequest } from '@kata/core/types';
/**
* Permission request with session context (for multi-session Electron app)
*/
export interface PermissionRequest extends BasePermissionRequest {
sessionId: string
}
// ============================================
// Credential Input Types (Secure Auth UI)
// ============================================
// CredentialInputMode is imported from @kata/shared/agent above
/**
* Credential response from user (for credential auth requests)
*/
export interface CredentialResponse {
type: 'credential'
/** Single value for bearer/header/query modes */
value?: string
/** Username for basic auth */
username?: string
/** Password for basic auth */
password?: string
/** Whether user cancelled */
cancelled: boolean
}
// ============================================
// Plan Types (SubmitPlan workflow)
// ============================================
/**
* Step in a plan
*/
export interface PlanStep {
id: string
description: string
tools?: string[]
status?: 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped'
}
/**
* Plan from the agent
*/
export interface Plan {
id: string
title: string
summary?: string
steps: PlanStep[]
questions?: string[]
state?: 'creating' | 'refining' | 'ready' | 'executing' | 'completed' | 'cancelled'
createdAt?: number
updatedAt?: number
}
// ============================================
// Onboarding Types
// ============================================
/**
* Git Bash detection status (Windows only)
*/
export interface GitBashStatus {
found: boolean
path: string | null
platform: 'win32' | 'darwin' | 'linux'
}
/**
* Result of saving onboarding configuration
*/
export interface OnboardingSaveResult {
success: boolean
error?: string
workspaceId?: string
}
/**
* File attachment for sending with messages
* Matches the FileAttachment interface from src/utils/files.ts
*/
export interface FileAttachment {
type: 'image' | 'text' | 'pdf' | 'office' | 'unknown'
path: string
name: string
mimeType: string
base64?: string // For images, PDFs, and Office files
text?: string // For text files
size: number
thumbnailBase64?: string // Quick Look thumbnail (generated by Electron main process)
}
// Import types needed for Session interface
import type { Message } from '@kata/core/types';
/**
* Electron-specific Session type (includes runtime state)
* Extends core Session with messages array and processing state
*/
/**
* Todo state for sessions (user-controlled, never automatic)
*
* Dynamic status ID referencing workspace status config.
* Validated at runtime via validateSessionStatus().
* Falls back to 'todo' if status doesn't exist.
*
* Built-in status IDs (for reference):
* - 'todo': Not started
* - 'in-progress': Currently working on
* - 'needs-review': Awaiting review
* - 'done': Completed successfully
* - 'cancelled': Cancelled/abandoned
*/
export type TodoState = string
// Helper type for TypeScript consumers
export type BuiltInStatusId = 'todo' | 'in-progress' | 'needs-review' | 'done' | 'cancelled'
export interface Session {
id: string
workspaceId: string
workspaceName: string
name?: string // User-defined or AI-generated session name
/** Preview of first user message (from JSONL header, for lazy-loaded sessions) */
preview?: string
lastMessageAt: number
messages: Message[]
isProcessing: boolean
// Session metadata
isFlagged?: boolean
// Advanced options (persisted per session)
/** Permission mode for this session ('safe', 'ask', 'allow-all') */
permissionMode?: PermissionMode
// Todo state (user-controlled) - determines open vs closed
todoState?: TodoState
// Labels (additive tags, many-per-session — bare IDs or "id::value" entries)
labels?: string[]
// Read/unread tracking - ID of last message user has read
lastReadMessageId?: string
/**
* Explicit unread flag - single source of truth for NEW badge.
* Set to true when assistant message completes while user is NOT viewing.
* Set to false when user views the session (and not processing).
*/
hasUnread?: boolean
// Per-session source selection (source slugs)
enabledSourceSlugs?: string[]
// Working directory for this session (used by agent for bash commands)
workingDirectory?: string
// Session folder path (for "Reset to Session Root" option)
sessionFolderPath?: string
// Shared viewer URL (if shared via viewer)
sharedUrl?: string
// Shared session ID in viewer (for revoke)
sharedId?: string
// Model to use for this session (overrides global config if set)
model?: string
// Thinking level for this session ('off', 'think', 'max')
thinkingLevel?: ThinkingLevel
// Role/type of the last message (for badge display without loading messages)
lastMessageRole?: 'user' | 'assistant' | 'plan' | 'tool' | 'error'
// ID of the last final (non-intermediate) assistant message - pre-computed for unread detection
lastFinalMessageId?: string
// Whether an async operation is ongoing (sharing, updating share, revoking, title regeneration)
// Used for shimmer effect on session title in sidebar and panel header
isAsyncOperationOngoing?: boolean
/** @deprecated Use isAsyncOperationOngoing instead */
isRegeneratingTitle?: boolean
// Current status for ProcessingIndicator (e.g., compacting)
currentStatus?: {
message: string
statusType?: string
}
// When the session was first created (ms timestamp)
createdAt?: number
// Total message count (pre-computed in JSONL header)
messageCount?: number
/** Channel origin for daemon-created sessions (absent for direct/interactive sessions) */
channel?: {
/** Adapter type: 'slack', 'whatsapp', etc. */
adapter: string
/** Channel config slug */
slug: string
/** Display name for the channel source (e.g., '#general', 'Support Group') */
displayName?: string
}
// Token usage for context tracking
tokenUsage?: {
inputTokens: number
outputTokens: number
totalTokens: number
contextTokens: number
costUsd: number
cacheReadTokens?: number
cacheCreationTokens?: number
/** Model's context window size in tokens (from SDK modelUsage) */
contextWindow?: number
}
}
/**
* Options for creating a new session
* Note: Session creation itself has no options - auto-send is handled by NavigationContext
*/
export interface CreateSessionOptions {
/** Initial permission mode for the session (overrides workspace default) */
permissionMode?: PermissionMode
/**
* Working directory for the session:
* - 'user_default' or undefined: Use workspace's configured default working directory
* - 'none': No working directory (session folder only)
* - Absolute path string: Use this specific path
*/
workingDirectory?: string | 'user_default' | 'none'
}
// Events sent from main to renderer
// turnId: Correlation ID from the API's message.id, groups all events in an assistant turn
export type SessionEvent =
| { type: 'text_delta'; sessionId: string; delta: string; turnId?: string }
| { type: 'text_complete'; sessionId: string; text: string; isIntermediate?: boolean; turnId?: string; parentToolUseId?: string }
| { type: 'tool_start'; sessionId: string; toolName: string; toolUseId: string; toolInput: Record<string, unknown>; toolIntent?: string; toolDisplayName?: string; toolDisplayMeta?: import('@kata/core').ToolDisplayMeta; turnId?: string; parentToolUseId?: string }
| { type: 'tool_result'; sessionId: string; toolUseId: string; toolName: string; result: string; turnId?: string; parentToolUseId?: string; isError?: boolean }
| { type: 'error'; sessionId: string; error: string }
| { type: 'typed_error'; sessionId: string; error: TypedError }
| { type: 'complete'; sessionId: string; tokenUsage?: Session['tokenUsage']; hasUnread?: boolean }
| { type: 'interrupted'; sessionId: string; message?: Message }
| { type: 'status'; sessionId: string; message: string; statusType?: 'compacting' }
| { type: 'info'; sessionId: string; message: string; statusType?: 'compaction_complete'; level?: 'info' | 'warning' | 'error' | 'success' }
| { type: 'title_generated'; sessionId: string; title: string }
| { type: 'title_regenerating'; sessionId: string; isRegenerating: boolean }
// Generic async operation state (sharing, updating share, revoking, title regeneration)
| { type: 'async_operation'; sessionId: string; isOngoing: boolean }
| { type: 'working_directory_changed'; sessionId: string; workingDirectory: string }
| { type: 'permission_request'; sessionId: string; request: PermissionRequest }
| { type: 'credential_request'; sessionId: string; request: CredentialRequest }
// Permission mode events
| { type: 'permission_mode_changed'; sessionId: string; permissionMode: PermissionMode }
| { type: 'plan_submitted'; sessionId: string; message: CoreMessage }
// Source events
| { type: 'sources_changed'; sessionId: string; enabledSourceSlugs: string[] }
| { type: 'labels_changed'; sessionId: string; labels: string[] }
// Background task/shell events
| { type: 'task_backgrounded'; sessionId: string; toolUseId: string; taskId: string; intent?: string; turnId?: string }
| { type: 'shell_backgrounded'; sessionId: string; toolUseId: string; shellId: string; intent?: string; command?: string; turnId?: string }
| { type: 'task_progress'; sessionId: string; toolUseId: string; elapsedSeconds: number; turnId?: string }
| { type: 'shell_killed'; sessionId: string; shellId: string }
// User message events (for optimistic UI with backend as source of truth)
| { type: 'user_message'; sessionId: string; message: Message; status: 'accepted' | 'queued' | 'processing' }
// Session metadata events (for multi-window sync)
| { type: 'session_flagged'; sessionId: string }
| { type: 'session_unflagged'; sessionId: string }
| { type: 'session_model_changed'; sessionId: string; model: string | null }
| { type: 'todo_state_changed'; sessionId: string; todoState: TodoState }
| { type: 'session_deleted'; sessionId: string }
| { type: 'session_shared'; sessionId: string; sharedUrl: string }
| { type: 'session_unshared'; sessionId: string }
// Auth request events (unified auth flow)
| { type: 'auth_request'; sessionId: string; message: CoreMessage; request: SharedAuthRequest }
| { type: 'auth_completed'; sessionId: string; requestId: string; success: boolean; cancelled?: boolean; error?: string }
// Source activation events (for auto-retry on mid-turn activation)
| { type: 'source_activated'; sessionId: string; sourceSlug: string; originalMessage: string }
// Real-time usage update during processing (for context display)
| { type: 'usage_update'; sessionId: string; tokenUsage: { inputTokens: number; contextWindow?: number } }
// Options for sendMessage
export interface SendMessageOptions {
/** Enable ultrathink mode for extended reasoning */
ultrathinkEnabled?: boolean
/** Skill slugs to activate for this message (from @mentions) */
skillSlugs?: string[]
/** Content badges for inline display (sources, skills with embedded icons) */
badges?: import('@kata/core').ContentBadge[]
}
// =============================================================================
// IPC Command Pattern Types
// =============================================================================
/**
* SessionCommand - Consolidated session operations
* Replaces individual IPC calls: flag, unflag, rename, setTodoState, etc.
*/
export type SessionCommand =
| { type: 'flag' }
| { type: 'unflag' }
| { type: 'rename'; name: string }
| { type: 'setTodoState'; state: TodoState }
| { type: 'markRead' }
| { type: 'markUnread' }
/** Track which session user is actively viewing (for unread state machine) */
| { type: 'setActiveViewing'; workspaceId: string }
| { type: 'setPermissionMode'; mode: PermissionMode }
| { type: 'setThinkingLevel'; level: ThinkingLevel }
| { type: 'updateWorkingDirectory'; dir: string }
| { type: 'setSources'; sourceSlugs: string[] }
| { type: 'setLabels'; labels: string[] }
| { type: 'showInFinder' }
| { type: 'copyPath' }
| { type: 'shareToViewer' }
| { type: 'updateShare' }
| { type: 'revokeShare' }
| { type: 'startOAuth'; requestId: string }
| { type: 'refreshTitle' }
// Pending plan execution (Accept & Compact flow)
| { type: 'setPendingPlanExecution'; planPath: string }
| { type: 'markCompactionComplete' }
| { type: 'clearPendingPlanExecution' }
/**
* Parameters for opening a new chat session
*/
export interface NewChatActionParams {
/** Text to pre-fill in the input (not sent automatically) */
input?: string
/** Session name */
name?: string
}
// IPC channel names
export const IPC_CHANNELS = {
// Session management
GET_SESSIONS: 'sessions:get',
CREATE_SESSION: 'sessions:create',
DELETE_SESSION: 'sessions:delete',
GET_SESSION_MESSAGES: 'sessions:getMessages',
SEND_MESSAGE: 'sessions:sendMessage',
CANCEL_PROCESSING: 'sessions:cancel',
KILL_SHELL: 'sessions:killShell',
GET_TASK_OUTPUT: 'tasks:getOutput',
RESPOND_TO_PERMISSION: 'sessions:respondToPermission',
RESPOND_TO_CREDENTIAL: 'sessions:respondToCredential',
// Consolidated session command
SESSION_COMMAND: 'sessions:command',
// Pending plan execution (for reload recovery)
GET_PENDING_PLAN_EXECUTION: 'sessions:getPendingPlanExecution',
// Workspace management
GET_WORKSPACES: 'workspaces:get',
CREATE_WORKSPACE: 'workspaces:create',
CHECK_WORKSPACE_SLUG: 'workspaces:checkSlug',
// Window management
GET_WINDOW_WORKSPACE: 'window:getWorkspace',
GET_WINDOW_MODE: 'window:getMode',
OPEN_WORKSPACE: 'window:openWorkspace',
OPEN_SESSION_IN_NEW_WINDOW: 'window:openSessionInNewWindow',
SWITCH_WORKSPACE: 'window:switchWorkspace',
CLOSE_WINDOW: 'window:close',
// Close request events (main → renderer, for intercepting X button / Cmd+W)
WINDOW_CLOSE_REQUESTED: 'window:closeRequested',
WINDOW_CONFIRM_CLOSE: 'window:confirmClose',
// Traffic light visibility (macOS only - hide when fullscreen overlays are open)
WINDOW_SET_TRAFFIC_LIGHTS: 'window:setTrafficLights',
// Events from main to renderer
SESSION_EVENT: 'session:event',
// File operations
READ_FILE: 'file:read',
READ_FILE_DATA_URL: 'file:readDataUrl',
READ_FILE_BINARY: 'file:readBinary',
OPEN_FILE_DIALOG: 'file:openDialog',
READ_FILE_ATTACHMENT: 'file:readAttachment',
STORE_ATTACHMENT: 'file:storeAttachment',
GENERATE_THUMBNAIL: 'file:generateThumbnail',
// Filesystem search (for @ mention file selection)
FS_SEARCH: 'fs:search',
// Debug logging from renderer → main log file
DEBUG_LOG: 'debug:log',
// Session info panel
GET_SESSION_FILES: 'sessions:getFiles',
GET_SESSION_NOTES: 'sessions:getNotes',
SET_SESSION_NOTES: 'sessions:setNotes',
WATCH_SESSION_FILES: 'sessions:watchFiles', // Start watching session directory
UNWATCH_SESSION_FILES: 'sessions:unwatchFiles', // Stop watching
SESSION_FILES_CHANGED: 'sessions:filesChanged', // Event: main → renderer
// Theme
GET_SYSTEM_THEME: 'theme:getSystemPreference',
SYSTEM_THEME_CHANGED: 'theme:systemChanged',
// System
GET_VERSIONS: 'system:versions',
GET_HOME_DIR: 'system:homeDir',
IS_DEBUG_MODE: 'system:isDebugMode',
// Auto-update
UPDATE_CHECK: 'update:check',
UPDATE_GET_INFO: 'update:getInfo',
UPDATE_INSTALL: 'update:install',
UPDATE_DISMISS: 'update:dismiss', // Dismiss update for this version (persists across restarts)
UPDATE_GET_DISMISSED: 'update:getDismissed', // Get dismissed version
UPDATE_AVAILABLE: 'update:available', // main → renderer broadcast
UPDATE_DOWNLOAD_PROGRESS: 'update:downloadProgress', // main → renderer broadcast
// Shell operations (open external URLs/files)
OPEN_URL: 'shell:openUrl',
OPEN_FILE: 'shell:openFile',
SHOW_IN_FOLDER: 'shell:showInFolder',
// Menu actions (main → renderer)
MENU_NEW_CHAT: 'menu:newChat',
MENU_NEW_WINDOW: 'menu:newWindow',
MENU_OPEN_SETTINGS: 'menu:openSettings',
MENU_KEYBOARD_SHORTCUTS: 'menu:keyboardShortcuts',
// Deep link navigation (main → renderer, for external craftagents:// URLs)
DEEP_LINK_NAVIGATE: 'deeplink:navigate',
// Auth
LOGOUT: 'auth:logout',
SHOW_LOGOUT_CONFIRMATION: 'auth:showLogoutConfirmation',
SHOW_DELETE_SESSION_CONFIRMATION: 'auth:showDeleteSessionConfirmation',
// Onboarding
ONBOARDING_GET_AUTH_STATE: 'onboarding:getAuthState',
ONBOARDING_VALIDATE_MCP: 'onboarding:validateMcp',
ONBOARDING_START_MCP_OAUTH: 'onboarding:startMcpOAuth',
ONBOARDING_SAVE_CONFIG: 'onboarding:saveConfig',
// Claude OAuth (two-step flow)
ONBOARDING_START_CLAUDE_OAUTH: 'onboarding:startClaudeOAuth',
ONBOARDING_EXCHANGE_CLAUDE_CODE: 'onboarding:exchangeClaudeCode',
ONBOARDING_HAS_CLAUDE_OAUTH_STATE: 'onboarding:hasClaudeOAuthState',
ONBOARDING_CLEAR_CLAUDE_OAUTH_STATE: 'onboarding:clearClaudeOAuthState',
// Settings - API Setup
SETTINGS_GET_API_SETUP: 'settings:getApiSetup',
SETTINGS_UPDATE_API_SETUP: 'settings:updateApiSetup',
SETTINGS_TEST_API_CONNECTION: 'settings:testApiConnection',
// Settings - Model
SETTINGS_GET_MODEL: 'settings:getModel',
SETTINGS_SET_MODEL: 'settings:setModel',
SESSION_GET_MODEL: 'session:getModel',
SESSION_SET_MODEL: 'session:setModel',
// Folder dialog (for selecting working directory)
OPEN_FOLDER_DIALOG: 'dialog:openFolder',
// User Preferences
PREFERENCES_READ: 'preferences:read',
PREFERENCES_WRITE: 'preferences:write',
// Session Drafts (input text persisted across app restarts)
DRAFTS_GET: 'drafts:get',
DRAFTS_SET: 'drafts:set',
DRAFTS_DELETE: 'drafts:delete',
DRAFTS_GET_ALL: 'drafts:getAll',
// Sources (workspace-scoped)
SOURCES_GET: 'sources:get',
SOURCES_CREATE: 'sources:create',
SOURCES_DELETE: 'sources:delete',
SOURCES_START_OAUTH: 'sources:startOAuth',
SOURCES_SAVE_CREDENTIALS: 'sources:saveCredentials',
SOURCES_CHANGED: 'sources:changed',
// Source permissions config
SOURCES_GET_PERMISSIONS: 'sources:getPermissions',
// Workspace permissions config (for Explore mode)
WORKSPACE_GET_PERMISSIONS: 'workspace:getPermissions',
// Default permissions from ~/.kata-cli/agent/permissions/default.json
DEFAULT_PERMISSIONS_GET: 'permissions:getDefaults',
// Broadcast when default permissions change (file watcher)
DEFAULT_PERMISSIONS_CHANGED: 'permissions:defaultsChanged',
// MCP tools listing
SOURCES_GET_MCP_TOOLS: 'sources:getMcpTools',
// Skills (workspace-scoped)
SKILLS_GET: 'skills:get',
SKILLS_GET_FILES: 'skills:getFiles',
SKILLS_DELETE: 'skills:delete',
SKILLS_OPEN_EDITOR: 'skills:openEditor',
SKILLS_OPEN_FINDER: 'skills:openFinder',
SKILLS_CHANGED: 'skills:changed',
// Status management (workspace-scoped)
STATUSES_LIST: 'statuses:list',
STATUSES_REORDER: 'statuses:reorder', // Reorder statuses (drag-and-drop)
STATUSES_CHANGED: 'statuses:changed', // Broadcast event
// Label management (workspace-scoped)
LABELS_LIST: 'labels:list',
LABELS_CREATE: 'labels:create',
LABELS_DELETE: 'labels:delete',
LABELS_CHANGED: 'labels:changed', // Broadcast event
// Views management (workspace-scoped, stored in views.json)
VIEWS_LIST: 'views:list',
VIEWS_SAVE: 'views:save',
// Theme management (cascading: app → workspace)
THEME_APP_CHANGED: 'theme:appChanged', // Broadcast event
// Generic workspace image loading/saving (for icons, etc.)
WORKSPACE_READ_IMAGE: 'workspace:readImage',
WORKSPACE_WRITE_IMAGE: 'workspace:writeImage',
// Workspace settings (per-workspace configuration)
WORKSPACE_SETTINGS_GET: 'workspaceSettings:get',
WORKSPACE_SETTINGS_UPDATE: 'workspaceSettings:update',
// Theme (app-level only)
THEME_GET_APP: 'theme:getApp',
THEME_GET_PRESETS: 'theme:getPresets',
THEME_LOAD_PRESET: 'theme:loadPreset',
THEME_GET_COLOR_THEME: 'theme:getColorTheme',
THEME_SET_COLOR_THEME: 'theme:setColorTheme',
THEME_BROADCAST_PREFERENCES: 'theme:broadcastPreferences', // Send preferences to main for broadcast
THEME_PREFERENCES_CHANGED: 'theme:preferencesChanged', // Broadcast: preferences changed in another window
// Tool icon mappings (for Appearance settings)
TOOL_ICONS_GET_MAPPINGS: 'toolIcons:getMappings',
// Logo URL resolution (uses Node.js filesystem cache)
LOGO_GET_URL: 'logo:getUrl',
// Notifications
NOTIFICATION_SHOW: 'notification:show',
NOTIFICATION_NAVIGATE: 'notification:navigate', // Broadcast: { workspaceId, sessionId }
NOTIFICATION_GET_ENABLED: 'notification:getEnabled',
NOTIFICATION_SET_ENABLED: 'notification:setEnabled',
BADGE_UPDATE: 'badge:update',
BADGE_CLEAR: 'badge:clear',
BADGE_SET_ICON: 'badge:setIcon',
BADGE_DRAW: 'badge:draw', // Broadcast: { count: number, iconDataUrl: string }
WINDOW_FOCUS_STATE: 'window:focusState', // Broadcast: boolean (isFocused)
WINDOW_GET_FOCUS_STATE: 'window:getFocusState',
// Git operations
/** @deprecated Use GIT_STATUS instead. Kept for backward compatibility. */
GET_GIT_BRANCH: 'git:getBranch',
GIT_STATUS: 'git:status', // Full GitState (async)
PR_STATUS: 'pr:status', // PR info for current branch (async)
// Git real-time events (main -> renderer broadcast)
GIT_STATUS_CHANGED: 'git:statusChanged', // Payload: workspaceDir string
// Daemon management
DAEMON_START: 'daemon:start',
DAEMON_STOP: 'daemon:stop',
DAEMON_STATUS: 'daemon:status',
// Daemon events (main -> renderer broadcast)
DAEMON_STATE_CHANGED: 'daemon:stateChanged',
DAEMON_EVENT: 'daemon:event',
// Channel configuration (workspace-scoped)
CHANNELS_GET: 'channels:get',
CHANNELS_UPDATE: 'channels:update',
CHANNELS_DELETE: 'channels:delete',
// Channel credentials (workspace-scoped, renderer never sees raw values)
CHANNEL_CREDENTIAL_SET: 'channel-credential:set',
CHANNEL_CREDENTIAL_DELETE: 'channel-credential:delete',
CHANNEL_CREDENTIAL_EXISTS: 'channel-credential:exists',
// Git Bash (Windows)
GITBASH_CHECK: 'gitbash:check',
GITBASH_BROWSE: 'gitbash:browse',
GITBASH_SET_PATH: 'gitbash:setPath',
// Menu actions (renderer → main for window/app control)
MENU_QUIT: 'menu:quit',
MENU_MINIMIZE: 'menu:minimize',
MENU_MAXIMIZE: 'menu:maximize',
MENU_ZOOM_IN: 'menu:zoomIn',
MENU_ZOOM_OUT: 'menu:zoomOut',
MENU_ZOOM_RESET: 'menu:zoomReset',
MENU_TOGGLE_DEVTOOLS: 'menu:toggleDevTools',
MENU_UNDO: 'menu:undo',
MENU_REDO: 'menu:redo',
MENU_CUT: 'menu:cut',
MENU_COPY: 'menu:copy',
MENU_PASTE: 'menu:paste',
MENU_SELECT_ALL: 'menu:selectAll',
} as const
// Re-import types for ElectronAPI
import type { Workspace, SessionMetadata, StoredAttachment as StoredAttachmentType } from '@kata/core/types';
/** Tool icon mapping entry from tool-icons.json (with icon resolved to data URL) */
export interface ToolIconMapping {
id: string
displayName: string
/** Data URL of the icon (e.g., data:image/png;base64,...) */
iconDataUrl: string
commands: string[]
}
// Type-safe IPC API exposed to renderer
export interface ElectronAPI {
// Session management
getSessions(): Promise<Session[]>
getSessionMessages(sessionId: string): Promise<Session | null>
createSession(workspaceId: string, options?: CreateSessionOptions): Promise<Session>
deleteSession(sessionId: string): Promise<void>
sendMessage(sessionId: string, message: string, attachments?: FileAttachment[], storedAttachments?: StoredAttachmentType[], options?: SendMessageOptions): Promise<void>
cancelProcessing(sessionId: string, silent?: boolean): Promise<void>
killShell(sessionId: string, shellId: string): Promise<{ success: boolean; error?: string }>
getTaskOutput(taskId: string): Promise<string | null>
respondToPermission(sessionId: string, requestId: string, allowed: boolean, alwaysAllow: boolean): Promise<boolean>
respondToCredential(sessionId: string, requestId: string, response: CredentialResponse): Promise<boolean>
// Consolidated session command handler
sessionCommand(sessionId: string, command: SessionCommand): Promise<void | ShareResult | RefreshTitleResult>
// Pending plan execution (for reload recovery)
getPendingPlanExecution(sessionId: string): Promise<{ planPath: string; awaitingCompaction: boolean } | null>
// Workspace management
getWorkspaces(): Promise<Workspace[]>
createWorkspace(folderPath: string, name: string): Promise<Workspace>
checkWorkspaceSlug(slug: string): Promise<{ exists: boolean; path: string }>
// Window management
getWindowWorkspace(): Promise<string | null>
getWindowMode(): Promise<string | null>
openWorkspace(workspaceId: string): Promise<void>
openSessionInNewWindow(workspaceId: string, sessionId: string): Promise<void>
switchWorkspace(workspaceId: string): Promise<void>
closeWindow(): Promise<void>
confirmCloseWindow(): Promise<void>
/** Listen for close requests (X button, Cmd+W). Returns cleanup function. */
onCloseRequested(callback: () => void): () => void
/** Show/hide macOS traffic light buttons (for fullscreen overlays) */
setTrafficLightsVisible(visible: boolean): Promise<void>
// Event listeners
onSessionEvent(callback: (event: SessionEvent) => void): () => void
// File operations
readFile(path: string): Promise<string>
/** Read a file as a data URL (data:{mime};base64,...) for binary preview (images, PDFs) */
readFileDataUrl(path: string): Promise<string>
openFileDialog(): Promise<string[]>
readFileAttachment(path: string): Promise<FileAttachment | null>
storeAttachment(sessionId: string, attachment: FileAttachment): Promise<import('../../../../packages/core/src/types/index.ts').StoredAttachment>
generateThumbnail(base64: string, mimeType: string): Promise<string | null>
// Filesystem search (for @ mention file selection)
searchFiles(basePath: string, query: string): Promise<FileSearchResult[]>
// Debug: send renderer logs to main process log file
debugLog(...args: unknown[]): void
// Theme
getSystemTheme(): Promise<boolean>
onSystemThemeChange(callback: (isDark: boolean) => void): () => void
// System
getVersions(): { node: string; chrome: string; electron: string }
getHomeDir(): Promise<string>
isDebugMode(): Promise<boolean>
// Auto-update
checkForUpdates(): Promise<UpdateInfo>
getUpdateInfo(): Promise<UpdateInfo>
installUpdate(): Promise<void>
dismissUpdate(version: string): Promise<void>
getDismissedUpdateVersion(): Promise<string | null>
onUpdateAvailable(callback: (info: UpdateInfo) => void): () => void
onUpdateDownloadProgress(callback: (progress: number) => void): () => void
// Shell operations
openUrl(url: string): Promise<void>
openFile(path: string): Promise<void>
showInFolder(path: string): Promise<void>
// Menu event listeners
onMenuNewChat(callback: () => void): () => void
onMenuOpenSettings(callback: () => void): () => void
onMenuKeyboardShortcuts(callback: () => void): () => void
// Deep link navigation listener (for external craftagents:// URLs)
onDeepLinkNavigate(callback: (nav: DeepLinkNavigation) => void): () => void
// Auth
showLogoutConfirmation(): Promise<boolean>
showDeleteSessionConfirmation(name: string): Promise<boolean>
logout(): Promise<void>
// Onboarding
getAuthState(): Promise<AuthState>
getSetupNeeds(): Promise<SetupNeeds>
startWorkspaceMcpOAuth(mcpUrl: string): Promise<OAuthResult & { accessToken?: string; clientId?: string }>
saveOnboardingConfig(config: {
authType?: AuthType // Optional - if not provided, preserves existing auth type (for add workspace)
workspace?: { name: string; iconUrl?: string; mcpUrl?: string } // Optional - if not provided, only updates billing
credential?: string // API key or OAuth token based on authType
mcpCredentials?: { accessToken: string; clientId?: string } // MCP OAuth credentials
anthropicBaseUrl?: string | null // Custom Anthropic API base URL
customModel?: string | null // Custom model ID override
}): Promise<OnboardingSaveResult>
// Claude OAuth (two-step flow)
startClaudeOAuth(): Promise<{ success: boolean; authUrl?: string; error?: string }>
exchangeClaudeCode(code: string): Promise<ClaudeOAuthResult>
hasClaudeOAuthState(): Promise<boolean>
clearClaudeOAuthState(): Promise<{ success: boolean }>
// Settings - API Setup
getApiSetup(): Promise<ApiSetupInfo>
updateApiSetup(authType: AuthType, credential?: string, anthropicBaseUrl?: string | null, customModel?: string | null): Promise<void>
testApiConnection(apiKey: string, baseUrl?: string, modelName?: string): Promise<{ success: boolean; error?: string; modelCount?: number }>
// Settings - Model (global default)
getModel(): Promise<string | null>
setModel(model: string): Promise<void>
// Session-specific model (overrides global)
getSessionModel(sessionId: string, workspaceId: string): Promise<string | null>
setSessionModel(sessionId: string, workspaceId: string, model: string | null): Promise<void>
// Workspace Settings (per-workspace configuration)
getWorkspaceSettings(workspaceId: string): Promise<WorkspaceSettings | null>
updateWorkspaceSetting<K extends keyof WorkspaceSettings>(workspaceId: string, key: K, value: WorkspaceSettings[K]): Promise<void>
// Folder dialog
openFolderDialog(): Promise<string | null>
// User Preferences
readPreferences(): Promise<{ content: string; exists: boolean; path: string }>
writePreferences(content: string): Promise<{ success: boolean; error?: string }>
// Session Drafts (persisted input text)
getDraft(sessionId: string): Promise<string | null>
setDraft(sessionId: string, text: string): Promise<void>
deleteDraft(sessionId: string): Promise<void>
getAllDrafts(): Promise<Record<string, string>>
// Session Info Panel
getSessionFiles(sessionId: string): Promise<SessionFile[]>
getSessionNotes(sessionId: string): Promise<string>
setSessionNotes(sessionId: string, content: string): Promise<void>
watchSessionFiles(sessionId: string): Promise<void>
unwatchSessionFiles(): Promise<void>
onSessionFilesChanged(callback: (sessionId: string) => void): () => void
// Sources
getSources(workspaceId: string): Promise<LoadedSource[]>
createSource(workspaceId: string, config: Partial<FolderSourceConfig>): Promise<FolderSourceConfig>
deleteSource(workspaceId: string, sourceSlug: string): Promise<void>
startSourceOAuth(workspaceId: string, sourceSlug: string): Promise<{ success: boolean; error?: string; accessToken?: string }>
saveSourceCredentials(workspaceId: string, sourceSlug: string, credential: string): Promise<void>
getSourcePermissionsConfig(workspaceId: string, sourceSlug: string): Promise<import('@kata/shared/agent').PermissionsConfigFile | null>
getWorkspacePermissionsConfig(workspaceId: string): Promise<import('@kata/shared/agent').PermissionsConfigFile | null>
getDefaultPermissionsConfig(): Promise<{ config: import('@kata/shared/agent').PermissionsConfigFile | null; path: string }>
getMcpTools(workspaceId: string, sourceSlug: string): Promise<McpToolsResult>
// Sources change listener (live updates when sources are added/removed)
onSourcesChanged(callback: (sources: LoadedSource[]) => void): () => void
// Default permissions change listener (live updates when default.json changes)
onDefaultPermissionsChanged(callback: () => void): () => void
// Skills
getSkills(workspaceId: string): Promise<LoadedSkill[]>
getSkillFiles?(workspaceId: string, skillSlug: string): Promise<SkillFile[]>
deleteSkill(workspaceId: string, skillSlug: string): Promise<void>
openSkillInEditor(workspaceId: string, skillSlug: string): Promise<void>
openSkillInFinder(workspaceId: string, skillSlug: string): Promise<void>
// Skills change listener (live updates when skills are added/removed/modified)
onSkillsChanged(callback: (skills: LoadedSkill[]) => void): () => void
// Statuses (workspace-scoped)
listStatuses(workspaceId: string): Promise<import('@kata/shared/statuses').StatusConfig[]>
reorderStatuses(workspaceId: string, orderedIds: string[]): Promise<void>
// Statuses change listener (live updates when statuses config or icon files change)
onStatusesChanged(callback: (workspaceId: string) => void): () => void
// Labels (workspace-scoped)
listLabels(workspaceId: string): Promise<import('@kata/shared/labels').LabelConfig[]>
createLabel(workspaceId: string, input: import('@kata/shared/labels').CreateLabelInput): Promise<import('@kata/shared/labels').LabelConfig>
deleteLabel(workspaceId: string, labelId: string): Promise<{ stripped: number }>
// Labels change listener (live updates when labels config changes)
onLabelsChanged(callback: (workspaceId: string) => void): () => void
// Views (workspace-scoped, stored in views.json)
listViews(workspaceId: string): Promise<import('@kata/shared/views').ViewConfig[]>
saveViews(workspaceId: string, views: import('@kata/shared/views').ViewConfig[]): Promise<void>
// Generic workspace image loading/saving (returns data URL for images, raw string for SVG)
readWorkspaceImage(workspaceId: string, relativePath: string): Promise<string>
writeWorkspaceImage(workspaceId: string, relativePath: string, base64: string, mimeType: string): Promise<void>
// Tool icon mappings (for Appearance settings page)
getToolIconMappings(): Promise<ToolIconMapping[]>
// Theme (app-level only)
getAppTheme(): Promise<import('@config/theme').ThemeOverrides | null>
// Preset themes (app-level)
loadPresetThemes(): Promise<import('@config/theme').PresetTheme[]>
loadPresetTheme(themeId: string): Promise<import('@config/theme').PresetTheme | null>
getColorTheme(): Promise<string>
setColorTheme(themeId: string): Promise<void>
// Theme change listeners (live updates when theme.json files change)
onAppThemeChange(callback: (theme: import('@config/theme').ThemeOverrides | null) => void): () => void
// Logo URL resolution (uses Node.js filesystem cache for provider domains)
getLogoUrl(serviceUrl: string, provider?: string): Promise<string | null>
// Notifications
showNotification(title: string, body: string, workspaceId: string, sessionId: string): Promise<void>
getNotificationsEnabled(): Promise<boolean>
setNotificationsEnabled(enabled: boolean): Promise<void>
updateBadgeCount(count: number): Promise<void>
clearBadgeCount(): Promise<void>
setDockIconWithBadge(dataUrl: string): Promise<void>
onBadgeDraw(callback: (data: { count: number; iconDataUrl: string }) => void): () => void
getWindowFocusState(): Promise<boolean>
onWindowFocusChange(callback: (isFocused: boolean) => void): () => void
onNotificationNavigate(callback: (data: { workspaceId: string; sessionId: string }) => void): () => void
// Theme preferences sync across windows (mode, colorTheme, font)
broadcastThemePreferences(preferences: { mode: string; colorTheme: string; font: string }): Promise<void>
onThemePreferencesChange(callback: (preferences: { mode: string; colorTheme: string; font: string }) => void): () => void
// Git operations
/** @deprecated Use getGitStatus instead. Returns branch string only, no detached HEAD info. */
getGitBranch(dirPath: string): Promise<string | null>
getGitStatus(dirPath: string): Promise<GitState>
getPrStatus(dirPath: string): Promise<PrInfo | null>
// Daemon management
getDaemonStatus(): Promise<DaemonManagerState>
startDaemon(): Promise<DaemonManagerState>
stopDaemon(): Promise<DaemonManagerState>
onDaemonStateChanged(callback: (state: DaemonManagerState) => void): () => void
onDaemonEvent(callback: (event: import('@kata/core/types').DaemonEvent) => void): () => void
// Channel configuration (workspace-scoped)
getChannels(workspaceId: string): Promise<import('@kata/shared/channels').ChannelConfig[]>
updateChannel(workspaceId: string, config: import('@kata/shared/channels').ChannelConfig): Promise<void>