mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-20 15:19:16 +00:00
* fix: prevent crash when clicking external links with no default browser (#663) On systems like Tiny11 where no default browser is associated with http/https URLs, shell.openExternal() rejects with Windows error 0x483 ("No application is associated..."). The main process treated that rejection as an unhandledRejection, which the global handler re-throws as fatal, crashing the entire app. Root cause: windowManager.cjs used `void shell?.openExternal?.(url)` inside a try/catch, assuming the try would cover the call. `void` only discards the returned Promise — it does not catch async rejections, so when openExternal rejected, the error escaped as a floating unhandledRejection. The IPC handler in main.cjs (`netcatty:openExternal`) also awaited shell.openExternal() without any try/catch. Electron's ipcMain.handle forwards rejections to the renderer over IPC, but the renderer-side fallback called `window.open()`, which re-entered the same buggy windowManager path — and that is where the process actually died. Changes: - windowManager.cjs: attach an explicit `.catch` on the openExternal Promise in both createExternalOnlyWindowOpenHandler and createAppWindowOpenHandler so rejections cannot propagate. - main.cjs: wrap the IPC handler in try/catch and return a structured { success, error } result instead of throwing. This lets the renderer render an informative message. - global.d.ts: update the openExternal return type to match. - useApplicationBackend.ts: read the structured result and throw on failure so callers can react; drop the now-redundant window.open() fallback for the Electron branch (kept only for non-Electron envs). - SettingsApplicationTab.tsx: show a friendly toast ("No default browser configured — please set one in system settings") when openExternal fails, instead of the previous silent failure. - i18n: add en + zh-CN strings for the toast. Closes #663 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: fall back to in-app browser window when system has no default browser Instead of showing a toast when shell.openExternal() fails (e.g. Tiny11 with no default browser), open the URL in a minimal in-app BrowserWindow so users can still read the linked page. windowManager.cjs now exposes: - openFallbackBrowser(url, opts): creates a stripped-down BrowserWindow that loads the URL. No preload script (remote content must never touch contextBridge), contextIsolation/nodeIntegration/sandbox all set to safe defaults, and an isolated persist:netcatty-fallback-browser session so cookies and storage do not leak into the main app. Basic Alt+Left / Alt+Right / Ctrl-or-Cmd+R shortcuts for navigation and reload. - tryOpenExternalWithFallback(shell, url, opts): tries shell.openExternal first; on rejection, falls back to openFallbackBrowser. Returns { success, fallback?: "in-app-browser" }. All three external-URL call paths now route through this helper: - main.cjs netcatty:openExternal IPC handler - createExternalOnlyWindowOpenHandler (popup blocker for child windows) - createAppWindowOpenHandler (main/settings window window-open handler) The renderer-side toast is retained as a last-resort for the rare case that both system and in-app browsers fail (e.g. BrowserWindow creation error). Copy updated to reflect the new behavior. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: preserve rejection semantics for failed external opens Per Codex review on PR #676: returning { success, error } from bridge.openExternal changed the contract from "reject on failure" to "resolve with a failure object on failure", which silently broke callers that rely on rejection to abort flows. useCloudSync's OAuth path is the clearest example: it wraps bridge.openExternal in a try/catch and rejects browserPromise inside the catch. With the resolved-failure contract, that catch never fires, so Promise.race([callbackPromise, browserPromise]) can hang indefinitely when no browser is available. Revert the contract: - tryOpenExternalWithFallback resolves void on success (system browser or in-app fallback) and throws on total failure - main.cjs IPC handler awaits and lets rejections propagate - global.d.ts openExternal is Promise<void> again - useApplicationBackend just awaits — rejections propagate naturally - SettingsApplicationTab's existing try/catch + toast continues to work as before Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: propagate fallback browser loadURL failures Per Codex P2: openFallbackBrowser swallowed loadURL rejections by attaching a .catch that only logged, so any caller using tryOpenExternalWithFallback as a success signal saw an opened window as success even when the page failed to load. OAuth flows would then wait for the downstream callback timeout instead of canceling early on malformed or unreachable URLs. openFallbackBrowser now returns { window, loaded } where `loaded` is the raw loadURL Promise, and tryOpenExternalWithFallback awaits it in the fallback path. On initial load failure, the broken window is closed and the original shell.openExternal error is re-thrown. The internal popup handler inside the fallback window keeps its fire-and-forget behavior (it must return synchronously) but now explicitly catches the loaded rejection to avoid unhandledRejection. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
239 lines
8.8 KiB
TypeScript
239 lines
8.8 KiB
TypeScript
import React, { useEffect, useMemo, useState } from "react";
|
|
import { ArrowUpCircle, Bug, Check, Github, Loader2, MessageCircle, Newspaper, RefreshCcw } from "lucide-react";
|
|
import AppLogo from "./AppLogo";
|
|
import { Button } from "./ui/button";
|
|
import { cn } from "../lib/utils";
|
|
import { useApplicationBackend } from "../application/state/useApplicationBackend";
|
|
import type { UpdateState, UseUpdateCheckResult } from "../application/state/useUpdateCheck";
|
|
import { useI18n } from "../application/i18n/I18nProvider";
|
|
import { SettingsTabContent } from "./settings/settings-ui";
|
|
import { toast } from "./ui/toast";
|
|
|
|
type AppInfo = {
|
|
name: string;
|
|
version: string;
|
|
platform?: string;
|
|
};
|
|
|
|
const REPO_URL = "https://github.com/binaricat/Netcatty";
|
|
|
|
const buildIssueUrl = (appInfo: AppInfo) => {
|
|
const title = "Bug: ";
|
|
const bodyLines = [
|
|
"## Describe the problem",
|
|
"",
|
|
"## Steps to reproduce",
|
|
"1.",
|
|
"",
|
|
"## Expected behavior",
|
|
"",
|
|
"## Actual behavior",
|
|
"",
|
|
"## Environment",
|
|
`- App: ${appInfo.name} ${appInfo.version}`,
|
|
`- Platform: ${appInfo.platform || "unknown"}`,
|
|
`- UA: ${typeof navigator !== "undefined" ? navigator.userAgent : "unknown"}`,
|
|
];
|
|
const params = new URLSearchParams({
|
|
title,
|
|
body: bodyLines.join("\n"),
|
|
});
|
|
return `${REPO_URL}/issues/new?${params.toString()}`;
|
|
};
|
|
|
|
const ActionRow: React.FC<{
|
|
icon: React.ReactNode;
|
|
title: string;
|
|
subtitle: string;
|
|
onClick: () => void;
|
|
}> = ({ icon, title, subtitle, onClick }) => (
|
|
<button
|
|
type="button"
|
|
onClick={onClick}
|
|
className={cn(
|
|
"w-full flex items-center gap-3 rounded-lg px-3 py-3 text-left",
|
|
"hover:bg-muted/50 transition-colors"
|
|
)}
|
|
>
|
|
<div className="shrink-0 text-muted-foreground">{icon}</div>
|
|
<div className="min-w-0">
|
|
<div className="text-sm font-medium leading-tight">{title}</div>
|
|
<div className="text-xs text-muted-foreground mt-0.5 truncate">{subtitle}</div>
|
|
</div>
|
|
</button>
|
|
);
|
|
|
|
interface SettingsApplicationTabProps {
|
|
updateState: UpdateState;
|
|
checkNow: UseUpdateCheckResult['checkNow'];
|
|
openReleasePage: UseUpdateCheckResult['openReleasePage'];
|
|
installUpdate: UseUpdateCheckResult['installUpdate'];
|
|
startDownload: UseUpdateCheckResult['startDownload'];
|
|
isUpdateDemoMode: boolean;
|
|
}
|
|
|
|
export default function SettingsApplicationTab({ updateState, checkNow, openReleasePage, installUpdate, startDownload, isUpdateDemoMode }: SettingsApplicationTabProps) {
|
|
const { t } = useI18n();
|
|
const { openExternal, getApplicationInfo } = useApplicationBackend();
|
|
const [appInfo, setAppInfo] = useState<AppInfo>({ name: "Netcatty", version: "" });
|
|
const [lastCheckResult, setLastCheckResult] = useState<'none' | 'available' | 'upToDate'>('none');
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
const load = async () => {
|
|
try {
|
|
const info = await getApplicationInfo();
|
|
if (!cancelled && info?.name && typeof info?.version === "string") {
|
|
setAppInfo(info);
|
|
}
|
|
} catch {
|
|
// Ignore: running in browser/dev without Electron bridge
|
|
}
|
|
};
|
|
void load();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [getApplicationInfo]);
|
|
|
|
const handleOpenExternal = async (url: string) => {
|
|
try {
|
|
await openExternal(url);
|
|
} catch (err) {
|
|
console.warn("[SettingsApplicationTab] openExternal failed:", err);
|
|
toast.error(
|
|
t("settings.application.openExternal.failedBody"),
|
|
t("settings.application.openExternal.failedTitle"),
|
|
);
|
|
}
|
|
};
|
|
|
|
const handleCheckForUpdates = async () => {
|
|
// In demo mode, allow checking even for dev builds
|
|
if (!isUpdateDemoMode && (!appInfo.version || appInfo.version === '0.0.0')) {
|
|
// Dev build - just open releases page
|
|
openReleasePage();
|
|
return;
|
|
}
|
|
|
|
setLastCheckResult('none');
|
|
|
|
const result = await checkNow();
|
|
|
|
if (result?.hasUpdate && result.latestRelease) {
|
|
setLastCheckResult('available');
|
|
toast.info(
|
|
t('update.available.message', { version: result.latestRelease.version }),
|
|
t('update.available.title')
|
|
);
|
|
// Don't auto-open the release page here — checkNow() already triggers
|
|
// electron-updater on supported platforms, and the Settings > System tab
|
|
// shows a "Manual Download" link on unsupported platforms.
|
|
} else if (result) {
|
|
setLastCheckResult('upToDate');
|
|
toast.success(
|
|
t('update.upToDate.message', { version: appInfo.version }),
|
|
t('update.upToDate.title')
|
|
);
|
|
}
|
|
|
|
// Reset the result after 3 seconds
|
|
setTimeout(() => setLastCheckResult('none'), 3000);
|
|
};
|
|
|
|
const issueUrl = useMemo(() => buildIssueUrl(appInfo), [appInfo]);
|
|
const releasesUrl = `${REPO_URL}/releases`;
|
|
const discussionsUrl = `${REPO_URL}/discussions`;
|
|
|
|
return (
|
|
<SettingsTabContent value="application">
|
|
<div className="flex flex-col lg:flex-row gap-10 lg:gap-14">
|
|
<div className="lg:w-[320px] shrink-0">
|
|
<div className="flex items-center gap-4">
|
|
<AppLogo className="w-16 h-16" />
|
|
<div>
|
|
<div className="text-3xl font-semibold leading-none">{appInfo.name}</div>
|
|
<div className="flex items-center gap-2 mt-1">
|
|
<span className="text-sm text-muted-foreground">
|
|
{appInfo.version ? appInfo.version : " "}
|
|
</span>
|
|
{/* Update badge - reflects auto-download state */}
|
|
{updateState.latestRelease && (updateState.hasUpdate || updateState.autoDownloadStatus === 'downloading' || updateState.autoDownloadStatus === 'ready') && (
|
|
<button
|
|
onClick={() => updateState.autoDownloadStatus === 'ready' ? installUpdate() : updateState.autoDownloadStatus === 'downloading' ? undefined : startDownload()}
|
|
className={cn(
|
|
"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium",
|
|
updateState.autoDownloadStatus === 'ready'
|
|
? "bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 hover:bg-green-200 dark:hover:bg-green-800"
|
|
: "bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 hover:bg-blue-200 dark:hover:bg-blue-800",
|
|
"transition-colors cursor-pointer"
|
|
)}
|
|
>
|
|
<ArrowUpCircle size={12} />
|
|
v{updateState.latestRelease.version}{' '}
|
|
{updateState.autoDownloadStatus === 'ready'
|
|
? t('update.restartNow')
|
|
: updateState.autoDownloadStatus === 'downloading'
|
|
? `${updateState.downloadPercent}%`
|
|
: t('update.downloadNow')}
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="mt-6">
|
|
<Button
|
|
variant="secondary"
|
|
className="gap-2"
|
|
onClick={() => void handleCheckForUpdates()}
|
|
disabled={updateState.isChecking || updateState.manualCheckStatus === 'checking' || updateState.autoDownloadStatus === 'downloading' || updateState.autoDownloadStatus === 'ready'}
|
|
>
|
|
{updateState.isChecking ? (
|
|
<Loader2 size={16} className="animate-spin" />
|
|
) : lastCheckResult === 'upToDate' ? (
|
|
<Check size={16} />
|
|
) : (
|
|
<RefreshCcw size={16} />
|
|
)}
|
|
{updateState.isChecking
|
|
? t("update.checking")
|
|
: t("settings.application.checkUpdates")
|
|
}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex-1">
|
|
<div className="space-y-2">
|
|
<ActionRow
|
|
icon={<Bug size={18} />}
|
|
title={t("settings.application.reportProblem")}
|
|
subtitle={t("settings.application.reportProblem.subtitle")}
|
|
onClick={() => void handleOpenExternal(issueUrl)}
|
|
/>
|
|
<ActionRow
|
|
icon={<MessageCircle size={18} />}
|
|
title={t("settings.application.community")}
|
|
subtitle={t("settings.application.community.subtitle")}
|
|
onClick={() => void handleOpenExternal(discussionsUrl)}
|
|
/>
|
|
<ActionRow
|
|
icon={<Github size={18} />}
|
|
title="GitHub"
|
|
subtitle={t("settings.application.github.subtitle")}
|
|
onClick={() => void handleOpenExternal(REPO_URL)}
|
|
/>
|
|
<ActionRow
|
|
icon={<Newspaper size={18} />}
|
|
title={t("settings.application.whatsNew")}
|
|
subtitle={t("settings.application.whatsNew.subtitle")}
|
|
onClick={() => void handleOpenExternal(releasesUrl)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</SettingsTabContent>
|
|
);
|
|
}
|