fix desktop copilot fallback inside electron

This commit is contained in:
dirtydishes 2026-05-20 18:37:57 -04:00
parent 1543f419e6
commit 7b87f976a2
5 changed files with 751 additions and 94 deletions

View file

@ -29,6 +29,12 @@ type DesktopAiBridge = {
};
};
type DesktopAiRuntime = {
shellAvailable: boolean;
bridgeAvailable: boolean;
bridge: DesktopAiBridge | null;
};
declare global {
interface Window {
islandflowDesktop?: DesktopAiBridge;
@ -37,6 +43,7 @@ declare global {
type DesktopAiContextValue = {
bridgeAvailable: boolean;
shellAvailable: boolean;
state: IslandflowAiState;
loginWithBrowser: () => Promise<void>;
loginWithDeviceCode: () => Promise<void>;
@ -48,69 +55,113 @@ type DesktopAiContextValue = {
runTask: (request: IslandflowAiTaskRequest) => Promise<{ taskId: string }>;
};
const createUnavailableState = (): IslandflowAiState => ({
desktopAvailable: false,
transportStatus: "stopped",
transportError: "Desktop AI is only available inside the Islandflow Electron app.",
profiles: [
{
id: "managed-chatgpt",
label: "Managed ChatGPT login",
description: "Available only in the desktop app.",
mode: "managed-chatgpt",
enabled: false,
selected: true,
statusLabel: "Desktop only"
}
],
selectedProfileId: "managed-chatgpt",
account: {
loggedIn: false,
email: null,
planType: null,
authMode: null,
requiresOpenaiAuth: true,
login: {
status: "idle",
message: "Open Islandflow Desktop to connect a ChatGPT or Codex account."
}
},
preferences: {
model: null,
reasoningEffort: "high"
},
models: [],
rateLimitsByLimitId: {},
usage: {
today: {
breakdown: {
totalTokens: 0,
inputTokens: 0,
cachedInputTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0
},
normalizedCostUsd: 0,
turnCount: 0,
activeDays: 0
const BRIDGE_POLL_INTERVAL_MS = 250;
const BRIDGE_POLL_MAX_ATTEMPTS = 20;
const ELECTRON_USER_AGENT_PATTERN = /\bElectron\/\S+/i;
export const detectDesktopShell = (userAgent: string | null | undefined): boolean =>
Boolean(userAgent && ELECTRON_USER_AGENT_PATTERN.test(userAgent));
export const resolveDesktopAiRuntime = (
value:
| {
islandflowDesktop?: DesktopAiBridge;
navigator?: { userAgent?: string | null };
}
| null
| undefined
): DesktopAiRuntime => {
const bridge = value?.islandflowDesktop?.ai ? value.islandflowDesktop : null;
const bridgeAvailable = Boolean(bridge?.ai);
const shellAvailable = bridgeAvailable || detectDesktopShell(value?.navigator?.userAgent);
return {
shellAvailable,
bridgeAvailable,
bridge
};
};
export const createUnavailableState = (runtime?: Partial<DesktopAiRuntime>): IslandflowAiState => {
const shellAvailable = Boolean(runtime?.shellAvailable || runtime?.bridgeAvailable);
const bridgeAvailable = Boolean(runtime?.bridgeAvailable);
const transportError = !shellAvailable
? "Desktop AI is only available inside the Islandflow Electron app."
: bridgeAvailable
? "The desktop AI bridge loaded, but its initial state could not be read."
: "Islandflow Desktop is open, but the native AI bridge is unavailable in this session.";
const loginMessage = !shellAvailable
? "Open Islandflow Desktop to connect a ChatGPT or Codex account."
: bridgeAvailable
? "The desktop bridge connected, but its initial state did not load. Retry the action or restart Islandflow if this persists."
: "This desktop window is missing its native AI bridge. Reload the window or restart Islandflow if this persists.";
return {
desktopAvailable: shellAvailable,
transportStatus: shellAvailable ? "error" : "stopped",
transportError,
profiles: [
{
id: "managed-chatgpt",
label: "Managed ChatGPT login",
description: shellAvailable
? "Managed ChatGPT login belongs to the desktop shell, but this window is not connected to the native bridge yet."
: "Available only in the desktop app.",
mode: "managed-chatgpt",
enabled: shellAvailable,
selected: true,
statusLabel: shellAvailable ? "Bridge unavailable" : "Desktop only"
}
],
selectedProfileId: "managed-chatgpt",
account: {
loggedIn: false,
email: null,
planType: null,
authMode: null,
requiresOpenaiAuth: true,
login: {
status: "idle",
message: loginMessage
}
},
lifetime: {
breakdown: {
totalTokens: 0,
inputTokens: 0,
cachedInputTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0
},
normalizedCostUsd: 0,
turnCount: 0,
activeDays: 0
preferences: {
model: null,
reasoningEffort: "high"
},
recentTurns: []
},
tasks: [],
updatedAt: Date.now()
});
models: [],
rateLimitsByLimitId: {},
usage: {
today: {
breakdown: {
totalTokens: 0,
inputTokens: 0,
cachedInputTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0
},
normalizedCostUsd: 0,
turnCount: 0,
activeDays: 0
},
lifetime: {
breakdown: {
totalTokens: 0,
inputTokens: 0,
cachedInputTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0
},
normalizedCostUsd: 0,
turnCount: 0,
activeDays: 0
},
recentTurns: []
},
tasks: [],
updatedAt: Date.now()
};
};
const DesktopAiContext = createContext<DesktopAiContextValue | null>(null);
@ -121,34 +172,81 @@ const rejectDesktopOnly = async (): Promise<never> => {
export function DesktopAiProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<IslandflowAiState>(() => createUnavailableState());
const [bridge, setBridge] = useState<DesktopAiBridge | null>(null);
const [shellAvailable, setShellAvailable] = useState(false);
useEffect(() => {
if (typeof window === "undefined") {
return;
}
const nextBridge = window.islandflowDesktop ?? null;
if (!nextBridge?.ai) {
let disposed = false;
let unsubscribe = () => {};
let pollTimer: number | null = null;
let attempts = 0;
const connectBridge = (runtime: DesktopAiRuntime): boolean => {
if (!runtime.bridge) {
return false;
}
setShellAvailable(runtime.shellAvailable);
setBridge(runtime.bridge);
void runtime.bridge.ai.getState().then(
(nextState) => {
if (!disposed) {
setState(nextState);
}
},
() => {
if (!disposed) {
setState(createUnavailableState(runtime));
}
}
);
unsubscribe = runtime.bridge.ai.subscribe((nextState) => {
if (!disposed) {
setState(nextState);
}
});
return true;
};
const syncRuntime = (): boolean => {
const runtime = resolveDesktopAiRuntime(window);
setShellAvailable(runtime.shellAvailable);
if (connectBridge(runtime)) {
return true;
}
setBridge(null);
setState(createUnavailableState());
return;
setState(createUnavailableState(runtime));
return false;
};
if (!syncRuntime()) {
const pollForBridge = () => {
if (disposed) {
return;
}
attempts += 1;
if (syncRuntime() || attempts >= BRIDGE_POLL_MAX_ATTEMPTS) {
return;
}
pollTimer = window.setTimeout(pollForBridge, BRIDGE_POLL_INTERVAL_MS);
};
pollTimer = window.setTimeout(pollForBridge, BRIDGE_POLL_INTERVAL_MS);
}
setBridge(nextBridge);
let unsubscribe = () => {};
void nextBridge.ai.getState().then(setState).catch(() => {
setState((current) => ({
...current,
transportStatus: "error",
transportError: "The desktop AI bridge could not load its initial state."
}));
});
unsubscribe = nextBridge.ai.subscribe((nextState) => {
setState(nextState);
});
return () => {
disposed = true;
if (pollTimer !== null) {
window.clearTimeout(pollTimer);
}
unsubscribe();
};
}, []);
@ -156,6 +254,7 @@ export function DesktopAiProvider({ children }: { children: ReactNode }) {
const value = useMemo<DesktopAiContextValue>(
() => ({
bridgeAvailable: Boolean(bridge?.ai),
shellAvailable,
state,
loginWithBrowser: bridge?.ai.loginWithBrowser ?? rejectDesktopOnly,
loginWithDeviceCode: bridge?.ai.loginWithDeviceCode ?? rejectDesktopOnly,
@ -164,7 +263,7 @@ export function DesktopAiProvider({ children }: { children: ReactNode }) {
updatePreferences: bridge?.ai.updatePreferences ?? rejectDesktopOnly,
runTask: bridge?.ai.runTask ?? rejectDesktopOnly
}),
[bridge, state]
[bridge, shellAvailable, state]
);
return <DesktopAiContext.Provider value={value}>{children}</DesktopAiContext.Provider>;