feat(profiles): reduce the connection form to what a connection needs

Adding an AstrBot connection asked for eleven fields. Three of them
reach nothing: the SSE URL has no consumer anywhere in networking (the
desktop transport builds its own endpoint and AstrBot never reads it),
the certificate fingerprint is stored but TLS pinning is not
implemented, and the role only decides a word in the profile list.

The form is now the four things an activation actually requires — server
address, adapter id, API key, slot — with everything else behind a
collapsed advanced section.

The adapter id is the remote username. It was previously entered twice,
once in the profile form and again in the credential card, and it is
what keeps two slots on one server from sharing a conversation, so the
field now says that.

Three values are derived rather than asked for. The display name falls
back to identity@host. The role follows the chosen slot. The insecure
HTTP approval appears only for an http:// address and is required there,
because normalize_url rejects such an address without it — showing it
unconditionally invited enabling it for an https:// endpoint that never
needed it.

Choosing a slot now does the whole job: it assigns the slot, sets the
role, and points startup auto-connect at it, replacing a separate slot
card interaction and a separate auto-connect slot dropdown that could
disagree with each other. The API key is enrolled in the same submit.
Both steps need the profile to exist, so they run after the save and
report their own failures rather than failing the save.

Verified in a browser against the real stylesheet: four fields plus a
collapsed advanced section, the insecure checkbox appears only for
http:// and carries required, and the display name placeholder resolves
to identity@host.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
这个提交存在于:
YokiiroBW 2026-07-27 01:41:42 +08:00
父节点 ef8bc430d9
当前提交 79dbb40a25
共有 3 个文件被更改,包括 343 次插入 和 228 次删除

查看文件

