Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(ai): separate provider connect from selection

Rahmanc7747d5ff82a
diff --git a/.env.example b/.env.example
index e0694f26..6f6c616c 100644
--- a/.env.example
+++ b/.env.example
@@ -40,6 +40,11 @@ OS_SESSION_SECRET=
# moving; it is here because the updater runs as a transient systemd unit and the
# path is passed to it explicitly rather than inherited.
# MSO_UPDATE_LOG=~/.mso/self-update.log
+# Optional advanced SSH transport override for custom/private Git origins. Canonical
+# MSO origins are normalized to public HTTPS, so ordinary installs should leave this
+# unset. When unset, MSO update paths use `ssh -oBatchMode=yes` for non-interactive
+# custom SSH remotes; set only when your private/fork origin needs another SSH command.
+# GIT_SSH_COMMAND=
# Number of trusted reverse-proxy hops in front of the app. The login rate
# limiter keys on the (N-from-last) x-forwarded-for hop, so a wrong value
# collapses every client into one bucket (too small N) or trusts spoofed
diff --git a/app/api/config/route.test.ts b/app/api/config/route.test.ts
index a9615a7e..9fd4adc3 100644
--- a/app/api/config/route.test.ts
+++ b/app/api/config/route.test.ts
@@ -55,7 +55,7 @@ describe("/api/config provider-auth vs model-selection contract", () => {
expect(writeConfig).not.toHaveBeenCalled();
});
- it("keeps legacy/default POST behavior selecting provider+model when select is omitted", async () => {
+ it("keeps normal POST behavior selecting an explicitly chosen provider+model", async () => {
const { POST } = await import("./route");
await POST(request({ provider: "openrouter", model: "openai/gpt-4o" }));
expect(writeConfig).toHaveBeenCalledWith({ provider: "openrouter", model: "openai/gpt-4o" });
@@ -73,4 +73,32 @@ describe("/api/config provider-auth vs model-selection contract", () => {
expect(writeConfig).not.toHaveBeenCalled();
expect(await res.json()).toMatchObject({ slug: "my-hub", selected: false });
});
+
+ it("keeps Google active and connected after Codex credentials are added", async () => {
+ readConfig.mockResolvedValue({
+ provider: "google",
+ model: "gemini-2.0-flash",
+ keys: { google: "google-secret" },
+ customProviders: {},
+ oauthTokens: { "openai-codex": { kind: "oauth", access: "codex-token", expires: Date.now() + 60_000 } },
+ });
+ const { GET } = await import("./route");
+ const res = await GET();
+ const body = await res.json();
+ expect(body).toMatchObject({ provider: "google", model: "gemini-2.0-flash", hasApiKey: true });
+ expect(body.providers).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "google", kind: "builtin", hasKey: true }),
+ expect.objectContaining({ id: "openai-codex", kind: "oauth", hasKey: true }),
+ ]));
+ });
+
+ it("can explicitly switch Codex on and then return to Google Gemini without touching credentials", async () => {
+ const { POST } = await import("./route");
+ await POST(request({ provider: "openai-codex", model: "gpt-account-model" }));
+ await POST(request({ provider: "google", model: "gemini-2.0-flash" }));
+ expect(writeConfig).toHaveBeenNthCalledWith(1, { provider: "openai-codex", model: "gpt-account-model" });
+ expect(writeConfig).toHaveBeenNthCalledWith(2, { provider: "google", model: "gemini-2.0-flash" });
+ expect(setKey).not.toHaveBeenCalled();
+ expect(deleteKey).not.toHaveBeenCalled();
+ });
});
diff --git a/app/api/oauth/[provider]/route.test.ts b/app/api/oauth/[provider]/route.test.ts
index 4a9b3aac..b4584ffe 100644
--- a/app/api/oauth/[provider]/route.test.ts
+++ b/app/api/oauth/[provider]/route.test.ts
@@ -37,18 +37,28 @@ describe("OpenAI Codex OAuth selection semantics", () => {
codexPoll.mockReset().mockResolvedValue({ bundle: { access: "token" } });
});
- it("stores OAuth credentials but preserves active model when select:false", async () => {
+ it("connects credentials without replacing the active provider when select is omitted", async () => {
const { POST } = await import("./route");
- const res = await POST(request({ action: "poll", select: false }), ctx);
+ const res = await POST(request({ action: "poll" }), ctx);
expect(res.status).toBe(200);
expect(writeOAuthBundle).toHaveBeenCalled();
expect(writeConfig).not.toHaveBeenCalled();
expect(await res.json()).toMatchObject({ slug: "openai-codex", selected: false, model: "gpt-account-model" });
});
- it("keeps existing callers selecting the OAuth provider when select is omitted", async () => {
+ it("keeps explicit select:false as connect-only", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(request({ action: "poll", select: false }), ctx);
+ expect(res.status).toBe(200);
+ expect(writeOAuthBundle).toHaveBeenCalled();
+ expect(writeConfig).not.toHaveBeenCalled();
+ expect(await res.json()).toMatchObject({ slug: "openai-codex", selected: false });
+ });
+
+ it("switches Alfa only when select:true is explicit", async () => {
const { POST } = await import("./route");
- await POST(request({ action: "poll" }), ctx);
+ const res = await POST(request({ action: "poll", select: true }), ctx);
expect(writeConfig).toHaveBeenCalledWith({ provider: "openai-codex", model: "gpt-account-model" });
+ expect(await res.json()).toMatchObject({ slug: "openai-codex", selected: true, model: "gpt-account-model" });
});
});
diff --git a/app/api/oauth/[provider]/route.ts b/app/api/oauth/[provider]/route.ts
index 67ec9ddb..989d4333 100644
--- a/app/api/oauth/[provider]/route.ts
+++ b/app/api/oauth/[provider]/route.ts
@@ -9,9 +9,9 @@ export const dynamic = "force-dynamic";
// OAuth "sign in with…" for subscription providers. POST { action:"start"|"poll" }.
// Only OpenAI (Codex device-code) is wired today; others return not-supported.
-// Session-gated; the token bundle lands in the 0600 host config file, and on
-// success the provider is selected by default so existing Settings behavior stays compatible;
-// callers may send select:false when they are only adding provider credentials.
+// Session-gated; the token bundle lands in the 0600 host config file.
+// Connecting credentials is intentionally separate from choosing the active runtime:
+// callers must send select:true on the successful poll to switch Alfa immediately.
export async function POST(req: NextRequest, ctx: { params: Promise<{ provider: string }> }) {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { provider } = await ctx.params;
@@ -42,12 +42,12 @@ export async function POST(req: NextRequest, ctx: { params: Promise<{ provider:
clearFlow(SLUG);
await writeOAuthBundle(SLUG, res.bundle);
const models = await codexModels(res.bundle);
- // The account's own first model. No literal fallback — "gpt-5-codex" is refused
- // by the backend, so writing it here just made the first request after a
- // successful sign-in fail.
+ // The account's own first model. No literal fallback — account-scoped
+ // Codex availability changes over time and stale literals can be rejected.
const model = models[0] ?? "";
- if (body.select !== false) await writeConfig({ provider: SLUG, model });
- return NextResponse.json({ ok: true, slug: SLUG, model, selected: body.select !== false });
+ const selected = body.select === true;
+ if (selected) await writeConfig({ provider: SLUG, model });
+ return NextResponse.json({ ok: true, slug: SLUG, model, selected });
}
default:
return NextResponse.json({ error: "bad_action" }, { status: 400 });
diff --git a/bin/mso-update-offline.test.ts b/bin/mso-update-offline.test.ts
index 01f8116e..41c2fb3d 100644
--- a/bin/mso-update-offline.test.ts
+++ b/bin/mso-update-offline.test.ts
@@ -46,6 +46,7 @@ function fixture() {
"scripts/lib/runtime-exclusion.sh",
"scripts/lib/update-gateway-runtimes.sh",
"scripts/lib/update-git-authority.sh",
+ "scripts/lib/update-remote-authority.sh",
]) copy(repo, rel);
fs.writeFileSync(
path.join(fakebin, "curl"),
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index d53efaa2..8bf569b1 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -92,6 +92,10 @@ Useful flags:
```
Public environment equivalents are `MSO_DIR`, `MSO_REF`, `MSO_PORT`, `MSO_BIND`, and `MSO_REPO`.
+The default repository is the public canonical HTTPS URL. Existing canonical SSH origins are
+normalized to that public HTTPS origin before update so normal MSO maintenance never needs a
+GitHub username/token. A non-canonical `MSO_REPO` or existing fork/private origin remains its own
+`origin/main` authority and is never rewritten; it must have non-interactive credentials configured.
`MSO_BIN_DIR`, `MSO_SYSTEM_BIN_DIR`, `MSO_SKILL_DIR`, `MSO_UPDATE_STATE_DIR`, and
`MSO_UPDATE_LOCK_TIMEOUT_SECONDS` are advanced operator/test overrides rather than normal install UX;
avoid them unless you are deliberately changing those boundaries.
@@ -501,8 +505,10 @@ include Anthropic/OpenAI/OpenRouter/Google/Groq/xAI/DeepSeek/Mistral; custom com
endpoints are supported and SSRF-checked.
The optional `openai-codex` provider uses a separate ChatGPT consumer OAuth/device flow for
-Alfa inference. It is unrelated to the ChatGPT MCP connector. See
-`docs/MODELS-INTEGRATION.md`.
+Alfa inference. It is unrelated to the ChatGPT MCP connector. **Connect OpenAI** stores that
+credential without changing Alfa's current provider/model; **Connect & use** explicitly switches.
+Alfa Cockpit can then switch among providers that are already connected, while credentials remain
+managed in Settings. See `docs/MODELS-INTEGRATION.md`.
## 8. Curated skill installation
diff --git a/docs/MODELS-INTEGRATION.md b/docs/MODELS-INTEGRATION.md
index f0ca85fd..1089f8f9 100644
--- a/docs/MODELS-INTEGRATION.md
+++ b/docs/MODELS-INTEGRATION.md
@@ -58,6 +58,12 @@ This path exists so the owner can choose to run Alfa against an eligible ChatGPT
subscription. It is a consumer-backend integration and can be more fragile than the public
Platform API. Tokens are host-side private state.
+Connecting this OAuth credential and selecting it for inference are separate actions. The default
+Settings action stores `openai-codex` without changing the current provider/model; an explicit
+**Connect & use** action switches Alfa after authorization. Existing BYOK credentials such as Google
+Gemini remain stored and selectable. Alfa Cockpit may switch provider/model only among connections
+already present in Settings; it never creates or copies credentials.
+
Current Alfa requests through this adapter can carry Alfa's tool definitions; the older
"chat-only/no tools" limitation from the original July plan no longer describes `main`.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index c2970f20..37b53941 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -20,6 +20,12 @@ the gate, session metadata and server-side transport probe. The probe still send
credentials, follows no redirects, requires HTTPS and keeps the existing SSRF/TLS checks.
Targeted regressions verify the exact namespaced HEAD request, viewer gate, service route and
client connection behavior.
+## 2026-09-19 — Separate AI connection from selection and harden public updates
+
+- OpenAI/Codex OAuth now connects credentials without changing Alfa's active provider/model unless the owner explicitly chooses **Connect & use**. Existing Google Gemini and other BYOK connections remain stored and selectable.
+- Alfa Cockpit can switch provider + model only among already-connected providers; credential creation/copy stays in Settings. A release browser journey proves Google Gemini → Codex → Google Gemini while both credentials remain connected.
+- Canonical MSO Git remotes are recognized across HTTPS/SSH forms and canonical SSH is normalized to the public HTTPS repository before install/update fetches. Git fetch/clone is non-interactive by default; explicit forks/private/custom `MSO_REPO` origins are never rewritten and retain their own `origin/main` authority.
+- Focused provider/updater regressions, full TypeScript/ESLint, production build and release E2E pass on the isolated candidate.
## 2026-09-19 — Bind Convex snapshot authorization to the opened descriptor
diff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.md
index 7c94de52..dd2b7725 100644
--- a/frontend/slices/assistant/CONTRACT.md
+++ b/frontend/slices/assistant/CONTRACT.md
@@ -131,7 +131,7 @@ The Assistant chat now has a compact **Cockpit** bar + responsive panel (desktop
- Typed memory is owner-visible as metadata/current records, but non-`normal` keys/values are masked as `Private memory`. Raw `KNOWLEDGE.md` content and raw repo-memory bodies are not copied into the Cockpit response.
- `Activity & Runs` merges client-side Alfa host-tool events with server MCP workflow activity only at the presentation layer. The execution engines remain separate; this is observability, not a fake shared workflow id.
- Native MSO Agent sessions shown in Cockpit are **read-only summaries** and are explicitly separate from Alfa's browser YAML chat threads.
-- Provider/credential management remains Settings' responsibility. Cockpit can switch/test a model only inside the provider that is already configured.
+- Provider/credential management remains Settings' responsibility. Cockpit can switch/test provider + model only among providers that are already connected; it never creates, copies, or exposes credentials.
Browser Automations likewise do not introduce a second executor. `Run` turns the saved ordered recipe into one Alfa task; the normal host-tool schemas, server guards, and approval rendezvous remain the execution path.
diff --git a/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx b/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx
index 5eee5e9d..23adc87e 100644
--- a/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx
+++ b/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx
@@ -55,7 +55,7 @@ export function AlfaCockpitDialog({
{data?.model.tokenSaver && data.model.tokenSaver !== "off" ? <Badge variant="outline">token saver · {data.model.tokenSaver}</Badge> : null}
<Button size="sm" variant="ghost" className="ml-auto h-8" onClick={() => openWindow("settings", "Settings", undefined, { tab: "ai" })}><Settings2 className="size-3.5" />AI settings</Button>
</div>
- {data ? <ModelQuickControl provider={data.model.provider} model={data.model.model} onSaved={onRefresh} /> : null}
+ {data ? <ModelQuickControl key={`${data.model.provider}/${data.model.model}`} provider={data.model.provider} model={data.model.model} onSaved={onRefresh} /> : null}
</Section>
<Section title="Project Context" icon={FolderGit2}>
diff --git a/frontend/slices/assistant/components/model-quick-control.tsx b/frontend/slices/assistant/components/model-quick-control.tsx
index 6b798286..37732ee8 100644
--- a/frontend/slices/assistant/components/model-quick-control.tsx
+++ b/frontend/slices/assistant/components/model-quick-control.tsx
@@ -4,34 +4,84 @@ import { useEffect, useMemo, useState } from "react";
import { CheckCircle2, Loader2, TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import {
+ quickModelForProvider,
+ quickProviderIds,
+ quickProviderLabel,
+ type QuickCatalogModel,
+ type QuickConnectedProvider,
+} from "./model-quick-options";
-type CatalogModel = { id: string; name?: string; tools?: boolean; reasoning?: boolean; vision?: boolean };
+type ConfigSnapshot = { providers?: QuickConnectedProvider[] };
export function ModelQuickControl({ provider, model, onSaved }: { provider: string; model: string; onSaved: () => void }) {
- const [rows, setRows] = useState<CatalogModel[]>([]);
+ const [providerIds, setProviderIds] = useState<string[]>([provider]);
+ const [activeProvider, setActiveProvider] = useState(provider);
+ const [activeModel, setActiveModel] = useState(model);
+ const [rows, setRows] = useState<QuickCatalogModel[]>([]);
const [saving, setSaving] = useState(false);
const [test, setTest] = useState<{ ok: boolean; text: string } | null>(null);
useEffect(() => {
const ctrl = new AbortController();
- fetch(`/api/models?provider=${encodeURIComponent(provider)}`, { cache: "no-store", signal: ctrl.signal })
- .then((response) => response.ok ? response.json() : { models: [] })
- .then((body) => setRows((body.models ?? []) as CatalogModel[]))
+ fetch("/api/config", { cache: "no-store", signal: ctrl.signal })
+ .then((response) => response.ok ? response.json() : null)
+ .then((body: ConfigSnapshot | null) => body && setProviderIds(quickProviderIds(provider, body.providers ?? [])))
.catch(() => undefined);
return () => ctrl.abort();
}, [provider]);
- const options = useMemo(() => rows.some((row) => row.id === model) ? rows : [{ id: model, name: model }, ...rows], [model, rows]);
+ useEffect(() => {
+ const ctrl = new AbortController();
+ fetch(`/api/models?provider=${encodeURIComponent(activeProvider)}`, { cache: "no-store", signal: ctrl.signal })
+ .then((response) => response.ok ? response.json() : { models: [] })
+ .then((body) => setRows((body.models ?? []) as QuickCatalogModel[]))
+ .catch(() => setRows([]));
+ return () => ctrl.abort();
+ }, [activeProvider]);
+
+ const options = useMemo(
+ () => rows.some((row) => row.id === activeModel) ? rows : activeModel ? [{ id: activeModel, name: activeModel }, ...rows] : rows,
+ [activeModel, rows],
+ );
+
+ async function save(nextProvider: string, nextModel: string) {
+ const response = await fetch("/api/config", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ provider: nextProvider, model: nextModel }),
+ });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ }
+
+ async function selectProvider(nextProvider: string) {
+ if (!nextProvider || nextProvider === activeProvider || saving) return;
+ setSaving(true);
+ setTest(null);
+ try {
+ const response = await fetch(`/api/models?provider=${encodeURIComponent(nextProvider)}`, { cache: "no-store" });
+ const nextRows = response.ok ? (((await response.json()).models ?? []) as QuickCatalogModel[]) : [];
+ const nextModel = quickModelForProvider(nextProvider, nextRows, provider, model);
+ if (!nextModel) throw new Error("No selectable model");
+ await save(nextProvider, nextModel);
+ setRows(nextRows);
+ setActiveProvider(nextProvider);
+ setActiveModel(nextModel);
+ onSaved();
+ } catch {
+ setTest({ ok: false, text: "Provider switch failed" });
+ } finally {
+ setSaving(false);
+ }
+ }
- async function select(next: string) {
- if (!next || next === model || saving) return;
+ async function selectModel(nextModel: string) {
+ if (!nextModel || nextModel === activeModel || saving) return;
setSaving(true);
setTest(null);
try {
- const response = await fetch("/api/config", {
- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ provider, model: next }),
- });
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ await save(activeProvider, nextModel);
+ setActiveModel(nextModel);
onSaved();
} catch {
setTest({ ok: false, text: "Model switch failed" });
@@ -56,19 +106,25 @@ export function ModelQuickControl({ provider, model, onSaved }: { provider: stri
return (
<div className="space-y-2">
- <div className="flex items-center gap-2">
- <Select value={model} onValueChange={select} disabled={saving}>
- <SelectTrigger className="min-w-0 flex-1"><SelectValue /></SelectTrigger>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <Select value={activeProvider} onValueChange={selectProvider} disabled={saving}>
+ <SelectTrigger aria-label="Alfa provider"><SelectValue /></SelectTrigger>
+ <SelectContent position="popper" align="start">
+ {providerIds.map((id) => <SelectItem key={id} value={id}>{quickProviderLabel(id)}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ <Select value={activeModel} onValueChange={selectModel} disabled={saving || !activeModel}>
+ <SelectTrigger aria-label="Alfa model"><SelectValue placeholder="Choose model" /></SelectTrigger>
<SelectContent position="popper" align="start">
{options.slice(0, 80).map((row) => <SelectItem key={row.id} value={row.id}>{row.name || row.id}</SelectItem>)}
</SelectContent>
</Select>
- <Button size="sm" variant="outline" className="h-9 shrink-0" onClick={testSelected} disabled={saving}>
- {saving ? <Loader2 className="size-3.5 animate-spin" /> : "Test"}
- </Button>
</div>
+ <Button size="sm" variant="outline" className="h-9" onClick={testSelected} disabled={saving}>
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : "Test active"}
+ </Button>
{test ? <p className={`flex items-center gap-1 text-[10px] ${test.ok ? "text-success" : "text-destructive"}`}>{test.ok ? <CheckCircle2 className="size-3" /> : <TriangleAlert className="size-3" />}{test.text}</p> : null}
- <p className="text-[10px] text-muted-foreground">Switches only the model for the already-configured provider. Credentials and providers stay in Settings.</p>
+ <p className="text-[10px] text-muted-foreground">Switches Alfa among providers already connected in Settings. Credentials remain managed in Settings.</p>
</div>
);
}
diff --git a/frontend/slices/assistant/components/model-quick-options.test.ts b/frontend/slices/assistant/components/model-quick-options.test.ts
new file mode 100644
index 00000000..75804d6e
--- /dev/null
+++ b/frontend/slices/assistant/components/model-quick-options.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { quickModelForProvider, quickProviderIds, quickProviderLabel } from "./model-quick-options";
+
+describe("Alfa connected-provider quick selection", () => {
+ it("shows only the active and already-connected providers", () => {
+ expect(quickProviderIds("google", [
+ { id: "google", kind: "builtin", hasKey: true },
+ { id: "openai-codex", kind: "oauth", hasKey: true },
+ { id: "openrouter", kind: "builtin", hasKey: false },
+ ])).toEqual(["google", "openai-codex"]);
+ });
+
+ it("keeps Gemini available after Codex is connected and prefers the Google default when switching back", () => {
+ const googleModels = [{ id: "gemini-2.0-flash" }, { id: "gemini-2.5-pro" }];
+ expect(quickModelForProvider("google", googleModels, "openai-codex", "gpt-account-model")).toBe("gemini-2.0-flash");
+ expect(quickProviderLabel("google")).toBe("Google Gemini");
+ expect(quickProviderLabel("openai-codex")).toBe("OpenAI Codex");
+ });
+
+ it("never invents a Codex fallback outside the account model list", () => {
+ expect(quickModelForProvider("openai-codex", [{ id: "gpt-account-model" }], "google", "gemini-2.0-flash")).toBe("gpt-account-model");
+ expect(quickModelForProvider("openai-codex", [], "google", "gemini-2.0-flash")).toBe("");
+ });
+});
diff --git a/frontend/slices/assistant/components/model-quick-options.ts b/frontend/slices/assistant/components/model-quick-options.ts
new file mode 100644
index 00000000..f125a7e8
--- /dev/null
+++ b/frontend/slices/assistant/components/model-quick-options.ts
@@ -0,0 +1,57 @@
+import { DEFAULT_MODELS } from "@/lib/models/defaults";
+
+export type QuickConnectedProvider = {
+ id: string;
+ kind?: "builtin" | "custom" | "oauth";
+ hasKey?: boolean;
+};
+
+export type QuickCatalogModel = {
+ id: string;
+ name?: string;
+ tools?: boolean;
+ reasoning?: boolean;
+ vision?: boolean;
+};
+
+const LABELS: Record<string, string> = {
+ anthropic: "Anthropic",
+ openai: "OpenAI Platform",
+ "openai-codex": "OpenAI Codex",
+ google: "Google Gemini",
+ openrouter: "OpenRouter",
+ groq: "Groq",
+ xai: "xAI",
+ deepseek: "DeepSeek",
+ mistral: "Mistral",
+ opencode: "OpenCode Zen",
+};
+
+export function quickProviderLabel(id: string): string {
+ return LABELS[id] ?? id;
+}
+
+export function quickProviderIds(currentProvider: string, connected: QuickConnectedProvider[]): string[] {
+ const ids: string[] = [];
+ const add = (id: string) => {
+ const normalized = id.trim();
+ if (normalized && !ids.includes(normalized)) ids.push(normalized);
+ };
+ add(currentProvider);
+ for (const provider of connected) {
+ if (provider.hasKey || provider.kind === "oauth") add(provider.id);
+ }
+ return ids;
+}
+
+export function quickModelForProvider(
+ provider: string,
+ rows: QuickCatalogModel[],
+ activeProvider: string,
+ activeModel: string,
+): string {
+ if (provider === activeProvider && activeModel && rows.some((row) => row.id === activeModel)) return activeModel;
+ const preferred = DEFAULT_MODELS[provider] ?? "";
+ if (preferred && rows.some((row) => row.id === preferred)) return preferred;
+ return rows[0]?.id ?? (provider === activeProvider ? activeModel : preferred);
+}
diff --git a/frontend/slices/os-settings/components/oauth-connect.tsx b/frontend/slices/os-settings/components/oauth-connect.tsx
index 954885dd..1b33c3b8 100644
--- a/frontend/slices/os-settings/components/oauth-connect.tsx
+++ b/frontend/slices/os-settings/components/oauth-connect.tsx
@@ -4,12 +4,13 @@ import { useEffect, useRef, useState } from "react";
import { CopyButton, toast } from "@/features/appshell";
import { Button } from "@/components/ui/button";
-// "Sign in with OpenAI" (ChatGPT Codex, device-code). Starts the flow, shows the
-// user code + opens the verification page, polls until the token lands, then
-// onConnected() refreshes the parent (the provider becomes openai-codex, selected).
+// OpenAI/ChatGPT Codex device OAuth. Credential connection and active-provider
+// selection are deliberately separate: "Connect OpenAI" preserves Alfa's current
+// provider/model, while "Connect & use" explicitly switches after authorization.
export function OAuthConnect({ onConnected }: { onConnected: () => void }) {
const [flow, setFlow] = useState<{ userCode: string; url: string } | null>(null);
const [busy, setBusy] = useState(false);
+ const [selectAfterConnect, setSelectAfterConnect] = useState(false);
const timer = useRef<number | null>(null);
useEffect(() => () => { if (timer.current) window.clearTimeout(timer.current); }, []);
@@ -19,10 +20,12 @@ export function OAuthConnect({ onConnected }: { onConnected: () => void }) {
timer.current = null;
setBusy(false);
setFlow(null);
+ setSelectAfterConnect(false);
}
- async function start() {
+ async function start(select: boolean) {
setBusy(true);
+ setSelectAfterConnect(select);
try {
const r = await fetch("/api/oauth/openai", {
method: "POST",
@@ -33,29 +36,31 @@ export function OAuthConnect({ onConnected }: { onConnected: () => void }) {
if (!r.ok) {
toast(d.error || "Couldn’t start sign-in", { tone: "error" });
setBusy(false);
+ setSelectAfterConnect(false);
return;
}
setFlow({ userCode: d.userCode, url: d.verificationUrl });
window.open(d.verificationUrl, "_blank", "noopener,noreferrer");
- schedule(Math.max(3000, d.intervalMs || 5000));
+ schedule(Math.max(3000, d.intervalMs || 5000), select);
} catch {
toast("Couldn’t reach the server", { tone: "error" });
setBusy(false);
+ setSelectAfterConnect(false);
}
}
- function schedule(intervalMs: number) {
+ function schedule(intervalMs: number, select: boolean) {
timer.current = window.setTimeout(async () => {
try {
const r = await fetch("/api/oauth/openai", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ action: "poll" }),
+ body: JSON.stringify({ action: "poll", select }),
});
const d = await r.json().catch(() => ({}));
if (r.ok && d.ok) {
stop();
- toast("Signed in with OpenAI");
+ toast(select ? "OpenAI connected and selected" : "OpenAI connected — current Alfa provider kept");
onConnected();
return;
}
@@ -67,37 +72,38 @@ export function OAuthConnect({ onConnected }: { onConnected: () => void }) {
} catch {
/* transient network blip — keep polling */
}
- schedule(intervalMs); // still pending
+ schedule(intervalMs, select);
}, intervalMs);
}
return (
<div>
{!flow ? (
- <div className="space-y-1.5">
- <Button variant="outline" size="sm" className="[@media(pointer:coarse)]:min-h-[44px]" disabled={busy} onClick={start}>
- {busy ? "Starting…" : "Sign in with OpenAI (ChatGPT)"}
- </Button>
+ <div className="space-y-2">
+ <div className="flex flex-wrap gap-2">
+ <Button variant="outline" size="sm" className="[@media(pointer:coarse)]:min-h-[44px]" disabled={busy} onClick={() => start(false)}>
+ {busy ? "Starting…" : "Connect OpenAI"}
+ </Button>
+ <Button size="sm" className="[@media(pointer:coarse)]:min-h-[44px]" disabled={busy} onClick={() => start(true)}>
+ Connect &amp; use
+ </Button>
+ </div>
<p className="text-xs text-muted-foreground">
- Uses your ChatGPT Codex subscription through device OAuth. Alfa&apos;s normal tool catalog is forwarded on this path too.
+ Connect OpenAI keeps Alfa&apos;s current provider/model. Connect &amp; use switches Alfa to an account-available Codex model after authorization.
</p>
</div>
) : (
<div className="space-y-1 rounded-lg border border-border p-3 text-sm">
+ <p>{selectAfterConnect ? "Connect OpenAI and use it for Alfa." : "Connect OpenAI and keep the current Alfa provider."}</p>
<p>Enter this code at:</p>
<div className="flex items-center gap-1">
<a className="min-w-0 flex-1 truncate text-primary underline" href={flow.url} target="_blank" rel="noreferrer">
{flow.url}
</a>
- {/* The popup below is opened AFTER an await, so it lands outside the
- transient user-activation window and browsers routinely block it.
- When that happens this link + button is the only way through. */}
<CopyButton value={flow.url} label="verification link" />
</div>
<div className="flex items-center gap-1">
<p className="font-mono text-lg tracking-widest">{flow.userCode}</p>
- {/* history={false}: a live auth factor, valid ~15 min. The clipboard panel
- persists what it records, and this must not outlive the flow there. */}
<CopyButton value={flow.userCode} label="device code" history={false} />
</div>
<p className="text-xs text-muted-foreground">Waiting for authorization…</p>
diff --git a/lib/host/self-update-status.test.ts b/lib/host/self-update-status.test.ts
index 1fe33514..5bde89ca 100644
--- a/lib/host/self-update-status.test.ts
+++ b/lib/host/self-update-status.test.ts
@@ -11,6 +11,7 @@ vi.mock("node:child_process", () => ({
else if (command !== "git") code = 1; // This deployment has no systemd manager, but does have detached handoff.
else if (key === "rev-parse --is-inside-work-tree") { output = "true"; code = fixture.noGit ? 1 : 0; }
else if (key === "branch --show-current") output = fixture.branch;
+ else if (key === "remote get-url origin") output = "https://github.com/rahmanef63/mso.git";
else if (key === "rev-parse --short HEAD") output = "16860d9";
else if (key === "rev-parse --short origin/main") output = "7cffd11";
else if (args[0] === "fetch") code = fixture.fetchFails ? 1 : 0;
diff --git a/lib/host/self-update.test.ts b/lib/host/self-update.test.ts
index 29159726..e294af3d 100644
--- a/lib/host/self-update.test.ts
+++ b/lib/host/self-update.test.ts
@@ -8,6 +8,7 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
const { parseCommits, blockingReason, updateBranchReason, updateUnitArgs } = await import("./self-update");
+const { isCanonicalMsoRemote, CANONICAL_MSO_REMOTE } = await import("./update-remote-authority");
const { offlineUpdateArgs } = await import("./self-update-offline");
const status = (over: Partial<Parameters<typeof blockingReason>[0]> = {}) => ({
@@ -27,6 +28,18 @@ const status = (over: Partial<Parameters<typeof blockingReason>[0]> = {}) => ({
...over,
});
+
+describe("canonical Git remote recognition", () => {
+ it("recognizes canonical HTTPS and SSH forms without treating forks as upstream", () => {
+ expect(isCanonicalMsoRemote(CANONICAL_MSO_REMOTE)).toBe(true);
+ expect(isCanonicalMsoRemote("https://github.com/rahmanef63/mso")).toBe(true);
+ expect(isCanonicalMsoRemote("[email protected]:rahmanef63/mso.git")).toBe(true);
+ expect(isCanonicalMsoRemote("ssh://[email protected]/rahmanef63/mso")).toBe(true);
+ expect(isCanonicalMsoRemote("https://github.com/example/mso.git")).toBe(false);
+ expect(isCanonicalMsoRemote("[email protected]:example/private-mso.git")).toBe(false);
+ });
+});
+
describe("parseCommits", () => {
it("splits the unit-separated format git is asked for", () => {
const out = ["9f3c9ee\x1ffix(deps): pin nanoid\x1f2026-08-17", "ecce676\x1fMerge pull request #3\x1f2026-08-16"].join("\n");
diff --git a/lib/host/self-update.ts b/lib/host/self-update.ts
index fe643ecb..76624fd5 100644
--- a/lib/host/self-update.ts
+++ b/lib/host/self-update.ts
@@ -6,6 +6,7 @@ import os from "node:os";
import path from "node:path";
import { HostError } from "./host-error";
import { offlineUpdateArgs, offlineUpdateRunning } from "./self-update-offline";
+import { prepareUpdateOrigin, updateGitEnv } from "./update-remote-authority";
// SERVER-ONLY. "Is there a newer MSO, and pull it in" — the deploy that CLAUDE.md
// describes (`git pull` → build → restart), driven from Settings instead of from a
@@ -101,12 +102,12 @@ interface Ran {
stderr: string;
}
-function run(command: string, args: readonly string[], timeout = GIT_TIMEOUT_MS): Promise<Ran> {
+function run(command: string, args: readonly string[], timeout = GIT_TIMEOUT_MS, env?: NodeJS.ProcessEnv): Promise<Ran> {
return new Promise((resolve) => {
execFile(
command,
[...args],
- { cwd: repoRoot(), timeout, maxBuffer: 1024 * 1024, windowsHide: true, shell: false },
+ { cwd: repoRoot(), timeout, maxBuffer: 1024 * 1024, windowsHide: true, shell: false, ...(env ? { env } : {}) },
(error, stdout, stderr) => {
const code = typeof (error as { code?: number } | null)?.code === "number" ? (error as { code: number }).code : error ? 1 : 0;
resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
@@ -115,7 +116,7 @@ function run(command: string, args: readonly string[], timeout = GIT_TIMEOUT_MS)
});
}
-const git = (args: readonly string[], timeout?: number) => run("git", args, timeout);
+const git = (args: readonly string[], timeout?: number) => run("git", args, timeout, updateGitEnv());
/** `<sha>\x1f<subject>\x1f<iso date>` per line — a separator no subject can contain. */
export function parseCommits(stdout: string): UpdateCommit[] {
@@ -247,7 +248,10 @@ export async function getUpdateStatus(fetchRemote = true): Promise<UpdateStatus>
if (fetchRemote && !running) {
// Quiet + a hard timeout: an unreachable remote must degrade to "could not
// check", never hang the Settings panel that is waiting on this.
- const fetched = await git(["fetch", "--quiet", "origin", "main"], FETCH_TIMEOUT_MS);
+ const originReady = await prepareUpdateOrigin(git);
+ const fetched = originReady
+ ? await git(["fetch", "--quiet", "origin", "main"], FETCH_TIMEOUT_MS)
+ : { code: 1, stdout: "", stderr: "origin unavailable" };
remoteChecked = fetched.code === 0;
}
diff --git a/lib/host/update-remote-authority.ts b/lib/host/update-remote-authority.ts
new file mode 100644
index 00000000..5c49737d
--- /dev/null
+++ b/lib/host/update-remote-authority.ts
@@ -0,0 +1,37 @@
+export const CANONICAL_MSO_REMOTE = "https://github.com/rahmanef63/mso.git";
+
+const CANONICAL_FORMS = new Set([
+ "https://github.com/rahmanef63/mso",
+ CANONICAL_MSO_REMOTE,
+ "https://github.com/rahmanef63/mso/",
+ "https://github.com/rahmanef63/mso.git/",
+ "[email protected]:rahmanef63/mso",
+ "[email protected]:rahmanef63/mso.git",
+ "ssh://[email protected]/rahmanef63/mso",
+ "ssh://[email protected]/rahmanef63/mso.git",
+]);
+
+export type UpdateGitResult = { code: number; stdout: string; stderr: string };
+export type UpdateGitRunner = (args: readonly string[], timeout?: number) => Promise<UpdateGitResult>;
+
+export function isCanonicalMsoRemote(url: string): boolean {
+ return CANONICAL_FORMS.has(url.trim());
+}
+
+export function updateGitEnv(): NodeJS.ProcessEnv {
+ return {
+ ...process.env,
+ GIT_TERMINAL_PROMPT: "0",
+ GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND?.trim() || "ssh -oBatchMode=yes",
+ };
+}
+
+export async function prepareUpdateOrigin(git: UpdateGitRunner): Promise<boolean> {
+ const remote = await git(["remote", "get-url", "origin"]);
+ if (remote.code !== 0 || !remote.stdout.trim()) return false;
+ const url = remote.stdout.trim();
+ if (isCanonicalMsoRemote(url) && url !== CANONICAL_MSO_REMOTE) {
+ return (await git(["remote", "set-url", "origin", CANONICAL_MSO_REMOTE])).code === 0;
+ }
+ return true;
+}
diff --git a/scripts/e2e/ai-provider-switch.mjs b/scripts/e2e/ai-provider-switch.mjs
new file mode 100644
index 00000000..3dd9bda7
--- /dev/null
+++ b/scripts/e2e/ai-provider-switch.mjs
@@ -0,0 +1,74 @@
+import { expect } from "@playwright/test";
+
+export async function aiProviderSwitchJourney(page, fixture) {
+ await fixture.setAiConfig({
+ provider: "google",
+ model: "gemini-2.0-flash",
+ keys: { google: "synthetic-google-key" },
+ oauthTokens: {
+ "openai-codex": {
+ kind: "oauth",
+ access: "synthetic-codex-access",
+ refresh: "synthetic-codex-refresh",
+ expires: Date.now() + 3_600_000,
+ },
+ },
+ });
+
+ await page.route("**/api/models?provider=google", async route => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ models: [
+ { ref: "google/gemini-2.0-flash", provider: "google", id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", agentReady: true },
+ { ref: "google/gemini-2.5-pro", provider: "google", id: "gemini-2.5-pro", name: "Gemini 2.5 Pro", agentReady: true },
+ ],
+ }),
+ });
+ });
+ await page.route("**/api/models?provider=openai-codex", async route => {
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ models: [
+ { ref: "openai-codex/gpt-account-model", provider: "openai-codex", id: "gpt-account-model", name: "gpt-account-model", agentReady: true },
+ ],
+ }),
+ });
+ });
+
+ await page.goto(fixture.base + "/assistant");
+ await expect(page.getByRole("button", { name: "Cockpit", exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Cockpit", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Alfa Cockpit", exact: true })).toBeVisible();
+ await expect(page.getByLabel("Alfa provider")).toContainText("Google Gemini");
+ await expect(page.getByLabel("Alfa model")).toContainText(/Gemini 2\.0 Flash|gemini-2\.0-flash/);
+
+ await page.getByLabel("Alfa provider").click();
+ await page.getByRole("option", { name: "OpenAI Codex", exact: true }).click();
+ await expect.poll(async () => (await page.evaluate(async () => (await fetch("/api/config", { cache: "no-store" })).json())).provider).toBe("openai-codex");
+ await expect(page.getByLabel("Alfa model")).toContainText("gpt-account-model");
+
+ let config = await page.evaluate(async () => (await fetch("/api/config", { cache: "no-store" })).json());
+ expect(config.providers).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "google", kind: "builtin", hasKey: true }),
+ expect.objectContaining({ id: "openai-codex", kind: "oauth", hasKey: true }),
+ ]));
+
+ await page.getByLabel("Alfa provider").click();
+ await page.getByRole("option", { name: "Google Gemini", exact: true }).click();
+ await expect.poll(async () => (await page.evaluate(async () => (await fetch("/api/config", { cache: "no-store" })).json())).provider).toBe("google");
+ config = await page.evaluate(async () => (await fetch("/api/config", { cache: "no-store" })).json());
+ expect(config.model).toBe("gemini-2.0-flash");
+ expect(config.providers).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "google", hasKey: true }),
+ expect.objectContaining({ id: "openai-codex", kind: "oauth", hasKey: true }),
+ ]));
+ await expect(page.getByLabel("Alfa model")).toContainText(/Gemini 2\.0 Flash|gemini-2\.0-flash/);
+
+ await page.unroute("**/api/models?provider=google");
+ await page.unroute("**/api/models?provider=openai-codex");
+ console.log("PASS Alfa connected-provider switching: Google Gemini -> Codex -> Google Gemini");
+}
diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjs
index 5ab73f07..631550ad 100644
--- a/scripts/e2e/release-fixture.mjs
+++ b/scripts/e2e/release-fixture.mjs
@@ -89,6 +89,9 @@ export async function releaseFixture({ live = false, surfaceApps = [] } = {}) {
await new Promise(resolve => setTimeout(resolve, 250));
}
if (!ready) throw new Error("Fixture server did not become ready: " + logs);
- return { dir, base, device, password, setRole, seedMcp, mcpToken, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };
+ const setAiConfig = async config => {
+ await writeFile(env.OS_CONFIG_STORE, JSON.stringify(config, null, 2), { mode: 0o600 });
+ };
+ return { dir, base, device, password, setRole, seedMcp, mcpToken, setAiConfig, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };
} catch (error) { await close(); throw error; }
}
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index abfa824f..13f754b6 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -10,6 +10,7 @@ import { workflowCanvasJourney } from "./workflow-canvas.mjs";
import { storeExtensionsJourney } from "./store-extensions.mjs";
import { releaseFixture } from "./release-fixture.mjs";
import { camoufoxConnectionJourney } from "./camoufox-connection.mjs";
+import { aiProviderSwitchJourney } from "./ai-provider-switch.mjs";
execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/workflow-embeds.mjs"], { stdio: "inherit" });
@@ -127,6 +128,7 @@ try {
await automationJourney(page, fixture);
await organizationJourney(page, fixture);
await workflowCanvasJourney(page, fixture);
+ await aiProviderSwitchJourney(page, fixture);
await fixture.setRole("viewer");
expect((await call("/api/v1/agent-sessions?view=monitor")).status).toBe(403);
expect((await call("/api/v1/integrations")).status).toBe(403);
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index 3ceec9c1..90aa407f 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -10,7 +10,8 @@
set -Eeuo pipefail
# ---- config: env override > flag > default ----
-REPO_URL="${MSO_REPO:-https://github.com/rahmanef63/mso.git}"
+CANONICAL_REPO_URL="https://github.com/rahmanef63/mso.git"
+REPO_URL="${MSO_REPO:-$CANONICAL_REPO_URL}"
DIR="${MSO_DIR:-$HOME/mso}"
DIR_EXPLICIT=0
REF="${MSO_REF:-main}"
@@ -408,6 +409,10 @@ rand_password() {
node -e 'const c="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";const b=require("crypto").randomBytes(24);let s="";for(const x of b)s+=c[x%c.length];process.stdout.write(s)'
}
+install_repo_is_canonical_url() { case "$1" in https://github.com/rahmanef63/mso|https://github.com/rahmanef63/mso.git|https://github.com/rahmanef63/mso/|https://github.com/rahmanef63/mso.git/|[email protected]:rahmanef63/mso|[email protected]:rahmanef63/mso.git|ssh://[email protected]/rahmanef63/mso|ssh://[email protected]/rahmanef63/mso.git) return 0 ;; *) return 1 ;; esac; }
+install_git_noninteractive() { GIT_TERMINAL_PROMPT=0 GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -oBatchMode=yes}" "$@"; }
+install_prepare_origin() { local url; url="$(git -C "$DIR" remote get-url origin 2>/dev/null || true)"; [ -n "$url" ] || die "existing checkout has no readable origin remote"; if install_repo_is_canonical_url "$url" && [ "$url" != "$CANONICAL_REPO_URL" ]; then git -C "$DIR" remote set-url origin "$CANONICAL_REPO_URL" || die "could not normalize canonical origin to public HTTPS"; fi; }
+
INSTALL_PHASE=checkout
# ---- clone or update (idempotent, resilient to a dirty tree) ----
if [ -d "$DIR/.git" ]; then
@@ -417,14 +422,16 @@ if [ -d "$DIR/.git" ]; then
die "checkout has uncommitted changes at $DIR. Commit/stash them, or install into another --dir. Current commit: $old_commit"
fi
info "current commit: $old_commit"
- git -C "$DIR" fetch --quiet origin "$REF" || die "could not fetch origin $REF"
+ install_prepare_origin
+ install_git_noninteractive git -C "$DIR" fetch --quiet origin "$REF" || die "could not fetch origin $REF non-interactively; canonical MSO uses public HTTPS, custom/private origins need preconfigured credentials"
target_commit="$(git -C "$DIR" rev-parse --short FETCH_HEAD)" || die "could not resolve fetched ref $REF"
info "target commit: $target_commit"
git -C "$DIR" checkout --quiet FETCH_HEAD || die "could not check out $target_commit"
ok "updated checkout $old_commit → $(git -C "$DIR" rev-parse --short HEAD)"
else
+ if install_repo_is_canonical_url "$REPO_URL"; then REPO_URL="$CANONICAL_REPO_URL"; fi
info "cloning $REPO_URL → $DIR"
- git clone --quiet --branch "$REF" "$REPO_URL" "$DIR" 2>/dev/null || git clone --quiet "$REPO_URL" "$DIR"
+ install_git_noninteractive git clone --quiet --branch "$REF" "$REPO_URL" "$DIR" 2>/dev/null || install_git_noninteractive git clone --quiet "$REPO_URL" "$DIR"
fi
cd "$DIR"
diff --git a/scripts/install-remote-authority.test.ts b/scripts/install-remote-authority.test.ts
new file mode 100644
index 00000000..6300ae21
--- /dev/null
+++ b/scripts/install-remote-authority.test.ts
@@ -0,0 +1,31 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const core = fs.readFileSync(path.join(process.cwd(), "scripts/install-core.sh"), "utf8");
+
+describe("installer Git remote authority", () => {
+ it("keeps MSO_REPO as an explicit override while defaulting to canonical HTTPS", () => {
+ expect(core).toContain('CANONICAL_REPO_URL="https://github.com/rahmanef63/mso.git"');
+ expect(core).toContain('REPO_URL="${MSO_REPO:-$CANONICAL_REPO_URL}"');
+ });
+
+ it("normalizes only recognized canonical origins before updating an existing checkout", () => {
+ expect(core).toContain('if install_repo_is_canonical_url "$url" && [ "$url" != "$CANONICAL_REPO_URL" ]; then');
+ expect(core).toContain('git -C "$DIR" remote set-url origin "$CANONICAL_REPO_URL"');
+ expect(core).not.toContain('remote set-url origin "$REPO_URL"');
+ });
+
+ it("runs clone and fetch with terminal prompting disabled", () => {
+ expect(core).toContain('GIT_TERMINAL_PROMPT=0');
+ expect(core).toContain('GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -oBatchMode=yes}"');
+ expect(core).toContain('install_git_noninteractive git -C "$DIR" fetch --quiet origin "$REF"');
+ expect(core).toContain('install_git_noninteractive git clone --quiet --branch "$REF" "$REPO_URL" "$DIR"');
+ });
+
+ it("converts canonical SSH clone requests to public HTTPS but leaves noncanonical URLs outside that rewrite", () => {
+ expect(core).toContain('[email protected]:rahmanef63/mso.git');
+ expect(core).toContain('ssh://[email protected]/rahmanef63/mso');
+ expect(core).toContain('if install_repo_is_canonical_url "$REPO_URL"; then REPO_URL="$CANONICAL_REPO_URL"; fi');
+ });
+});
diff --git a/scripts/install-update-lock-contract.test.ts b/scripts/install-update-lock-contract.test.ts
index 111f7a51..c3f8d381 100644
--- a/scripts/install-update-lock-contract.test.ts
+++ b/scripts/install-update-lock-contract.test.ts
@@ -8,7 +8,7 @@ describe("installer update transaction ordering", () => {
it("acquires the checkout transaction lock before fetch/checkout mutation", () => {
const core = fs.readFileSync(path.join(ROOT, "scripts/install-core.sh"), "utf8");
const acquire = core.indexOf("\ninstall_early_update_lock_acquire\n");
- const fetch = core.indexOf('git -C "$DIR" fetch --quiet origin "$REF"');
+ const fetch = core.indexOf('install_git_noninteractive git -C "$DIR" fetch --quiet origin "$REF"');
const checkout = core.indexOf('git -C "$DIR" checkout --quiet FETCH_HEAD');
expect(acquire).toBeGreaterThan(0);
expect(fetch).toBeGreaterThan(acquire);
diff --git a/scripts/install.sh b/scripts/install.sh
index d6a6e233..1b03a795 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -11,7 +11,7 @@ umask 077
RAW_BASE="${MSO_INSTALL_RAW_BASE:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts}"
CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
-CORE_SHA256="c2b5685734c9474c56b8d4a20cde3d4d4e9e1cfa0209744c4e3b337590a27144"
+CORE_SHA256="5f0ed84924773d906cf0abc7499911ed5cfa6b31890b0bacc9dbe8bcbdfd0e52"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
MACOS_SHA256="668ec3c8bbf3ee36dc2ae70952c3ba43c6f73ebc3acd6956fa4be2f65a076bfe"
TERMUX_SHA256="27c1a7d558c51ec875d17fd4a02a49e9e309eeb57fb306f62ea8de890ae2e65d"
diff --git a/scripts/lib/update-remote-authority.sh b/scripts/lib/update-remote-authority.sh
new file mode 100644
index 00000000..3299f7f8
--- /dev/null
+++ b/scripts/lib/update-remote-authority.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+# Git remote policy for MSO self-update.
+# Canonical MSO installs are public, so canonical SSH origins are normalized to
+# public HTTPS before fetch. Non-canonical forks/private remotes are never rewritten.
+MSO_CANONICAL_REMOTE_HTTPS="https://github.com/rahmanef63/mso.git"
+UPDATE_ORIGIN_CLASS="unknown"
+
+update_origin_is_canonical_url() {
+ case "$1" in
+ https://github.com/rahmanef63/mso|https://github.com/rahmanef63/mso.git|https://github.com/rahmanef63/mso/|https://github.com/rahmanef63/mso.git/|\
+ [email protected]:rahmanef63/mso|[email protected]:rahmanef63/mso.git|\
+ ssh://[email protected]/rahmanef63/mso|ssh://[email protected]/rahmanef63/mso.git)
+ return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+update_origin_classify_url() {
+ local url="$1"
+ if update_origin_is_canonical_url "$url"; then
+ printf 'canonical'
+ else
+ case "$url" in
+ https://*|http://*) printf 'custom-https' ;;
+ git@*:*|ssh://*) printf 'custom-ssh' ;;
+ *) printf 'custom' ;;
+ esac
+ fi
+}
+
+update_prepare_origin() {
+ local root="$1" url
+ url="$(git -C "$root" remote get-url origin 2>/dev/null || true)"
+ [ -n "$url" ] || return 1
+ UPDATE_ORIGIN_CLASS="$(update_origin_classify_url "$url")"
+ if [ "$UPDATE_ORIGIN_CLASS" = canonical ] && [ "$url" != "$MSO_CANONICAL_REMOTE_HTTPS" ]; then
+ git -C "$root" remote set-url origin "$MSO_CANONICAL_REMOTE_HTTPS" || return 1
+ fi
+}
+
+update_git_fetch_origin() {
+ local root="$1" ref="$2"
+ shift 2
+ update_prepare_origin "$root" || {
+ printf 'MSO Git: origin is missing or unreadable.\n' >&2
+ return 1
+ }
+ if ! GIT_TERMINAL_PROMPT=0 GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -oBatchMode=yes}" \
+ git -C "$root" fetch --quiet "$@" origin "$ref"; then
+ printf 'MSO Git: fetch failed for %s origin; canonical installs use public HTTPS, while custom/private origins require preconfigured non-interactive credentials.\n' "$UPDATE_ORIGIN_CLASS" >&2
+ return 1
+ fi
+}
diff --git a/scripts/mso-model-dx-contract.test.ts b/scripts/mso-model-dx-contract.test.ts
index cdede114..d013efd1 100644
--- a/scripts/mso-model-dx-contract.test.ts
+++ b/scripts/mso-model-dx-contract.test.ts
@@ -43,7 +43,8 @@ describe("MSO model/provider/session CLI contract", () => {
expect(agentCli).toContain("custom_provider_body_unselected");
expect(all).toContain("select:false");
expect(configRoute).toContain("body.select !== false");
- expect(oauthRoute).toContain("body.select !== false");
+ expect(oauthRoute).toContain("body.select === true");
+ expect(oauthRoute).not.toContain("body.select !== false");
expect(slash).toMatch(/text:\s*"\/models"[\s\S]{0,120}meta:\s*"Configure AI providers and authentication"/);
expect(slash).toMatch(/text:\s*"\/model"[\s\S]{0,120}meta:\s*"Select the active model from connected providers"/);
});
diff --git a/scripts/mso-update b/scripts/mso-update
index f4a1e1d2..177c072a 100755
--- a/scripts/mso-update
+++ b/scripts/mso-update
@@ -18,6 +18,8 @@ GATEWAY="$ROOT/scripts/mso-gateway"
. "$ROOT/scripts/lib/update-gateway-runtimes.sh"
# shellcheck source=scripts/lib/update-git-authority.sh
. "$ROOT/scripts/lib/update-git-authority.sh"
+# shellcheck source=scripts/lib/update-remote-authority.sh
+. "$ROOT/scripts/lib/update-remote-authority.sh"
fail() { printf 'mso update: %s\n' "$*" >&2; exit 1; }
git_root() { [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null || true)" = "$ROOT" ]; }
current_version() { sed -n 's/^VERSION="\([^"]*\)".*/\1/p' "$ROOT/bin/mso" | head -1; }
@@ -27,7 +29,7 @@ require_checkout() {
[ "$(git -C "$ROOT" branch --show-current)" = main ] || fail "updates require the installed checkout to be on main"
[ -z "$(git -C "$ROOT" status --porcelain)" ] || fail "checkout has local changes; refusing to overwrite them"
}
-fetch_main() { git -C "$ROOT" fetch --quiet origin main || fail "could not reach origin/main"; }
+fetch_main() { update_git_fetch_origin "$ROOT" main || fail "could not reach origin/main"; }
service_is_active() {
# Containers/Codespaces often ship the systemctl binary without systemd as PID 1.
# A read-only probe must classify that as "no active service" without leaking
@@ -156,7 +158,7 @@ notice() {
if [ -s "$stamp" ] && mso_private_state_validate_file "$stamp" >/dev/null 2>&1; then last="$(cat "$stamp" 2>/dev/null || printf 0)"; fi
if ! [[ "$last" =~ ^[0-9]+$ ]] || [ $((now-last)) -ge 21600 ]; then
printf '%s\n' "$now" | mso_private_state_atomic_write "$stamp" >/dev/null 2>&1 || true
- (cd "$ROOT" && nohup git fetch --quiet --no-write-fetch-head origin main >/dev/null 2>&1 </dev/null &) || true
+ (cd "$ROOT" && nohup bash -c 'source "$1/scripts/lib/update-remote-authority.sh"; update_git_fetch_origin "$1" main --no-write-fetch-head' _ "$ROOT" >/dev/null 2>&1 </dev/null &) || true
fi
read -r relation ahead n < <(update_git_relation "$ROOT") || return 0
if [ "$relation" = ahead ] || [ "$relation" = diverged ]; then
diff --git a/scripts/mso-update-authority.test.ts b/scripts/mso-update-authority.test.ts
index c8cbc1fe..235d5b33 100644
--- a/scripts/mso-update-authority.test.ts
+++ b/scripts/mso-update-authority.test.ts
@@ -18,7 +18,7 @@ function fixture() {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "mso-update-authority-")); roots.push(base);
const repo = path.join(base, "repo"), remote = path.join(base, "remote.git"), fakebin = path.join(base, "bin"), capture = path.join(base, "capture");
fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true }); fs.mkdirSync(path.join(repo, "bin")); fs.mkdirSync(fakebin);
- for (const rel of ["scripts/lib/private-state.sh", "scripts/lib/update-state.sh", "scripts/lib/runtime-exclusion.sh", "scripts/lib/update-gateway-runtimes.sh", "scripts/lib/update-git-authority.sh", "scripts/self-update.sh"]) copy(path.join(ROOT, rel), path.join(repo, rel));
+ for (const rel of ["scripts/lib/private-state.sh", "scripts/lib/update-state.sh", "scripts/lib/runtime-exclusion.sh", "scripts/lib/update-gateway-runtimes.sh", "scripts/lib/update-git-authority.sh", "scripts/lib/update-remote-authority.sh", "scripts/self-update.sh"]) copy(path.join(ROOT, rel), path.join(repo, rel));
fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.0.0"\n', { mode: 0o755 });
git(repo, "init", "-q", "-b", "main"); git(repo, "config", "user.name", "MSO Test"); git(repo, "config", "user.email", "[email protected]");
git(repo, "add", "."); git(repo, "commit", "-q", "-m", "remote base");
diff --git a/scripts/mso-update-notice-contract.test.ts b/scripts/mso-update-notice-contract.test.ts
index 093c3170..1876563b 100644
--- a/scripts/mso-update-notice-contract.test.ts
+++ b/scripts/mso-update-notice-contract.test.ts
@@ -3,9 +3,10 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
describe("background update notice", () => {
- it("fetches origin/main without mutating FETCH_HEAD", () => {
+ it("fetches origin/main without mutating FETCH_HEAD through the non-interactive remote policy", () => {
const src = fs.readFileSync(path.join(process.cwd(), "scripts/mso-update"), "utf8");
- const line = src.split("\n").find((value) => value.includes("nohup git fetch") && value.includes("origin main"));
- expect(line).toContain("--no-write-fetch-head");
+ const line = src.split("\n").find((value) => value.includes("update_git_fetch_origin") && value.includes("--no-write-fetch-head"));
+ expect(line).toContain("main --no-write-fetch-head");
+ expect(src).toContain("update-remote-authority.sh");
});
});
diff --git a/scripts/mso-update-reconcile.test.ts b/scripts/mso-update-reconcile.test.ts
index 47763f5e..c63f0283 100644
--- a/scripts/mso-update-reconcile.test.ts
+++ b/scripts/mso-update-reconcile.test.ts
@@ -33,6 +33,7 @@ function fixture() {
"scripts/lib/runtime-exclusion.sh",
"scripts/lib/update-gateway-runtimes.sh",
"scripts/lib/update-git-authority.sh",
+ "scripts/lib/update-remote-authority.sh",
]) copy(repo, rel);
fs.mkdirSync(path.join(repo, "bin"), { recursive: true });
fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="test"\n', { mode: 0o755 });
diff --git a/scripts/mso-update-service-status.test.ts b/scripts/mso-update-service-status.test.ts
index d3656811..1dd11771 100644
--- a/scripts/mso-update-service-status.test.ts
+++ b/scripts/mso-update-service-status.test.ts
@@ -5,7 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
const SCRIPT = path.join(process.cwd(), "scripts/mso-update");
-const LIBS = ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "update-git-authority.sh"];
+const LIBS = ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "update-git-authority.sh", "update-remote-authority.sh"];
const roots: string[] = [];
function git(cwd: string, ...args: string[]) {
diff --git a/scripts/mso-update-version-labels.test.ts b/scripts/mso-update-version-labels.test.ts
index 88c15aed..175883e5 100644
--- a/scripts/mso-update-version-labels.test.ts
+++ b/scripts/mso-update-version-labels.test.ts
@@ -13,7 +13,7 @@ function fixture() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-update-labels-")); roots.push(root);
const repo = path.join(root, "repo"), remote = path.join(root, "remote.git"), fakeBin = path.join(root, "bin");
fs.mkdirSync(path.join(repo, "scripts/lib"), { recursive: true }); fs.mkdirSync(path.join(repo, "bin")); fs.mkdirSync(fakeBin);
- for (const name of ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "update-git-authority.sh"]) {
+ for (const name of ["private-state.sh", "update-state.sh", "runtime-exclusion.sh", "update-gateway-runtimes.sh", "update-git-authority.sh", "update-remote-authority.sh"]) {
fs.copyFileSync(path.join(process.cwd(), "scripts/lib", name), path.join(repo, "scripts/lib", name));
}
fs.writeFileSync(path.join(repo, "bin/mso"), '#!/bin/sh\nVERSION="1.3.0"\n', { mode: 0o755 });
diff --git a/scripts/mso-update.test.ts b/scripts/mso-update.test.ts
index 4ac8bfa4..fefe0a09 100644
--- a/scripts/mso-update.test.ts
+++ b/scripts/mso-update.test.ts
@@ -20,7 +20,7 @@ function fixture(options: { failInstallOnce?: boolean; activeService?: "same" |
fs.copyFileSync(UPDATE_STATE, path.join(repo, "scripts/lib/update-state.sh"));
fs.copyFileSync(RUNTIME_EXCLUSION, path.join(repo, "scripts/lib/runtime-exclusion.sh"));
fs.copyFileSync(UPDATE_GATEWAYS, path.join(repo, "scripts/lib/update-gateway-runtimes.sh"));
- fs.copyFileSync(path.join(process.cwd(), "scripts/lib/update-git-authority.sh"), path.join(repo, "scripts/lib/update-git-authority.sh"));
+ for (const name of ["update-git-authority.sh", "update-remote-authority.sh"]) fs.copyFileSync(path.join(process.cwd(), "scripts/lib", name), path.join(repo, "scripts/lib", name));
fs.copyFileSync(SERVICE_UPDATE, path.join(repo, "scripts/mso-service-update")); fs.chmodSync(path.join(repo, "scripts/mso-service-update"), 0o755);
fs.writeFileSync(path.join(repo, "scripts/self-update.sh"), `#!/bin/sh\nprintf 'self-update %s\\n' "$*" >> "${capture}"\n`, { mode: 0o755 });
fs.writeFileSync(path.join(repo, "scripts/verify-build.sh"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
diff --git a/scripts/self-update.sh b/scripts/self-update.sh
index c3e7a9e0..a13ca7b8 100755
--- a/scripts/self-update.sh
+++ b/scripts/self-update.sh
@@ -18,6 +18,8 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" || exit 1
cd "$ROOT" || exit 1
# shellcheck source=scripts/lib/update-git-authority.sh
. "$ROOT/scripts/lib/update-git-authority.sh"
+# shellcheck source=scripts/lib/update-remote-authority.sh
+. "$ROOT/scripts/lib/update-remote-authority.sh"
LOG="${MSO_UPDATE_LOG:-$HOME/.mso/self-update.log}"
mkdir -p "$(dirname "$LOG")"
@@ -65,7 +67,7 @@ fi
if [ "$REBUILD_ONLY" -eq 0 ]; then
step "fetching origin/main"
- git fetch --quiet origin main || die "could not reach the remote"
+ update_git_fetch_origin "$ROOT" main || die "could not reach the remote"
step "verifying remote authority / fast-forwarding"
read -r RELATION AHEAD_COUNT BEHIND_COUNT < <(update_git_relation "$ROOT") \
|| die "could not compare checkout with origin/main"
diff --git a/scripts/update-remote-authority.test.ts b/scripts/update-remote-authority.test.ts
new file mode 100644
index 00000000..101f6b3a
--- /dev/null
+++ b/scripts/update-remote-authority.test.ts
@@ -0,0 +1,52 @@
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const HELPER = path.join(process.cwd(), "scripts/lib/update-remote-authority.sh");
+const roots: string[] = [];
+
+function git(cwd: string, ...args: string[]) {
+ return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
+}
+
+function repo(origin: string) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-remote-authority-"));
+ roots.push(root);
+ git(root, "init", "-q", "-b", "main");
+ git(root, "remote", "add", "origin", origin);
+ return root;
+}
+
+function prepare(root: string) {
+ execFileSync("bash", ["-c", 'source "$1"; update_prepare_origin "$2"', "_", HELPER, root], { encoding: "utf8" });
+ return git(root, "remote", "get-url", "origin");
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe("MSO update remote authority", () => {
+ it("normalizes canonical SSH origins to public HTTPS", () => {
+ expect(prepare(repo("[email protected]:rahmanef63/mso.git"))).toBe("https://github.com/rahmanef63/mso.git");
+ expect(prepare(repo("ssh://[email protected]/rahmanef63/mso"))).toBe("https://github.com/rahmanef63/mso.git");
+ });
+
+ it("keeps canonical public HTTPS stable", () => {
+ expect(prepare(repo("https://github.com/rahmanef63/mso.git"))).toBe("https://github.com/rahmanef63/mso.git");
+ });
+
+ it("never rewrites explicit HTTPS or SSH forks/private origins", () => {
+ expect(prepare(repo("https://github.com/example/mso.git"))).toBe("https://github.com/example/mso.git");
+ expect(prepare(repo("[email protected]:example/private-mso.git"))).toBe("[email protected]:example/private-mso.git");
+ });
+
+ it("forces non-interactive fetch while still honoring an explicit SSH command", () => {
+ const source = fs.readFileSync(HELPER, "utf8");
+ expect(source).toContain("GIT_TERMINAL_PROMPT=0");
+ expect(source).toContain('GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-ssh -oBatchMode=yes}"');
+ expect(source).toContain('git -C "$root" fetch --quiet "$@" origin "$ref"');
+ });
+});