diff --git a/apps/android/src/state/store-state.ts b/apps/android/src/state/store-state.ts new file mode 100644 index 0000000..69e5598 --- /dev/null +++ b/apps/android/src/state/store-state.ts @@ -0,0 +1,279 @@ +import type { AgentAcpFrameData } from '@dsh-remote/protocol' +import type { AppLanguage, LanguagePreference } from '../locales/i18n' +import type { OAuthProviderInfo, OAuthQrPollResult, OAuthQrSession } from '../services/api' +import type { + AgentBackend, + AgentPresetOption, + ChatItem, + ChatMessage, + ConnectionNetworkDetails, + ConnectionProbeTransport, + ConnectionSnapshot, + ConnectionStage, + DefaultPermissionPreset, + DeviceIdentity, + HostDescriptor, + ModelSelection, + MuxStreamFrame, + PromptImage, + RedirectLoginMethod, + RemoteDevice, + RemoteSession, + ScheduleCatalogEntry, + ScheduleCreateRequest, + ScheduleDeliveryRecord, + ScheduleRecord, + ScheduleTimingChange, + ScheduleUpdateRequest, + ScheduleUpdateResult, + SendMessageResult, + ServerConfig, + SessionModels, + TransportPreference, + WorkspaceShortcut, + WorkspaceView, +} from '../types' +import type { ActivityDockMode, ThemePreference, TypographyDensity } from '../ui/theme' + +type BootPhase = 'loading' | 'ready' | 'error' + +type AuthPhase = 'idle' | 'authenticating' | 'complete' | 'error' + +/** Provider discovery result for QR sign-in; the Base URL is already normalized. */ +export interface QrProviderList { + baseUrl: string + providers: OAuthProviderInfo[] +} + +/** A QR sign-in session bound to the Server and provider that created it. */ +export interface QrLoginStart { + baseUrl: string + provider: OAuthProviderInfo + session: OAuthQrSession +} + +export interface AppState { + bootPhase: BootPhase + config?: ServerConfig + identity?: DeviceIdentity + account?: string + devices: RemoteDevice[] + selectedDevice?: RemoteDevice + connection: ConnectionSnapshot + connectionStage?: ConnectionStage + connectionProbeOrder: ConnectionProbeTransport[] + connectionNetworkDetails?: ConnectionNetworkDetails + hostDescriptor?: HostDescriptor + codexAvailable: boolean + cursorAvailable: boolean + antigravityAvailable: boolean + piAvailable: boolean + opencodeAvailable: boolean + claudeAvailable: boolean + hermesAvailable: boolean + workspaceCatalog?: { backend: AgentBackend; loading: boolean; error?: string } + workspaces: WorkspaceView[] + favoriteWorkspaces: WorkspaceShortcut[] + /** Newest first; the home screen falls back to these when Favorites is empty. */ + recentWorkspaces: WorkspaceShortcut[] + archivedSessionIds: string[] + pinnedSessionIds: string[] + sessions: RemoteSession[] + selectedSession?: RemoteSession + /** History and the current connection's Codex event subscription are ready. */ + codexReadySessionId?: string + /** Successfully opened in this remote-use lifecycle; retained across transport recovery. */ + currentWorkSessionIds: string[] + messages: Record + sessionLifecycles: Record + sessionProjectionSeqs: Record> + feedbackBySession: Record> + sessionModels?: SessionModels + modelSelecting: boolean + permissionSelecting: boolean + agentPresetOptions?: AgentPresetOption[] + agentPresetLoading: boolean + agentPresetSelecting: boolean + historyHasMore: boolean + historyLoadingOlder: boolean + oldestLoadedSeq?: number + previewImageUri?: string + setPreviewImageUri(uri?: string): void + transportPreference: TransportPreference + /** + * Until this timestamp, connections to the current host skip WebRTC and go + * straight to the relay data plane. Set when an established P2P path drops + * or WebRTC negotiation keeps failing; expires so 'auto' can retry P2P. + */ + relayOnlyUntil?: number + compactHistory: boolean + setCompactHistory(value: boolean): Promise + languagePreference: LanguagePreference + language: AppLanguage + statusBarVisible: boolean + themePreference: ThemePreference + typographyDensity: TypographyDensity + activityDockMode: ActivityDockMode + defaultPermissionPreset: DefaultPermissionPreset + pendingOAuthBaseUrl?: string + pendingOAuthLoginMethod?: RedirectLoginMethod + scheduleTasks: ScheduleCatalogEntry[] + scheduleLoading: boolean + scheduleError?: string + authPhase: AuthPhase + refreshing: boolean + busyAction?: string + error?: string + commandResult?: { sessionId: string; text: string } + /** Remembered host from the last successful connect (persisted). */ + lastConnectedDeviceId?: string + /** + * Set during bootstrap when that host is trusted + online. Retained for the + * auto-connect entry point; boot routing currently lands on the device list. + */ + pendingAutoConnectDeviceId?: string + /** True when credentials are invalid and the UI should show the sign-in screen. */ + reauthRequired: boolean + + loadScheduleTasks(): Promise + createScheduleTask(sessionId: string, request: ScheduleCreateRequest): Promise + updateScheduleTask(sessionId: string, id: string, expected: ScheduleRecord, options?: { change?: ScheduleTimingChange; title?: string; prompt?: string }): Promise + toggleScheduleTask(task: ScheduleCatalogEntry): Promise + deleteScheduleTask(sessionId: string, id: string): Promise + loadScheduleHistory(sessionId: string, id: string): Promise + bootstrap(): Promise + requireReauth(message?: string): Promise + consumePendingAutoConnect(): string | undefined + selectServer(input: string): Promise + configureServer(input: string, email: string, password: string): Promise + startOAuth(input: string): Promise + startGithubOAuth(input: string): Promise + startGoogleOAuth(input: string): Promise + completeOAuth(token: string): Promise + listLoginProviders(input: string): Promise + listQrProviders(input: string): Promise + startQrLogin(input: string, providerId: string): Promise + pollQrLogin(baseUrl: string, qrId: string): Promise + completeQrLogin(baseUrl: string, token: string, method: RedirectLoginMethod): Promise + refreshDevices(): Promise + refreshWorkspaces(backend?: AgentBackend): Promise + refreshSessionStatus(): Promise + refreshConnectionNetworkDetails(): Promise + resumeConnection(): Promise + trustDevice(device: RemoteDevice): Promise + forgetDevice(deviceId: string): Promise + renameDevice(deviceId: string, name: string): Promise + connectDevice(device: RemoteDevice, options?: { forceRelay?: boolean }): Promise + reconnect(options?: { forceRelay?: boolean; restoreSession?: boolean }): Promise + disconnect(): Promise + openSession(session: RemoteSession): Promise + sendMessage(text: string, images?: PromptImage[], reuseRpcId?: string): Promise + retrySendMessage(itemId: string): Promise + updateQueueItem(itemId: string, action: 'remove' | 'steer', rpcId?: string): Promise + forkChatMessage(message: ChatMessage): Promise + quoteChatMessage(text: string, sessionId?: string): void + rateMessage(message: ChatMessage, rating: 'positive' | 'negative'): Promise + stopSession(): Promise + respondApproval(itemId: string, outcome: 'allowed-once' | 'rejected'): Promise + respondQuestion(itemId: string, selected: Record, custom?: Record): Promise + createSession(workspaceId?: string, backend?: AgentBackend): Promise + forkSession(sessionId: string, backend?: RemoteSession['backend']): Promise + archiveSession(sessionId: string): Promise + unarchiveSession(sessionId: string, backend?: RemoteSession['backend']): Promise + pinSession(sessionId: string, backend?: RemoteSession['backend']): Promise + unpinSession(sessionId: string, backend?: RemoteSession['backend']): Promise + renameSession(sessionId: string, title: string, backend?: RemoteSession['backend']): Promise + selectModel(selection: ModelSelection): Promise + selectPermission(preset: string): Promise + loadAgentPresets(): Promise + selectAgentPreset(preset: string): Promise + loadOlderHistory(): Promise + workspaceCreate(path: string, backend?: 'harness' | 'codex' | 'cursor' | 'antigravity' | 'pi' | 'opencode' | 'claude' | 'hermes'): Promise + workspaceRename(workspaceId: string, title: string): Promise + workspaceDelete(workspaceId: string): Promise + workspaceMove(workspaceId: string, beforeWorkspaceId?: string): Promise + /** Toggle the home-screen shortcut for a workspace; resolves to its new favorited state. */ + toggleFavoriteWorkspace(workspace: WorkspaceView): Promise + removeFavoriteWorkspace(deviceId: string, key: string): Promise + /** Open the most recently updated conversation of a saved workspace; undefined when it has none. */ + openFavoriteWorkspaceSession(key: string): Promise + hostListDirectory(path?: string): Promise + setTransportPreference(preference: TransportPreference): Promise + setLanguagePreference(preference: LanguagePreference): Promise + setStatusBarVisible(visible: boolean): Promise + setThemePreference(preference: ThemePreference): Promise + setTypographyDensity(density: TypographyDensity): Promise + setActivityDockMode(mode: ActivityDockMode): Promise + setDefaultPermissionPreset(preset: DefaultPermissionPreset): Promise + syncSystemLocales(localeTags: readonly string[]): void + resetLocalData(): Promise + signOut(): Promise + setOffline(): void + clearError(): void + handleMuxFrame(frame: MuxStreamFrame): void + handleCodexFrame(frame: { method: string; params: unknown }): void + handleCodexFrames(frames: { method: string; params: unknown }[]): void + handleCursorFrame(frame: AgentAcpFrameData): void +} + +export const disconnected: ConnectionSnapshot = { + phase: 'disconnected', + stats: { mode: 'Disconnected', connected: false }, +} + +export function initialData(): Pick { + return { + config: undefined, + account: undefined, + devices: [], + selectedDevice: undefined, + connection: disconnected, + connectionProbeOrder: [], + connectionNetworkDetails: undefined, + hostDescriptor: undefined, + codexAvailable: false, + cursorAvailable: false, + antigravityAvailable: false, + piAvailable: false, + opencodeAvailable: false, + claudeAvailable: false, + hermesAvailable: false, + workspaceCatalog: undefined, + workspaces: [], + favoriteWorkspaces: [], + recentWorkspaces: [], + archivedSessionIds: [], + pinnedSessionIds: [], + sessions: [], + selectedSession: undefined, + codexReadySessionId: undefined, + currentWorkSessionIds: [], + messages: {}, + sessionLifecycles: {}, + sessionProjectionSeqs: {}, + feedbackBySession: {}, + commandResult: undefined, + sessionModels: undefined, + modelSelecting: false, + permissionSelecting: false, + historyHasMore: false, + historyLoadingOlder: false, + oldestLoadedSeq: undefined, + transportPreference: 'auto', + authPhase: 'idle', + refreshing: false, + busyAction: undefined, + error: undefined, + reauthRequired: false, + } +} + +/** Shared action signatures; the connection and stream lifecycle remain owned by SessionRuntime. */ +export interface StoreAccess { + get: () => AppState + set: (partial: Partial | ((state: AppState) => Partial)) => void +}