@ -227,15 +227,16 @@ describe("App", () => {
await openConnectionsPage();
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("服务器地址"), {
target: { value: "https://ops.example.test" },
});
fireEvent.change(screen.getByLabelText("适配器 ID"), {
target: { value: "opsbot" },
});
// Lives under 高级设置; the disclosure only hides it visually.
fireEvent.change(screen.getByLabelText("显示名称"), {
target: { value: "家庭运维" },
});
fireEvent.change(screen.getByLabelText("角色"), {
target: { value: "operations" },
});
fireEvent.change(screen.getByLabelText("REST 基础 URL"), {
target: { value: "https://ops.example.test" },
});
fireEvent.click(screen.getByRole("button", { name: "保存 Profile" }));
expect(
@ -354,13 +355,24 @@ describe("App", () => {
const created: ConnectionProfile = {
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
...request,
transportKind: "desktop-v1",
transportKind: request.transportKind ?? "astr-bot-open-api",
createdAt: "2026-07-19T03:00:00Z",
updatedAt: "2026-07-19T03:00:00Z",
};
profiles = [created];
return created;
}
if (command === "assign_connection_slot") {
const { request } = args as {
request: { slot: ActiveSlotKind; profileId: string };
};
return {
slot: request.slot,
profileId: request.profileId,
state: "disconnected",
unreadCount: 0,
};
}
throw new Error(`Unexpected command: ${command}`);
});
@ -368,19 +380,18 @@ describe("App", () => {
await openConnectionsPage();
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
fireEvent.change(screen.getByLabelText("服务器地址"), {
target: { value: "https://companion.example.test" },
});
fireEvent.change(screen.getByLabelText("适配器 ID"), {
target: { value: "companionbot" },
});
fireEvent.change(screen.getByLabelText("显示名称"), {
target: { value: "自动陪伴" },
});
fireEvent.change(screen.getByLabelText("角色"), {
target: { value: "companion" },
});
fireEvent.change(screen.getByLabelText("REST 基础 URL"), {
target: { value: "https://companion.example.test" },
});
fireEvent.click(
screen.getByLabelText("启动时自动连接(不会在本阶段真正建立网络会话)"),
);
fireEvent.change(screen.getByLabelText("自动连接槽位"), {
// Choosing a slot is now the single control: it assigns the slot, sets the
// role, and points startup auto-connect at it.
fireEvent.change(screen.getByLabelText("槽位"), {
target: { value: "companion" },
});
fireEvent.click(screen.getByRole("button", { name: "保存 Profile" }));
@ -388,19 +399,25 @@ describe("App", () => {
expect(
await screen.findByText("已创建 Profile:自动陪伴"),
).toBeInTheDocument();
expect(screen.getByText("自动连接:陪伴")).toBeInTheDocument();
expect(invoke).toHaveBeenCalledWith("create_connection_profile", {
request: {
displayName: "自动陪伴",
role: "companion",
baseUrl: "https://companion.example.test",
authenticationType: "device-token",
transportKind: "desktop-v1",
authenticationType: "api-key",
transportKind: "astr-bot-open-api",
remoteUsername: "companionbot",
allowInsecureHttp: false,
autoConnect: true,
autoConnectSlot: "companion",
},
});
expect(invoke).toHaveBeenCalledWith("assign_connection_slot", {
request: {
slot: "companion",
profileId: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
},
});
});
it("shows duplicate server-instance warnings and locks the operations slot", async () => {

查看文件

@ -25,35 +25,68 @@ import { errorMessage } from "../../lib/errorMessage";
import { CredentialEnrollmentCard } from "./CredentialEnrollmentCard";
interface ProfileFormState {
displayName: string;
role: ProfileRole;
baseUrl: string;
eventStreamUrl: string;
apiKey: string;
remoteUsername: string;
slot: "" | ActiveSlotKind;
displayName: string;
remoteDisplayName: string;
authenticationType: AuthenticationType;
transportKind: TransportKind;
remoteUsername: string;
remoteDisplayName: string;
allowInsecureHttp: boolean;
pinnedCertificateFingerprint: string;
autoConnect: boolean;
autoConnectSlot: "" | ActiveSlotKind;
}
const emptyForm: ProfileFormState = {
displayName: "",
role: "general",
baseUrl: "https://",
eventStreamUrl: "",
authenticationType: "device-token",
transportKind: "desktop-v1",
baseUrl: "http://",
apiKey: "",
remoteUsername: "",
slot: "",
displayName: "",
remoteDisplayName: "",
authenticationType: "api-key",
transportKind: "astr-bot-open-api",
allowInsecureHttp: false,
pinnedCertificateFingerprint: "",
autoConnect: false,
autoConnectSlot: "",
autoConnect: true,
};
/// Names the connection after the server and identity when the user did not.
///
/// The display name is `NOT NULL` in the database and is what the profile list
/// and the slot cards show, but asking for it adds a field that carries no
/// information the other three do not already provide.
function derivedDisplayName(form: ProfileFormState): string {
const explicit = form.displayName.trim();
if (explicit) return explicit;
const username = form.remoteUsername.trim();
const host = hostOf(form.baseUrl);
if (host && username) return `${username}@${host}`;
return username || host || "AstrBot 连接";
}
function hostOf(value: string): string {
try {
return new URL(value.trim()).host;
} catch {
return "";
}
}
/// The slot a profile serves is the only meaningful reading of its role.
function roleForSlot(slot: "" | ActiveSlotKind): ProfileRole {
return slot === "" ? "general" : slot;
}
/// True when the address needs the explicit insecure-transport approval.
///
/// `normalize_url` in `profiles.rs` rejects an `http://` base URL unless the
/// profile carries that approval, so the checkbox has to appear before the user
/// can save a LAN address — but showing it unconditionally invites turning it on
/// for an `https://` endpoint that never needed it.
function needsInsecureApproval(baseUrl: string): boolean {
return baseUrl.trim().toLowerCase().startsWith("http://");
}
const emptyPolicy: ConnectionPolicyStatus = {
operationsSwitchLocked: false,
activeOperationsTaskCount: 0,
@ -103,7 +136,10 @@ export function ProfileManager() {
useEffect(() => {
void loadProfiles();
const refreshTimer = window.setInterval(() => void refreshRuntimeStatus(), 2000);
const refreshTimer = window.setInterval(
() => void refreshRuntimeStatus(),
2000,
);
return () => window.clearInterval(refreshTimer);
}, [loadProfiles, refreshRuntimeStatus]);
@ -132,15 +168,65 @@ export function ProfileManager() {
saved,
]),
);
// The remaining steps each need the profile to exist, so they cannot be
// folded into the create call. A failure in either leaves a usable
// profile, so report it rather than treating the save as failed.
const followUp: string[] = [];
if (form.slot) {
try {
const assigned = connectionSlotSchema.parse(
await invoke<unknown>("assign_connection_slot", {
request: {
slot: form.slot,
profileId: saved.id,
} satisfies AssignConnectionSlotRequest,
}),
);
setSlots((current) =>
current.map((item) =>
item.slot === assigned.slot ? assigned : item,
),
);
} catch (reason) {
followUp.push(`槽位指派失败:${errorMessage(reason)}`);
}
}
const secret = form.apiKey.trim();
if (secret) {
try {
await invoke("enroll_profile_credential", {
request: {
profileId: saved.id,
authenticationType: saved.authenticationType,
secret,
username: saved.remoteUsername ?? undefined,
},
});
} catch (reason) {
followUp.push(
`凭据登记失败:${errorMessage(reason)}。Profile 已保存,可在下方凭据卡片重试。`,
);
}
}
await loadProfiles();
await refreshPolicy();
setNotice(
editingId
? `已更新 Profile:${saved.displayName}`
: `已创建 Profile:${saved.displayName}`,
);
if (followUp.length > 0) {
setError(followUp.join(" "));
setNotice(`已保存 Profile:${saved.displayName}`);
} else {
setNotice(
editingId
? `已更新 Profile:${saved.displayName}`
: `已创建 Profile:${saved.displayName}`,
);
}
resetForm();
} catch (reason) {
setError(`Profile save failed: ${errorMessage(reason)}`);
setError(`Profile 保存失败:${errorMessage(reason)}`);
} finally {
setBusy(false);
}
@ -148,19 +234,25 @@ export function ProfileManager() {
function editProfile(profile: ConnectionProfile) {
setEditingId(profile.id);
// The persisted slot assignment is authoritative for which slot a profile
// serves; `autoConnectSlot` only says where startup connection should go.
const assignedSlot = slots.find(
(slot) => slot.profileId === profile.id,
)?.slot;
setForm({
displayName: profile.displayName,
role: profile.role,
baseUrl: profile.baseUrl,
eventStreamUrl: profile.eventStreamUrl ?? "",
authenticationType: profile.authenticationType,
transportKind: profile.transportKind ?? "desktop-v1",
// Never populated from a stored profile: the secret lives in Windows
// Credential Manager and never crosses IPC. Rotation goes through the
// credential card.
apiKey: "",
remoteUsername: profile.remoteUsername ?? "",
slot: assignedSlot ?? profile.autoConnectSlot ?? "",
displayName: profile.displayName,
remoteDisplayName: profile.remoteDisplayName ?? "",
authenticationType: profile.authenticationType,
transportKind: profile.transportKind ?? "astr-bot-open-api",
allowInsecureHttp: profile.allowInsecureHttp,
pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "",
autoConnect: profile.autoConnect,
autoConnectSlot: profile.autoConnectSlot ?? "",
});
setError(null);
setNotice(null);
@ -335,45 +427,12 @@ export function ProfileManager() {
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
<label>
<span>显示名称</span>
<input
name="displayName"
required
maxLength={80}
value={form.displayName}
onChange={(event) =>
setForm((current) => ({
...current,
displayName: event.target.value,
}))
}
/>
</label>
<label>
<span>角色</span>
<select
name="role"
value={form.role}
onChange={(event) =>
setForm((current) => ({
...current,
role: event.target.value as ProfileRole,
}))
}
>
<option value="general">通用</option>
<option value="companion">陪伴</option>
<option value="operations">运维</option>
</select>
</label>
<label>
<span>REST 基础 URL</span>
<span>服务器地址</span>
<input
name="baseUrl"
type="url"
required
placeholder="http://192.168.1.10:6185"
value={form.baseUrl}
onChange={(event) =>
setForm((current) => ({
@ -385,90 +444,12 @@ export function ProfileManager() {
</label>
<label>
<span>SSE URL(可选)</span>
<input
name="eventStreamUrl"
type="url"
value={form.eventStreamUrl}
onChange={(event) =>
setForm((current) => ({
...current,
eventStreamUrl: event.target.value,
}))
}
/>
</label>
<label>
<span>认证类型</span>
<select
name="authenticationType"
value={form.authenticationType}
onChange={(event) =>
setForm((current) => ({
...current,
authenticationType: event.target.value as AuthenticationType,
}))
}
>
<option value="device-token">设备 Token</option>
<option value="api-key">API Key</option>
<option value="jwt">AstrBot JWT</option>
</select>
</label>
<label>
<span>证书 SHA-256 指纹(可选)</span>
<input
name="pinnedCertificateFingerprint"
inputMode="text"
placeholder="64 位十六进制"
value={form.pinnedCertificateFingerprint}
onChange={(event) =>
setForm((current) => ({
...current,
pinnedCertificateFingerprint: event.target.value,
}))
}
/>
</label>
<label className="checkbox-field">
<input
name="allowInsecureHttp"
type="checkbox"
checked={form.allowInsecureHttp}
onChange={(event) =>
setForm((current) => ({
...current,
allowInsecureHttp: event.target.checked,
}))
}
/>
<span>明确允许不安全 HTTP(仅限受信任网络)</span>
</label>
<label>
传输协议
<select
value={form.transportKind}
onChange={(event) =>
setForm((current) => ({
...current,
transportKind: event.target.value as TransportKind,
}))
}
>
<option value="desktop-v1">Desktop Mock/Gateway</option>
<option value="astr-bot-open-api">AstrBot OpenAPI</option>
</select>
</label>
{form.transportKind === "astr-bot-open-api" ? (
<>
<label>
AstrBot 用户名
<span>适配器 ID</span>
<input
name="remoteUsername"
required={form.transportKind === "astr-bot-open-api"}
pattern="[A-Za-z0-9]{3,32}"
placeholder="yoki"
value={form.remoteUsername}
onChange={(event) =>
setForm((current) => ({
@ -476,67 +457,159 @@ export function ProfileManager() {
remoteUsername: event.target.value,
}))
}
placeholder="desktop-companion"
/>
</label>
<label>
BOT 称呼昵称
<input
value={form.remoteDisplayName}
maxLength={80}
onChange={(event) =>
setForm((current) => ({
...current,
remoteDisplayName: event.target.value,
}))
}
placeholder="小明"
/>
</label>
</>
) : null}
<label className="checkbox-field">
<input
name="autoConnect"
type="checkbox"
checked={form.autoConnect}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnect: event.target.checked,
autoConnectSlot: event.target.checked
? current.autoConnectSlot || "companion"
: "",
}))
}
/>
<span>启动时自动连接(不会在本阶段真正建立网络会话)</span>
</label>
<p className="form-note">
AstrBot 的会话身份,3–32 位英文或数字。两个槽位必须使用不同的
ID,否则会共用同一段对话。
</p>
{editingId ? null : (
<>
<label>
<span>API Key</span>
<input
name="apiKey"
type="password"
autoComplete="off"
value={form.apiKey}
onChange={(event) =>
setForm((current) => ({
...current,
apiKey: event.target.value,
}))
}
/>
</label>
<p className="form-note">
保存时一次性写入 Windows
凭据管理器,不会进入本地数据库或前端状态。
</p>
</>
)}
<label>
<span>自动连接槽位</span>
<span>槽位</span>
<select
name="autoConnectSlot"
aria-label="自动连接槽位"
disabled={!form.autoConnect}
value={form.autoConnectSlot}
name="slot"
value={form.slot}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnectSlot: event.target.value as "" | ActiveSlotKind,
slot: event.target.value as "" | ActiveSlotKind,
}))
}
>
<option value="">不自动连接</option>
<option value="companion">陪伴槽位</option>
<option value="operations">运维槽位</option>
<option value="">暂不指派</option>
<option value="companion">陪伴</option>
<option value="operations">运维</option>
</select>
</label>
<p className="form-note">
自动连接配置最多两个 Profile,且槽位不可重复;真正的 REST/SSE
激活仍需等待协议与凭据边界确认。
</p>
{needsInsecureApproval(form.baseUrl) ? (
<label className="checkbox-field">
<input
name="allowInsecureHttp"
type="checkbox"
required
checked={form.allowInsecureHttp}
onChange={(event) =>
setForm((current) => ({
...current,
allowInsecureHttp: event.target.checked,
}))
}
/>
<span>这是明文 HTTP 地址,确认仅在受信任的局域网内使用</span>
</label>
) : null}
<details className="profile-advanced">
<summary>高级设置</summary>
<label>
<span>显示名称</span>
<input
name="displayName"
maxLength={80}
placeholder={derivedDisplayName(form)}
value={form.displayName}
onChange={(event) =>
setForm((current) => ({
...current,
displayName: event.target.value,
}))
}
/>
</label>
<label>
<span>传输协议</span>
<select
name="transportKind"
value={form.transportKind}
onChange={(event) =>
setForm((current) => ({
...current,
transportKind: event.target.value as TransportKind,
}))
}
>
<option value="astr-bot-open-api">AstrBot OpenAPI</option>
<option value="desktop-v1">Desktop Mock/Gateway</option>
</select>
</label>
<label>
<span>认证类型</span>
<select
name="authenticationType"
value={form.authenticationType}
onChange={(event) =>
setForm((current) => ({
...current,
authenticationType: event.target
.value as AuthenticationType,
}))
}
>
<option value="api-key">API Key</option>
<option value="jwt">AstrBot JWT</option>
<option value="device-token">设备 Token</option>
</select>
</label>
<label>
<span>BOT 称呼昵称</span>
<input
name="remoteDisplayName"
maxLength={80}
placeholder="小明"
value={form.remoteDisplayName}
onChange={(event) =>
setForm((current) => ({
...current,
remoteDisplayName: event.target.value,
}))
}
/>
</label>
<label className="checkbox-field">
<input
name="autoConnect"
type="checkbox"
checked={form.autoConnect}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnect: event.target.checked,
}))
}
/>
<span>启动时自动连接所选槽位</span>
</label>
</details>
<div className="button-row">
<button type="submit" disabled={busy}>
@ -602,12 +675,12 @@ export function ProfileManager() {
删除
</button>
</div>
<CredentialEnrollmentCard
profile={profile}
onChanged={loadProfiles}
/>
</article>
</article>
))
)}
</div>
@ -628,23 +701,22 @@ export function ProfileManager() {
}
function toProfileInput(form: ProfileFormState): ConnectionProfileInput {
const eventStreamUrl = form.eventStreamUrl.trim();
const fingerprint = form.pinnedCertificateFingerprint.trim();
const slot = form.slot || undefined;
return {
displayName: form.displayName.trim(),
role: form.role,
displayName: derivedDisplayName(form),
role: roleForSlot(form.slot),
baseUrl: form.baseUrl.trim(),
eventStreamUrl: eventStreamUrl || undefined,
authenticationType: form.authenticationType,
transportKind: form.transportKind,
remoteUsername: form.remoteUsername.trim() || undefined,
remoteDisplayName: form.remoteDisplayName.trim() || undefined,
allowInsecureHttp: form.allowInsecureHttp,
pinnedCertificateFingerprint: fingerprint || undefined,
autoConnect: form.autoConnect,
autoConnectSlot: form.autoConnect
? form.autoConnectSlot || undefined
: undefined,
// `normalize_url` only consults this for an `http://` address, and leaving a
// stale approval on an `https://` profile would silently permit a later
// downgrade of that address.
allowInsecureHttp:
needsInsecureApproval(form.baseUrl) && form.allowInsecureHttp,
autoConnect: form.autoConnect && Boolean(slot),
autoConnectSlot: form.autoConnect ? slot : undefined,
};
}

查看文件

@ -265,6 +265,32 @@ select:focus {
font-size: 0.9rem;
}
/* Everything the AstrBot connection does not need in order to work. Collapsed
by default so the common path is four fields. */
.profile-advanced {
padding: 0.75rem 0.9rem;
border: 1px solid var(--ui-line, rgb(137 175 232 / 26%));
border-radius: 0.65rem;
background: var(--ui-surface-soft, rgb(11 27 49 / 45%));
}
.profile-advanced > summary {
color: var(--ui-subtle, #9fb4d4);
font-size: 0.9rem;
font-weight: 650;
cursor: pointer;
list-style-position: inside;
}
.profile-advanced[open] > summary {
margin-bottom: 0.9rem;
}
.profile-advanced > label:not(:last-child),
.profile-advanced > .checkbox-field:not(:last-child) {
margin-bottom: 0.9rem;
}
.button-row {
display: flex;
flex-wrap: wrap;